]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_gcc/src/archive.rs
Auto merge of #97925 - the8472:cgroupv1, r=joshtriplett
[rust.git] / compiler / rustc_codegen_gcc / src / archive.rs
1 use std::fs::File;
2 use std::path::{Path, PathBuf};
3
4 use rustc_codegen_ssa::back::archive::ArchiveBuilder;
5 use rustc_session::Session;
6
7 use rustc_data_structures::temp_dir::MaybeTempDir;
8 use rustc_session::cstore::DllImport;
9
10 struct ArchiveConfig<'a> {
11     sess: &'a Session,
12     dst: PathBuf,
13     use_native_ar: bool,
14     use_gnu_style_archive: bool,
15 }
16
17 #[derive(Debug)]
18 enum ArchiveEntry {
19     FromArchive {
20         archive_index: usize,
21         entry_index: usize,
22     },
23     File(PathBuf),
24 }
25
26 pub struct ArArchiveBuilder<'a> {
27     config: ArchiveConfig<'a>,
28     src_archives: Vec<(PathBuf, ar::Archive<File>)>,
29     // Don't use `HashMap` here, as the order is important. `rust.metadata.bin` must always be at
30     // the end of an archive for linkers to not get confused.
31     entries: Vec<(String, ArchiveEntry)>,
32 }
33
34 impl<'a> ArchiveBuilder<'a> for ArArchiveBuilder<'a> {
35     fn new(sess: &'a Session, output: &Path) -> Self {
36         let config = ArchiveConfig {
37             sess,
38             dst: output.to_path_buf(),
39             use_native_ar: false,
40             // FIXME test for linux and System V derivatives instead
41             use_gnu_style_archive: sess.target.options.archive_format == "gnu",
42         };
43
44         ArArchiveBuilder {
45             config,
46             src_archives: vec![],
47             entries: vec![],
48         }
49     }
50
51     fn add_file(&mut self, file: &Path) {
52         self.entries.push((
53             file.file_name().unwrap().to_str().unwrap().to_string(),
54             ArchiveEntry::File(file.to_owned()),
55         ));
56     }
57
58     fn add_archive<F>(&mut self, archive_path: &Path, mut skip: F) -> std::io::Result<()>
59     where
60         F: FnMut(&str) -> bool + 'static,
61     {
62         let mut archive = ar::Archive::new(std::fs::File::open(&archive_path)?);
63         let archive_index = self.src_archives.len();
64
65         let mut i = 0;
66         while let Some(entry) = archive.next_entry() {
67             let entry = entry?;
68             let file_name = String::from_utf8(entry.header().identifier().to_vec())
69                 .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))?;
70             if !skip(&file_name) {
71                 self.entries
72                     .push((file_name, ArchiveEntry::FromArchive { archive_index, entry_index: i }));
73             }
74             i += 1;
75         }
76
77         self.src_archives.push((archive_path.to_owned(), archive));
78         Ok(())
79     }
80
81     fn build(mut self) -> bool {
82         use std::process::Command;
83
84         fn add_file_using_ar(archive: &Path, file: &Path) {
85             Command::new("ar")
86                 .arg("r") // add or replace file
87                 .arg("-c") // silence created file message
88                 .arg(archive)
89                 .arg(&file)
90                 .status()
91                 .unwrap();
92         }
93
94         enum BuilderKind<'a> {
95             Bsd(ar::Builder<File>),
96             Gnu(ar::GnuBuilder<File>),
97             NativeAr(&'a Path),
98         }
99
100         let mut builder = if self.config.use_native_ar {
101             BuilderKind::NativeAr(&self.config.dst)
102         } else if self.config.use_gnu_style_archive {
103             BuilderKind::Gnu(ar::GnuBuilder::new(
104                 File::create(&self.config.dst).unwrap(),
105                 self.entries
106                     .iter()
107                     .map(|(name, _)| name.as_bytes().to_vec())
108                     .collect(),
109             ))
110         } else {
111             BuilderKind::Bsd(ar::Builder::new(File::create(&self.config.dst).unwrap()))
112         };
113
114         let any_members = !self.entries.is_empty();
115
116         // Add all files
117         for (entry_name, entry) in self.entries.into_iter() {
118             match entry {
119                 ArchiveEntry::FromArchive {
120                     archive_index,
121                     entry_index,
122                 } => {
123                     let (ref src_archive_path, ref mut src_archive) =
124                         self.src_archives[archive_index];
125                     let entry = src_archive.jump_to_entry(entry_index).unwrap();
126                     let header = entry.header().clone();
127
128                     match builder {
129                         BuilderKind::Bsd(ref mut builder) => {
130                             builder.append(&header, entry).unwrap()
131                         }
132                         BuilderKind::Gnu(ref mut builder) => {
133                             builder.append(&header, entry).unwrap()
134                         }
135                         BuilderKind::NativeAr(archive_file) => {
136                             Command::new("ar")
137                                 .arg("x")
138                                 .arg(src_archive_path)
139                                 .arg(&entry_name)
140                                 .status()
141                                 .unwrap();
142                             add_file_using_ar(archive_file, Path::new(&entry_name));
143                             std::fs::remove_file(entry_name).unwrap();
144                         }
145                     }
146                 }
147                 ArchiveEntry::File(file) =>
148                     match builder {
149                         BuilderKind::Bsd(ref mut builder) => {
150                             builder
151                                 .append_file(entry_name.as_bytes(), &mut File::open(file).expect("file for bsd builder"))
152                                 .unwrap()
153                         },
154                         BuilderKind::Gnu(ref mut builder) => {
155                             builder
156                                 .append_file(entry_name.as_bytes(), &mut File::open(&file).expect(&format!("file {:?} for gnu builder", file)))
157                                 .unwrap()
158                         },
159                         BuilderKind::NativeAr(archive_file) => add_file_using_ar(archive_file, &file),
160                     },
161             }
162         }
163
164         // Finalize archive
165         std::mem::drop(builder);
166
167         // Run ranlib to be able to link the archive
168         let status = std::process::Command::new("ranlib")
169             .arg(self.config.dst)
170             .status()
171             .expect("Couldn't run ranlib");
172
173         if !status.success() {
174             self.config.sess.fatal(&format!("Ranlib exited with code {:?}", status.code()));
175         }
176
177         any_members
178     }
179
180     fn inject_dll_import_lib(&mut self, _lib_name: &str, _dll_imports: &[DllImport], _tmpdir: &MaybeTempDir) {
181         unimplemented!();
182     }
183 }