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 back::link::{get_ar_prog};
14 use driver::session::Session;
15 use metadata::filesearch;
16 use lib::llvm::{ArchiveRef, llvm};
23 use std::io::process::{ProcessConfig, Process, ProcessOutput};
26 use extra::tempfile::TempDir;
29 pub static METADATA_FILENAME: &'static str = "rust.metadata.bin";
36 pub struct ArchiveRO {
40 fn run_ar(sess: Session, args: &str, cwd: Option<&Path>,
41 paths: &[&Path]) -> ProcessOutput {
42 let ar = get_ar_prog(sess);
44 let mut args = ~[args.to_owned()];
45 let mut paths = paths.iter().map(|p| p.as_str().unwrap().to_owned());
46 args.extend(&mut paths);
47 debug!("{} {}", ar, args.connect(" "));
49 Some(p) => { debug!("inside {}", p.display()); }
52 match Process::configure(ProcessConfig {
53 program: ar.as_slice(),
54 args: args.as_slice(),
55 cwd: cwd.map(|a| &*a),
56 .. ProcessConfig::new()
59 let o = prog.wait_with_output();
60 if !o.status.success() {
61 sess.err(format!("{} {} failed with: {}", ar, args.connect(" "),
63 sess.note(format!("stdout ---\n{}", str::from_utf8(o.output).unwrap()));
64 sess.note(format!("stderr ---\n{}", str::from_utf8(o.error).unwrap()));
65 sess.abort_if_errors();
70 sess.err(format!("could not exec `{}`: {}", ar, e));
71 sess.abort_if_errors();
72 fail!("rustc::back::archive::run_ar() should not reach this point");
78 /// Initializes a new static archive with the given object file
79 pub fn create<'a>(sess: Session, dst: &'a Path,
80 initial_object: &'a Path) -> Archive {
81 run_ar(sess, "crus", None, [dst, initial_object]);
82 Archive { sess: sess, dst: dst.clone() }
85 /// Opens an existing static archive
86 pub fn open(sess: Session, dst: Path) -> Archive {
87 assert!(dst.exists());
88 Archive { sess: sess, dst: dst }
91 /// Read a file in the archive
92 pub fn read(&self, file: &str) -> ~[u8] {
93 // Apparently if "ar p" is used on windows, it generates a corrupt file
94 // which has bad headers and LLVM will immediately choke on it
95 if cfg!(windows) && cfg!(windows) { // FIXME(#10734) double-and
96 let loc = TempDir::new("rsar").unwrap();
97 let archive = os::make_absolute(&self.dst);
98 run_ar(self.sess, "x", Some(loc.path()), [&archive,
100 fs::File::open(&loc.path().join(file)).read_to_end().unwrap()
102 run_ar(self.sess, "p", None, [&self.dst, &Path::new(file)]).output
106 /// Adds all of the contents of a native library to this archive. This will
107 /// search in the relevant locations for a library named `name`.
108 pub fn add_native_library(&mut self, name: &str) -> io::IoResult<()> {
109 let location = self.find_library(name);
110 self.add_archive(&location, name, [])
113 /// Adds all of the contents of the rlib at the specified path to this
116 /// This ignores adding the bytecode from the rlib, and if LTO is enabled
117 /// then the object file also isn't added.
118 pub fn add_rlib(&mut self, rlib: &Path, name: &str,
119 lto: bool) -> io::IoResult<()> {
120 let object = format!("{}.o", name);
121 let bytecode = format!("{}.bc", name);
122 let mut ignore = ~[METADATA_FILENAME, bytecode.as_slice()];
124 ignore.push(object.as_slice());
126 self.add_archive(rlib, name, ignore)
129 /// Adds an arbitrary file to this archive
130 pub fn add_file(&mut self, file: &Path, has_symbols: bool) {
131 let cmd = if has_symbols {"r"} else {"rS"};
132 run_ar(self.sess, cmd, None, [&self.dst, file]);
135 /// Removes a file from this archive
136 pub fn remove_file(&mut self, file: &str) {
137 run_ar(self.sess, "d", None, [&self.dst, &Path::new(file)]);
140 /// Updates all symbols in the archive (runs 'ar s' over it)
141 pub fn update_symbols(&mut self) {
142 run_ar(self.sess, "s", None, [&self.dst]);
145 /// Lists all files in an archive
146 pub fn files(&self) -> ~[~str] {
147 let output = run_ar(self.sess, "t", None, [&self.dst]);
148 let output = str::from_utf8(output.output).unwrap();
149 // use lines_any because windows delimits output with `\r\n` instead of
151 output.lines_any().map(|s| s.to_owned()).collect()
154 fn add_archive(&mut self, archive: &Path, name: &str,
155 skip: &[&str]) -> io::IoResult<()> {
156 let loc = TempDir::new("rsar").unwrap();
158 // First, extract the contents of the archive to a temporary directory
159 let archive = os::make_absolute(archive);
160 run_ar(self.sess, "x", Some(loc.path()), [&archive]);
162 // Next, we must rename all of the inputs to "guaranteed unique names".
163 // The reason for this is that archives are keyed off the name of the
164 // files, so if two files have the same name they will override one
165 // another in the archive (bad).
167 // We skip any files explicitly desired for skipping, and we also skip
168 // all SYMDEF files as these are just magical placeholders which get
169 // re-created when we make a new archive anyway.
170 let files = try!(fs::readdir(loc.path()));
171 let mut inputs = ~[];
172 for file in files.iter() {
173 let filename = file.filename_str().unwrap();
174 if skip.iter().any(|s| *s == filename) { continue }
175 if filename.contains(".SYMDEF") { continue }
177 let filename = format!("r-{}-{}", name, filename);
178 let new_filename = file.with_filename(filename);
179 try!(fs::rename(file, &new_filename));
180 inputs.push(new_filename);
182 if inputs.len() == 0 { return Ok(()) }
184 // Finally, add all the renamed files to this archive
185 let mut args = ~[&self.dst];
186 args.extend(&mut inputs.iter());
187 run_ar(self.sess, "r", None, args.as_slice());
191 fn find_library(&self, name: &str) -> Path {
192 let (osprefix, osext) = match self.sess.targ_cfg.os {
193 abi::OsWin32 => ("", "lib"), _ => ("lib", "a"),
195 // On Windows, static libraries sometimes show up as libfoo.a and other
196 // times show up as foo.lib
197 let oslibname = format!("{}{}.{}", osprefix, name, osext);
198 let unixlibname = format!("lib{}.a", name);
200 let mut rustpath = filesearch::rust_path();
201 rustpath.push(self.sess.filesearch.get_target_lib_path());
202 let addl_lib_search_paths = self.sess
204 .addl_lib_search_paths
206 let path = addl_lib_search_paths.get().iter();
207 for path in path.chain(rustpath.iter()) {
208 debug!("looking for {} inside {}", name, path.display());
209 let test = path.join(oslibname.as_slice());
210 if test.exists() { return test }
211 if oslibname != unixlibname {
212 let test = path.join(unixlibname.as_slice());
213 if test.exists() { return test }
216 self.sess.fatal(format!("could not find native static library `{}`, \
217 perhaps an -L flag is missing?", name));
222 /// Opens a static archive for read-only purposes. This is more optimized
223 /// than the `open` method because it uses LLVM's internal `Archive` class
224 /// rather than shelling out to `ar` for everything.
226 /// If this archive is used with a mutable method, then an error will be
228 pub fn open(dst: &Path) -> Option<ArchiveRO> {
230 let ar = dst.with_c_str(|dst| {
231 llvm::LLVMRustOpenArchive(dst)
236 Some(ArchiveRO { ptr: ar })
241 /// Reads a file in the archive
242 pub fn read<'a>(&'a self, file: &str) -> Option<&'a [u8]> {
244 let mut size = 0 as libc::size_t;
245 let ptr = file.with_c_str(|file| {
246 llvm::LLVMRustArchiveReadSection(self.ptr, file, &mut size)
251 Some(cast::transmute(raw::Slice {
260 impl Drop for ArchiveRO {
263 llvm::LLVMRustDestroyArchive(self.ptr);