]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/back/linker.rs
Add support for full RELRO
[rust.git] / src / librustc_trans / back / linker.rs
1 // Copyright 2015 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 use std::collections::HashMap;
12 use std::ffi::{OsStr, OsString};
13 use std::fs::{self, File};
14 use std::io::prelude::*;
15 use std::io::{self, BufWriter};
16 use std::path::{Path, PathBuf};
17 use std::process::Command;
18
19 use context::SharedCrateContext;
20
21 use back::archive;
22 use back::symbol_export::{self, ExportedSymbols};
23 use rustc::middle::dependency_format::Linkage;
24 use rustc::hir::def_id::{LOCAL_CRATE, CrateNum};
25 use rustc_back::LinkerFlavor;
26 use rustc::session::Session;
27 use rustc::session::config::{self, CrateType, OptLevel, DebugInfoLevel};
28 use serialize::{json, Encoder};
29
30 /// For all the linkers we support, and information they might
31 /// need out of the shared crate context before we get rid of it.
32 pub struct LinkerInfo {
33     exports: HashMap<CrateType, Vec<String>>,
34 }
35
36 impl<'a, 'tcx> LinkerInfo {
37     pub fn new(scx: &SharedCrateContext<'a, 'tcx>,
38                exports: &ExportedSymbols) -> LinkerInfo {
39         LinkerInfo {
40             exports: scx.sess().crate_types.borrow().iter().map(|&c| {
41                 (c, exported_symbols(scx, exports, c))
42             }).collect(),
43         }
44     }
45
46     pub fn to_linker(&'a self,
47                      cmd: Command,
48                      sess: &'a Session) -> Box<Linker+'a> {
49         match sess.linker_flavor() {
50             LinkerFlavor::Msvc => {
51                 Box::new(MsvcLinker {
52                     cmd: cmd,
53                     sess: sess,
54                     info: self
55                 }) as Box<Linker>
56             }
57             LinkerFlavor::Em =>  {
58                 Box::new(EmLinker {
59                     cmd: cmd,
60                     sess: sess,
61                     info: self
62                 }) as Box<Linker>
63             }
64             LinkerFlavor::Gcc =>  {
65                 Box::new(GccLinker {
66                     cmd: cmd,
67                     sess: sess,
68                     info: self,
69                     hinted_static: false,
70                     is_ld: false,
71                 }) as Box<Linker>
72             }
73             LinkerFlavor::Ld => {
74                 Box::new(GccLinker {
75                     cmd: cmd,
76                     sess: sess,
77                     info: self,
78                     hinted_static: false,
79                     is_ld: true,
80                 }) as Box<Linker>
81             }
82         }
83     }
84 }
85
86 /// Linker abstraction used by back::link to build up the command to invoke a
87 /// linker.
88 ///
89 /// This trait is the total list of requirements needed by `back::link` and
90 /// represents the meaning of each option being passed down. This trait is then
91 /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
92 /// MSVC linker (e.g. `link.exe`) is being used.
93 pub trait Linker {
94     fn link_dylib(&mut self, lib: &str);
95     fn link_rust_dylib(&mut self, lib: &str, path: &Path);
96     fn link_framework(&mut self, framework: &str);
97     fn link_staticlib(&mut self, lib: &str);
98     fn link_rlib(&mut self, lib: &Path);
99     fn link_whole_rlib(&mut self, lib: &Path);
100     fn link_whole_staticlib(&mut self, lib: &str, search_path: &[PathBuf]);
101     fn include_path(&mut self, path: &Path);
102     fn framework_path(&mut self, path: &Path);
103     fn output_filename(&mut self, path: &Path);
104     fn add_object(&mut self, path: &Path);
105     fn gc_sections(&mut self, keep_metadata: bool);
106     fn position_independent_executable(&mut self);
107     fn full_relro(&mut self);
108     fn optimize(&mut self);
109     fn debuginfo(&mut self);
110     fn no_default_libraries(&mut self);
111     fn build_dylib(&mut self, out_filename: &Path);
112     fn args(&mut self, args: &[String]);
113     fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType);
114     fn subsystem(&mut self, subsystem: &str);
115     // Should have been finalize(self), but we don't support self-by-value on trait objects (yet?).
116     fn finalize(&mut self) -> Command;
117 }
118
119 pub struct GccLinker<'a> {
120     cmd: Command,
121     sess: &'a Session,
122     info: &'a LinkerInfo,
123     hinted_static: bool, // Keeps track of the current hinting mode.
124     // Link as ld
125     is_ld: bool,
126 }
127
128 impl<'a> GccLinker<'a> {
129     /// Argument that must be passed *directly* to the linker
130     ///
131     /// These arguments need to be prepended with '-Wl,' when a gcc-style linker is used
132     fn linker_arg<S>(&mut self, arg: S) -> &mut Self
133         where S: AsRef<OsStr>
134     {
135         if !self.is_ld {
136             let mut os = OsString::from("-Wl,");
137             os.push(arg.as_ref());
138             self.cmd.arg(os);
139         } else {
140             self.cmd.arg(arg);
141         }
142         self
143     }
144
145     fn takes_hints(&self) -> bool {
146         !self.sess.target.target.options.is_like_osx
147     }
148
149     // Some platforms take hints about whether a library is static or dynamic.
150     // For those that support this, we ensure we pass the option if the library
151     // was flagged "static" (most defaults are dynamic) to ensure that if
152     // libfoo.a and libfoo.so both exist that the right one is chosen.
153     fn hint_static(&mut self) {
154         if !self.takes_hints() { return }
155         if !self.hinted_static {
156             self.linker_arg("-Bstatic");
157             self.hinted_static = true;
158         }
159     }
160
161     fn hint_dynamic(&mut self) {
162         if !self.takes_hints() { return }
163         if self.hinted_static {
164             self.linker_arg("-Bdynamic");
165             self.hinted_static = false;
166         }
167     }
168 }
169
170 impl<'a> Linker for GccLinker<'a> {
171     fn link_dylib(&mut self, lib: &str) { self.hint_dynamic(); self.cmd.arg("-l").arg(lib); }
172     fn link_staticlib(&mut self, lib: &str) { self.hint_static(); self.cmd.arg("-l").arg(lib); }
173     fn link_rlib(&mut self, lib: &Path) { self.hint_static(); self.cmd.arg(lib); }
174     fn include_path(&mut self, path: &Path) { self.cmd.arg("-L").arg(path); }
175     fn framework_path(&mut self, path: &Path) { self.cmd.arg("-F").arg(path); }
176     fn output_filename(&mut self, path: &Path) { self.cmd.arg("-o").arg(path); }
177     fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
178     fn position_independent_executable(&mut self) { self.cmd.arg("-pie"); }
179     fn full_relro(&mut self) { self.linker_arg("-z,relro,-z,now"); }
180     fn args(&mut self, args: &[String]) { self.cmd.args(args); }
181
182     fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
183         self.hint_dynamic();
184         self.cmd.arg("-l").arg(lib);
185     }
186
187     fn link_framework(&mut self, framework: &str) {
188         self.hint_dynamic();
189         self.cmd.arg("-framework").arg(framework);
190     }
191
192     // Here we explicitly ask that the entire archive is included into the
193     // result artifact. For more details see #15460, but the gist is that
194     // the linker will strip away any unused objects in the archive if we
195     // don't otherwise explicitly reference them. This can occur for
196     // libraries which are just providing bindings, libraries with generic
197     // functions, etc.
198     fn link_whole_staticlib(&mut self, lib: &str, search_path: &[PathBuf]) {
199         self.hint_static();
200         let target = &self.sess.target.target;
201         if !target.options.is_like_osx {
202             self.linker_arg("--whole-archive").cmd.arg("-l").arg(lib);
203             self.linker_arg("--no-whole-archive");
204         } else {
205             // -force_load is the macOS equivalent of --whole-archive, but it
206             // involves passing the full path to the library to link.
207             let mut v = OsString::from("-force_load,");
208             v.push(&archive::find_library(lib, search_path, &self.sess));
209             self.linker_arg(&v);
210         }
211     }
212
213     fn link_whole_rlib(&mut self, lib: &Path) {
214         self.hint_static();
215         if self.sess.target.target.options.is_like_osx {
216             let mut v = OsString::from("-force_load,");
217             v.push(lib);
218             self.linker_arg(&v);
219         } else {
220             self.linker_arg("--whole-archive").cmd.arg(lib);
221             self.linker_arg("--no-whole-archive");
222         }
223     }
224
225     fn gc_sections(&mut self, keep_metadata: bool) {
226         // The dead_strip option to the linker specifies that functions and data
227         // unreachable by the entry point will be removed. This is quite useful
228         // with Rust's compilation model of compiling libraries at a time into
229         // one object file. For example, this brings hello world from 1.7MB to
230         // 458K.
231         //
232         // Note that this is done for both executables and dynamic libraries. We
233         // won't get much benefit from dylibs because LLVM will have already
234         // stripped away as much as it could. This has not been seen to impact
235         // link times negatively.
236         //
237         // -dead_strip can't be part of the pre_link_args because it's also used
238         // for partial linking when using multiple codegen units (-r).  So we
239         // insert it here.
240         if self.sess.target.target.options.is_like_osx {
241             self.linker_arg("-dead_strip");
242         } else if self.sess.target.target.options.is_like_solaris {
243             self.linker_arg("-z");
244             self.linker_arg("ignore");
245
246         // If we're building a dylib, we don't use --gc-sections because LLVM
247         // has already done the best it can do, and we also don't want to
248         // eliminate the metadata. If we're building an executable, however,
249         // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
250         // reduction.
251         } else if !keep_metadata {
252             self.linker_arg("--gc-sections");
253         }
254     }
255
256     fn optimize(&mut self) {
257         if !self.sess.target.target.options.linker_is_gnu { return }
258
259         // GNU-style linkers support optimization with -O. GNU ld doesn't
260         // need a numeric argument, but other linkers do.
261         if self.sess.opts.optimize == config::OptLevel::Default ||
262            self.sess.opts.optimize == config::OptLevel::Aggressive {
263             self.linker_arg("-O1");
264         }
265     }
266
267     fn debuginfo(&mut self) {
268         // Don't do anything special here for GNU-style linkers.
269     }
270
271     fn no_default_libraries(&mut self) {
272         if !self.is_ld {
273             self.cmd.arg("-nodefaultlibs");
274         }
275     }
276
277     fn build_dylib(&mut self, out_filename: &Path) {
278         // On mac we need to tell the linker to let this library be rpathed
279         if self.sess.target.target.options.is_like_osx {
280             self.cmd.arg("-dynamiclib");
281             self.linker_arg("-dylib");
282
283             // Note that the `osx_rpath_install_name` option here is a hack
284             // purely to support rustbuild right now, we should get a more
285             // principled solution at some point to force the compiler to pass
286             // the right `-Wl,-install_name` with an `@rpath` in it.
287             if self.sess.opts.cg.rpath ||
288                self.sess.opts.debugging_opts.osx_rpath_install_name {
289                 let mut v = OsString::from("-install_name,@rpath/");
290                 v.push(out_filename.file_name().unwrap());
291                 self.linker_arg(&v);
292             }
293         } else {
294             self.cmd.arg("-shared");
295         }
296     }
297
298     fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
299         // If we're compiling a dylib, then we let symbol visibility in object
300         // files to take care of whether they're exported or not.
301         //
302         // If we're compiling a cdylib, however, we manually create a list of
303         // exported symbols to ensure we don't expose any more. The object files
304         // have far more public symbols than we actually want to export, so we
305         // hide them all here.
306         if crate_type == CrateType::CrateTypeDylib ||
307            crate_type == CrateType::CrateTypeProcMacro {
308             return
309         }
310
311         let mut arg = OsString::new();
312         let path = tmpdir.join("list");
313
314         debug!("EXPORTED SYMBOLS:");
315
316         if self.sess.target.target.options.is_like_osx {
317             // Write a plain, newline-separated list of symbols
318             let res = (|| -> io::Result<()> {
319                 let mut f = BufWriter::new(File::create(&path)?);
320                 for sym in self.info.exports[&crate_type].iter() {
321                     debug!("  _{}", sym);
322                     writeln!(f, "_{}", sym)?;
323                 }
324                 Ok(())
325             })();
326             if let Err(e) = res {
327                 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
328             }
329         } else {
330             // Write an LD version script
331             let res = (|| -> io::Result<()> {
332                 let mut f = BufWriter::new(File::create(&path)?);
333                 writeln!(f, "{{\n  global:")?;
334                 for sym in self.info.exports[&crate_type].iter() {
335                     debug!("    {};", sym);
336                     writeln!(f, "    {};", sym)?;
337                 }
338                 writeln!(f, "\n  local:\n    *;\n}};")?;
339                 Ok(())
340             })();
341             if let Err(e) = res {
342                 self.sess.fatal(&format!("failed to write version script: {}", e));
343             }
344         }
345
346         if self.sess.target.target.options.is_like_osx {
347             if !self.is_ld {
348                 arg.push("-Wl,")
349             }
350             arg.push("-exported_symbols_list,");
351         } else if self.sess.target.target.options.is_like_solaris {
352             if !self.is_ld {
353                 arg.push("-Wl,")
354             }
355             arg.push("-M,");
356         } else {
357             if !self.is_ld {
358                 arg.push("-Wl,")
359             }
360             arg.push("--version-script=");
361         }
362
363         arg.push(&path);
364         self.cmd.arg(arg);
365     }
366
367     fn subsystem(&mut self, subsystem: &str) {
368         self.linker_arg(&format!("--subsystem,{}", subsystem));
369     }
370
371     fn finalize(&mut self) -> Command {
372         self.hint_dynamic(); // Reset to default before returning the composed command line.
373         let mut cmd = Command::new("");
374         ::std::mem::swap(&mut cmd, &mut self.cmd);
375         cmd
376     }
377 }
378
379 pub struct MsvcLinker<'a> {
380     cmd: Command,
381     sess: &'a Session,
382     info: &'a LinkerInfo
383 }
384
385 impl<'a> Linker for MsvcLinker<'a> {
386     fn link_rlib(&mut self, lib: &Path) { self.cmd.arg(lib); }
387     fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
388     fn args(&mut self, args: &[String]) { self.cmd.args(args); }
389
390     fn build_dylib(&mut self, out_filename: &Path) {
391         self.cmd.arg("/DLL");
392         let mut arg: OsString = "/IMPLIB:".into();
393         arg.push(out_filename.with_extension("dll.lib"));
394         self.cmd.arg(arg);
395     }
396
397     fn gc_sections(&mut self, _keep_metadata: bool) {
398         // MSVC's ICF (Identical COMDAT Folding) link optimization is
399         // slow for Rust and thus we disable it by default when not in
400         // optimization build.
401         if self.sess.opts.optimize != config::OptLevel::No {
402             self.cmd.arg("/OPT:REF,ICF");
403         } else {
404             // It is necessary to specify NOICF here, because /OPT:REF
405             // implies ICF by default.
406             self.cmd.arg("/OPT:REF,NOICF");
407         }
408     }
409
410     fn link_dylib(&mut self, lib: &str) {
411         self.cmd.arg(&format!("{}.lib", lib));
412     }
413
414     fn link_rust_dylib(&mut self, lib: &str, path: &Path) {
415         // When producing a dll, the MSVC linker may not actually emit a
416         // `foo.lib` file if the dll doesn't actually export any symbols, so we
417         // check to see if the file is there and just omit linking to it if it's
418         // not present.
419         let name = format!("{}.dll.lib", lib);
420         if fs::metadata(&path.join(&name)).is_ok() {
421             self.cmd.arg(name);
422         }
423     }
424
425     fn link_staticlib(&mut self, lib: &str) {
426         self.cmd.arg(&format!("{}.lib", lib));
427     }
428
429     fn position_independent_executable(&mut self) {
430         // noop
431     }
432
433     fn full_relro(&mut self) {
434         // noop
435     }
436
437     fn no_default_libraries(&mut self) {
438         // Currently we don't pass the /NODEFAULTLIB flag to the linker on MSVC
439         // as there's been trouble in the past of linking the C++ standard
440         // library required by LLVM. This likely needs to happen one day, but
441         // in general Windows is also a more controlled environment than
442         // Unix, so it's not necessarily as critical that this be implemented.
443         //
444         // Note that there are also some licensing worries about statically
445         // linking some libraries which require a specific agreement, so it may
446         // not ever be possible for us to pass this flag.
447     }
448
449     fn include_path(&mut self, path: &Path) {
450         let mut arg = OsString::from("/LIBPATH:");
451         arg.push(path);
452         self.cmd.arg(&arg);
453     }
454
455     fn output_filename(&mut self, path: &Path) {
456         let mut arg = OsString::from("/OUT:");
457         arg.push(path);
458         self.cmd.arg(&arg);
459     }
460
461     fn framework_path(&mut self, _path: &Path) {
462         bug!("frameworks are not supported on windows")
463     }
464     fn link_framework(&mut self, _framework: &str) {
465         bug!("frameworks are not supported on windows")
466     }
467
468     fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
469         // not supported?
470         self.link_staticlib(lib);
471     }
472     fn link_whole_rlib(&mut self, path: &Path) {
473         // not supported?
474         self.link_rlib(path);
475     }
476     fn optimize(&mut self) {
477         // Needs more investigation of `/OPT` arguments
478     }
479
480     fn debuginfo(&mut self) {
481         // This will cause the Microsoft linker to generate a PDB file
482         // from the CodeView line tables in the object files.
483         self.cmd.arg("/DEBUG");
484     }
485
486     // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
487     // export symbols from a dynamic library. When building a dynamic library,
488     // however, we're going to want some symbols exported, so this function
489     // generates a DEF file which lists all the symbols.
490     //
491     // The linker will read this `*.def` file and export all the symbols from
492     // the dynamic library. Note that this is not as simple as just exporting
493     // all the symbols in the current crate (as specified by `trans.reachable`)
494     // but rather we also need to possibly export the symbols of upstream
495     // crates. Upstream rlibs may be linked statically to this dynamic library,
496     // in which case they may continue to transitively be used and hence need
497     // their symbols exported.
498     fn export_symbols(&mut self,
499                       tmpdir: &Path,
500                       crate_type: CrateType) {
501         let path = tmpdir.join("lib.def");
502         let res = (|| -> io::Result<()> {
503             let mut f = BufWriter::new(File::create(&path)?);
504
505             // Start off with the standard module name header and then go
506             // straight to exports.
507             writeln!(f, "LIBRARY")?;
508             writeln!(f, "EXPORTS")?;
509             for symbol in self.info.exports[&crate_type].iter() {
510                 debug!("  _{}", symbol);
511                 writeln!(f, "  {}", symbol)?;
512             }
513             Ok(())
514         })();
515         if let Err(e) = res {
516             self.sess.fatal(&format!("failed to write lib.def file: {}", e));
517         }
518         let mut arg = OsString::from("/DEF:");
519         arg.push(path);
520         self.cmd.arg(&arg);
521     }
522
523     fn subsystem(&mut self, subsystem: &str) {
524         // Note that previous passes of the compiler validated this subsystem,
525         // so we just blindly pass it to the linker.
526         self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
527
528         // Windows has two subsystems we're interested in right now, the console
529         // and windows subsystems. These both implicitly have different entry
530         // points (starting symbols). The console entry point starts with
531         // `mainCRTStartup` and the windows entry point starts with
532         // `WinMainCRTStartup`. These entry points, defined in system libraries,
533         // will then later probe for either `main` or `WinMain`, respectively to
534         // start the application.
535         //
536         // In Rust we just always generate a `main` function so we want control
537         // to always start there, so we force the entry point on the windows
538         // subsystem to be `mainCRTStartup` to get everything booted up
539         // correctly.
540         //
541         // For more information see RFC #1665
542         if subsystem == "windows" {
543             self.cmd.arg("/ENTRY:mainCRTStartup");
544         }
545     }
546
547     fn finalize(&mut self) -> Command {
548         let mut cmd = Command::new("");
549         ::std::mem::swap(&mut cmd, &mut self.cmd);
550         cmd
551     }
552 }
553
554 pub struct EmLinker<'a> {
555     cmd: Command,
556     sess: &'a Session,
557     info: &'a LinkerInfo
558 }
559
560 impl<'a> Linker for EmLinker<'a> {
561     fn include_path(&mut self, path: &Path) {
562         self.cmd.arg("-L").arg(path);
563     }
564
565     fn link_staticlib(&mut self, lib: &str) {
566         self.cmd.arg("-l").arg(lib);
567     }
568
569     fn output_filename(&mut self, path: &Path) {
570         self.cmd.arg("-o").arg(path);
571     }
572
573     fn add_object(&mut self, path: &Path) {
574         self.cmd.arg(path);
575     }
576
577     fn link_dylib(&mut self, lib: &str) {
578         // Emscripten always links statically
579         self.link_staticlib(lib);
580     }
581
582     fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
583         // not supported?
584         self.link_staticlib(lib);
585     }
586
587     fn link_whole_rlib(&mut self, lib: &Path) {
588         // not supported?
589         self.link_rlib(lib);
590     }
591
592     fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
593         self.link_dylib(lib);
594     }
595
596     fn link_rlib(&mut self, lib: &Path) {
597         self.add_object(lib);
598     }
599
600     fn position_independent_executable(&mut self) {
601         // noop
602     }
603
604     fn full_relro(&mut self) {
605         // noop
606     }
607
608     fn args(&mut self, args: &[String]) {
609         self.cmd.args(args);
610     }
611
612     fn framework_path(&mut self, _path: &Path) {
613         bug!("frameworks are not supported on Emscripten")
614     }
615
616     fn link_framework(&mut self, _framework: &str) {
617         bug!("frameworks are not supported on Emscripten")
618     }
619
620     fn gc_sections(&mut self, _keep_metadata: bool) {
621         // noop
622     }
623
624     fn optimize(&mut self) {
625         // Emscripten performs own optimizations
626         self.cmd.arg(match self.sess.opts.optimize {
627             OptLevel::No => "-O0",
628             OptLevel::Less => "-O1",
629             OptLevel::Default => "-O2",
630             OptLevel::Aggressive => "-O3",
631             OptLevel::Size => "-Os",
632             OptLevel::SizeMin => "-Oz"
633         });
634         // Unusable until https://github.com/rust-lang/rust/issues/38454 is resolved
635         self.cmd.args(&["--memory-init-file", "0"]);
636     }
637
638     fn debuginfo(&mut self) {
639         // Preserve names or generate source maps depending on debug info
640         self.cmd.arg(match self.sess.opts.debuginfo {
641             DebugInfoLevel::NoDebugInfo => "-g0",
642             DebugInfoLevel::LimitedDebugInfo => "-g3",
643             DebugInfoLevel::FullDebugInfo => "-g4"
644         });
645     }
646
647     fn no_default_libraries(&mut self) {
648         self.cmd.args(&["-s", "DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=[]"]);
649     }
650
651     fn build_dylib(&mut self, _out_filename: &Path) {
652         bug!("building dynamic library is unsupported on Emscripten")
653     }
654
655     fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
656         let symbols = &self.info.exports[&crate_type];
657
658         debug!("EXPORTED SYMBOLS:");
659
660         self.cmd.arg("-s");
661
662         let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
663         let mut encoded = String::new();
664
665         {
666             let mut encoder = json::Encoder::new(&mut encoded);
667             let res = encoder.emit_seq(symbols.len(), |encoder| {
668                 for (i, sym) in symbols.iter().enumerate() {
669                     encoder.emit_seq_elt(i, |encoder| {
670                         encoder.emit_str(&("_".to_string() + sym))
671                     })?;
672                 }
673                 Ok(())
674             });
675             if let Err(e) = res {
676                 self.sess.fatal(&format!("failed to encode exported symbols: {}", e));
677             }
678         }
679         debug!("{}", encoded);
680         arg.push(encoded);
681
682         self.cmd.arg(arg);
683     }
684
685     fn subsystem(&mut self, _subsystem: &str) {
686         // noop
687     }
688
689     fn finalize(&mut self) -> Command {
690         let mut cmd = Command::new("");
691         ::std::mem::swap(&mut cmd, &mut self.cmd);
692         cmd
693     }
694 }
695
696 fn exported_symbols(scx: &SharedCrateContext,
697                     exported_symbols: &ExportedSymbols,
698                     crate_type: CrateType)
699                     -> Vec<String> {
700     let export_threshold = symbol_export::crate_export_threshold(crate_type);
701
702     let mut symbols = Vec::new();
703     exported_symbols.for_each_exported_symbol(LOCAL_CRATE, export_threshold, |name, _| {
704         symbols.push(name.to_owned());
705     });
706
707     let formats = scx.sess().dependency_formats.borrow();
708     let deps = formats[&crate_type].iter();
709
710     for (index, dep_format) in deps.enumerate() {
711         let cnum = CrateNum::new(index + 1);
712         // For each dependency that we are linking to statically ...
713         if *dep_format == Linkage::Static {
714             // ... we add its symbol list to our export list.
715             exported_symbols.for_each_exported_symbol(cnum, export_threshold, |name, _| {
716                 symbols.push(name.to_owned());
717             })
718         }
719     }
720
721     symbols
722 }