]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/back/archive.rs
Auto merge of #43710 - zackmdavis:field_init_shorthand_power_slam, r=Mark-Simulacrum
[rust.git] / src / librustc_trans / back / archive.rs
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.
4 //
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.
10
11 //! A helper class for dealing with static archives
12
13 use std::ffi::{CString, CStr, OsString};
14 use std::io;
15 use std::mem;
16 use std::path::{Path, PathBuf};
17 use std::ptr;
18 use std::str;
19
20 use libc;
21 use llvm::archive_ro::{ArchiveRO, Child};
22 use llvm::{self, ArchiveKind};
23 use metadata::METADATA_FILENAME;
24 use rustc::session::Session;
25
26 pub struct ArchiveConfig<'a> {
27     pub sess: &'a Session,
28     pub dst: PathBuf,
29     pub src: Option<PathBuf>,
30     pub lib_search_paths: Vec<PathBuf>,
31     pub ar_prog: String,
32     pub command_path: OsString,
33 }
34
35 /// Helper for adding many files to an archive with a single invocation of
36 /// `ar`.
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>>,
44 }
45
46 enum Addition {
47     File {
48         path: PathBuf,
49         name_in_archive: String,
50     },
51     Archive {
52         archive: ArchiveRO,
53         skip: Box<FnMut(&str) -> bool>,
54     },
55 }
56
57 pub fn find_library(name: &str, search_paths: &[PathBuf], sess: &Session)
58                     -> PathBuf {
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,
63                             name,
64                             sess.target.target.options.staticlib_suffix);
65     let unixlibname = format!("lib{}.a", name);
66
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 }
74         }
75     }
76     sess.fatal(&format!("could not find native static library `{}`, \
77                          perhaps an -L flag is missing?", name));
78 }
79
80 fn is_relevant_child(c: &Child) -> bool {
81     match c.name() {
82         Some(name) => !name.contains("SYMDEF"),
83         None => false,
84     }
85 }
86
87 impl<'a> ArchiveBuilder<'a> {
88     /// Create a new static archive, ready for modifying the archive specified
89     /// by `config`.
90     pub fn new(config: ArchiveConfig<'a>) -> ArchiveBuilder<'a> {
91         ArchiveBuilder {
92             config,
93             removals: Vec::new(),
94             additions: Vec::new(),
95             should_update_symbols: false,
96             src_archive: None,
97         }
98     }
99
100     /// Removes a file from this archive
101     pub fn remove_file(&mut self, file: &str) {
102         self.removals.push(file.to_string());
103     }
104
105     /// Lists all files in an archive
106     pub fn src_files(&mut self) -> Vec<String> {
107         if self.src_archive().is_none() {
108             return Vec::new()
109         }
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())
117                          .collect();
118         return ret;
119     }
120
121     fn src_archive(&mut self) -> Option<&ArchiveRO> {
122         if let Some(ref a) = self.src_archive {
123             return a.as_ref()
124         }
125         let src = match self.config.src {
126             Some(ref src) => src,
127             None => return None,
128         };
129         self.src_archive = Some(ArchiveRO::open(src).ok());
130         self.src_archive.as_ref().unwrap().as_ref()
131     }
132
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,
137                                     self.config.sess);
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));
141         });
142     }
143
144     /// Adds all of the contents of the rlib at the specified path to this
145     /// archive.
146     ///
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,
150                     rlib: &Path,
151                     name: &str,
152                     lto: bool,
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);
158
159         // Ignoring all bytecode files, no matter of
160         // name
161         let bc_ext = ".bytecode.deflate";
162
163         self.add_archive(rlib, move |fname: &str| {
164             if fname.ends_with(bc_ext) || fname == METADATA_FILENAME {
165                 return true
166             }
167
168             // Don't include Rust objects if LTO is enabled
169             if lto && fname.starts_with(&obj_start) && fname.ends_with(".o") {
170                 return true
171             }
172
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")) {
176                 return true
177             }
178
179             // ok, don't skip this
180             return false
181         })
182     }
183
184     fn add_archive<F>(&mut self, archive: &Path, skip: F)
185                       -> io::Result<()>
186         where F: FnMut(&str) -> bool + 'static
187     {
188         let archive = match ArchiveRO::open(archive) {
189             Ok(ar) => ar,
190             Err(e) => return Err(io::Error::new(io::ErrorKind::Other, e)),
191         };
192         self.additions.push(Addition::Archive {
193             archive,
194             skip: Box::new(skip),
195         });
196         Ok(())
197     }
198
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(),
205         });
206     }
207
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;
212     }
213
214     /// Combine the provided files, rlibs, and native libraries into a single
215     /// `Archive`.
216     pub fn build(&mut self) {
217         let kind = match self.llvm_archive_kind() {
218             Ok(kind) => kind,
219             Err(kind) => {
220                 self.config.sess.fatal(&format!("Don't know how to build archive of type: {}",
221                                                 kind));
222             }
223         };
224
225         if let Err(e) = self.build_with_llvm(kind) {
226             self.config.sess.fatal(&format!("failed to build archive: {}", e));
227         }
228
229     }
230
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)
234     }
235
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());
241
242         unsafe {
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() {
247                         Some(s) => s,
248                         None => continue,
249                     };
250                     if removals.iter().any(|r| r == child_name) {
251                         continue
252                     }
253
254                     let name = CString::new(child_name)?;
255                     members.push(llvm::LLVMRustArchiveMemberNew(ptr::null(),
256                                                                 name.as_ptr(),
257                                                                 child.raw()));
258                     strings.push(name);
259                 }
260             }
261             for addition in mem::replace(&mut self.additions, Vec::new()) {
262                 match addition {
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(),
267                                                                     name.as_ptr(),
268                                                                     ptr::null_mut()));
269                         strings.push(path);
270                         strings.push(name);
271                     }
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) {
276                                 continue
277                             }
278                             let child_name = child.name().unwrap();
279                             if skip(child_name) {
280                                 continue
281                             }
282
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
286                             // pass it in.
287                             //
288                             // See LLVM bug 25877 for more info.
289                             let child_name = Path::new(child_name)
290                                                   .file_name().unwrap()
291                                                   .to_str().unwrap();
292                             let name = CString::new(child_name)?;
293                             let m = llvm::LLVMRustArchiveMemberNew(ptr::null(),
294                                                                    name.as_ptr(),
295                                                                    child.raw());
296                             members.push(m);
297                             strings.push(name);
298                         }
299                         archives.push(archive);
300                     }
301                 }
302             }
303
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,
308                                                members.as_ptr(),
309                                                self.should_update_symbols,
310                                                kind);
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()
315                 } else {
316                     String::from_utf8_lossy(CStr::from_ptr(err).to_bytes())
317                             .into_owned()
318                 };
319                 Err(io::Error::new(io::ErrorKind::Other, msg))
320             } else {
321                 Ok(())
322             };
323             for member in members {
324                 llvm::LLVMRustArchiveMemberFree(member);
325             }
326             return ret
327         }
328     }
329 }
330
331 fn string_to_io_error(s: String) -> io::Error {
332     io::Error::new(io::ErrorKind::Other, format!("bad archive: {}", s))
333 }