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::ffi::{CString, CStr, OsString};
16 use std::path::{Path, PathBuf};
21 use llvm::archive_ro::{ArchiveRO, Child};
22 use llvm::{self, ArchiveKind};
23 use metadata::METADATA_FILENAME;
24 use rustc::session::Session;
26 pub struct ArchiveConfig<'a> {
27 pub sess: &'a Session,
29 pub src: Option<PathBuf>,
30 pub lib_search_paths: Vec<PathBuf>,
32 pub command_path: OsString,
35 /// Helper for adding many files to an archive with a single invocation of
37 #[must_use = "must call build() to finish building the archive"]
38 pub struct ArchiveBuilder<'a> {
39 config: ArchiveConfig<'a>,
40 removals: Vec<String>,
41 additions: Vec<Addition>,
42 should_update_symbols: bool,
43 src_archive: Option<Option<ArchiveRO>>,
49 name_in_archive: String,
53 skip: Box<FnMut(&str) -> bool>,
57 pub fn find_library(name: &str, search_paths: &[PathBuf], sess: &Session)
59 // On Windows, static libraries sometimes show up as libfoo.a and other
60 // times show up as foo.lib
61 let oslibname = format!("{}{}{}",
62 sess.target.target.options.staticlib_prefix,
64 sess.target.target.options.staticlib_suffix);
65 let unixlibname = format!("lib{}.a", name);
67 for path in search_paths {
68 debug!("looking for {} inside {:?}", name, path);
69 let test = path.join(&oslibname);
70 if test.exists() { return test }
71 if oslibname != unixlibname {
72 let test = path.join(&unixlibname);
73 if test.exists() { return test }
76 sess.fatal(&format!("could not find native static library `{}`, \
77 perhaps an -L flag is missing?", name));
80 fn is_relevant_child(c: &Child) -> bool {
82 Some(name) => !name.contains("SYMDEF"),
87 impl<'a> ArchiveBuilder<'a> {
88 /// Create a new static archive, ready for modifying the archive specified
90 pub fn new(config: ArchiveConfig<'a>) -> ArchiveBuilder<'a> {
94 additions: Vec::new(),
95 should_update_symbols: false,
100 /// Removes a file from this archive
101 pub fn remove_file(&mut self, file: &str) {
102 self.removals.push(file.to_string());
105 /// Lists all files in an archive
106 pub fn src_files(&mut self) -> Vec<String> {
107 if self.src_archive().is_none() {
110 let archive = self.src_archive.as_ref().unwrap().as_ref().unwrap();
111 let ret = archive.iter()
112 .filter_map(|child| child.ok())
113 .filter(is_relevant_child)
114 .filter_map(|child| child.name())
115 .filter(|name| !self.removals.iter().any(|x| x == name))
116 .map(|name| name.to_string())
121 fn src_archive(&mut self) -> Option<&ArchiveRO> {
122 if let Some(ref a) = self.src_archive {
125 let src = match self.config.src {
126 Some(ref src) => src,
129 self.src_archive = Some(ArchiveRO::open(src).ok());
130 self.src_archive.as_ref().unwrap().as_ref()
133 /// Adds all of the contents of a native library to this archive. This will
134 /// search in the relevant locations for a library named `name`.
135 pub fn add_native_library(&mut self, name: &str) {
136 let location = find_library(name, &self.config.lib_search_paths,
138 self.add_archive(&location, |_| false).unwrap_or_else(|e| {
139 self.config.sess.fatal(&format!("failed to add native library {}: {}",
140 location.to_string_lossy(), e));
144 /// Adds all of the contents of the rlib at the specified path to this
147 /// This ignores adding the bytecode from the rlib, and if LTO is enabled
148 /// then the object file also isn't added.
149 pub fn add_rlib(&mut self,
153 skip_objects: bool) -> io::Result<()> {
154 // Ignoring obj file starting with the crate name
155 // as simple comparison is not enough - there
156 // might be also an extra name suffix
157 let obj_start = format!("{}", name);
159 // Ignoring all bytecode files, no matter of
161 let bc_ext = ".bytecode.deflate";
163 self.add_archive(rlib, move |fname: &str| {
164 if fname.ends_with(bc_ext) || fname == METADATA_FILENAME {
168 // Don't include Rust objects if LTO is enabled
169 if lto && fname.starts_with(&obj_start) && fname.ends_with(".o") {
173 // Otherwise if this is *not* a rust object and we're skipping
174 // objects then skip this file
175 if skip_objects && (!fname.starts_with(&obj_start) || !fname.ends_with(".o")) {
179 // ok, don't skip this
184 fn add_archive<F>(&mut self, archive: &Path, skip: F)
186 where F: FnMut(&str) -> bool + 'static
188 let archive = match ArchiveRO::open(archive) {
190 Err(e) => return Err(io::Error::new(io::ErrorKind::Other, e)),
192 self.additions.push(Addition::Archive {
194 skip: Box::new(skip),
199 /// Adds an arbitrary file to this archive
200 pub fn add_file(&mut self, file: &Path) {
201 let name = file.file_name().unwrap().to_str().unwrap();
202 self.additions.push(Addition::File {
203 path: file.to_path_buf(),
204 name_in_archive: name.to_string(),
208 /// Indicate that the next call to `build` should updates all symbols in
209 /// the archive (run 'ar s' over it).
210 pub fn update_symbols(&mut self) {
211 self.should_update_symbols = true;
214 /// Combine the provided files, rlibs, and native libraries into a single
216 pub fn build(&mut self) {
217 let kind = match self.llvm_archive_kind() {
220 self.config.sess.fatal(&format!("Don't know how to build archive of type: {}",
225 if let Err(e) = self.build_with_llvm(kind) {
226 self.config.sess.fatal(&format!("failed to build archive: {}", e));
231 fn llvm_archive_kind(&self) -> Result<ArchiveKind, &str> {
232 let kind = &*self.config.sess.target.target.options.archive_format;
233 kind.parse().map_err(|_| kind)
236 fn build_with_llvm(&mut self, kind: ArchiveKind) -> io::Result<()> {
237 let mut archives = Vec::new();
238 let mut strings = Vec::new();
239 let mut members = Vec::new();
240 let removals = mem::replace(&mut self.removals, Vec::new());
243 if let Some(archive) = self.src_archive() {
244 for child in archive.iter() {
245 let child = child.map_err(string_to_io_error)?;
246 let child_name = match child.name() {
250 if removals.iter().any(|r| r == child_name) {
254 let name = CString::new(child_name)?;
255 members.push(llvm::LLVMRustArchiveMemberNew(ptr::null(),
261 for addition in mem::replace(&mut self.additions, Vec::new()) {
263 Addition::File { path, name_in_archive } => {
264 let path = CString::new(path.to_str().unwrap())?;
265 let name = CString::new(name_in_archive)?;
266 members.push(llvm::LLVMRustArchiveMemberNew(path.as_ptr(),
272 Addition::Archive { archive, mut skip } => {
273 for child in archive.iter() {
274 let child = child.map_err(string_to_io_error)?;
275 if !is_relevant_child(&child) {
278 let child_name = child.name().unwrap();
279 if skip(child_name) {
283 // It appears that LLVM's archive writer is a little
284 // buggy if the name we pass down isn't just the
285 // filename component, so chop that off here and
288 // See LLVM bug 25877 for more info.
289 let child_name = Path::new(child_name)
290 .file_name().unwrap()
292 let name = CString::new(child_name)?;
293 let m = llvm::LLVMRustArchiveMemberNew(ptr::null(),
299 archives.push(archive);
304 let dst = self.config.dst.to_str().unwrap().as_bytes();
305 let dst = CString::new(dst)?;
306 let r = llvm::LLVMRustWriteArchive(dst.as_ptr(),
307 members.len() as libc::size_t,
309 self.should_update_symbols,
311 let ret = if r.into_result().is_err() {
312 let err = llvm::LLVMRustGetLastError();
313 let msg = if err.is_null() {
314 "failed to write archive".to_string()
316 String::from_utf8_lossy(CStr::from_ptr(err).to_bytes())
319 Err(io::Error::new(io::ErrorKind::Other, msg))
323 for member in members {
324 llvm::LLVMRustArchiveMemberFree(member);
331 fn string_to_io_error(s: String) -> io::Error {
332 io::Error::new(io::ErrorKind::Other, format!("bad archive: {}", s))