diff --git a/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs b/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs index 1a21534dd..633f7296f 100644 --- a/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs +++ b/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs @@ -3625,6 +3625,32 @@ end File.write("Makefile", "all:\n\ninstall:\n\nclean:\n\n") "##; +/// `sp_wrap` with a build script that uses up a file the gem ships, as +/// argon2's does (`File.rename('Makefile.real', 'Makefile')`): the +/// installed tree holds no `Makefile.real`, and the script cannot run +/// there a second time. +const ONE_SHOT_EXTCONF: &str = r##"require "rbconfig" +Dir.chdir(__dir__) +name = RbConfig::CONFIG["host_os"] =~ /darwin/ ? "libsp_wrap.dylib" : "libsp_wrap.so" +cc = RbConfig::CONFIG["CC"].split +abort "could not build #{name}" unless system(*cc, "-shared", "-fPIC", "-o", name, "wrap.c") +File.rename("Makefile.real", "Makefile") +"##; +/// [`ONE_SHOT_EXTCONF`] with a build that only a fresh tree lets finish: +/// run over an installed one it compiles the library, uses the shipped +/// file up and then fails. +const ONCE_ONLY_EXTCONF: &str = r##"require "rbconfig" +Dir.chdir(__dir__) +name = RbConfig::CONFIG["host_os"] =~ /darwin/ ? "libsp_wrap.dylib" : "libsp_wrap.so" +cc = RbConfig::CONFIG["CC"].split +installed = File.exist?("Makefile") +abort "could not build #{name}" unless system(*cc, "-shared", "-fPIC", "-o", name, "wrap.c") +File.rename("Makefile.real", "Makefile") +abort "this tree was built before" if installed +"##; +/// The file [`ONE_SHOT_EXTCONF`] uses up, relative to the gem dir. +const ONE_SHOT_FILE: &str = "ext/sp_wrap/Makefile.real"; + /// A project with `sp_wrap` (built by `extconf`) installed into /// `vendor/bundle/ruby/` by the real `gem`, its archive in the home's /// `cache/`, and a record that changes `SpWrap.value` from 1 to 2. @@ -3645,11 +3671,13 @@ impl WrapGem { std::fs::write(src.join("ext/sp_wrap/extconf.rb"), extconf).unwrap(); std::fs::write(src.join(WRAP_C_KEY), wrap_c(1)).unwrap(); std::fs::write(src.join("lib/sp_wrap.rb"), WRAP_LIB).unwrap(); + // Shipped with every variant; only `ONE_SHOT_EXTCONF` touches it. + std::fs::write(src.join(ONE_SHOT_FILE), "all:\n\ninstall:\n\nclean:\n\n").unwrap(); std::fs::write( src.join("sp_wrap.gemspec"), "Gem::Specification.new do |s|\n s.name = \"sp_wrap\"\n s.version = \"1.0.0\"\n \ s.summary = \"t\"\n s.authors = [\"t\"]\n \ - s.files = Dir[\"lib/**/*.rb\", \"ext/**/*.{c,rb}\"]\n \ + s.files = Dir[\"lib/**/*.rb\", \"ext/**/*.{c,rb,real}\"]\n \ s.extensions = [\"ext/sp_wrap/extconf.rb\"]\nend\n", ) .unwrap(); @@ -3838,6 +3866,118 @@ fn a_build_that_keeps_a_stale_library_is_made_to_rebuild_it() { assert_eq!(fx.c_file(), wrap_c(1)); } +/// A build script that uses up a file the gem ships cannot run a second +/// time over the installed tree (argon2's renames `Makefile.real`). The +/// source gem still holds the file, so it is put back for the in-place +/// build: the patch is built, and nothing is left in the tree that the +/// build did not leave there itself. `rollback` gives the installed tree +/// back, with or without the backup of the original build (#2106). +#[test] +#[ignore = "host capstone: compiles a C extension with the real ruby/gem toolchain; \ + the unpinned `test` job skips it, the pinned-Ruby e2e leg runs it via --ignored"] +fn a_build_script_that_uses_up_a_shipped_file_is_given_it_back() { + let Some(abi) = toolchain() else { + return; + }; + let fx = WrapGem::new(&abi, ONE_SHOT_EXTCONF); + assert_eq!(fx.value(), "1"); + assert!( + !fx.gem_dir.join(ONE_SHOT_FILE).exists(), + "the install-time build used the file up" + ); + let installed = walk_files(&fx.gem_dir); + let extensions = walk_files(&fx.home.join("extensions")); + + let (code, stdout, stderr) = fx.run(&["apply", "--json", "--offline"]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!( + fx.value(), + "2", + "Ruby must load the library built from the patched source:\n{stdout}" + ); + let mut changed: Vec = tree_diff(&installed, &walk_files(&fx.gem_dir)) + .into_iter() + .filter(|line| !line.contains(".socket-patch-native-")) + .collect(); + changed.sort(); + assert_eq!( + changed, + [format!("~{}", fx.library()), format!("~{WRAP_C_KEY}")], + "the patched source and the library built from it are all that changed" + ); + let (code, stdout, stderr) = fx.run(&["apply", "--check"]); + assert_eq!(code, 0, "a rebuilt patch checks clean:\n{stdout}\n{stderr}"); + assert!(vex_attests(|args| fx.run(args))); + + let (code, stdout, stderr) = fx.run(&["rollback", "--json", "--offline"]); + assert_eq!(code, 0, "rollback failed:\n{stdout}\n{stderr}"); + assert_eq!(fx.value(), "1", "Ruby must load the original library again"); + assert_tree(&fx.gem_dir, &installed, "after rollback"); + assert_tree(&fx.home.join("extensions"), &extensions, "after rollback"); + + // A rollback that has lost the backup rebuilds from the restored + // source, with the same script. (The first rollback dropped the + // record.) + write_record( + &fx.proj.join(".socket"), + WRAP_PURL, + &[(WRAP_C_KEY, Some(&wrap_c(1)), &wrap_c(2))], + ); + let (code, stdout, stderr) = fx.run(&["apply", "--json", "--offline"]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!(fx.value(), "2"); + std::fs::remove_dir_all(fx.gem_dir.join(".socket-patch-native-orig")).unwrap(); + let (code, stdout, stderr) = fx.run(&["rollback", "--json", "--offline"]); + assert_eq!(code, 0, "rollback failed:\n{stdout}\n{stderr}"); + assert_eq!( + fx.value(), + "1", + "the library is rebuilt from the restored source:\n{stdout}" + ); + assert_eq!(fx.c_file(), wrap_c(1)); + assert!( + !fx.gem_dir.join(ONE_SHOT_FILE).exists(), + "the file put back for the build is not left behind" + ); +} + +/// A build that fails in the installed tree after it was given the +/// shipped file back, and after it compiled the patched library and used +/// the file up: the undo takes everything the build did with it, and the +/// gem is exactly as installed (#2106). +#[test] +#[ignore = "host capstone: compiles a C extension with the real ruby/gem toolchain; \ + the unpinned `test` job skips it, the pinned-Ruby e2e leg runs it via --ignored"] +fn a_failed_build_takes_the_shipped_file_it_was_given_away_again() { + let Some(abi) = toolchain() else { + return; + }; + let fx = WrapGem::new(&abi, ONCE_ONLY_EXTCONF); + let installed = walk_files(&fx.gem_dir); + let extensions = walk_files(&fx.home.join("extensions")); + + let (code, stdout, stderr) = fx.run(&["apply", "--json", "--offline"]); + assert_ne!(code, 0, "the in-place build fails:\n{stdout}\n{stderr}"); + let env = parse_json_envelope(&stdout); + let event = common::envelope::event_for(&env, WRAP_PURL); + assert!( + event["error"].as_str().is_some_and(|e| { + e.starts_with("native_extension_build_failed:") + && e.contains("this tree was built before") + }), + "the build got as far as the script's last line, so it was given the file:\n{stdout}" + ); + assert_eq!(fx.value(), "1"); + assert_tree(&fx.gem_dir, &installed, "after the failed apply"); + assert_tree( + &fx.home.join("extensions"), + &extensions, + "after the failed apply", + ); + assert!(!fx.home.join(".socket-patch-build").exists()); + assert!(!vex_attests(|args| fx.run(args))); +} + /// Without the source gem nothing says which files the build makes, so /// none can be removed for it. A build that then exits cleanly and leaves /// every library as it was has not built the patched source: the patch is diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 4688c1a16..ba70434df 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -3243,10 +3243,15 @@ fn stale_build( } /// Rebuild `copy`'s extension from the sources on disk with `probe.ruby`, -/// in its installed tree. `stale` are files of that tree the gem's build is -/// known to make ([`StageFailure::InTree`]): they are taken out of the -/// build's way, as a fresh install has none of them, so a build that would -/// take them for current makes them again. +/// in its installed tree, as close to a fresh install's as `seen` (what +/// the build of its source gem showed, [`StageFailure::InTree`]) lets it +/// be made. The files of the tree that build is known to make are taken +/// out of the build's way, as a fresh install has none of them, so a build +/// that would take them for current makes them again. The files the gem +/// ships that the tree no longer holds are put back for it ([`give_back`]), +/// so a build script that uses one up can run again (#2106); those the +/// build leaves as they were are taken away after it, whether it finished +/// or not. /// /// The gem's own tree is snapshotted first ([`TreeSnapshot`]). What a /// finished build replaced or added there is backed up with the original @@ -3265,7 +3270,7 @@ async fn rebuild( files: &HashMap, env: &RubyEnv, back_up: bool, - stale: &[String], + seen: &SeenInStage, ) -> Result<(), NotRebuilt> { // A backup this rebuild made is dropped again when the build does not // land: the install-time build is back in place, so the copy is as it @@ -3281,8 +3286,9 @@ async fn rebuild( .keys() .map(|key| normalize_file_path(key).to_string()) .collect(); - let (aside, made_backup, snapshot, removed) = { - let (copy, probe, stale) = (copy.clone(), probe.clone(), stale.to_vec()); + let (aside, made_backup, snapshot, removed, given) = { + let (copy, probe) = (copy.clone(), probe.clone()); + let (stale, used_up) = (seen.created.clone(), seen.used_up.clone()); crate::utils::fs::run_blocking(move || { let made = if back_up { back_up_original(©, &probe, &[]) @@ -3311,8 +3317,16 @@ async fn rebuild( } Ok((snapshot, removed)) }); + // What is written here is in no snapshot: the undo of a failed + // build removes it. Files that cannot be written (a full + // disk) leave the tree as it is, which is what the build ran + // over before there was anything to give it. + let prepared = prepared.map(|(snapshot, removed)| { + let given = give_back(©, &snapshot, &used_up, &left).unwrap_or_default(); + (snapshot, removed, given) + }); match prepared { - Ok((snapshot, removed)) => Ok((aside, made, snapshot, removed)), + Ok((snapshot, removed, given)) => Ok((aside, made, snapshot, removed, given)), Err(e) => { // The parked build stays where it is when the tree // cannot be put back: the next run tries again. @@ -3368,6 +3382,9 @@ async fn rebuild( let unread = watch .as_ref() .and_then(|watch| unread_inputs(©.gem_dir, watch, &snapshot.dir)); + // What the build left of the files it was given is no + // change it made. + take_away(©, &given); let changes = tree_changes(©, &snapshot); let stale = stale_build(©, &probe, &removed, &snapshot, &changes); match (stale, unread) { @@ -3414,8 +3431,13 @@ async fn rebuild( // The gem's own tree first, while the parked build still says a // rebuild is under way: if it cannot be put back, the parked build // stays, and the next run tries again from the snapshot. - let undone = - restore_tree(©, &snapshot.dir).and_then(|()| put_back(©, &probe, aside)); + let undone = restore_tree(©, &snapshot.dir) + .map(|()| { + // The files went with the restore; the dirs made for them + // are left to go. + take_away(©, &given); + }) + .and_then(|()| put_back(©, &probe, aside)); match undone { Ok(()) => { drop_new_backup(©, made_backup); @@ -3657,12 +3679,206 @@ enum StageFailure { /// in for it. InTree { products: Vec, - /// Those of `products` the source gem does not ship: the build - /// made them, and a fresh install builds without them. - created: Vec, + /// What the staged build showed that a build of the installed + /// tree goes by. + seen: SeenInStage, }, } +/// A file the source gem ships that the installed copy does not hold. +#[derive(Debug, Clone, PartialEq, Eq)] +struct ShippedFile { + /// Its path in the gem dir, `/`-separated. + rel: String, + bytes: Vec, + permissions: std::fs::Permissions, + /// When the stage's copy was written: before the record's files were, + /// in the stage and in the installed copy. + modified: Option, +} + +/// What building a gem's source gem in a stage showed of its build, for a +/// build of the installed tree ([`rebuild`]) to go by. The default (no +/// staged build to learn from) changes nothing of that build. +#[derive(Debug, Default)] +struct SeenInStage { + /// The files Ruby loads that the build made in the gem's own tree and + /// the source gem does not ship ([`in_tree_products`]): a fresh + /// install builds without them. + created: Vec, + /// The files the source gem ships that the installed copy no longer + /// holds ([`used_up_files`]): a fresh install builds with them. + used_up: Vec, +} + +/// The most bytes of [`used_up_files`] a run keeps while the staged build +/// runs. A gem that ships more than this and installs without it is built +/// in place from the tree as it is. +const USED_UP_LIMIT: u64 = 64 * 1024 * 1024; + +/// The files of the pristine source gem unpacked at `staged` that the +/// copy at `installed` does not hold, with their content. +/// +/// RubyGems installs every file of a gem, so one that is gone was taken +/// away after the install, as a rule by the gem's own build: a script that +/// renames a file it ships (argon2's `extconf.rb` makes `Makefile.real` +/// its `Makefile`), or one that deletes the sources it has compiled. That +/// build cannot run a second time over what it left, and the build of the +/// stage uses the staged files up the same way, so they are read before +/// it. All of them or none: a file that cannot be read, or more than +/// [`USED_UP_LIMIT`] in all, keeps nothing. +/// +/// Each keeps the time the stage's copy was written, which is before the +/// record's files are written anywhere. A file given back with the time +/// of its writing would be newer than the patched sources, and a build +/// that makes one from the other (a parser the gem ships generated) would +/// take the shipped one for current. +fn used_up_files(installed: &Path, staged: &Path) -> Vec { + let mut files = Vec::new(); + let mut total = 0u64; + for rel in tree_files(staged) { + if !is_safe_relative_subpath(&rel) || is_own_entry(&rel) { + continue; + } + // Only a file that is not there is one the copy does not hold. + if !matches!(try_entry_type(&installed.join(&rel)), Ok(None)) { + continue; + } + let path = staged.join(&rel); + // Its size before its bytes: one that is over the limit is not + // read to find that out. + let Ok(meta) = std::fs::symlink_metadata(&path) else { + return Vec::new(); + }; + total = total.saturating_add(meta.len()); + if total > USED_UP_LIMIT { + return Vec::new(); + } + let Ok(bytes) = read_regular_to_bytes_sync(&path) else { + return Vec::new(); + }; + files.push(ShippedFile { + rel, + bytes, + permissions: meta.permissions(), + modified: meta.modified().ok(), + }); + } + files +} + +/// The files [`give_back`] wrote, and the dirs it made for them. +#[derive(Debug, Default)] +struct GivenBack { + /// Gem-dir path → git-sha256 of what was written. + files: Vec<(String, String)>, + /// Deepest first. + dirs: Vec, +} + +/// Write the files a fresh install of the gem would hold and `copy` does +/// not (`used_up`) into its tree, for an in-place build to find: after +/// `snapshot` was taken, so the undo of a failed build removes them +/// ([`restore_tree`]). A path the tree holds by now, one of the record's +/// (`left`), and one under a link in the gem dir (it would be written +/// through the link) are left alone. On `Err` nothing of it is left. +fn give_back( + copy: &GemCopy, + snapshot: &TreeSnapshot, + used_up: &[ShippedFile], + left: &[String], +) -> std::io::Result { + let mut given = GivenBack::default(); + let written = write_used_up(copy, snapshot, used_up, left, &mut given); + // Deepest first, each once. + given + .dirs + .sort_by_key(|dir| std::cmp::Reverse(dir.components().count())); + given.dirs.dedup(); + match written { + Ok(()) => Ok(given), + Err(e) => { + // Nothing has run since: every file listed is this call's, + // whole or not. + for (rel, _) in &given.files { + let _ = std::fs::remove_file(copy.gem_dir.join(rel)); + } + take_away(copy, &given); + Err(e) + } + } +} + +/// [`give_back`]'s writes, each listed in `given` before it is made. +fn write_used_up( + copy: &GemCopy, + snapshot: &TreeSnapshot, + used_up: &[ShippedFile], + left: &[String], + given: &mut GivenBack, +) -> std::io::Result<()> { + for file in used_up { + let rel = &file.rel; + if !is_safe_relative_subpath(rel) + || is_own_entry(rel) + || left.contains(rel) + || snapshot.files.contains_key(rel) + { + continue; + } + let path = copy.gem_dir.join(rel); + if crate::utils::containment::try_linked_level(©.gem_dir, &path)?.is_some() + || try_entry_type(&path)?.is_some() + { + continue; + } + // The dirs that are made for it, to take away again with it. + let mut made = Vec::new(); + let mut dir = path.parent(); + while let Some(parent) = dir.filter(|parent| *parent != copy.gem_dir) { + if try_entry_type(parent)?.is_some() { + break; + } + made.push(parent.to_path_buf()); + dir = parent.parent(); + } + given.dirs.extend(made); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + given + .files + .push((rel.clone(), compute_git_sha256_from_bytes(&file.bytes))); + std::fs::write(&path, &file.bytes)?; + if let Some(modified) = file.modified { + // Before the permissions, which may not let it be opened. + std::fs::OpenOptions::new() + .write(true) + .open(&path)? + .set_modified(modified)?; + } + std::fs::set_permissions(&path, file.permissions.clone())?; + } + Ok(()) +} + +/// Take away what [`give_back`] wrote and the build left as it was: a +/// file of the gem that the installed copy did not hold before the build +/// is not left in it after. A file the build changed is the build's, and +/// stays. So does a dir that still holds something. +fn take_away(copy: &GemCopy, given: &GivenBack) { + for (rel, hash) in &given.files { + let path = copy.gem_dir.join(rel); + if is_real_file(&path) && compute_file_git_sha256_sync(&path).ok().as_ref() == Some(hash) { + let _ = std::fs::remove_file(&path); + } + } + for dir in &given.dirs { + // Fails on a dir that is not empty, which is the point. + let _ = std::fs::remove_dir(dir); + } +} + impl StageFailure { /// The failure as a clause of a message. fn describe(&self) -> String { @@ -4122,6 +4338,14 @@ async fn build_in_stage( .await .map_err(StageFailure::NotOwnSource)?; } + // What the installed copy's build used up of the gem, while the stage + // still holds it: only a copy RubyGems built is ever built in place. + let used_up = if source.full_name() == copy.full_name { + let (installed, unpacked) = (copy.gem_dir.clone(), staged.gem_dir.clone()); + crate::utils::fs::run_blocking(move || used_up_files(&installed, &unpacked)).await + } else { + Vec::new() + }; // The record over the pristine source gem, before anything runs. if let Some(record) = record { let blobs = stage_blobs(record.pkg_path, record.files, record.sources).await; @@ -4219,7 +4443,10 @@ async fn build_in_stage( .await }; if !products.is_empty() { - return Err(StageFailure::InTree { products, created }); + return Err(StageFailure::InTree { + products, + seen: SeenInStage { created, used_up }, + }); } Ok(built) } @@ -5416,12 +5643,13 @@ async fn rebuild_in_place( warning: None, }; } - // What the source gem's build was seen to make in the gem's own tree. - let stale: &[String] = match staged { - StageFailure::InTree { created, .. } => created, - _ => &[], + // What the source gem's build showed of this gem's build. + let nothing = SeenInStage::default(); + let seen = match staged { + StageFailure::InTree { seen, .. } => seen, + _ => ¬hing, }; - match rebuild(job.copy, probe, job.scope, job.files, job.env, true, stale).await { + match rebuild(job.copy, probe, job.scope, job.files, job.env, true, seen).await { Ok(()) => job.built(result), // The previous build is back, and the sources stay written. Err(NotRebuilt::NotOfPatch(why)) => { @@ -5686,9 +5914,9 @@ pub async fn restore_original_build(pkg_path: &Path, env: &RubyEnv) -> Result rebuilt, - Err(stale) => { + Err(seen) => { let scope = NativeScope::default(); - rebuild(©, &probe, &scope, &HashMap::new(), env, false, &stale) + rebuild(©, &probe, &scope, &HashMap::new(), env, false, &seen) .await .map_err(NotRebuilt::into_detail) } @@ -5708,32 +5936,32 @@ pub async fn restore_original_build(pkg_path: &Path, env: &RubyEnv) -> Result Result, Vec> { +) -> Result, SeenInStage> { let spec_text = crate::utils::fs::read_regular_to_string(©.spec_path) .await - .map_err(|_| Vec::new())?; + .map_err(|_| SeenInStage::default())?; let facts = SpecFacts::of(&spec_text, ©.full_name); let source = facts .release .filter(|_| facts.extensions.declared) - .ok_or_else(Vec::new)?; + .ok_or_else(SeenInStage::default)?; let gems = GemSource::of(&env.cwd, env.offline).await; let archive = gems .archive(©.home, &source) .await - .map_err(|_| Vec::new())?; + .map_err(|_| SeenInStage::default())?; let (stage, built) = match build_from_source_gem(copy, probe, &source, archive, &gems, env, None).await { Ok(staged) => staged, Err(StageFailure::Busy(why)) => return Ok(Err(why)), - Err(StageFailure::InTree { created, .. }) => return Err(created), - Err(_) => return Err(Vec::new()), + Err(StageFailure::InTree { seen, .. }) => return Err(seen), + Err(_) => return Err(SeenInStage::default()), }; let moved_in = { let (copy, probe) = (copy.clone(), probe.clone()); @@ -8520,6 +8748,171 @@ mod tests { ); } + /// The source gem of [`in_tree_gem`], unpacked: what the installed + /// copy holds of it, a Makefile its build script renames and a dir of + /// sources its build deletes. + fn source_gem_of(copy: &GemCopy, at: &Path) -> PathBuf { + let staged = at.join("staged"); + for (rel, bytes) in [ + ("ext/a/a.c", "patched source"), + ("ext/a/Makefile.real", "the makefile"), + ("ext/a/vendor/src/b.c", "packed source"), + ("lib/a.rb", "ruby"), + (MARKER_FILE, "not the gem's"), + ] { + let path = staged.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); + } + assert!(!copy.gem_dir.join("ext/a/Makefile.real").exists()); + staged + } + + fn rels(files: &[ShippedFile]) -> Vec<&str> { + files.iter().map(|file| file.rel.as_str()).collect() + } + + /// The files a fresh install would hold and the copy does not are the + /// ones its build used up: they are read from the pristine source gem, + /// with nothing of this module's among them (#2106). + #[test] + fn the_files_a_build_used_up_are_read_from_the_source_gem() { + let tmp = tempfile::tempdir().unwrap(); + let (copy, _probe) = in_tree_gem(tmp.path()); + let staged = source_gem_of(©, tmp.path()); + let used_up = used_up_files(©.gem_dir, &staged); + assert_eq!( + rels(&used_up), + ["ext/a/Makefile.real", "ext/a/vendor/src/b.c"] + ); + assert_eq!(used_up[0].bytes, b"the makefile"); + assert_eq!( + used_up[0].modified, + std::fs::metadata(staged.join("ext/a/Makefile.real")) + .unwrap() + .modified() + .ok() + ); + } + + /// The used-up files are put back for the in-place build, after the + /// snapshot: a failed build's undo removes them, and after a finished + /// one those the build left alone go again, with the dirs made for + /// them. One the build wrote to is the build's (#2106). + #[test] + fn used_up_files_are_given_back_for_the_build_and_taken_away_after() { + let tmp = tempfile::tempdir().unwrap(); + let (copy, probe) = in_tree_gem(tmp.path()); + let staged = source_gem_of(©, tmp.path()); + // The stage was unpacked before the patched sources were written. + let unpacked = std::time::SystemTime::now() - Duration::from_secs(3600); + std::fs::File::options() + .write(true) + .open(staged.join("ext/a/Makefile.real")) + .unwrap() + .set_modified(unpacked) + .unwrap(); + let used_up = used_up_files(©.gem_dir, &staged); + let installed = tree_bytes(©.gem_dir); + let dirs = |copy: &GemCopy| copy.gem_dir.join("ext/a/vendor").exists(); + + // A build that fails: the snapshot's undo, then the dirs. + let snapshot = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); + let given = give_back(©, &snapshot, &used_up, &record_paths()).unwrap(); + assert_eq!( + std::fs::read(copy.gem_dir.join("ext/a/Makefile.real")).unwrap(), + b"the makefile" + ); + assert!(copy.gem_dir.join("ext/a/vendor/src/b.c").is_file()); + // Not newer than the patched source: a build that makes one from + // the other would take the file given back for current. + let written = |rel: &str| { + std::fs::metadata(copy.gem_dir.join(rel)) + .unwrap() + .modified() + .unwrap() + }; + assert_eq!(Some(written("ext/a/Makefile.real")), used_up[0].modified); + assert!(written("ext/a/Makefile.real") < written("ext/a/a.c")); + build_in_tree(©, &probe); + restore_tree(©, &snapshot.dir).unwrap(); + take_away(©, &given); + assert_eq!(tree_bytes(©.gem_dir), installed); + assert!(!dirs(©), "the dirs made for the files go with them"); + + // A build that finishes, having renamed one file as argon2's + // script does and left the other: neither is a change it made. + let snapshot = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); + let given = give_back(©, &snapshot, &used_up, &record_paths()).unwrap(); + std::fs::rename( + copy.gem_dir.join("ext/a/Makefile.real"), + copy.gem_dir.join("ext/a/Makefile"), + ) + .unwrap(); + take_away(©, &given); + assert!(!dirs(©)); + assert_eq!( + tree_changes(©, &snapshot), + TreeChanges { + replaced: vec!["ext/a/Makefile".to_string()], + created: vec![], + } + ); + restore_tree(©, &snapshot.dir).unwrap(); + + // A file the build wrote to stays, and is one it created. + let snapshot = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); + let given = give_back(©, &snapshot, &used_up, &record_paths()).unwrap(); + std::fs::write(copy.gem_dir.join("ext/a/vendor/src/b.c"), b"generated").unwrap(); + take_away(©, &given); + assert_eq!( + tree_changes(©, &snapshot).created, + ["ext/a/vendor/src/b.c"] + ); + restore_tree(©, &snapshot.dir).unwrap(); + take_away(©, &given); + assert_eq!(tree_bytes(©.gem_dir), installed); + } + + /// Nothing is written over a file the tree holds, in place of a file + /// of the record, or through a link in the gem dir (#2106). + #[test] + fn a_used_up_file_is_only_written_where_the_tree_has_none() { + let tmp = tempfile::tempdir().unwrap(); + let (copy, probe) = in_tree_gem(tmp.path()); + let shipped = |rel: &str| ShippedFile { + rel: rel.to_string(), + bytes: b"shipped".to_vec(), + permissions: std::fs::metadata(copy.gem_dir.join("lib/a.rb")) + .unwrap() + .permissions(), + modified: None, + }; + #[cfg_attr(not(unix), allow(unused_mut))] + let mut used_up = vec![ + shipped("ext/a/Makefile"), + shipped("ext/a/a.c"), + shipped("../outside"), + shipped(MARKER_FILE), + ]; + let outside = tmp.path().join("elsewhere"); + #[cfg(unix)] + { + std::fs::create_dir(&outside).unwrap(); + std::os::unix::fs::symlink(&outside, copy.gem_dir.join("linked")).unwrap(); + used_up.push(shipped("linked/planted")); + } + // The record's file is gone from the tree (a patch may delete one). + std::fs::remove_file(copy.gem_dir.join("ext/a/a.c")).unwrap(); + let installed = tree_bytes(©.gem_dir); + let snapshot = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); + let given = give_back(©, &snapshot, &used_up, &record_paths()).unwrap(); + assert!(given.files.is_empty(), "{given:?}"); + assert_eq!(tree_bytes(©.gem_dir), installed); + assert!(!outside.join("planted").exists()); + assert!(!tmp.path().join("gems/outside").exists()); + } + /// A build that fails part-way has already written into the gem's own /// tree. The snapshot puts every file back, and goes. #[test] diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 2e0c021f6..94bfd223e 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2198,12 +2198,16 @@ are never printed. The JRuby (`-java`) build of a gem ships jars and is always refused for such a patch. A gem that builds a library into its own directory and loads it from there (an FFI gem such as -scrypt, a Rakefile build such as digest-crc) is always rebuilt from its installed tree. The -libraries the gem's build makes there are removed first, as a fresh install has none of them, so -a build script that would take an existing library for current compiles the patched source. When -`apply` can't tell which files those are (no source gem to compare with) and the build exits -without changing any compiled code, the package fails with `native_extension_build_failed` -instead of being reported as patched. +scrypt or argon2, a Rakefile build such as digest-crc) is always rebuilt from its installed tree. +The libraries the gem's build makes there are removed first, as a fresh install has none of them, +so a build script that would take an existing library for current compiles the patched source. +The files the gem ships that its first build used up are put back from the source gem for the +build, so a build script that can only run once (argon2's renames a file it ships) runs again; +those the build leaves untouched are removed again afterwards. When `apply` has no source gem to +compare with, it can do neither: a build script that needs a file that is gone fails, and a build +that exits without changing any compiled code is not taken for one. Either way the package fails +with `native_extension_build_failed` instead of being reported as patched, and the gem is left as +it was. Ruby files are never build inputs outside `ext/` and a build script's directory: a patch that only changes `.rb` or `.rbs` files needs no compiler, wherever the gem keeps them.