|
1 |
| -use std::io::{Cursor, Write}; |
2 |
| -use std::path::Path; |
| 1 | +use std::io::{self, Cursor, Read, Seek, Write}; |
| 2 | +use std::path::{Path, PathBuf}; |
3 | 3 |
|
| 4 | +use fs_err::File; |
4 | 5 | use thiserror::Error;
|
5 | 6 | use uv_fs::Simplified;
|
6 | 7 | use zip::write::FileOptions;
|
@@ -30,28 +31,160 @@ const LAUNCHER_AARCH64_GUI: &[u8] =
|
30 | 31 | const LAUNCHER_AARCH64_CONSOLE: &[u8] =
|
31 | 32 | include_bytes!("../../uv-trampoline/trampolines/uv-trampoline-aarch64-console.exe");
|
32 | 33 |
|
| 34 | +// See `uv-trampoline::bounce`. These numbers must match. |
| 35 | +const PATH_LENGTH_SIZE: usize = size_of::<u32>(); |
| 36 | +const MAX_PATH_LENGTH: u32 = 32 * 1024; |
| 37 | +const MAGIC_NUMBER_SIZE: usize = 4; |
| 38 | + |
| 39 | +#[derive(Debug)] |
| 40 | +pub struct Launcher { |
| 41 | + pub kind: LauncherKind, |
| 42 | + pub python_path: PathBuf, |
| 43 | +} |
| 44 | + |
| 45 | +impl Launcher { |
| 46 | + /// Read [`Launcher`] metadata from a trampoline executable file. |
| 47 | + /// |
| 48 | + /// Returns `Ok(None)` if the file is not a trampoline executable. |
| 49 | + /// Returns `Err` if the file looks like a trampoline executable but is formatted incorrectly. |
| 50 | + /// |
| 51 | + /// Expects the following metadata to be at the end of the file: |
| 52 | + /// |
| 53 | + /// ```text |
| 54 | + /// - file path (no greater than 32KB) |
| 55 | + /// - file path length (u32) |
| 56 | + /// - magic number(4 bytes) |
| 57 | + /// ``` |
| 58 | + /// |
| 59 | + /// This should only be used on Windows, but should just return `Ok(None)` on other platforms. |
| 60 | + /// |
| 61 | + /// This is an implementation of [`uv-trampoline::bounce::read_trampoline_metadata`] that |
| 62 | + /// returns errors instead of panicking. Unlike the utility there, we don't assume that the |
| 63 | + /// file we are reading is a trampoline. |
| 64 | + #[allow(clippy::cast_possible_wrap)] |
| 65 | + pub fn try_from_path(path: &Path) -> Result<Option<Self>, Error> { |
| 66 | + let mut file = File::open(path)?; |
| 67 | + |
| 68 | + // Read the magic number |
| 69 | + let Some(kind) = LauncherKind::try_from_file(&mut file)? else { |
| 70 | + return Ok(None); |
| 71 | + }; |
| 72 | + |
| 73 | + // Seek to the start of the path length. |
| 74 | + let Ok(_) = file.seek(io::SeekFrom::End( |
| 75 | + -((MAGIC_NUMBER_SIZE + PATH_LENGTH_SIZE) as i64), |
| 76 | + )) else { |
| 77 | + return Err(Error::InvalidLauncher( |
| 78 | + "Unable to seek to the start of the path length".to_string(), |
| 79 | + )); |
| 80 | + }; |
| 81 | + |
| 82 | + // Read the path length |
| 83 | + let mut buffer = [0; PATH_LENGTH_SIZE]; |
| 84 | + file.read_exact(&mut buffer) |
| 85 | + .map_err(|err| Error::InvalidLauncherRead("path length".to_string(), err))?; |
| 86 | + |
| 87 | + let path_length = { |
| 88 | + let raw_length = u32::from_le_bytes(buffer); |
| 89 | + |
| 90 | + if raw_length > MAX_PATH_LENGTH { |
| 91 | + return Err(Error::InvalidLauncher(format!( |
| 92 | + "Only paths with a length up to 32KBs are supported but the Python executable path has a length of {raw_length}" |
| 93 | + ))); |
| 94 | + } |
| 95 | + |
| 96 | + // SAFETY: Above we guarantee the length is less than 32KB |
| 97 | + raw_length as usize |
| 98 | + }; |
| 99 | + |
| 100 | + // Seek to the start of the path |
| 101 | + let Ok(_) = file.seek(io::SeekFrom::End( |
| 102 | + -((MAGIC_NUMBER_SIZE + PATH_LENGTH_SIZE + path_length) as i64), |
| 103 | + )) else { |
| 104 | + return Err(Error::InvalidLauncher( |
| 105 | + "Unable to seek to the start of the path".to_string(), |
| 106 | + )); |
| 107 | + }; |
| 108 | + |
| 109 | + // Read the path |
| 110 | + let mut buffer = vec![0u8; path_length]; |
| 111 | + file.read_exact(&mut buffer) |
| 112 | + .map_err(|err| Error::InvalidLauncherRead("executable path".to_string(), err))?; |
| 113 | + |
| 114 | + let path = PathBuf::from(String::from_utf8(buffer).map_err(|_| { |
| 115 | + Error::InvalidLauncher("Python executable path was not valid UTF-8".to_string()) |
| 116 | + })?); |
| 117 | + |
| 118 | + Ok(Some(Self { |
| 119 | + kind, |
| 120 | + python_path: path, |
| 121 | + })) |
| 122 | + } |
| 123 | +} |
| 124 | + |
33 | 125 | /// The kind of trampoline launcher to create.
|
34 | 126 | ///
|
35 | 127 | /// See [`uv-trampoline::bounce::TrampolineKind`].
|
36 |
| -enum LauncherKind { |
| 128 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 129 | +pub enum LauncherKind { |
37 | 130 | /// The trampoline should execute itself, it's a zipped Python script.
|
38 | 131 | Script,
|
39 | 132 | /// The trampoline should just execute Python, it's a proxy Python executable.
|
40 | 133 | Python,
|
41 | 134 | }
|
42 | 135 |
|
43 | 136 | impl LauncherKind {
|
44 |
| - const fn magic_number(&self) -> &'static [u8; 4] { |
| 137 | + /// Return the magic number for this [`LauncherKind`]. |
| 138 | + const fn magic_number(self) -> &'static [u8; 4] { |
45 | 139 | match self {
|
46 | 140 | Self::Script => b"UVSC",
|
47 | 141 | Self::Python => b"UVPY",
|
48 | 142 | }
|
49 | 143 | }
|
| 144 | + |
| 145 | + /// Read a [`LauncherKind`] from 4 byte buffer. |
| 146 | + /// |
| 147 | + /// If the buffer does not contain a matching magic number, `None` is returned. |
| 148 | + fn try_from_bytes(bytes: [u8; MAGIC_NUMBER_SIZE]) -> Option<Self> { |
| 149 | + if &bytes == Self::Script.magic_number() { |
| 150 | + return Some(Self::Script); |
| 151 | + } |
| 152 | + if &bytes == Self::Python.magic_number() { |
| 153 | + return Some(Self::Python); |
| 154 | + } |
| 155 | + None |
| 156 | + } |
| 157 | + |
| 158 | + /// Read a [`LauncherKind`] from a file handle, based on the magic number. |
| 159 | + /// |
| 160 | + /// This will mutate the file handle, seeking to the end of the file. |
| 161 | + /// |
| 162 | + /// If the file cannot be read, an [`io::Error`] is returned. If the path is not a launcher, |
| 163 | + /// `None` is returned. |
| 164 | + #[allow(clippy::cast_possible_wrap)] |
| 165 | + pub fn try_from_file(file: &mut File) -> Result<Option<Self>, Error> { |
| 166 | + // If the file is less than four bytes, it's not a launcher. |
| 167 | + let Ok(_) = file.seek(io::SeekFrom::End(-(MAGIC_NUMBER_SIZE as i64))) else { |
| 168 | + return Ok(None); |
| 169 | + }; |
| 170 | + |
| 171 | + let mut buffer = [0; MAGIC_NUMBER_SIZE]; |
| 172 | + file.read_exact(&mut buffer) |
| 173 | + .map_err(|err| Error::InvalidLauncherRead("magic number".to_string(), err))?; |
| 174 | + |
| 175 | + Ok(Self::try_from_bytes(buffer)) |
| 176 | + } |
50 | 177 | }
|
51 | 178 |
|
52 | 179 | /// Note: The caller is responsible for adding the path of the wheel we're installing.
|
53 | 180 | #[derive(Error, Debug)]
|
54 | 181 | pub enum Error {
|
| 182 | + #[error(transparent)] |
| 183 | + Io(#[from] io::Error), |
| 184 | + #[error("Invalid launcher: {0}")] |
| 185 | + InvalidLauncher(String), |
| 186 | + #[error("Failed to read launcher {0}")] |
| 187 | + InvalidLauncherRead(String, #[source] io::Error), |
55 | 188 | #[error(
|
56 | 189 | "Unable to create Windows launcher for: {0} (only x86_64, x86, and arm64 are supported)"
|
57 | 190 | )]
|
@@ -192,7 +325,7 @@ mod test {
|
192 | 325 |
|
193 | 326 | use which::which;
|
194 | 327 |
|
195 |
| - use super::{windows_python_launcher, windows_script_launcher}; |
| 328 | + use super::{windows_python_launcher, windows_script_launcher, Launcher, LauncherKind}; |
196 | 329 |
|
197 | 330 | #[test]
|
198 | 331 | #[cfg(all(windows, target_arch = "x86", feature = "production"))]
|
@@ -340,6 +473,13 @@ if __name__ == "__main__":
|
340 | 473 | .stdout(stdout_predicate)
|
341 | 474 | .stderr(stderr_predicate);
|
342 | 475 |
|
| 476 | + let launcher = Launcher::try_from_path(console_bin_path.path()) |
| 477 | + .expect("We should succeed at reading the launcher") |
| 478 | + .expect("The launcher should be valid"); |
| 479 | + |
| 480 | + assert!(launcher.kind == LauncherKind::Script); |
| 481 | + assert!(launcher.python_path == python_executable_path); |
| 482 | + |
343 | 483 | Ok(())
|
344 | 484 | }
|
345 | 485 |
|
@@ -371,6 +511,13 @@ if __name__ == "__main__":
|
371 | 511 | .success()
|
372 | 512 | .stdout("Hello from Python Launcher\r\n");
|
373 | 513 |
|
| 514 | + let launcher = Launcher::try_from_path(console_bin_path.path()) |
| 515 | + .expect("We should succeed at reading the launcher") |
| 516 | + .expect("The launcher should be valid"); |
| 517 | + |
| 518 | + assert!(launcher.kind == LauncherKind::Python); |
| 519 | + assert!(launcher.python_path == python_executable_path); |
| 520 | + |
374 | 521 | Ok(())
|
375 | 522 | }
|
376 | 523 |
|
|
0 commit comments