diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index a14c8e681..3e1dd79a7 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1369,6 +1369,39 @@ lookup of `get` / `scan` do not judge the ruby-platform record on that copy eith other installed copy to match, that record is `package_not_installed` in `apply` and in `apply --check` alike, and `vex` omits it as not installed. +**A platform record that brings its binaries.** A record for a precompiled copy's own platform +that replaces or adds a shared library (`.so`, `.bundle`, `.dylib`, `.dll`) is the diff of the +platform gem itself: the sources the gem packs and the binaries built from them, one per Ruby the +gem supports. It has no build inputs on that copy. `apply` writes its files and starts no build, +and leaves no build marker and no backup, so the copy holds the files of the patched platform gem, +which is what hosted mode installs. `apply --check`, `vex` and `rollback` judge the copy by the +record's files alone. A record for the copy's platform that changes a build input and brings no +library is built like the ruby-platform record: no binary in it was built from that input. So is +one that brings a library kept per Ruby (`lib/a/3.4/a.so`) and leaves out the same library of +another Ruby the copy ships it for: that Ruby would go on loading the unpatched code. Such a +record is handled as 5.2.0 handled every platform record, with the failure described next when the +build lands on a binary the record brings, and that copy is not repaired. + +5.2.0 built the source gem for such a record too, and put that build over the record's binary for +the Ruby that ran `apply`. That file then held neither content of the record, so `apply`, +`apply --check`, `vex` and `rollback` failed on the copy (`hash_mismatch`). `apply` and +`rollback` now put the binary that build replaced back first, from the backup that run took, and +drop its marker and backup. They do so only when the record can then be applied, or rolled back: + +- `apply`: with the replaced binaries left out, the rest of the record passes a dry run under the + run's own mismatch policy (so files an earlier Socket patch wrote count as they do in any + apply), and every blob the record writes is stored and holds the content the record names. +- `rollback`: every other file of the record holds its original or its patched content. +- Neither puts anything back when the backup holds content the record does not know or a file + that is not the record's, or lists files the patch added to the copy. + +Any other copy is left as it is, with the build that runs the patched source in place, and fails +as before. A dry run of either command puts nothing back and reports what the run does: +`apply --dry-run` counts the copy as one that can be patched, not as already patched. A put-back +that fails partway is `native_extension_restore_failed`, and names `gem pristine`. +After `apply` writes such a record whole, a marker or backup an earlier graft left on the copy is +dropped when every file it names is one the record wrote. + **Without a build from the source gem.** Whatever keeps a gem RubyGems built from being rebuilt from its source gem, before anything of the installed copy is written, leaves it the rebuild it had in 5.1.0: in place, from its own tree. That is: no archive (offline and not cached, a private diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index 59e68a242..608d5e1d7 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -4098,23 +4098,31 @@ pub(crate) async fn rollback_patches_inner( None => { use socket_patch_core::patch::gem_ext; let is_gem = Ecosystem::from_purl(purl) == Some(Ecosystem::Gem); - // A build input `apply` added to a gem copy that did not - // hold it (a precompiled gem never shipped it; a build - // removed it) is removed, not restored. - let gem_files = if is_gem { - Some(gem_ext::rollback_files(pkg_path, purl, &patch.files).await) + // A gem's files go back through `rollback_gem_patch`, + // which first puts back a build an earlier release made + // over a binary the record itself brings, and removes a + // build input `apply` added rather than restoring it. + let mut result = if is_gem { + gem_ext::rollback_gem_patch( + common.read_scope(), + purl, + pkg_path, + &patch.files, + &blobs_path, + common.dry_run, + ) + .await } else { - None + rollback_package_patch( + common.read_scope(), + purl, + pkg_path, + &patch.files, + &blobs_path, + common.dry_run, + ) + .await }; - let mut result = rollback_package_patch( - common.read_scope(), - purl, - pkg_path, - gem_files.as_ref().unwrap_or(&patch.files), - &blobs_path, - common.dry_run, - ) - .await; // A gem whose native extension `apply` rebuilt gets its // original compiled extension back with its sources // (#1996). diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 0026ae438..1da7d1e6c 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -1180,10 +1180,33 @@ impl InstalledGem { Some((self.copy.as_ref()?, self.facts.jvm_platform()?)) } - /// The record's native scope on this copy. No inputs: the record is - /// plain Ruby for it. - fn scope(&self, files: &HashMap) -> NativeScope { - classify(&self.facts, files) + /// The native scope of the record `key` (a manifest purl) with `files` + /// on this copy. No inputs: nothing of the record is built here. It is + /// plain Ruby for the copy, or it brings the copy's compiled code + /// itself ([`brings_own_build`]). + fn scope(&self, key: &str, files: &HashMap) -> NativeScope { + let mut scope = classify(&self.facts, files); + if self.brings_own_build(key, files) { + scope.inputs.clear(); + } + scope + } + + /// Whether the record `key` with `files` brings this copy its compiled + /// code ([`brings_own_build`]): the copy is a precompiled platform gem + /// and the record is its own platform's, binaries included, one for + /// every Ruby the copy ships one for ([`covers_every_ruby`]). + fn brings_own_build(&self, key: &str, files: &HashMap) -> bool { + let precompiled = self + .facts + .platform + .as_deref() + .filter(|_| !self.facts.extensions.declared); + precompiled.is_some_and(|platform| brings_own_build(platform, key, files)) + && self + .copy + .as_ref() + .is_some_and(|copy| covers_every_ruby(©.gem_dir, files)) } /// The record `key` (a manifest purl) with `files`, as this copy takes @@ -1429,25 +1452,49 @@ fn minor_layout(target: &str) -> Option<(&str, &str, &str)> { /// The binaries a precompiled gem ships for other Rubies beside `target`: /// the same file name in the sibling dirs named for a Ruby `major.minor` /// (`lib/nokogiri/3.4/nokogiri.bundle` → `lib/nokogiri/3.3/nokogiri.bundle`, -/// …). None for a binary that is not kept per Ruby minor. +/// …). None for a binary that is not kept per Ruby minor, and none when +/// the gem's dirs cannot be read ([`prebuilt_siblings_checked`] tells +/// that apart). fn prebuilt_siblings(gem_dir: &Path, target: &str) -> Vec { + prebuilt_siblings_checked(gem_dir, target).unwrap_or_default() +} + +/// [`prebuilt_siblings`], with an `Err` when what the gem ships for other +/// Rubies cannot be told: its base dir, an entry of it, or a sibling dir +/// cannot be read or stat'ed. A base dir that is not there ships nothing. +fn prebuilt_siblings_checked(gem_dir: &Path, target: &str) -> std::io::Result> { let Some((base, minor, leaf)) = minor_layout(target) else { - return Vec::new(); + return Ok(Vec::new()); }; - let Ok(entries) = std::fs::read_dir(gem_dir.join(base)) else { - return Vec::new(); + let entries = match std::fs::read_dir(gem_dir.join(base)) { + Ok(entries) => entries, + Err(e) if crate::patch::apply::is_missing_path(&e) => return Ok(Vec::new()), + Err(e) => return Err(e), }; - let mut out: Vec = entries - .flatten() - .filter_map(|entry| { - let name = entry.file_name().to_str()?.to_string(); - let other = name != minor && ruby_minor(&name).as_deref() == Some(name.as_str()); - (other && is_real_dir(&entry.path()) && is_real_file(&entry.path().join(leaf))) - .then(|| [base, name.as_str(), leaf].join("/")) - }) - .collect(); + // Whether `path` is an entry of the kind `is`; an entry that is not + // there is not one, and one that cannot be stat'ed is an error. + let entry_is = + |path: &Path, is: fn(&std::fs::Metadata) -> bool| match std::fs::symlink_metadata(path) { + Ok(meta) => Ok(is(&meta)), + Err(e) if crate::patch::apply::is_missing_path(&e) => Ok(false), + Err(e) => Err(e), + }; + let mut out = Vec::new(); + for entry in entries { + let entry = entry?; + let Some(name) = entry.file_name().to_str().map(str::to_string) else { + continue; + }; + let other = name != minor && ruby_minor(&name).as_deref() == Some(name.as_str()); + if other + && entry_is(&entry.path(), std::fs::Metadata::is_dir)? + && entry_is(&entry.path().join(leaf), std::fs::Metadata::is_file)? + { + out.push([base, name.as_str(), leaf].join("/")); + } + } out.sort(); - out + Ok(out) } /// Whether `marker` was built from exactly the record's patched native @@ -1563,7 +1610,7 @@ impl InstalledGem { Err(NOT_REBUILT_REASON.to_string()) }; } - let scope = self.scope(files); + let scope = self.scope(key, files); if scope.inputs.is_empty() { return Ok(()); } @@ -5364,6 +5411,58 @@ fn names_platform(key: &str, platform: &str) -> bool { .is_some_and(|named| plain(named) == plain(platform)) } +/// Whether the record `key` (a manifest purl) with `files` brings a +/// precompiled copy of `platform` its compiled code: it is the record +/// written for that platform ([`names_platform`]), and it replaces or adds +/// a shared library ([`is_library_name`]). +/// +/// Such a record is the diff of the platform gem itself: the sources it +/// packs and the binaries built from them, one per Ruby minor the gem +/// supports. Applied whole it leaves the files of the patched platform +/// gem, which is what hosted mode installs. So nothing of it is a build +/// input here: a build of the source gem would replace the record's +/// binary for the Ruby that runs `apply` with a local one, and every +/// later check of that file would find neither content +/// (`apply --check`, `vex`, `rollback`). +/// +/// A record for the copy's platform that changes a build input and brings +/// no library is not one: no binary in it was built from that input, so +/// the extension is rebuilt as it is for the ruby-platform record. +fn brings_own_build(platform: &str, key: &str, files: &HashMap) -> bool { + names_platform(key, platform) + && files.iter().any(|(file, info)| { + !info.is_permissions_only() && is_library_name(leaf_of(normalize_file_path(file)), None) + }) +} + +/// Whether the record `files` brings the gem at `gem_dir` a binary for +/// every Ruby it ships one for: each library of the record that is kept +/// per Ruby minor (`lib/a/3.4/a.so`) has every sibling the gem ships +/// ([`prebuilt_siblings`]) in the record too. +/// +/// A record that leaves a Ruby's binary out is not applied as the copy's +/// own build ([`brings_own_build`]): that Ruby would go on loading the +/// unpatched code under a copy reported as patched. Its sources stay +/// build inputs, and the extension is built for the Ruby that runs +/// `apply`, as for any other record. So is one where what the gem ships +/// for other Rubies cannot be read ([`prebuilt_siblings_checked`]): an +/// unreadable dir is not a gem that ships no other Ruby. +fn covers_every_ruby(gem_dir: &Path, files: &HashMap) -> bool { + let brought: std::collections::HashSet<&str> = files + .iter() + .filter(|(_, info)| !info.is_permissions_only()) + .map(|(file, _)| normalize_file_path(file)) + .filter(|rel| is_library_name(leaf_of(rel), None)) + .collect(); + brought.iter().all(|library| { + prebuilt_siblings_checked(gem_dir, library).is_ok_and(|siblings| { + siblings + .iter() + .all(|sibling| brought.contains(sibling.as_str())) + }) + }) +} + /// The files of the record `key` (a manifest purl) that can tell whether the /// gem copy at `pkg_path` is the distribution the record was written for. /// A release variant is matched to an installed copy by a file it replaces @@ -5400,7 +5499,7 @@ pub async fn discriminating_files<'f>( if gem.jvm().is_some() { return taken; } - let scope = gem.scope(&taken); + let scope = gem.scope(key, &taken); let Some(copy) = gem.copy.filter(|_| !scope.inputs.is_empty()) else { return taken; }; @@ -5942,8 +6041,24 @@ pub async fn apply_gem_package_patch( }; return jvm.apply(files).await; } - let scope = gem.scope(files); + let scope = gem.scope(package_key, files); + let own_build = gem.brings_own_build(package_key, files); let copy = gem.copy; + // The record brings the copy's binaries: it is applied whole, after a + // build an earlier release made over one of them is put back. (Boxed: + // its own `plain_apply` calls stay out of this function's poll frame.) + if let (true, false, Some(copy)) = (own_build, unreadable_mode, ©) { + let own = OwnBuildApply { + read_scope, + package_key, + pkg_path, + sources, + dry_run, + policy, + copy, + }; + return Box::pin(own.apply(files)).await; + } if unreadable_mode || scope.inputs.is_empty() { return plain_apply( read_scope, @@ -6708,6 +6823,456 @@ async fn rebuild_unpatched_from_source_gem( Ok(moved_in) } +/// The apply of a record that brings a precompiled copy its compiled code +/// ([`brings_own_build`]): the record's files are written as they are. +struct OwnBuildApply<'a> { + read_scope: crate::utils::repo_root::ReadScope, + package_key: &'a str, + pkg_path: &'a Path, + sources: &'a PatchSources<'a>, + dry_run: bool, + policy: MismatchPolicy, + copy: &'a GemCopy, +} + +impl OwnBuildApply<'_> { + async fn plain(&self, files: &HashMap, dry_run: bool) -> GemApplied { + plain_apply( + self.read_scope, + self.package_key, + self.pkg_path, + files, + self.sources, + dry_run, + self.policy, + ) + .await + } + + /// Whether the patched content of every file of `files` can be had, + /// whole: its blob is stored and holds the content the record names. A + /// record that cannot be written whole is not worth undoing a build + /// for, and a blob that is cut short or damaged would fail the write + /// after the build is gone. + async fn every_blob_is_whole(&self, files: &HashMap) -> bool { + for entry in files.values() { + let hash = entry.after_hash.as_str(); + if hash.is_empty() { + continue; + } + if !crate::patch::apply::is_valid_blob_hash(hash) { + return false; + } + let whole = match self.sources.mem_blobs.and_then(|m| m.get(hash)) { + Some(bytes) => compute_git_sha256_from_bytes(bytes).eq_ignore_ascii_case(hash), + None => crate::patch::apply::read_blob_entry(&self.sources.blobs_path.join(hash)) + .await + .is_ok_and(|bytes| { + compute_git_sha256_from_bytes(&bytes).eq_ignore_ascii_case(hash) + }), + }; + if !whole { + return false; + } + } + true + } + + /// Apply `files` to the copy. + /// + /// 5.2.0 took such a record's C sources for build inputs: it wrote + /// the record's files, then built the source gem and put that build's + /// library over the record's own, for the Ruby that ran `apply`. That + /// file holds neither content of the record since, so every later + /// command failed on the copy. Here the binary that build replaced is + /// put back first ([`replaced_binaries`], [`restore_backup`]), but only + /// when the record then applies: with those binaries left out, the + /// rest of the record passes a dry run under this run's own mismatch + /// policy, and every blob it writes is stored whole. Any other copy is left + /// as it is and fails as it did, with the build that runs the patched + /// source still in place. + /// + /// A dry run puts nothing back. It reports what the run would do: the + /// rest of the record as it stands, and each binary the run restores + /// first as a file to patch. + async fn apply(self, files: &HashMap) -> GemApplied { + let copy = self.copy; + // A build an earlier run started for this copy and did not finish + // left its stage, and may have parked the previous build. + if !self.dry_run { + if let Err(e) = recover_interrupted_rebuild(copy).await { + return refusal( + self.package_key, + self.pkg_path, + UNSUPPORTED_CODE, + format!("{}; nothing was written", recovery_refusal(copy, &e)), + ); + } + } + // A backup that cannot be read is no reason to refuse: the record + // is applied to the copy as it is. + let replaced = replaced_binaries(copy, files).await.unwrap_or_default(); + if !replaced.is_empty() && self.every_blob_is_whole(files).await { + let mut rest = files.clone(); + rest.retain(|key, _| !replaced.contains(key)); + let would = self.plain(&rest, true).await; + if would.result.success { + if self.dry_run { + let mut would = would; + // The run writes each of these once what the build + // replaced is back. That is content the record knows, + // so each is reported as verify reports a file ready + // to patch, not as one whose content matched nothing + // and was overwritten. + would + .result + .files_verified + .extend(replaced.iter().map(|file| { + crate::patch::apply::VerifyResult { + file: file.clone(), + status: crate::patch::apply::VerifyStatus::Ready, + message: Some( + "a build of an earlier socket-patch is replaced by the \ + patch's own binary" + .to_string(), + ), + current_hash: None, + expected_hash: None, + target_hash: Some(files[file].after_hash.clone()), + permissions_only: false, + } + })); + return would; + } + let c = copy.clone(); + let restored = crate::utils::fs::run_blocking(move || { + restore_backup(&c, read_marker_sync(&c.gem_dir).as_ref()) + }) + .await; + if let Err(e) = restored { + return refusal( + self.package_key, + self.pkg_path, + RESTORE_FAILED_CODE, + format!( + "an earlier socket-patch built over a binary this patch brings \ + ({}), and what that build replaced could not be put back ({e}); \ + part of it may be back, and nothing of the patch was written. \ + Run `gem pristine {}` to reinstall the gem as it shipped, then \ + apply again", + replaced.join(", "), + gem_name_of(©.full_name) + ), + ); + } + } + } + let applied = self.plain(files, self.dry_run).await; + if applied.result.success && !self.dry_run { + let (c, files) = (copy.clone(), files.clone()); + crate::utils::fs::run_blocking(move || drop_graft_leftovers(&c, &files)).await; + } + applied + } +} + +/// Whether the file at `path` holds content the record entry knows, its +/// original or its patched content. `None` when there is no file. +fn holds_known_content(path: &Path, entry: &PatchFileInfo) -> std::io::Result> { + let bytes = match read_regular_to_bytes_sync(path) { + Ok(bytes) => bytes, + Err(e) if crate::patch::apply::is_missing_path(&e) => return Ok(None), + Err(e) => return Err(e), + }; + let hash = compute_git_sha256_from_bytes(&bytes); + Ok(Some( + hash.eq_ignore_ascii_case(&entry.before_hash) + || hash.eq_ignore_ascii_case(&entry.after_hash), + )) +} + +/// The files of the record `files` (its keys, sorted) that a graft's +/// backup in `copy` would put right: each holds neither content of the +/// record, and the backup restores it to content the record knows. That +/// is a binary a build of the source gem replaced after the record's own +/// was written ([`OwnBuildApply::apply`]). +/// +/// Empty when the copy has no backup, when the backup is not a graft's, +/// when it holds a file that is not the record's or content the record +/// does not know (putting it back writes every file it holds), and when +/// it lists files the patch added to the copy (`absent_files`): `rollback` +/// reads that list from the backup, which putting the build back removes. +async fn replaced_binaries( + copy: &GemCopy, + files: &HashMap, +) -> std::io::Result> { + let (copy, files) = (copy.clone(), files.clone()); + crate::utils::fs::run_blocking(move || { + let backup = copy.gem_dir.join(BACKUP_DIR); + refuse_link(&backup, "a backup this tool made")?; + if try_entry_type(&backup.join(BACKUP_INFO))?.is_none() { + return Ok(Vec::new()); + } + let info: BackupInfo = + serde_json::from_slice(&read_regular_to_bytes_sync(&backup.join(BACKUP_INFO))?) + .map_err(std::io::Error::other)?; + if !info.grafted || !info.absent_files.is_empty() { + return Ok(Vec::new()); + } + // Putting the backup back writes every file it lists + // ([`restore_backup`]): each must be a file of the record, and + // hold content the record knows. + let mut replaced = Vec::new(); + for lib in &info.lib_files { + let listed = files.iter().find(|(file, entry)| { + !entry.is_permissions_only() && normalize_file_path(file) == lib + }); + let Some((file, entry)) = listed.filter(|_| is_safe_relative_subpath(lib)) else { + return Ok(Vec::new()); + }; + if holds_known_content(&backup.join("lib").join(lib), entry)? != Some(true) { + return Ok(Vec::new()); + } + if holds_known_content(©.gem_dir.join(lib), entry)? == Some(false) { + replaced.push(file.clone()); + } + } + replaced.sort(); + Ok(replaced) + }) + .await +} + +/// After the record `files` was applied whole to `copy`: drop what an +/// earlier graft left there and the record now makes stale, so the copy +/// carries no marker and no backup, as a copy the record was first applied +/// to carries none. A later `rollback` would otherwise restore that backup +/// over the record's own files, or refuse a marker with no backup. +/// +/// Only a graft's leftovers go, and only when every file they name is one +/// the record wrote: a backup with any other file, or one that lists files +/// the patch added (`absent_files`), is kept. +fn drop_graft_leftovers(copy: &GemCopy, files: &HashMap) { + let written = |rel: &String| { + files + .iter() + .any(|(key, entry)| !entry.is_permissions_only() && normalize_file_path(key) == rel) + }; + let backup = copy.gem_dir.join(BACKUP_DIR); + let info = refuse_link(&backup, "a backup this tool made") + .ok() + .and_then(|()| read_regular_to_bytes_sync(&backup.join(BACKUP_INFO)).ok()) + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()); + let stale_backup = info.as_ref().is_some_and(|info| { + info.grafted && info.absent_files.is_empty() && info.lib_files.iter().all(written) + }); + let no_backup = matches!(std::fs::symlink_metadata(&backup), Err(e) if crate::patch::apply::is_missing_path(&e)); + if !stale_backup && !no_backup { + return; + } + let stale_marker = read_marker_sync(©.gem_dir) + .is_some_and(|marker| marker.grafted && marker.lib_artifacts.keys().all(written)); + if stale_backup { + // No marker file at all. One that is there and cannot be read + // keeps its backup: `rollback` needs the pair. + let unmarked = matches!(try_entry_type(©.gem_dir.join(MARKER_FILE)), Ok(None)); + if stale_marker || unmarked { + let _ = remove_dir_if_exists(&backup); + } + } + if stale_marker { + let _ = std::fs::remove_file(copy.gem_dir.join(MARKER_FILE)); + } +} + +/// What `rollback` asks before it reads the gem copy at `pkg_path` for the +/// record `key` (a manifest purl): the files of the record that hold a +/// build an earlier release made over the record's own binary, and that +/// the backup of that run puts back ([`replaced_binaries`]). Empty for a +/// record that does not bring the copy its compiled code +/// ([`brings_own_build`]), unless every other file of the record +/// holds its original or its patched content, and unless every before +/// blob under `blobs_path` the rollback then reads is stored and holds the +/// content the record names: `rollback` restores no other copy, and +/// putting the build back drops its backup, so a rollback that would fail +/// after it leaves its build alone. +pub async fn replaced_build_files( + pkg_path: &Path, + key: &str, + files: &HashMap, + blobs_path: &Path, +) -> Vec { + let gem = InstalledGem::at(pkg_path).await; + if !gem.brings_own_build(key, files) { + return Vec::new(); + } + let Some(copy) = gem.copy else { + return Vec::new(); + }; + let replaced = replaced_binaries(©, files).await.unwrap_or_default(); + if replaced.is_empty() { + return replaced; + } + let (gem_dir, rest) = (copy.gem_dir.clone(), files.clone()); + let skip = replaced.clone(); + // The before blob of each file the rollback restores once the build + // is back: `None` when a file other than the replaced ones holds + // content the record does not know. + let to_read = crate::utils::fs::run_blocking(move || { + let mut to_read = Vec::new(); + for (key, entry) in &rest { + if entry.is_permissions_only() || entry.before_hash.is_empty() { + // A file the record adds is deleted, or may be gone already. + if !skip.contains(key) && !entry.is_permissions_only() { + let rel = normalize_file_path(key); + match holds_known_content(&gem_dir.join(rel), entry) { + Ok(Some(true) | None) => {} + _ => return None, + } + } + continue; + } + let rel = normalize_file_path(key); + // A replaced binary holds what the backup puts back. + let path = if skip.contains(key) { + gem_dir.join(BACKUP_DIR).join("lib").join(rel) + } else { + gem_dir.join(rel) + }; + let bytes = match read_regular_to_bytes_sync(&path) { + Ok(bytes) => bytes, + Err(_) => return None, + }; + let hash = compute_git_sha256_from_bytes(&bytes); + if hash.eq_ignore_ascii_case(&entry.before_hash) { + continue; + } + if !hash.eq_ignore_ascii_case(&entry.after_hash) { + return None; + } + to_read.push(entry.before_hash.clone()); + } + Some(to_read) + }) + .await; + let Some(to_read) = to_read else { + return Vec::new(); + }; + for hash in &to_read { + let whole = crate::patch::apply::is_valid_blob_hash(hash) + && crate::patch::apply::read_blob_entry(&blobs_path.join(hash)) + .await + .is_ok_and(|bytes| { + compute_git_sha256_from_bytes(&bytes).eq_ignore_ascii_case(hash) + }); + if !whole { + return Vec::new(); + } + } + replaced +} + +/// Put back the binaries [`replaced_build_files`] names for the gem copy +/// at `pkg_path`, from the backup of the run that replaced them, and drop +/// that run's marker and backup ([`restore_backup`]). `Ok(false)` when +/// there is nothing to put back. What `rollback` runs first: with those +/// binaries back, every file of the record holds content the record +/// knows, and the files can be restored from the blobs under `blobs_path`. +pub async fn put_back_replaced_build( + pkg_path: &Path, + key: &str, + files: &HashMap, + blobs_path: &Path, +) -> Result { + if replaced_build_files(pkg_path, key, files, blobs_path) + .await + .is_empty() + { + return Ok(false); + } + let Some(copy) = GemCopy::of(pkg_path) else { + return Ok(false); + }; + let gem_name = gem_name_of(©.full_name).to_string(); + crate::utils::fs::run_blocking(move || { + restore_backup(©, read_marker_sync(©.gem_dir).as_ref()) + }) + .await + .map(|()| true) + .map_err(|e| { + format!( + "an earlier socket-patch built over a binary this patch brings, and what that \ + build replaced could not be put back ({e}); run `gem pristine {gem_name}` to \ + reinstall the gem as it shipped" + ) + }) +} + +/// Roll the record `key` (a manifest purl) with `files` back in the gem +/// copy at `pkg_path`, from the before blobs under `blobs_path`: the +/// restore of the files `rollback` runs for a gem, before it restores a +/// build `apply` made ([`restore_original_build`]). +/// +/// First, a build an earlier release made over a binary the record itself +/// brings is put back ([`put_back_replaced_build`]): with it there, that +/// file holds neither content and nothing could be restored. A dry run +/// puts nothing back. It reads the copy without those files, and reports +/// each as a file the run restores: the run writes it from that build's +/// backup, whatever the rest of the copy holds. A copy this does not put +/// right is read as it is, and fails with what to run. +/// +/// A build input `apply` added to a gem copy that did not hold it is +/// removed, not restored ([`rollback_files`]). +pub async fn rollback_gem_patch( + scope: crate::utils::repo_root::ReadScope, + key: &str, + pkg_path: &Path, + files: &HashMap, + blobs_path: &Path, + dry_run: bool, +) -> crate::patch::rollback::RollbackResult { + let mut put_back_failed = None; + let mut restored_first = Vec::new(); + if dry_run { + restored_first = replaced_build_files(pkg_path, key, files, blobs_path).await; + } else { + put_back_failed = put_back_replaced_build(pkg_path, key, files, blobs_path) + .await + .err(); + } + let mut gem_files = rollback_files(pkg_path, key, files).await; + gem_files.retain(|file, _| !restored_first.contains(file)); + let mut result = crate::patch::rollback::rollback_package_patch( + scope, key, pkg_path, &gem_files, blobs_path, dry_run, + ) + .await; + // A put-back that failed partway is the cause, whatever the files then + // showed. + if let Some(why) = put_back_failed { + result.success = false; + result.error = Some(format!("{RESTORE_FAILED_CODE}: {why}")); + } + if dry_run && result.success { + use crate::patch::rollback::{VerifyRollbackResult, VerifyRollbackStatus}; + result + .files_verified + .extend(restored_first.iter().map(|file| { + VerifyRollbackResult { + file: file.clone(), + status: VerifyRollbackStatus::Ready, + message: Some( + "a build of an earlier socket-patch is replaced by the binary it replaced" + .to_string(), + ), + current_hash: None, + expected_hash: None, + target_hash: Some(files[file].before_hash.clone()), + } + })); + } + result +} + /// Put the backed-up original build back over socket-patch's build, then /// drop the marker and the backup. For a gem RubyGems built, the extension /// dir the backup names must be this gem's under the home @@ -8406,7 +8971,7 @@ mod tests { let purl = "pkg:gem/a@1?platform=ruby"; assert_eq!(*gem.record_files(purl, &record).await, record); assert_eq!(rollback_files(&gem_dir, purl, &record).await, record); - let scope = gem.scope(&record); + let scope = gem.scope(purl, &record); assert!(scope.builds_extensions); assert_eq!(scope.inputs, ["ext/a/a.c"]); // No marker: the extension was not built from the patched source. @@ -8944,7 +9509,7 @@ mod tests { .into(); let gem = InstalledGem::at(©.gem_dir).await; assert!(gem.copy.is_some()); - let scope = gem.scope(&record); + let scope = gem.scope("pkg:gem/a@1", &record); assert_eq!(scope.inputs, ["ext/a/a.c", "patches/0001.patch"]); assert_eq!(scope.precompiled.as_deref(), Some("arm64-darwin")); assert_eq!( @@ -9700,7 +10265,9 @@ mod tests { }, )] .into(); - let scope = InstalledGem::at(©.gem_dir).await.scope(&record); + let scope = InstalledGem::at(©.gem_dir) + .await + .scope("pkg:gem/a@1", &record); assert_eq!(built_state(©, &scope, &record), Built::No); // Ruby 3.4 runs `apply`: attested from here on. @@ -9773,6 +10340,816 @@ mod tests { } } + /// The record of the platform gem `a-1-arm64-darwin` itself: its C + /// source and the binary of each Ruby minor, with the blobs of the + /// patched and the original content under `blobs`. `(record, patched)`: `patched` is + /// the content each file holds after the patch. + fn own_build_record( + blobs: &Path, + ) -> (HashMap, Vec<(&'static str, Vec)>) { + std::fs::create_dir_all(blobs).unwrap(); + let patched: Vec<(&'static str, &[u8], Vec)> = vec![ + ("ext/a/a.c", b"int a;", b"int a = 1;".to_vec()), + ("lib/a/3.3/a.bundle", PREBUILT, b"the patch's 3.3".to_vec()), + ("lib/a/3.4/a.bundle", PREBUILT, b"the patch's 3.4".to_vec()), + ]; + let mut record = HashMap::new(); + for (file, before, after) in &patched { + let entry = PatchFileInfo { + before_hash: compute_git_sha256_from_bytes(before), + after_hash: compute_git_sha256_from_bytes(after), + mode: None, + }; + std::fs::write(blobs.join(&entry.after_hash), after).unwrap(); + // What `rollback` restores. + std::fs::write(blobs.join(&entry.before_hash), before).unwrap(); + record.insert(file.to_string(), entry); + } + let patched = patched.into_iter().map(|(file, _, after)| (file, after)); + (record, patched.collect()) + } + + const OWN_PURL: &str = "pkg:gem/a@1?platform=arm64-darwin"; + + /// `apply` of `record` under `purl` on `copy`, with a rebuild allowed + /// and no network: a run that started a build would need the source + /// gem and a Ruby, and has neither. + async fn apply_offline( + copy: &GemCopy, + purl: &str, + record: &HashMap, + blobs: &Path, + ) -> GemApplied { + apply_offline_with(copy, purl, record, blobs, false, MismatchPolicy::Strict).await + } + + async fn apply_offline_with( + copy: &GemCopy, + purl: &str, + record: &HashMap, + blobs: &Path, + dry_run: bool, + policy: MismatchPolicy, + ) -> GemApplied { + apply_gem_package_patch( + crate::utils::repo_root::ReadScope::Workspace, + purl, + ©.gem_dir, + record, + &PatchSources::blobs_only(blobs), + dry_run, + policy, + &RubyEnv { + cwd: copy.home.clone(), + rebuild: true, + offline: true, + progress: None, + }, + ) + .await + } + + /// Which record brings a precompiled copy its compiled code: the one + /// written for the copy's platform, when it replaces or adds a shared + /// library. + #[test] + fn a_record_brings_its_build_when_it_is_the_platforms_and_holds_a_library() { + let entry = info(&"c".repeat(64)); + let record = |keys: &[&str]| -> HashMap { + keys.iter() + .map(|key| (key.to_string(), entry.clone())) + .collect() + }; + let with_library = record(&["ext/a/a.c", "lib/a/3.4/a.so"]); + let linux = "pkg:gem/a@1?platform=x86_64-linux-gnu"; + assert!(brings_own_build("x86_64-linux-gnu", linux, &with_library)); + // RubyGems spells the glibc platform with and without `-gnu`. + assert!(brings_own_build("x86_64-linux", linux, &with_library)); + for library in [ + "lib/a.bundle", + "lib/a/a.dll", + "lib/liba.dylib", + "lib/liba.so.1", + ] { + assert!( + brings_own_build("x86_64-linux", linux, &record(&[library])), + "{library}" + ); + } + // A source alone: no binary of the record was built from it. + assert!(!brings_own_build( + "x86_64-linux", + linux, + &record(&["ext/a/a.c"]) + )); + assert!(!brings_own_build( + "x86_64-linux", + linux, + &record(&["lib/a.rb"]) + )); + // Another platform's record, and the ruby gem's. + assert!(!brings_own_build("arm64-darwin", linux, &with_library)); + for ruby in ["pkg:gem/a@1", "pkg:gem/a@1?platform=ruby"] { + assert!( + !brings_own_build("x86_64-linux", ruby, &with_library), + "{ruby}" + ); + } + // An entry that fixes a library's permissions alone brings no code. + let mode_only: HashMap = [ + ("ext/a/a.c".to_string(), entry.clone()), + ( + "lib/a/3.4/a.so".to_string(), + PatchFileInfo { + before_hash: "d".repeat(64), + after_hash: "d".repeat(64), + mode: crate::manifest::schema::FileMode::parse("0755"), + }, + ), + ] + .into(); + assert!(mode_only["lib/a/3.4/a.so"].is_permissions_only()); + assert!(!brings_own_build("x86_64-linux", linux, &mode_only)); + } + + /// The record of a precompiled copy's own platform, binaries included, + /// is applied whole: no build is started (this run could not start + /// one), nothing is backed up or marked, and the copy passes the + /// native check on its files alone. The same files under the ruby + /// gem's record are build inputs, as before. + #[tokio::test] + async fn a_platform_record_with_its_binaries_is_applied_without_a_build() { + let tmp = tempfile::tempdir().unwrap(); + let copy = precompiled_gem(&tmp.path().join("gems-home")); + let blobs = tmp.path().join("blobs"); + let (record, patched) = own_build_record(&blobs); + let gem = InstalledGem::at(©.gem_dir).await; + assert!(gem.scope(OWN_PURL, &record).inputs.is_empty()); + for ruby in ["pkg:gem/a@1", "pkg:gem/a@1?platform=ruby"] { + assert_eq!(gem.scope(ruby, &record).inputs, ["ext/a/a.c"], "{ruby}"); + assert_eq!( + gem.verify_native_build(ruby, &record).await, + Err(NOT_REBUILT_REASON.to_string()) + ); + } + // A record for the platform with the source alone is still built. + let source_only: HashMap = + [("ext/a/a.c".to_string(), record["ext/a/a.c"].clone())].into(); + assert_eq!(gem.scope(OWN_PURL, &source_only).inputs, ["ext/a/a.c"]); + // So is one that leaves out the binary of a Ruby the gem ships one + // for: that Ruby would go on loading the unpatched code. + let mut one_ruby = record.clone(); + one_ruby.remove("lib/a/3.3/a.bundle").unwrap(); + assert_eq!(gem.scope(OWN_PURL, &one_ruby).inputs, ["ext/a/a.c"]); + + let applied = apply_offline(©, OWN_PURL, &record, &blobs).await; + assert!(applied.result.success, "{:?}", applied.result.error); + assert_eq!(applied.warning, None); + assert_eq!(applied.caveat, None); + for (file, after) in &patched { + assert_eq!( + &std::fs::read(copy.gem_dir.join(file)).unwrap(), + after, + "{file}" + ); + } + assert!(!copy.gem_dir.join(MARKER_FILE).exists()); + assert!(!copy.gem_dir.join(BACKUP_DIR).exists()); + assert_eq!( + verify_native_build(©.gem_dir, OWN_PURL, &record).await, + Ok(()) + ); + // Rollback undoes the record's files and has no build to restore. + assert_eq!( + rollback_files(©.gem_dir, OWN_PURL, &record).await, + record + ); + let env = RubyEnv { + cwd: copy.home.clone(), + rebuild: true, + offline: true, + progress: None, + }; + assert_eq!(restore_original_build(©.gem_dir, &env).await, Ok(false)); + } + + /// The copy 5.2.0 left behind for such a record, as it made it: the + /// prebuilt binary of the Ruby that ran `apply` backed up, the + /// record's files written, a build of the source gem grafted over + /// that Ruby's binary. + fn copy_with_a_build_over_the_records_binary( + tmp: &Path, + record: &HashMap, + patched: &[(&'static str, Vec)], + ) -> GemCopy { + let copy = precompiled_gem(&tmp.join("gems-home")); + let staged = staged_build(&tmp.join("stage34"), &["a/a.bundle"], b"built by 3.4"); + let grafts = plan_graft(©, &probe_for(©, "3.4.10"), &staged).unwrap(); + assert!(back_up_prebuilt(©, &grafts, &[]).unwrap()); + for (file, after) in patched { + std::fs::write(copy.gem_dir.join(file), after).unwrap(); + } + // The scope 5.2.0 gave the record: its C source is a build input. + let facts = SpecFacts::of( + &std::fs::read_to_string(©.spec_path).unwrap(), + ©.full_name, + ); + let scope = classify(&facts, record); + assert_eq!(scope.inputs, ["ext/a/a.c"]); + graft_binaries(©, &scope, record, &grafts).unwrap(); + assert_eq!( + std::fs::read(copy.gem_dir.join("lib/a/3.4/a.bundle")).unwrap(), + b"built by 3.4" + ); + assert!(copy.gem_dir.join(MARKER_FILE).exists()); + copy + } + + /// `apply` puts such a copy right: the build over the record's binary + /// goes, the binary it replaced comes back, and the record is applied + /// whole. Nothing of the earlier build is left. + #[tokio::test] + async fn a_build_over_the_records_own_binary_is_put_back_and_the_record_applied() { + let tmp = tempfile::tempdir().unwrap(); + let blobs = tmp.path().join("blobs"); + let (record, patched) = own_build_record(&blobs); + let copy = copy_with_a_build_over_the_records_binary(tmp.path(), &record, &patched); + + let applied = apply_offline(©, OWN_PURL, &record, &blobs).await; + assert!(applied.result.success, "{:?}", applied.result.error); + for (file, after) in &patched { + assert_eq!( + &std::fs::read(copy.gem_dir.join(file)).unwrap(), + after, + "{file}" + ); + } + assert!(!copy.gem_dir.join(MARKER_FILE).exists()); + assert!(!copy.gem_dir.join(BACKUP_DIR).exists()); + // A second run has nothing to put back and nothing to write. + assert!(replaced_binaries(©, &record).await.unwrap().is_empty()); + let again = apply_offline(©, OWN_PURL, &record, &blobs).await; + assert!(again.result.success, "{:?}", again.result.error); + assert!(again.result.files_patched.is_empty()); + } + + /// `rollback` asks for the same: with the replaced binary back, every + /// file of the record holds content the record knows. + #[tokio::test] + async fn rollback_puts_a_build_over_the_records_own_binary_back_first() { + let tmp = tempfile::tempdir().unwrap(); + let blobs = tmp.path().join("blobs"); + let (record, patched) = own_build_record(&blobs); + let copy = copy_with_a_build_over_the_records_binary(tmp.path(), &record, &patched); + assert_eq!( + put_back_replaced_build(©.gem_dir, OWN_PURL, &record, &blobs).await, + Ok(true) + ); + assert_eq!( + std::fs::read(copy.gem_dir.join("lib/a/3.4/a.bundle")).unwrap(), + PREBUILT + ); + assert!(!copy.gem_dir.join(MARKER_FILE).exists()); + assert!(!copy.gem_dir.join(BACKUP_DIR).exists()); + // The ruby gem's record is built here: its build is not undone. + let other = + copy_with_a_build_over_the_records_binary(&tmp.path().join("other"), &record, &patched); + assert_eq!( + put_back_replaced_build(&other.gem_dir, "pkg:gem/a@1", &record, &blobs).await, + Ok(false) + ); + assert!(other.gem_dir.join(MARKER_FILE).exists()); + } + + const GRAFTED: &str = "lib/a/3.4/a.bundle"; + + /// The grafted build, its marker and its backup are all still there. + fn assert_build_kept(copy: &GemCopy) { + assert_eq!( + std::fs::read(copy.gem_dir.join(GRAFTED)).unwrap(), + b"built by 3.4" + ); + assert!(copy.gem_dir.join(MARKER_FILE).exists()); + assert!(copy.gem_dir.join(BACKUP_DIR).join(BACKUP_INFO).exists()); + } + + /// A copy the backup does not put right keeps the build over the + /// record's binary, which runs the patched source: `apply` fails as it + /// did and changes nothing. That is a copy where another file of the + /// record holds neither content (a source edited by hand), where one + /// the record replaces is gone, where a blob the record writes is + /// missing or damaged, where the backup holds content the record does + /// not know (for the replaced binary or any other file it would write) + /// or a file that is not the record's, or where the backup lists files + /// the patch added to the copy. + #[tokio::test] + async fn a_build_is_kept_when_the_backup_would_not_make_the_record_apply() { + let tmp = tempfile::tempdir().unwrap(); + let blobs = tmp.path().join("blobs"); + let (record, patched) = own_build_record(&blobs); + let stuck = |name: &str| { + copy_with_a_build_over_the_records_binary(&tmp.path().join(name), &record, &patched) + }; + + let edited = stuck("edited"); + std::fs::write(edited.gem_dir.join("ext/a/a.c"), b"int a = 2; /* mine */").unwrap(); + assert!( + !apply_offline(&edited, OWN_PURL, &record, &blobs) + .await + .result + .success + ); + assert_build_kept(&edited); + assert!( + replaced_build_files(&edited.gem_dir, OWN_PURL, &record, &blobs) + .await + .is_empty() + ); + assert_eq!( + put_back_replaced_build(&edited.gem_dir, OWN_PURL, &record, &blobs).await, + Ok(false) + ); + assert_build_kept(&edited); + + let missing = stuck("missing"); + std::fs::remove_file(missing.gem_dir.join("ext/a/a.c")).unwrap(); + assert!( + !apply_offline(&missing, OWN_PURL, &record, &blobs) + .await + .result + .success + ); + assert_build_kept(&missing); + assert!( + replaced_build_files(&missing.gem_dir, OWN_PURL, &record, &blobs) + .await + .is_empty() + ); + + let no_blob = stuck("no-blob"); + let other_blobs = tmp.path().join("other-blobs"); + std::fs::create_dir_all(&other_blobs).unwrap(); + for (file, entry) in &record { + if file != GRAFTED { + std::fs::copy( + blobs.join(&entry.after_hash), + other_blobs.join(&entry.after_hash), + ) + .unwrap(); + } + } + assert!( + !apply_offline(&no_blob, OWN_PURL, &record, &other_blobs) + .await + .result + .success + ); + assert_build_kept(&no_blob); + + // The blob is there, cut short: the write would fail after the + // build was gone. + let cut_blob = stuck("cut-blob"); + std::fs::write( + other_blobs.join(&record[GRAFTED].after_hash), + b"the patch's", + ) + .unwrap(); + assert!( + !apply_offline(&cut_blob, OWN_PURL, &record, &other_blobs) + .await + .result + .success + ); + assert_build_kept(&cut_blob); + + // The backup also holds another binary of the record, with content + // the record does not know: putting the backup back would write it + // over a file that holds the patch's. + let second = stuck("second-file"); + let backup = second.gem_dir.join(BACKUP_DIR); + let mut info = read_backup_info(&backup).unwrap(); + info.lib_files.push("lib/a/3.3/a.bundle".to_string()); + write_backup_info(&backup, &info).unwrap(); + std::fs::create_dir_all(backup.join("lib/lib/a/3.3")).unwrap(); + std::fs::write(backup.join("lib/lib/a/3.3/a.bundle"), b"something else").unwrap(); + assert!(replaced_binaries(&second, &record) + .await + .unwrap() + .is_empty()); + assert!( + !apply_offline(&second, OWN_PURL, &record, &blobs) + .await + .result + .success + ); + assert_build_kept(&second); + assert_eq!( + std::fs::read(second.gem_dir.join("lib/a/3.3/a.bundle")).unwrap(), + b"the patch's 3.3" + ); + + // The backup also holds a file the record does not write. + let foreign = stuck("foreign-file"); + let backup = foreign.gem_dir.join(BACKUP_DIR); + let mut info = read_backup_info(&backup).unwrap(); + info.lib_files.push("lib/a/other.bundle".to_string()); + write_backup_info(&backup, &info).unwrap(); + assert!(replaced_binaries(&foreign, &record) + .await + .unwrap() + .is_empty()); + assert_build_kept(&foreign); + + let other_backup = stuck("other-backup"); + std::fs::write( + other_backup + .gem_dir + .join(BACKUP_DIR) + .join("lib") + .join(GRAFTED), + b"not the prebuilt binary", + ) + .unwrap(); + assert!(replaced_binaries(&other_backup, &record) + .await + .unwrap() + .is_empty()); + assert!( + !apply_offline(&other_backup, OWN_PURL, &record, &blobs) + .await + .result + .success + ); + assert_build_kept(&other_backup); + + let added = stuck("added"); + let backup = added.gem_dir.join(BACKUP_DIR); + let mut info = read_backup_info(&backup).unwrap(); + info.absent_files = vec!["ext/a/a.c".to_string()]; + write_backup_info(&backup, &info).unwrap(); + assert!(replaced_binaries(&added, &record).await.unwrap().is_empty()); + assert!( + !apply_offline(&added, OWN_PURL, &record, &blobs) + .await + .result + .success + ); + assert_build_kept(&added); + } + + /// A platform record that leaves out the binary of a Ruby the copy + /// ships one for is handled as 5.2.0 handled every platform record: + /// its source is a build input, so `apply` builds for the Ruby that + /// runs it (this run cannot, and says so) and never reports the copy + /// patched on its files alone. A build 5.2.0 put over a binary of such + /// a record is not undone either. + #[tokio::test] + async fn a_record_that_leaves_out_a_rubys_binary_is_built_as_before() { + let tmp = tempfile::tempdir().unwrap(); + let blobs = tmp.path().join("blobs"); + let (record, patched) = own_build_record(&blobs); + let mut one_ruby = record.clone(); + one_ruby.remove("lib/a/3.3/a.bundle").unwrap(); + + let copy = precompiled_gem(&tmp.path().join("clean")); + let gem = InstalledGem::at(©.gem_dir).await; + assert_eq!(gem.scope(OWN_PURL, &one_ruby).inputs, ["ext/a/a.c"]); + let applied = apply_offline(©, OWN_PURL, &one_ruby, &blobs).await; + assert!(!applied.result.success); + assert_eq!( + applied.warning.map(|(code, _)| code).as_deref(), + Some(UNSUPPORTED_CODE) + ); + assert_eq!( + std::fs::read(copy.gem_dir.join("lib/a/3.4/a.bundle")).unwrap(), + PREBUILT, + "nothing was written" + ); + assert_eq!( + gem.verify_native_build(OWN_PURL, &one_ruby).await, + Err(NOT_REBUILT_REASON.to_string()) + ); + + let stuck = + copy_with_a_build_over_the_records_binary(&tmp.path().join("stuck"), &record, &patched); + assert!( + replaced_build_files(&stuck.gem_dir, OWN_PURL, &one_ruby, &blobs) + .await + .is_empty() + ); + assert_eq!( + put_back_replaced_build(&stuck.gem_dir, OWN_PURL, &one_ruby, &blobs).await, + Ok(false) + ); + assert_build_kept(&stuck); + } + + /// A dry run puts nothing back and says what the run does: the copy is + /// left as it was, and the result is the success `apply` then has. + #[tokio::test] + async fn a_dry_run_over_a_replaced_binary_reports_what_apply_does() { + let tmp = tempfile::tempdir().unwrap(); + let blobs = tmp.path().join("blobs"); + let (record, patched) = own_build_record(&blobs); + let copy = copy_with_a_build_over_the_records_binary(tmp.path(), &record, &patched); + let would = apply_offline_with( + ©, + OWN_PURL, + &record, + &blobs, + true, + MismatchPolicy::Strict, + ) + .await; + assert!(would.result.success, "{:?}", would.result.error); + // The run has that binary to write: the copy is not reported as + // already patched. + let ready: Vec<&str> = would + .result + .files_verified + .iter() + .filter(|v| v.status == crate::patch::apply::VerifyStatus::Ready) + .map(|v| v.file.as_str()) + .collect(); + assert_eq!(ready, [GRAFTED]); + assert_eq!(would.result.files_verified.len(), record.len()); + // Nor as a file whose content matched nothing and is overwritten. + assert!(would + .result + .files_verified + .iter() + .all(|v| v.expected_hash.is_none())); + assert_build_kept(©); + assert_eq!( + replaced_build_files(©.gem_dir, OWN_PURL, &record, &blobs).await, + [GRAFTED] + ); + assert_build_kept(©); + let applied = apply_offline(©, OWN_PURL, &record, &blobs).await; + assert!(applied.result.success, "{:?}", applied.result.error); + } + + /// `rollback` of `record` under `purl` on `copy`, as the command runs + /// it for a gem's files. + async fn rollback_record( + copy: &GemCopy, + record: &HashMap, + blobs: &Path, + dry_run: bool, + ) -> crate::patch::rollback::RollbackResult { + rollback_gem_patch( + crate::utils::repo_root::ReadScope::Workspace, + OWN_PURL, + ©.gem_dir, + record, + blobs, + dry_run, + ) + .await + } + + /// Putting the build back drops its backup, so `rollback` does it only + /// when it can then restore every file: each before blob it reads is + /// stored and holds the content the record names. A blob that is + /// missing or cut short keeps the build, its marker and its backup, + /// and the rollback fails with nothing changed. + #[tokio::test] + async fn rollback_keeps_the_build_when_a_before_blob_is_not_whole() { + let tmp = tempfile::tempdir().unwrap(); + let blobs = tmp.path().join("blobs"); + let (record, patched) = own_build_record(&blobs); + let source_before = record["ext/a/a.c"].before_hash.clone(); + let stuck = |name: &str| { + copy_with_a_build_over_the_records_binary(&tmp.path().join(name), &record, &patched) + }; + let blobs_but = |name: &str, cut: Option<&[u8]>| { + let dir = tmp.path().join(name); + std::fs::create_dir_all(&dir).unwrap(); + for entry in std::fs::read_dir(&blobs).unwrap() { + let entry = entry.unwrap(); + std::fs::copy(entry.path(), dir.join(entry.file_name())).unwrap(); + } + match cut { + Some(bytes) => std::fs::write(dir.join(&source_before), bytes).unwrap(), + None => std::fs::remove_file(dir.join(&source_before)).unwrap(), + } + dir + }; + + for (name, cut) in [("missing", None), ("cut", Some(&b"int"[..]))] { + let other_blobs = blobs_but(&format!("{name}-blobs"), cut); + let copy = stuck(name); + assert!( + replaced_build_files(©.gem_dir, OWN_PURL, &record, &other_blobs) + .await + .is_empty(), + "{name}" + ); + assert_eq!( + put_back_replaced_build(©.gem_dir, OWN_PURL, &record, &other_blobs).await, + Ok(false), + "{name}" + ); + assert_build_kept(©); + let rolled = rollback_record(©, &record, &other_blobs, false).await; + assert!(!rolled.success, "{name}"); + assert_build_kept(©); + assert_eq!( + std::fs::read(copy.gem_dir.join("ext/a/a.c")).unwrap(), + b"int a = 1;", + "{name}" + ); + } + + // With every blob whole the build is put back and the copy rolled + // back. + let copy = stuck("whole"); + let rolled = rollback_record(©, &record, &blobs, false).await; + assert!(rolled.success, "{:?}", rolled.error); + assert_eq!(std::fs::read(copy.gem_dir.join(GRAFTED)).unwrap(), PREBUILT); + assert_eq!( + std::fs::read(copy.gem_dir.join("ext/a/a.c")).unwrap(), + b"int a;" + ); + assert!(!copy.gem_dir.join(BACKUP_DIR).exists()); + } + + /// `rollback --dry-run` reports the binary the run puts back from the + /// build's backup as a file to restore, even when every other file of + /// the record already holds its original content: the run changes that + /// binary, so the dry run does not report a copy with nothing to do. + #[tokio::test] + async fn a_dry_run_rollback_reports_the_binary_it_puts_back() { + let tmp = tempfile::tempdir().unwrap(); + let blobs = tmp.path().join("blobs"); + let (record, patched) = own_build_record(&blobs); + let copy = copy_with_a_build_over_the_records_binary(tmp.path(), &record, &patched); + std::fs::write(copy.gem_dir.join("ext/a/a.c"), b"int a;").unwrap(); + std::fs::write(copy.gem_dir.join("lib/a/3.3/a.bundle"), PREBUILT).unwrap(); + + let would = rollback_record(©, &record, &blobs, true).await; + assert!(would.success, "{:?}", would.error); + let ready: Vec<&str> = would + .files_verified + .iter() + .filter(|v| v.status == crate::patch::rollback::VerifyRollbackStatus::Ready) + .map(|v| v.file.as_str()) + .collect(); + assert_eq!(ready, [GRAFTED]); + assert_eq!(would.files_verified.len(), record.len()); + assert_build_kept(©); + + let rolled = rollback_record(©, &record, &blobs, false).await; + assert!(rolled.success, "{:?}", rolled.error); + assert_eq!(std::fs::read(copy.gem_dir.join(GRAFTED)).unwrap(), PREBUILT); + assert!(!copy.gem_dir.join(MARKER_FILE).exists()); + } + + /// What a gem ships for other Rubies that cannot be read is not a gem + /// that ships no other Ruby: a record whose binary sits in such a dir + /// is not taken to cover every Ruby, and is built as before. + #[cfg(unix)] + #[test] + fn an_unreadable_library_dir_does_not_cover_every_ruby() { + let tmp = tempfile::tempdir().unwrap(); + let record: HashMap = + [("lib/a/3.4/a.so".to_string(), info(&"c".repeat(64)))].into(); + // No such dir: nothing else is shipped. + assert!(covers_every_ruby(tmp.path(), &record)); + // A dir that cannot be read (here a link to itself, which no read + // gets through, as root included). + std::fs::create_dir_all(tmp.path().join("lib")).unwrap(); + std::os::unix::fs::symlink("a", tmp.path().join("lib/a")).unwrap(); + assert!(prebuilt_siblings_checked(tmp.path(), "lib/a/3.4/a.so").is_err()); + assert!(!covers_every_ruby(tmp.path(), &record)); + } + + /// The patch was published again since: the copy holds the earlier + /// patch's files, and a build over one of its binaries. Under the + /// policy that overwrites content a Socket patch wrote, the record + /// applies once the replaced binary is back, so it is put back. Under + /// the strict policy the earlier patch's files are a mismatch, and the + /// build is kept. + #[tokio::test] + async fn a_build_over_an_earlier_patchs_binary_is_put_back_for_the_new_patch() { + let tmp = tempfile::tempdir().unwrap(); + let blobs = tmp.path().join("blobs"); + let (earlier, earlier_patched) = own_build_record(&blobs); + let copy = + copy_with_a_build_over_the_records_binary(tmp.path(), &earlier, &earlier_patched); + // The new patch of the same gem: other bytes for every file. + let mut record = earlier.clone(); + let mut patched = Vec::new(); + for (file, _) in &earlier_patched { + let after = format!("{file} of the new patch").into_bytes(); + let entry = record.get_mut(*file).unwrap(); + entry.after_hash = compute_git_sha256_from_bytes(&after); + std::fs::write(blobs.join(&entry.after_hash), &after).unwrap(); + patched.push((*file, after)); + } + let strict = apply_offline(©, OWN_PURL, &record, &blobs).await; + assert!(!strict.result.success); + assert_build_kept(©); + + let applied = apply_offline_with( + ©, + OWN_PURL, + &record, + &blobs, + false, + MismatchPolicy::SocketContent, + ) + .await; + assert!(applied.result.success, "{:?}", applied.result.error); + for (file, after) in &patched { + assert_eq!( + &std::fs::read(copy.gem_dir.join(file)).unwrap(), + after, + "{file}" + ); + } + assert!(!copy.gem_dir.join(MARKER_FILE).exists()); + assert!(!copy.gem_dir.join(BACKUP_DIR).exists()); + } + + /// What an earlier graft left on a copy the record then applies to + /// whole is dropped: a backup with no build over it (the run stopped + /// before the graft), and a build the run was told to overwrite. A + /// backup that holds any file the record did not write is kept. + #[tokio::test] + async fn leftovers_of_an_earlier_graft_go_once_the_record_is_applied_whole() { + let tmp = tempfile::tempdir().unwrap(); + let blobs = tmp.path().join("blobs"); + let (record, patched) = own_build_record(&blobs); + + // Backed up, the record's files written, never grafted. + let copy = precompiled_gem(&tmp.path().join("never-grafted")); + let staged = staged_build(&tmp.path().join("stage"), &["a/a.bundle"], b"built by 3.4"); + let grafts = plan_graft(©, &probe_for(©, "3.4.10"), &staged).unwrap(); + assert!(back_up_prebuilt(©, &grafts, &[]).unwrap()); + let applied = apply_offline(©, OWN_PURL, &record, &blobs).await; + assert!(applied.result.success, "{:?}", applied.result.error); + assert!(!copy.gem_dir.join(BACKUP_DIR).exists()); + + // A hand edit beside the build, and a run told to overwrite it. + let forced = copy_with_a_build_over_the_records_binary( + &tmp.path().join("forced"), + &record, + &patched, + ); + std::fs::write(forced.gem_dir.join("ext/a/a.c"), b"int a = 2; /* mine */").unwrap(); + let applied = apply_offline_with( + &forced, + OWN_PURL, + &record, + &blobs, + false, + MismatchPolicy::Warn, + ) + .await; + assert!(applied.result.success, "{:?}", applied.result.error); + for (file, after) in &patched { + assert_eq!( + &std::fs::read(forced.gem_dir.join(file)).unwrap(), + after, + "{file}" + ); + } + assert!(!forced.gem_dir.join(MARKER_FILE).exists()); + assert!(!forced.gem_dir.join(BACKUP_DIR).exists()); + + // A backup that also holds a file the record does not write. + let kept = precompiled_gem(&tmp.path().join("kept")); + assert!(back_up_prebuilt( + &kept, + &plan_graft(&kept, &probe_for(&kept, "3.4.10"), &staged).unwrap(), + &[] + ) + .unwrap()); + let backup = kept.gem_dir.join(BACKUP_DIR); + let mut info = read_backup_info(&backup).unwrap(); + info.lib_files.push("lib/a/other.bundle".to_string()); + write_backup_info(&backup, &info).unwrap(); + let applied = apply_offline(&kept, OWN_PURL, &record, &blobs).await; + assert!(applied.result.success, "{:?}", applied.result.error); + assert!(backup.join(BACKUP_INFO).exists()); + + // A marker that is there and cannot be read keeps its backup: + // `rollback` restores the pair, and refuses a marker left alone. + let unread = precompiled_gem(&tmp.path().join("unread")); + assert!(back_up_prebuilt( + &unread, + &plan_graft(&unread, &probe_for(&unread, "3.4.10"), &staged).unwrap(), + &[] + ) + .unwrap()); + std::fs::write(unread.gem_dir.join(MARKER_FILE), b"{ not a marker").unwrap(); + let applied = apply_offline(&unread, OWN_PURL, &record, &blobs).await; + assert!(applied.result.success, "{:?}", applied.result.error); + assert!(unread.gem_dir.join(BACKUP_DIR).join(BACKUP_INFO).exists()); + assert!(unread.gem_dir.join(MARKER_FILE).exists()); + } + /// A copy built from these sources starts no Ruby on the next `apply`, /// with one exception: a grafted copy whose gem ships a binary for /// another Ruby that may be sharing its gem home. A home laid out for diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 1425438fa..a5b87f9fd 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5852,7 +5852,7 @@ How each mode gets the patched code running: |---|---| | Hosted | Bundler installs the patched `.gem` from the patch registry, and RubyGems compiles it like any registry gem. A gem the lock pins as precompiled platform gems (`x86_64-linux-gnu`) is installed from the patched platform gem the registry serves for that platform, with nothing to compile; it is skipped with `redirect_gem_platform_unsupported` only while no one fix has a patch for every locked platform. | | Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from the patched platform gems of one fix. Each platform gem has a patch of its own, built from the patch of the ruby gem, and the vendored directory (named after that patch, so it does not move when the lock's platforms change; where that patch is not available to the run, after the patch of the first locked platform, and a gem already vendored stays in the directory it has while the lock still names that platform; once it does not, the next run moves the gem to the directory of the patch it is then vendored through, and removes the old directory and its ledger entry) holds each of them unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. The vendor ledger records each platform's tree with its own patch UUID and the checksums of the gem and gemspec it came from, `--json` reports one event per platform gem under its own patch (the summary lines count the gem as one package), and `vex` attests each platform gem by its own patch. Every platform in the lock needs a patch of that fix. While one of them has none the gem is skipped with `vendor_prebuilt_platform_pending`, which names each such platform and why (no patch on offer, a patched gem that is still being built, a patch of another fix): the run does not fail, nothing is written, a patch that is already vendored stays in place, and a later run vendors the gem once every platform has one. A gem that is already vendored this way and whose platforms no longer all have a patch is kept as committed (`vendor_gem_builds_kept`) while its trees still match the ledger. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the prebuilt binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again, which puts the gem back in the same directory (in the directory of the first locked platform's patch, which the new platform can be, where the ruby gem's patch is not available to the run). A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | -| Agent (`apply`) | The extension is rebuilt from the gem's source archive with the patch laid over it, using RubyGems' builder and the Ruby that owns the install, and the build is put where Ruby loads it: the extension directory of a gem RubyGems built, the prebuilt binary of a precompiled gem. | +| Agent (`apply`) | The extension is rebuilt from the gem's source archive with the patch laid over it, using RubyGems' builder and the Ruby that owns the install, and the build is put where Ruby loads it: the extension directory of a gem RubyGems built, the prebuilt binary of a precompiled gem. A patch made for the installed platform gem itself (`?platform=x86_64-linux-gnu`) that brings its compiled binaries, one for every Ruby the gem ships one for, is written as it is, with no build: the copy then holds the files of the patched platform gem. | `apply` takes the source gem (`-.gem`) from the gem home's `cache/` directory, where RubyGems and Bundler keep it for a gem they built. For a precompiled gem, or a pruned cache,