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