diff --git a/.github/workflows/build-runtime.yml b/.github/workflows/build-runtime.yml index 40234aa..6f6650d 100644 --- a/.github/workflows/build-runtime.yml +++ b/.github/workflows/build-runtime.yml @@ -132,6 +132,16 @@ jobs: git -C $work submodule update --init --depth 1 vendor/qemu if ($LASTEXITCODE) { git -C $work submodule update --init vendor/qemu } if ($LASTEXITCODE) { throw 'vendor/qemu submodule failed' } + $utilRepo = Join-Path $env:RUNNER_TEMP 'reims-util' + $utilPin = Get-Content -Raw -LiteralPath (Join-Path $work 'crates/reims-ctl/src/reims_util.rs') + if ($utilPin -notmatch 'pub const REV: &str = "([0-9a-f]{40})"') { throw 'reims-util REV not found' } + $utilRev = $Matches[1] + git init -q $utilRepo + if ($LASTEXITCODE) { throw 'reims-util init failed' } + git -C $utilRepo fetch -q --depth 1 https://github.com/steelbrain/reims-util.git $utilRev + if ($LASTEXITCODE) { throw 'reims-util fetch failed' } + git -C $utilRepo checkout -q --detach FETCH_HEAD + if ($LASTEXITCODE) { throw 'reims-util checkout failed' } $short = (git -C $work rev-parse --short=7 HEAD).Trim() $releaseId = "$short${{ needs.resolve.outputs.suffix }}" "short=$short" >> $env:GITHUB_OUTPUT @@ -141,7 +151,7 @@ jobs: # conflict without touching the patch (AGENTS.md rule 4). $resultFile = Join-Path $env:RUNNER_TEMP 'patches.json' try { - pwsh -NoProfile -File scripts/apply-patch-series.ps1 -ReimsRepo $work -ResultFile $resultFile + pwsh -NoProfile -File scripts/apply-patch-series.ps1 -ReimsRepo $work -UtilRepo $utilRepo -ResultFile $resultFile $ok = $LASTEXITCODE -eq 0 } finally { if (Test-Path $resultFile) { @@ -154,6 +164,7 @@ jobs: } if (-not $ok) { throw 'patch queue does not apply' } "UPSTREAM_DIR=$work" >> $env:GITHUB_ENV + "REIMS_UTIL_DIR=$utilRepo" >> $env:GITHUB_ENV "SHORT_COMMIT=$short" >> $env:GITHUB_ENV "RELEASE_ID=$releaseId" >> $env:GITHUB_ENV "CARGO_HOME=$(Join-Path $env:RUNNER_TEMP 'cargo')" >> $env:GITHUB_ENV @@ -169,6 +180,13 @@ jobs: cd "$(cygpath -u "$UPSTREAM_DIR")" # Upstream's own non-interactive CLANG64 build script. bash scripts/install-ctl.sh --yes + util_repo="$(cygpath -u "$REIMS_UTIL_DIR")" + if [[ -n "$(git -C "$util_repo" status --porcelain)" ]]; then + toolchain="$(sed -n 's/^channel *= *"\([^"]*\)".*/\1/p' rust-toolchain.toml)" + export PATH="$(cygpath -u "$CARGO_HOME")/bin:$PATH" + CC=clang CXX=clang++ AR=llvm-ar cargo +"$toolchain-x86_64-pc-windows-gnullvm" install \ + --locked --force --root "$CARGO_HOME" --path "$REIMS_UTIL_DIR" + fi - name: Package alpha runtime and source archives shell: pwsh @@ -181,6 +199,7 @@ jobs: $applied = @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ }) & ./scripts/pack-runtime.ps1 ` -ReimsRepo $env:UPSTREAM_DIR ` + -UtilRepo $env:REIMS_UTIL_DIR ` -CargoHome $env:CARGO_HOME ` -QemuDir (Join-Path $env:XDG_DATA_HOME 'reims-ctl\qemu\current') ` -Msys2 '${{ steps.msys2.outputs.msys2-location }}' ` diff --git a/patches/LICENSE b/patches/LICENSE index 42d8969..8803aeb 100644 --- a/patches/LICENSE +++ b/patches/LICENSE @@ -7,5 +7,5 @@ strict license compatibility with each target codebase: - `qemu-*.patch` (targeting `vendor/qemu` / QEMU) are licensed under **GPL-2.0-or-later**. -- `reims-*.patch` (targeting `steelbrain/reims-vgpu` / `reims-ctl`) are +- `reims-*.patch` (targeting `steelbrain/reims-vgpu` or `steelbrain/reims-util`) are dual-licensed under **GPL-2.0-or-later OR LGPL-3.0-or-later**. diff --git a/patches/README.md b/patches/README.md index 67677b0..695e20d 100644 --- a/patches/README.md +++ b/patches/README.md @@ -4,11 +4,13 @@ ## 维护原则 -1. **不长期维护 fork**:所有底层修复优先向上游仓库([`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) / [`steelbrain/qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu))提交 PR,目标是补丁队列清零。 +1. **不长期维护 fork**:所有底层修复优先向相应上游仓库提交 PR。目标仓库包括 [`reims-vgpu`](https://github.com/steelbrain/reims-vgpu)、[`qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu) 和 [`reims-util`](https://github.com/steelbrain/reims-util)。 2. **人工提 PR,冲突即停**:更新上游基线时由 [`scripts/apply-patch-series.ps1`](../scripts/apply-patch-series.ps1) 按顺序执行 `git apply --check`。已合入上游(反向检查通过)的补丁会自动跳过并开 Issue 提醒退役;遇到冲突时立刻中止构建,不自动改写补丁。 3. **文件格式约束**:所有 `.patch` 文件必须为 **无 BOM、LF 行尾**(由 `.gitattributes` 中的 `*.patch -text` 约束),避免 `git apply` 在 Windows 上失败。 4. **来源透明与协议兼容**:每个运行时包的 `manifest.json` 与 `patches/` 目录必须如实记录实际应用的全部补丁及哈希;本目录补丁不适用根目录的 Apache-2.0,而是遵循目标上游兼容协议(详见 [`patches/LICENSE`](LICENSE))。 +本地构建时,`-UtilRepo` 指向 `reims-ctl` 固定版本的 `reims-util` 工作树。用相同的 MSYS2 CLANG64 工具链安装其中的 `reims-util` 后,把同一工作树传给打包脚本。 + --- ## 当前补丁清单 @@ -23,6 +25,7 @@ | [`reims-ctl-win32-random-bytes.patch`](reims-ctl-win32-random-bytes.patch) | `reims-vgpu` (`crates/reims-ctl/src/vm.rs`) | 修复 Windows 下打不开 `/dev/urandom` 时回退到低熵时间戳种子的缺陷,改用标准库 `RandomState`(底层调用 `ProcessPrng`)生成 MAC/ROM 随机字节 | `git apply --check` 通过;待编入 `alpha` 验证后提 PR | | [`reims-ctl-virtio-discard-iothread.patch`](reims-ctl-virtio-discard-iothread.patch) | `reims-vgpu` (`crates/reims-ctl/src/qemu.rs`) | 为 VirtIO 系统盘补齐 `discard=unmap`(与 NVMe 一致透传客体 TRIM)并启用独立 `-object iothread,id=io0`,避免块完成回调与 QEMU 主循环争抢 | `git apply --check` 在 `3731afd9` 与上游 `main` 均通过;真机实测与休眠唤醒通过,暂留 `patches/` 待编入 `alpha` 验证后提 PR | | [`reims-ctl-qcow2-l2-cache.patch`](reims-ctl-qcow2-l2-cache.patch) | `reims-vgpu` (`crates/reims-ctl/src/qemu.rs`) | 按 `qcow2` 文件头虚拟容量与簇大小计算全覆盖所需 `l2-cache-size`(上限 32 MiB,仅大于 8 MiB 默认值时追加),避免非 Linux 宿主默认 8 MiB 上限仅覆盖 64 GiB | `git apply --check` 在 `3731afd9` 与上游 `main` 均通过;128 GiB 镜像真机实测通过,暂留 `patches/` 待编入 `alpha` 验证后提 PR | +| [`reims-util-parallel-offline-download.patch`](reims-util-parallel-offline-download.patch) | `reims-util` (`src/http.rs`, `src/installer.rs`) | 对有 Apple 分块校验数据的完整离线包并发请求四段,按顺序校验并写入镜像。分段读取失败时用原有单路下载继续 | 待编入 `alpha` 冒烟验证 | | [`qemu-whpx-win10-compat.patch`](qemu-whpx-win10-compat.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 修复 Windows 10 19045 上两处 WHPX 必现崩溃(探测 TSC deadline 污染主分区、`WHvResetPartition` 未判空) | 已在 Win10 19045 真机验证并随稳定运行时发布;待提 PR | | [`qemu-whpx-win10-startup-ipis.patch`](qemu-whpx-win10-startup-ipis.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 在 Win10 开启 `kernel-irqchip` 且多核启动时经 `WHvRequestInterrupt` 转发 INIT/SIPI,避免 XNU 从核卡死(依赖上一项) | 8/12 核冷启动通过;客体软重启待验证,待提 PR | | [`qemu-whpx-nested-virt-nonfatal.patch`](qemu-whpx-nested-virt-nonfatal.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 部分 Win11 宿主设置嵌套虚拟化属性返回 `0x80370302` 时改为警告并清零特性位,保留 `kernel-irqchip=on` 加速(依赖前两项) | 待编入 `alpha` 并在 Win11 真机验证后提 PR | diff --git a/patches/reims-util-parallel-offline-download.patch b/patches/reims-util-parallel-offline-download.patch new file mode 100644 index 0000000..4af222b --- /dev/null +++ b/patches/reims-util-parallel-offline-download.patch @@ -0,0 +1,524 @@ +diff --git a/src/http.rs b/src/http.rs +index 69aeb817b8dc1ff2cebb91bbcad5d4ad749b1540..777a7d8adf65faaff0f08e228a4165ed48984e42 100644 +--- a/src/http.rs ++++ b/src/http.rs +@@ -13,13 +13,15 @@ + use crate::progress::{self, Reporter}; + use anyhow::{Context, Result, bail}; + use std::fs::{File, OpenOptions}; +-use std::io::{Read, Seek, SeekFrom, Write}; ++use std::io::{Cursor, Read, Seek, SeekFrom, Write}; + use std::path::{Path, PathBuf}; ++use std::thread; + use std::time::Duration; + use ureq::Agent; + + /// The most each request asks for. + pub const SEGMENT: u64 = 64 << 20; ++const PARALLEL_REQUESTS: usize = 4; + /// How long a request may take to send its range: a stall is noticed within this. (On a + /// connection too slow to send a whole range in it, each request sends what it can.) + pub const SEGMENT_BUDGET: Duration = Duration::from_secs(180); +@@ -124,6 +126,8 @@ pub struct Download<'a> { + /// For requests the server refuses (401, 403): new headers, such as a fresh asset token. + pub refresh: Option<&'a mut dyn FnMut() -> Result>, + pub user_agent: Option<&'static str>, ++ /// Fetch the public installer package in parallel within each checked segment. ++ pub parallel: bool, + /// Failed requests in a row, with no byte received between them, before it gives up: + /// [`MAX_FAILURES`], or fewer when there is another place to download the file from. + pub tries: u32, +@@ -138,6 +142,7 @@ impl Download<'_> { + size: None, + refresh: None, + user_agent: None, ++ parallel: false, + tries: MAX_FAILURES, + } + } +@@ -229,6 +234,8 @@ pub fn download( + let mut failures = 0u32; + let mut bad_chunks = 0u32; + let mut buf = vec![0u8; 1 << 18]; ++ let mut parallel = ++ d.parallel && check.verifies() && d.headers.is_empty() && d.user_agent.is_none(); + r.progress(have, total); + + 'requests: loop { +@@ -240,94 +247,116 @@ pub fn download( + Some(t) => (have + SEGMENT).min(t) - 1, + None => have + SEGMENT - 1, + }; +- let mut req = agent +- .get(&d.url) +- .header("Range", format!("bytes={have}-{end}")); +- for (k, v) in &d.headers { +- req = req.header(k, v); +- } +- let mut cfg = req.config().timeout_recv_body(Some(SEGMENT_BUDGET)); +- if let Some(ua) = d.user_agent { +- cfg = cfg.user_agent(ua); +- } +- let resp = match cfg.build().call() { +- Ok(resp) => resp, +- Err(e) => { +- failures += 1; +- retry_or_fail(&mut failures, d.tries, &format!("{e}"), &d.url, r)?; +- continue; ++ // Keep one segment in memory and commit it through the same ordered ++ // writer and chunk checker used by serial downloads. ++ let batch = if parallel ++ && let Some(size) = total ++ && end - have >= (PARALLEL_REQUESTS - 1) as u64 ++ { ++ match read_parallel_segment(agent, &d.url, have, end, size, r) { ++ Ok(bytes) => Some(bytes), ++ Err(_) => { ++ progress::check(r)?; ++ parallel = false; ++ r.note("Parallel ranges could not be read. Continuing with one connection."); ++ None ++ } + } ++ } else { ++ None + }; +- let status = resp.status().as_u16(); +- match status { +- 206 => { +- let range = resp +- .headers() +- .get("content-range") +- .and_then(|v| v.to_str().ok()) +- .and_then(content_range) +- .with_context(|| format!("{} sent a range without Content-Range", d.url))?; +- if range.0 != have { +- bail!( +- "{} sent bytes from {} when asked for {have}", +- d.url, +- range.0 +- ); ++ let mut body: Box = if let Some(bytes) = batch { ++ Box::new(Cursor::new(bytes)) ++ } else { ++ let mut req = agent ++ .get(&d.url) ++ .header("Range", format!("bytes={have}-{end}")); ++ for (k, v) in &d.headers { ++ req = req.header(k, v); ++ } ++ let mut cfg = req.config().timeout_recv_body(Some(SEGMENT_BUDGET)); ++ if let Some(ua) = d.user_agent { ++ cfg = cfg.user_agent(ua); ++ } ++ let resp = match cfg.build().call() { ++ Ok(resp) => resp, ++ Err(e) => { ++ failures += 1; ++ retry_or_fail(&mut failures, d.tries, &format!("{e}"), &d.url, r)?; ++ continue; ++ } ++ }; ++ let status = resp.status().as_u16(); ++ match status { ++ 206 => { ++ let range = resp ++ .headers() ++ .get("content-range") ++ .and_then(|v| v.to_str().ok()) ++ .and_then(content_range) ++ .with_context(|| format!("{} sent a range without Content-Range", d.url))?; ++ if range.0 != have { ++ bail!( ++ "{} sent bytes from {} when asked for {have}", ++ d.url, ++ range.0 ++ ); ++ } ++ match (total, range.1) { ++ (Some(t), Some(rt)) if t != rt => bail!( ++ "{} is {} long, not the expected {}: it changed on the server", ++ d.url, ++ rt, ++ t ++ ), ++ (None, Some(rt)) => { ++ total = Some(rt); ++ r.progress(have, total); ++ } ++ _ => {} ++ } + } +- match (total, range.1) { +- (Some(t), Some(rt)) if t != rt => bail!( +- "{} is {} long, not the expected {}: it changed on the server", +- d.url, +- rt, +- t +- ), +- (None, Some(rt)) => { +- total = Some(rt); +- r.progress(have, total); ++ 200 => { ++ // The whole file: the server ignored the range. ++ if have > 0 { ++ cut(file, 0)?; ++ have = 0; ++ check.restart_at(0); ++ } ++ if total.is_none() { ++ total = resp.body().content_length(); + } +- _ => {} + } +- } +- 200 => { +- // The whole file: the server ignored the range. +- if have > 0 { ++ 416 if total.is_some_and(|t| have >= t) => break, ++ 416 => { ++ // Past the end: the file on the server is shorter than what we have. ++ if have == 0 { ++ bail!("{} refused every range", d.url); ++ } ++ r.note("The file changed on the server: starting over"); + cut(file, 0)?; + have = 0; + check.restart_at(0); ++ continue; + } +- if total.is_none() { +- total = resp.body().content_length(); +- } +- } +- 416 if total.is_some_and(|t| have >= t) => break, +- 416 => { +- // Past the end: the file on the server is shorter than what we have. +- if have == 0 { +- bail!("{} refused every range", d.url); ++ 401 | 403 if d.refresh.is_some() && failures < 3 => { ++ failures += 1; ++ if let Some(f) = d.refresh.as_mut() { ++ d.headers = f()?; ++ } ++ continue; + } +- r.note("The file changed on the server: starting over"); +- cut(file, 0)?; +- have = 0; +- check.restart_at(0); +- continue; +- } +- 401 | 403 if d.refresh.is_some() && failures < 3 => { +- failures += 1; +- if let Some(f) = d.refresh.as_mut() { +- d.headers = f()?; ++ 408 | 429 | 500..=599 => { ++ failures += 1; ++ retry_or_fail(&mut failures, d.tries, &format!("HTTP {status}"), &d.url, r)?; ++ continue; + } +- continue; +- } +- 408 | 429 | 500..=599 => { +- failures += 1; +- retry_or_fail(&mut failures, d.tries, &format!("HTTP {status}"), &d.url, r)?; +- continue; ++ _ => bail!("{} answered HTTP {status}", d.url), + } +- _ => bail!("{} answered HTTP {status}", d.url), +- } ++ Box::new(resp.into_body().into_reader()) ++ }; + + file.seek(SeekFrom::Start(base + have))?; +- let mut body = resp.into_body().into_reader(); + let start = have; + loop { + if r.cancelled() { +@@ -389,6 +418,79 @@ pub fn download( + Ok(()) + } + ++fn read_parallel_segment( ++ agent: &Agent, ++ url: &str, ++ start: u64, ++ end: u64, ++ total: u64, ++ r: &dyn Reporter, ++) -> Result> { ++ let mut segment = vec![0; (end - start + 1) as usize]; ++ let request_size = segment.len().div_ceil(PARALLEL_REQUESTS); ++ thread::scope(|scope| -> Result<()> { ++ let mut requests = Vec::with_capacity(PARALLEL_REQUESTS); ++ for (index, chunk) in segment.chunks_mut(request_size).enumerate() { ++ let first = start + (index * request_size) as u64; ++ let request = thread::Builder::new().spawn_scoped(scope, move || { ++ read_exact_range(agent, url, first, total, chunk, r) ++ })?; ++ requests.push(request); ++ } ++ for request in requests { ++ request ++ .join() ++ .map_err(|_| anyhow::anyhow!("range worker failed"))??; ++ } ++ Ok(()) ++ })?; ++ Ok(segment) ++} ++ ++fn read_exact_range( ++ agent: &Agent, ++ url: &str, ++ start: u64, ++ total: u64, ++ mut remaining: &mut [u8], ++ r: &dyn Reporter, ++) -> Result<()> { ++ let end = start + remaining.len() as u64 - 1; ++ progress::check(r)?; ++ let response = agent ++ .get(url) ++ .header("Range", format!("bytes={start}-{end}")) ++ .header("Accept-Encoding", "identity") ++ .config() ++ .timeout_recv_body(Some(SEGMENT_BUDGET)) ++ .build() ++ .call()?; ++ let expected = format!("bytes {start}-{end}/{total}"); ++ if response.status().as_u16() != 206 ++ || response ++ .headers() ++ .get("Content-Range") ++ .and_then(|value| value.to_str().ok()) ++ != Some(expected.as_str()) ++ { ++ bail!("server did not return the requested byte range"); ++ } ++ let mut body = response.into_body().into_reader(); ++ while !remaining.is_empty() { ++ progress::check(r)?; ++ let n = body.read(remaining)?; ++ if n == 0 { ++ bail!("range body ended before its declared length"); ++ } ++ remaining = &mut remaining[n..]; ++ } ++ progress::check(r)?; ++ if body.read(&mut [0u8; 1])? != 0 { ++ bail!("range body exceeded its declared length"); ++ } ++ Ok(()) ++} ++ + fn retry_or_fail( + failures: &mut u32, + tries: u32, +@@ -455,6 +557,173 @@ pub fn hex(b: &[u8]) -> String { + #[cfg(test)] + mod tests { + use super::*; ++ use std::io::{BufRead, BufReader}; ++ use std::net::{TcpListener, TcpStream}; ++ ++ struct Silent; ++ ++ impl Reporter for Silent { ++ fn event(&self, _: progress::Event) {} ++ } ++ ++ fn read_request(stream: &TcpStream) -> Result { ++ stream.set_read_timeout(Some(Duration::from_secs(5)))?; ++ let mut reader = BufReader::new(stream); ++ let mut range = String::new(); ++ loop { ++ let mut line = String::new(); ++ if reader.read_line(&mut line)? == 0 || line == "\r\n" { ++ break; ++ } ++ if let Some((name, value)) = line.split_once(':') ++ && name.eq_ignore_ascii_case("range") ++ { ++ range = value.trim().to_string(); ++ } ++ } ++ Ok(range) ++ } ++ ++ #[test] ++ fn sends_four_ranges_before_waiting_for_their_bodies() -> Result<()> { ++ let listener = TcpListener::bind("127.0.0.1:0")?; ++ listener.set_nonblocking(true)?; ++ let url = format!("http://{}", listener.local_addr()?); ++ let server = thread::spawn(move || -> Result<()> { ++ let deadline = std::time::Instant::now() + Duration::from_secs(5); ++ let mut requests = std::collections::BTreeMap::new(); ++ while requests.len() < 4 { ++ match listener.accept() { ++ Ok((stream, _)) => { ++ let range = read_request(&stream)?; ++ requests.insert(range, stream); ++ } ++ Err(e) ++ if e.kind() == std::io::ErrorKind::WouldBlock ++ && std::time::Instant::now() < deadline => ++ { ++ thread::sleep(Duration::from_millis(5)); ++ } ++ Err(e) => { ++ return Err(e).context("waiting for four simultaneous range requests"); ++ } ++ } ++ } ++ // No worker gets a response until all four requests have arrived. ++ let data = b"abcdefghijklmnop"; ++ for offset in (0..data.len()).step_by(4).rev() { ++ let mut stream = requests ++ .remove(&format!("bytes={offset}-{}", offset + 3)) ++ .context("missing requested range")?; ++ write!( ++ stream, ++ "HTTP/1.1 206 Partial Content\r\nContent-Length: 4\r\nContent-Range: bytes {offset}-{}/16\r\nConnection: close\r\n\r\n", ++ offset + 3 ++ )?; ++ stream.write_all(&data[offset..offset + 4])?; ++ } ++ Ok(()) ++ }); ++ let data = read_parallel_segment(&test_agent(), &url, 0, 15, 16, &Silent); ++ server ++ .join() ++ .map_err(|_| anyhow::anyhow!("test server failed"))??; ++ assert_eq!(data?, b"abcdefghijklmnop"); ++ Ok(()) ++ } ++ ++ #[test] ++ fn rejects_ignored_misaligned_and_truncated_ranges() -> Result<()> { ++ let listener = TcpListener::bind("127.0.0.1:0")?; ++ let url = format!("http://{}", listener.local_addr()?); ++ let server = thread::spawn(move || -> Result<()> { ++ for reply in [ ++ "HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\nabcd", ++ "HTTP/1.1 206 Partial Content\r\nContent-Length: 4\r\nContent-Range: bytes 5-8/16\r\nConnection: close\r\n\r\nabcd", ++ "HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 4-7/16\r\nConnection: close\r\n\r\nabc", ++ ] { ++ let (mut stream, _) = listener.accept()?; ++ read_request(&stream)?; ++ stream.write_all(reply.as_bytes())?; ++ } ++ Ok(()) ++ }); ++ let agent = test_agent(); ++ for _ in 0..3 { ++ assert!(read_exact_range(&agent, &url, 4, 16, &mut [0; 4], &Silent).is_err()); ++ } ++ server ++ .join() ++ .map_err(|_| anyhow::anyhow!("test server failed"))??; ++ Ok(()) ++ } ++ ++ #[test] ++ fn falls_back_to_a_single_request_from_the_verified_prefix() -> Result<()> { ++ use crate::chunklist::{ChunkCheck, Chunklist, Signature}; ++ use sha2::{Digest, Sha256}; ++ ++ let data = b"abcdefghijklmnop"; ++ let listener = TcpListener::bind("127.0.0.1:0")?; ++ let url = format!("http://{}", listener.local_addr()?); ++ let server = thread::spawn(move || -> Result<()> { ++ for _ in 0..PARALLEL_REQUESTS { ++ let (mut stream, _) = listener.accept()?; ++ read_request(&stream)?; ++ stream.write_all( ++ b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", ++ )?; ++ } ++ let (mut stream, _) = listener.accept()?; ++ assert_eq!(read_request(&stream)?, "bytes=4-15"); ++ stream.write_all( ++ b"HTTP/1.1 206 Partial Content\r\nContent-Length: 12\r\nContent-Range: bytes 4-15/16\r\nConnection: close\r\n\r\n", ++ )?; ++ stream.write_all(&data[4..])?; ++ Ok(()) ++ }); ++ let dir = std::env::temp_dir().join(format!("reims-util-fallback-{}", std::process::id())); ++ std::fs::create_dir_all(&dir)?; ++ let path = dir.join("download"); ++ std::fs::write(part_path(&path), &data[..4])?; ++ let chunks = data ++ .chunks_exact(4) ++ .map(|chunk| (4, Sha256::digest(chunk).into())) ++ .collect(); ++ let mut check = ChunkCheck::new(Chunklist { ++ chunks, ++ signature: Signature::Digest, ++ }); ++ let mut request = Download::new(&url, "Test download".into()); ++ request.size = Some(data.len() as u64); ++ request.parallel = true; ++ let result = download( ++ &test_agent(), ++ request, ++ Dest::File(&path), ++ &mut check, ++ &Silent, ++ ); ++ let actual = std::fs::read(&path); ++ let _ = std::fs::remove_file(&path); ++ let _ = std::fs::remove_file(part_path(&path)); ++ let _ = std::fs::remove_dir(&dir); ++ result?; ++ server ++ .join() ++ .map_err(|_| anyhow::anyhow!("test server failed"))??; ++ assert_eq!(actual?, data); ++ Ok(()) ++ } ++ ++ fn test_agent() -> Agent { ++ Agent::config_builder() ++ .proxy(None) ++ .http_status_as_error(false) ++ .timeout_global(Some(Duration::from_secs(5))) ++ .build() ++ .into() ++ } + + #[test] + fn parses_content_range() { +diff --git a/src/installer.rs b/src/installer.rs +index 7c17423300c153fd24fe9e031de3a835dcda57e1..265031a5d2ff54e0b8c9b752bad579c5927c5ef1 100644 +--- a/src/installer.rs ++++ b/src/installer.rs +@@ -475,6 +475,7 @@ pub fn offline_installer(inst: &Installer, dir: &Path, r: &dyn Reporter) -> Resu + progress::check(r)?; + let mut d = Download::new(&inst.url, format!("Downloading {}", inst.label())); + d.size = Some(inst.size); ++ d.parallel = true; + let pkg = Dest::Region { + file: &mut f, + offset: pkg_at, +@@ -746,6 +747,7 @@ mod tests { + /// macOS 12's and 26's do, through `Applications`), and where it fails after placing + /// the app (as Big Sur's does, needing zsh), the app gets the package as SharedSupport.dmg + /// and the script starts its startosinstall on the volume. ++ #[cfg(unix)] + #[test] + fn install_script_runs_without_dirname_or_zsh() { + use std::os::unix::fs::{PermissionsExt, symlink}; +diff --git a/src/recovery.rs b/src/recovery.rs +index fe4eadc745ac4867802254a53197821acac3d411..11406e790884549b7e4e6b297f29c3a0285c606f 100644 +--- a/src/recovery.rs ++++ b/src/recovery.rs +@@ -311,6 +311,7 @@ impl Image { + size: Some(self.size()), + refresh: Some(&mut refresh), + user_agent: Some(USER_AGENT), ++ parallel: false, + tries: http::MAX_FAILURES, + }; + http::download(&self.agent, d, dest, check, r) diff --git a/patches/series.txt b/patches/series.txt index fcc4326..1de7565 100644 --- a/patches/series.txt +++ b/patches/series.txt @@ -1,6 +1,6 @@ # Patch queue, in the order the patches are applied (see patches/README.md). # One patch per line: . -# target is "reims-vgpu" (the upstream repository root) or "vendor/qemu". +# Targets are "reims-vgpu", "vendor/qemu", and "reims-util". # CI (build-runtime.yml via scripts/apply-patch-series.ps1) and # scripts/pack-runtime.ps1 both read this file; add or retire patches here. reims-vgpu reims-vgpu-cargo-lock.patch @@ -9,6 +9,7 @@ reims-vgpu reims-vgpu-display-fixed-mode.patch reims-vgpu reims-ctl-win32-random-bytes.patch reims-vgpu reims-ctl-virtio-discard-iothread.patch reims-vgpu reims-ctl-qcow2-l2-cache.patch +reims-util reims-util-parallel-offline-download.patch vendor/qemu qemu-whpx-win10-compat.patch vendor/qemu qemu-whpx-win10-startup-ipis.patch vendor/qemu qemu-whpx-nested-virt-nonfatal.patch diff --git a/scripts/apply-patch-series.ps1 b/scripts/apply-patch-series.ps1 index dd76ddd..e04aeaa 100644 --- a/scripts/apply-patch-series.ps1 +++ b/scripts/apply-patch-series.ps1 @@ -1,6 +1,6 @@ <# .SYNOPSIS - Apply the patch queue in patches/series.txt to an upstream reims-vgpu checkout. + Apply the patch queue in patches/series.txt to the checked-out upstream sources. .DESCRIPTION For each patch, in series order: @@ -16,18 +16,24 @@ was really applied, AGENTS.md rule 5) and report merged or conflicting patches. .EXAMPLE - pwsh -File scripts/apply-patch-series.ps1 -ReimsRepo $env:RUNNER_TEMP\reims-vgpu -ResultFile patches.json + pwsh -File scripts/apply-patch-series.ps1 -ReimsRepo $env:RUNNER_TEMP\reims-vgpu -UtilRepo $env:RUNNER_TEMP\reims-util -ResultFile patches.json #> [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$ReimsRepo, - [string]$ResultFile = '' + [string]$ResultFile = '', + [string]$UtilRepo = '' ) $ErrorActionPreference = 'Stop' $repoRoot = Split-Path -Parent $PSScriptRoot $patchesDir = Join-Path $repoRoot 'patches' +$repositories = @{ + 'reims-vgpu' = $ReimsRepo + 'vendor/qemu' = Join-Path $ReimsRepo 'vendor\qemu' + 'reims-util' = $UtilRepo +} function Read-PatchSeries { $series = Join-Path $patchesDir 'series.txt' @@ -35,7 +41,7 @@ function Read-PatchSeries { $t = $line.Trim() if (-not $t -or $t.StartsWith('#')) { continue } $parts = $t -split '\s+' - if ($parts.Count -ne 2 -or $parts[0] -notin @('reims-vgpu', 'vendor/qemu')) { + if ($parts.Count -ne 2 -or -not $repositories.ContainsKey($parts[0])) { throw "Bad line in patches/series.txt: '$line'" } [pscustomobject]@{ Target = $parts[0]; Name = $parts[1] } @@ -49,17 +55,22 @@ function Save-Result { } } -foreach ($p in Read-PatchSeries) { +$series = @(Read-PatchSeries) +if (-not $UtilRepo -and $series.Target -contains 'reims-util') { + throw 'Pass -UtilRepo with a checkout at the reims-util revision pinned by reims-ctl.' +} + +foreach ($p in $series) { $file = Join-Path $patchesDir $p.Name if (-not (Test-Path -LiteralPath $file)) { throw "Patch listed in series.txt is missing: $file" } - $dir = if ($p.Target -eq 'vendor/qemu') { Join-Path $ReimsRepo 'vendor\qemu' } else { $ReimsRepo } + $dir = $repositories[$p.Target] # git -C into a missing or uninitialised submodule falls back to the outer # repository, where "git apply" silently skips paths outside the current # directory and reports success. Require $dir to be its own work tree. $top = (& git -C $dir rev-parse --show-toplevel 2>$null) if ($LASTEXITCODE -ne 0 -or -not $top -or [IO.Path]::GetFullPath($top.Trim()).TrimEnd([char[]]'\/') -ne [IO.Path]::GetFullPath($dir).TrimEnd([char[]]'\/')) { - throw "$dir is not a checked-out git work tree (is the vendor/qemu submodule initialised?)" + throw "$dir is not a checked-out git work tree for $($p.Target)" } & git -C $dir apply --check $file 2>$null diff --git a/scripts/pack-runtime.ps1 b/scripts/pack-runtime.ps1 index 29d7fa4..40928b9 100644 --- a/scripts/pack-runtime.ps1 +++ b/scripts/pack-runtime.ps1 @@ -34,6 +34,7 @@ [CmdletBinding(PositionalBinding = $false)] param( [string]$ReimsRepo = 'D:\DevTools\reims-vgpu', + [string]$UtilRepo = '', [string]$CargoHome = 'D:\DevTools\cargo', [string]$QemuDir = 'D:\Data\macos-vm-lab\reims\data\reims-ctl\qemu\current', [string]$Msys2 = 'D:\DevTools\msys64', @@ -126,6 +127,17 @@ $qemuCommit = (git -C $qemuRepo rev-parse HEAD).Trim() $utilSrc = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'crates\reims-ctl\src\reims_util.rs') if ($utilSrc -notmatch 'pub const REV: &str = "([0-9a-f]{40})"') { throw 'reims-util REV not found in reims_util.rs' } $utilCommit = $Matches[1] +$checkouts = Join-Path $CargoHome 'git\checkouts' +$utilTree = if ($UtilRepo) { + (Resolve-Path -LiteralPath $UtilRepo).Path +} else { + Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'reims-util-*' | + ForEach-Object { Join-Path $_.FullName $utilCommit.Substring(0, 7) } | + Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 +} +if (-not $utilTree) { throw "reims-util source at $utilCommit not found" } +$actualUtil = git -C $utilTree rev-parse HEAD +if ($LASTEXITCODE -ne 0 -or $actualUtil -ne $utilCommit) { throw "reims-util checkout must be at $utilCommit" } # metal2vulkan's git rev as built (Cargo.lock in the build tree). $lock = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.lock') @@ -136,11 +148,16 @@ $qemuVersionLine = (& $qemuExe --version | Select-Object -First 1).Trim() $utilVersionLine = (& $utilExe --version | Select-Object -First 1).Trim() # ── 2. Patches must equal the build tree's diffs ───────────── +$repositories = @{ + 'reims-vgpu' = $ReimsRepo + 'vendor/qemu' = $qemuRepo + 'reims-util' = $utilTree +} $series = @(foreach ($line in Get-Content -LiteralPath (Join-Path $patchesDir 'series.txt')) { $t = $line.Trim() if (-not $t -or $t.StartsWith('#')) { continue } $parts = $t -split '\s+' - if ($parts.Count -ne 2 -or $parts[0] -notin @('reims-vgpu', 'vendor/qemu')) { throw "Bad line in patches/series.txt: '$line'" } + if ($parts.Count -ne 2 -or -not $repositories.ContainsKey($parts[0])) { throw "Bad line in patches/series.txt: '$line'" } [pscustomobject]@{ Target = $parts[0]; Name = $parts[1] } }) # PowerShell -File passes "a,b" as one string: accept both forms. @@ -161,7 +178,7 @@ foreach ($e in $series) { $patchSpecs += @{ Name = $e.Name Target = $e.Target - Repo = $(if ($e.Target -eq 'vendor/qemu') { $qemuRepo } else { $ReimsRepo }) + Repo = $repositories[$e.Target] Paths = $paths } } @@ -254,8 +271,10 @@ function Get-Undeclared([string]$repo, [string]$target, [string[]]$statusArgs) { } $otherCtl = Get-Undeclared $ReimsRepo 'reims-vgpu' @('--ignore-submodules=all') $otherQemu = Get-Undeclared $qemuRepo 'vendor/qemu' @('--untracked-files=no') -if ($otherCtl.Count -or $otherQemu.Count) { - throw "Undeclared changes in the build trees:`n$($otherCtl + $otherQemu -join "`n")" +$utilStatusArgs = if ($UtilRepo) { '--untracked-files=all' } else { '--untracked-files=no' } +$otherUtil = Get-Undeclared $utilTree 'reims-util' @($utilStatusArgs) +if ($otherCtl.Count -or $otherQemu.Count -or $otherUtil.Count) { + throw "Undeclared changes in the build trees:`n$($otherCtl + $otherQemu + $otherUtil -join "`n")" } $bundleName = "reims-runtime-win-x64-$id" @@ -369,10 +388,7 @@ Get-ChildItem -LiteralPath (Join-Path $qemuRepo 'subprojects') -Directory | Where-Object { $_.Name -ne 'packagecache' -and -not (Test-Path -LiteralPath (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\$($_.Name)")) } | ForEach-Object { Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\") -Recurse -Force } -$checkouts = Join-Path $CargoHome 'git\checkouts' -$utilTree = Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'reims-util-*' | ForEach-Object { Join-Path $_.FullName $utilCommit.Substring(0, 7) } | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 $m2vTree = Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'metal2vulkan-*' | ForEach-Object { Join-Path $_.FullName $m2vCommit.Substring(0, 7) } | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 -if (-not $utilTree) { throw "reims-util source at $utilCommit not found under $checkouts" } if (-not $m2vTree) { throw "metal2vulkan source at $m2vCommit not found under $checkouts" } Export-GitTree $utilTree $utilCommit (Join-Path $srcDir "reims-util-$($utilCommit.Substring(0, 7))") Export-GitTree $m2vTree $m2vCommit (Join-Path $srcDir "metal2vulkan-$($m2vCommit.Substring(0, 7))") @@ -395,6 +411,22 @@ New-Item -ItemType Directory -Force -Path "$srcDir\patches" | Out-Null Copy-Item -Path "$bundleDir\patches\*" -Destination "$srcDir\patches\" Copy-Item -LiteralPath "$bundleDir\MSYS2-PACKAGES.txt" -Destination "$srcDir\MSYS2-PACKAGES.txt" Copy-Item -LiteralPath "$bundleDir\NOTICE.md" -Destination "$srcDir\NOTICE.md" +$utilBuildSteps = if ($byTarget.Contains('reims-util')) { + $utilDir = "reims-util-$($utilCommit.Substring(0, 7))" + $utilApply = ($byTarget['reims-util'] | ForEach-Object { " git -C $utilDir apply `"`$(pwd)/patches/$($_.Name)`"" }) -join "`n" +@" + +After the upstream build, run these commands from the extracted source +archive's root in the same MSYS2 CLANG64 shell. They apply the reims-util +patches and replace the stock reims-util executable with this build: + +$utilApply + cd reims-vgpu-$commit + toolchain=`$(sed -n 's/^channel *= *"\([^"]*\)".*/\1/p' rust-toolchain.toml) + CC=clang CXX=clang++ AR=llvm-ar cargo +"`$toolchain-x86_64-pc-windows-gnullvm" install --locked --force --path ../$utilDir + +"@ +} Write-Utf8 "$srcDir\README.md" @" # Source for $bundleName @@ -418,6 +450,7 @@ $((($patchSpecs | Where-Object { $_.Target -eq 'vendor/qemu' } | ForEach-Object (``patch -p1`` works too.) Then build as upstream documents (``scripts/install-ctl.sh`` in an MSYS2 CLANG64 shell). The DLLs in ``qemu/bin`` come from the MSYS2 packages listed in ``MSYS2-PACKAGES.txt``, with links to their sources. +$utilBuildSteps "@ # ── 5. Manifest (schema 2) ───────────────────────────────────