1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A helper class for dealing with static archives
13 use std::io::fs::PathExtensions;
14 use std::io::process::{Command, ProcessOutput};
15 use std::io::{fs, TempDir};
19 use syntax::diagnostic::Handler as ErrorHandler;
21 pub static METADATA_FILENAME: &'static str = "rust.metadata.bin";
23 pub struct ArchiveConfig<'a> {
24 pub handler: &'a ErrorHandler,
26 pub lib_search_paths: Vec<Path>,
27 pub slib_prefix: String,
28 pub slib_suffix: String,
29 pub maybe_ar_prog: Option<String>
32 pub struct Archive<'a> {
33 handler: &'a ErrorHandler,
35 lib_search_paths: Vec<Path>,
38 maybe_ar_prog: Option<String>
41 /// Helper for adding many files to an archive with a single invocation of
43 #[must_use = "must call build() to finish building the archive"]
44 pub struct ArchiveBuilder<'a> {
47 /// Filename of each member that should be added to the archive.
49 should_update_symbols: bool,
52 fn run_ar(handler: &ErrorHandler, maybe_ar_prog: &Option<String>,
53 args: &str, cwd: Option<&Path>,
54 paths: &[&Path]) -> ProcessOutput {
55 let ar = match *maybe_ar_prog {
56 Some(ref ar) => ar.as_slice(),
59 let mut cmd = Command::new(ar);
61 cmd.arg(args).args(paths);
67 debug!("inside {}", p.display());
74 let o = prog.wait_with_output().unwrap();
75 if !o.status.success() {
76 handler.err(format!("{} failed with: {}",
78 o.status).as_slice());
79 handler.note(format!("stdout ---\n{}",
80 str::from_utf8(o.output
81 .as_slice()).unwrap())
83 handler.note(format!("stderr ---\n{}",
84 str::from_utf8(o.error
85 .as_slice()).unwrap())
87 handler.abort_if_errors();
92 handler.err(format!("could not exec `{}`: {}", ar.as_slice(),
94 handler.abort_if_errors();
95 panic!("rustc::back::archive::run_ar() should not reach this point");
100 pub fn find_library(name: &str, osprefix: &str, ossuffix: &str,
101 search_paths: &[Path], handler: &ErrorHandler) -> Path {
102 // On Windows, static libraries sometimes show up as libfoo.a and other
103 // times show up as foo.lib
104 let oslibname = format!("{}{}{}", osprefix, name, ossuffix);
105 let unixlibname = format!("lib{}.a", name);
107 for path in search_paths.iter() {
108 debug!("looking for {} inside {}", name, path.display());
109 let test = path.join(oslibname.as_slice());
110 if test.exists() { return test }
111 if oslibname != unixlibname {
112 let test = path.join(unixlibname.as_slice());
113 if test.exists() { return test }
116 handler.fatal(format!("could not find native static library `{}`, \
117 perhaps an -L flag is missing?",
121 impl<'a> Archive<'a> {
122 fn new(config: ArchiveConfig<'a>) -> Archive<'a> {
123 let ArchiveConfig { handler, dst, lib_search_paths, slib_prefix, slib_suffix,
124 maybe_ar_prog } = config;
128 lib_search_paths: lib_search_paths,
129 slib_prefix: slib_prefix,
130 slib_suffix: slib_suffix,
131 maybe_ar_prog: maybe_ar_prog
135 /// Opens an existing static archive
136 pub fn open(config: ArchiveConfig<'a>) -> Archive<'a> {
137 let archive = Archive::new(config);
138 assert!(archive.dst.exists());
142 /// Removes a file from this archive
143 pub fn remove_file(&mut self, file: &str) {
144 run_ar(self.handler, &self.maybe_ar_prog, "d", None, &[&self.dst, &Path::new(file)]);
147 /// Lists all files in an archive
148 pub fn files(&self) -> Vec<String> {
149 let output = run_ar(self.handler, &self.maybe_ar_prog, "t", None, &[&self.dst]);
150 let output = str::from_utf8(output.output.as_slice()).unwrap();
151 // use lines_any because windows delimits output with `\r\n` instead of
153 output.lines_any().map(|s| s.to_string()).collect()
156 /// Creates an `ArchiveBuilder` for adding files to this archive.
157 pub fn extend(self) -> ArchiveBuilder<'a> {
158 ArchiveBuilder::new(self)
162 impl<'a> ArchiveBuilder<'a> {
163 fn new(archive: Archive<'a>) -> ArchiveBuilder<'a> {
166 work_dir: TempDir::new("rsar").unwrap(),
168 should_update_symbols: false,
172 /// Create a new static archive, ready for adding files.
173 pub fn create(config: ArchiveConfig<'a>) -> ArchiveBuilder<'a> {
174 let archive = Archive::new(config);
175 ArchiveBuilder::new(archive)
178 /// Adds all of the contents of a native library to this archive. This will
179 /// search in the relevant locations for a library named `name`.
180 pub fn add_native_library(&mut self, name: &str) -> io::IoResult<()> {
181 let location = find_library(name,
182 self.archive.slib_prefix.as_slice(),
183 self.archive.slib_suffix.as_slice(),
184 self.archive.lib_search_paths.as_slice(),
185 self.archive.handler);
186 self.add_archive(&location, name, |_| false)
189 /// Adds all of the contents of the rlib at the specified path to this
192 /// This ignores adding the bytecode from the rlib, and if LTO is enabled
193 /// then the object file also isn't added.
194 pub fn add_rlib(&mut self, rlib: &Path, name: &str,
195 lto: bool) -> io::IoResult<()> {
196 // Ignoring obj file starting with the crate name
197 // as simple comparison is not enough - there
198 // might be also an extra name suffix
199 let obj_start = format!("{}", name);
200 let obj_start = obj_start.as_slice();
201 // Ignoring all bytecode files, no matter of
203 let bc_ext = ".bytecode.deflate";
205 self.add_archive(rlib, name.as_slice(), |fname: &str| {
206 let skip_obj = lto && fname.starts_with(obj_start)
207 && fname.ends_with(".o");
208 skip_obj || fname.ends_with(bc_ext) || fname == METADATA_FILENAME
212 /// Adds an arbitrary file to this archive
213 pub fn add_file(&mut self, file: &Path) -> io::IoResult<()> {
214 let filename = Path::new(file.filename().unwrap());
215 let new_file = self.work_dir.path().join(&filename);
216 try!(fs::copy(file, &new_file));
217 self.members.push(filename);
221 /// Indicate that the next call to `build` should updates all symbols in
222 /// the archive (run 'ar s' over it).
223 pub fn update_symbols(&mut self) {
224 self.should_update_symbols = true;
227 /// Combine the provided files, rlibs, and native libraries into a single
229 pub fn build(self) -> Archive<'a> {
230 // Get an absolute path to the destination, so `ar` will work even
231 // though we run it from `self.work_dir`.
232 let abs_dst = os::getcwd().join(&self.archive.dst);
233 assert!(!abs_dst.is_relative());
234 let mut args = vec![&abs_dst];
235 let mut total_len = abs_dst.as_vec().len();
237 if self.members.is_empty() {
238 // OSX `ar` does not allow using `r` with no members, but it does
239 // allow running `ar s file.a` to update symbols only.
240 if self.should_update_symbols {
241 run_ar(self.archive.handler, &self.archive.maybe_ar_prog,
242 "s", Some(self.work_dir.path()), args.as_slice());
247 // Don't allow the total size of `args` to grow beyond 32,000 bytes.
248 // Windows will raise an error if the argument string is longer than
249 // 32,768, and we leave a bit of extra space for the program name.
250 static ARG_LENGTH_LIMIT: uint = 32000;
252 for member_name in self.members.iter() {
253 let len = member_name.as_vec().len();
255 // `len + 1` to account for the space that's inserted before each
256 // argument. (Windows passes command-line arguments as a single
257 // string, not an array of strings.)
258 if total_len + len + 1 > ARG_LENGTH_LIMIT {
259 // Add the archive members seen so far, without updating the
260 // symbol table (`S`).
261 run_ar(self.archive.handler, &self.archive.maybe_ar_prog,
262 "cruS", Some(self.work_dir.path()), args.as_slice());
266 total_len = abs_dst.as_vec().len();
269 args.push(member_name);
270 total_len += len + 1;
273 // Add the remaining archive members, and update the symbol table if
275 let flags = if self.should_update_symbols { "crus" } else { "cruS" };
276 run_ar(self.archive.handler, &self.archive.maybe_ar_prog,
277 flags, Some(self.work_dir.path()), args.as_slice());
282 fn add_archive(&mut self, archive: &Path, name: &str,
283 skip: |&str| -> bool) -> io::IoResult<()> {
284 let loc = TempDir::new("rsar").unwrap();
286 // First, extract the contents of the archive to a temporary directory.
287 // We don't unpack directly into `self.work_dir` due to the possibility
288 // of filename collisions.
289 let archive = os::make_absolute(archive);
290 run_ar(self.archive.handler, &self.archive.maybe_ar_prog,
291 "x", Some(loc.path()), &[&archive]);
293 // Next, we must rename all of the inputs to "guaranteed unique names".
294 // We move each file into `self.work_dir` under its new unique name.
295 // The reason for this renaming is that archives are keyed off the name
296 // of the files, so if two files have the same name they will override
297 // one another in the archive (bad).
299 // We skip any files explicitly desired for skipping, and we also skip
300 // all SYMDEF files as these are just magical placeholders which get
301 // re-created when we make a new archive anyway.
302 let files = try!(fs::readdir(loc.path()));
303 for file in files.iter() {
304 let filename = file.filename_str().unwrap();
305 if skip(filename) { continue }
306 if filename.contains(".SYMDEF") { continue }
308 let filename = format!("r-{}-{}", name, filename);
309 // LLDB (as mentioned in back::link) crashes on filenames of exactly
310 // 16 bytes in length. If we're including an object file with
311 // exactly 16-bytes of characters, give it some prefix so that it's
313 let filename = if filename.len() == 16 {
314 format!("lldb-fix-{}", filename)
318 let new_filename = self.work_dir.path().join(filename.as_slice());
319 try!(fs::rename(file, &new_filename));
320 self.members.push(Path::new(filename));