Skip to main content

cargo_zng/res/built_in/sfx_res/
sfx_main.rs

1// <windows-subsystem>
2#![windows_subsystem = "windows"]
3// </windows-subsystem>
4
5// source code for the generated self-extracting executable compiled by ./sfx.rs
6
7// [(name, compression, parts)]
8// data split in parts for performance and to avoid hard limits
9static DATA: &[(&str, Compression, &[&[u8]])] = &[];
10
11static ARGS: &[&str] = &[];
12static ENV: &[(&str, &str)] = &[];
13
14#[derive(Clone, Copy)]
15pub enum Compression {
16    None,
17    Zstd,
18    ZstdBcj(BcjFilter),
19}
20
21#[derive(Clone, Copy)]
22pub enum BcjFilter {
23    X86,
24    Arm,
25    Arm64,
26    ArmThumb,
27    Ppc,
28    Sparc,
29    Ia64,
30    Riscv,
31}
32
33use std::{
34    env,
35    fmt::Write as _,
36    fs,
37    io::{self, Read as _},
38    path::PathBuf,
39};
40
41use lzma_rust2::filter::bcj::BcjReader;
42
43pub fn main() {
44    // <windows-subsystem>
45    #[cfg(windows)]
46    attach_console();
47    // </windows-subsystem>
48
49    if let Ok(name) = std::env::var("SFX_GET_DATA") {
50        return serve_data(&name);
51    } else if std::env::var("SFX_GET_MANIFEST").is_ok() {
52        return serve_manifest();
53    }
54    run();
55}
56
57macro_rules! err_exit {
58    ($($msg:tt)*) => {
59        {
60            eprintln!($($msg)*);
61            std::process::exit(-1);
62        }
63    };
64}
65trait UnwrapOrExit<T> {
66    fn unwrap_or_exit(self, ctx: &str) -> T;
67}
68impl<T, E: std::error::Error> UnwrapOrExit<T> for Result<T, E> {
69    fn unwrap_or_exit(self, ctx: &str) -> T {
70        match self {
71            Ok(r) => r,
72            Err(e) => err_exit!("{ctx} error, {e}"),
73        }
74    }
75}
76
77fn read_data(name: &str) -> Box<dyn io::Read> {
78    for (key, compression, parts) in DATA {
79        if *key == name {
80            if parts.is_empty() {
81                return Box::new(&[0u8; 0][..]);
82            }
83            let mut data: Box<dyn io::Read> = Box::new(parts[0]);
84            for &part in parts[1..].iter() {
85                data = Box::new(data.chain(part));
86            }
87            match *compression {
88                Compression::None => {}
89                Compression::Zstd => {
90                    let d = zstd::stream::read::Decoder::new(data).unwrap_or_exit("Decoder::new");
91                    data = Box::new(d);
92                }
93                Compression::ZstdBcj(bcj) => {
94                    let d = zstd::stream::read::Decoder::new(data).unwrap_or_exit("Decoder::new");
95                    let d = match bcj {
96                        BcjFilter::X86 => BcjReader::new_x86(d, 0),
97                        BcjFilter::Arm => BcjReader::new_arm(d, 0),
98                        BcjFilter::Arm64 => BcjReader::new_arm64(d, 0),
99                        BcjFilter::ArmThumb => BcjReader::new_arm_thumb(d, 0),
100                        BcjFilter::Ppc => BcjReader::new_ppc(d, 0),
101                        BcjFilter::Sparc => BcjReader::new_sparc(d, 0),
102                        BcjFilter::Ia64 => BcjReader::new_ia64(d, 0),
103                        BcjFilter::Riscv => BcjReader::new_riscv(d, 0),
104                    };
105                    data = Box::new(d);
106                }
107            }
108            return data;
109        }
110    }
111    err_exit!("{name:?} not found")
112}
113
114fn serve_data(name: &str) {
115    let mut data = read_data(name);
116    io::copy(&mut data, &mut std::io::stdout()).unwrap_or_exit("serve_data/copy");
117}
118
119fn serve_manifest() {
120    for (name, compression, data) in DATA {
121        let len = match compression {
122            Compression::None => Some(data.iter().map(|d| d.len() as u64).sum::<u64>()),
123            Compression::Zstd | Compression::ZstdBcj(_) => zstd::zstd_safe::get_frame_content_size(data[0]).unwrap_or_default(),
124        };
125        print!("{name}:");
126        match len {
127            Some(l) => println!("{l}"),
128            None => println!("unknown"),
129        }
130    }
131}
132
133fn run() {
134    let run_file = tmp_run_file().unwrap_or_exit("tmp_run_file");
135    {
136        let mut data = read_data(":run");
137        let mut run_file = fs::File::create_new(&run_file).unwrap_or_exit("File::create_new");
138        io::copy(&mut data, &mut run_file).unwrap_or_exit("run/copy");
139    }
140    #[cfg(unix)]
141    {
142        use std::os::unix::fs::PermissionsExt as _;
143        let perms = fs::metadata(std::env::current_exe().unwrap())
144            .unwrap_or_exit("get-metadata")
145            .permissions();
146        fs::set_permissions(&run_file, perms).unwrap_or_exit("set-metadata");
147    }
148
149    let mut sfx_args = String::new();
150    let mut sep = "";
151    for arg in env::args() {
152        write!(&mut sfx_args, "{sep}{arg}").unwrap_or_exit("");
153        sep = "\n";
154    }
155
156    let mut run = std::process::Command::new(&run_file);
157    for arg in ARGS {
158        run.arg(arg);
159    }
160    for (key, value) in ENV {
161        run.env(key, value);
162    }
163    let s = run.env("SFX_ARGS", sfx_args).status().unwrap_or_exit("run");
164
165    if let Err(e) = fs::remove_file(run_file)
166        && !matches!(e.kind(), io::ErrorKind::NotFound)
167    {
168        err_exit!("run/remove error, {e:?}");
169    }
170    if !s.success() {
171        std::process::exit(s.code().unwrap_or(-1))
172    }
173}
174fn tmp_run_file() -> io::Result<PathBuf> {
175    let tmp = env::temp_dir().join("zng-sfx");
176    if let Err(e) = fs::create_dir(&tmp)
177        && !matches!(e.kind(), io::ErrorKind::AlreadyExists)
178    {
179        return Err(e);
180    }
181    for i in 0..1000 {
182        let tmp = tmp.join(format!("run-{i}.exe"));
183        if let Err(e) = fs::remove_file(&tmp)
184            && matches!(e.kind(), io::ErrorKind::NotFound)
185        {
186            return Ok(tmp);
187        }
188    }
189    Err(io::Error::new(io::ErrorKind::QuotaExceeded, "too many tmp exe"))
190}
191
192// <windows-subsystem>
193#[cfg(windows)]
194pub fn attach_console() {
195    #[link(name = "kernel32")]
196    unsafe extern "system" {
197        fn GetConsoleWindow() -> isize;
198        fn AttachConsole(process_id: u32) -> i32;
199    }
200    unsafe {
201        // If no console is attached, attempt to attach to parent
202        if GetConsoleWindow() == 0 {
203            let _ = AttachConsole(0xFFFFFFFF);
204        }
205    }
206}
207// </windows-subsystem>