]> git.lizzy.rs Git - rust.git/blob - src/driver/jit.rs
Always emit .eh_frame section
[rust.git] / src / driver / jit.rs
1 use std::ffi::CString;
2 use std::os::raw::{c_char, c_int};
3
4 use rustc_codegen_ssa::CrateInfo;
5
6 use crate::prelude::*;
7
8 pub(super) fn run_jit(tcx: TyCtxt<'_>) -> ! {
9     use cranelift_simplejit::{SimpleJITBackend, SimpleJITBuilder};
10
11     // Rustc opens us without the RTLD_GLOBAL flag, so __cg_clif_global_atomic_mutex will not be
12     // exported. We fix this by opening ourself again as global.
13     // FIXME remove once atomic_shim is gone
14     let cg_dylib = std::ffi::OsString::from(&tcx.sess.opts.debugging_opts.codegen_backend.as_ref().unwrap());
15     std::mem::forget(libloading::os::unix::Library::open(Some(cg_dylib), libc::RTLD_NOW | libc::RTLD_GLOBAL).unwrap());
16
17
18     let imported_symbols = load_imported_symbols_for_jit(tcx);
19
20     let mut jit_builder = SimpleJITBuilder::with_isa(
21         crate::build_isa(tcx.sess, false),
22         cranelift_module::default_libcall_names(),
23     );
24     jit_builder.symbols(imported_symbols);
25     let mut jit_module: Module<SimpleJITBackend> = Module::new(jit_builder);
26     assert_eq!(pointer_ty(tcx), jit_module.target_config().pointer_type());
27
28     let sig = Signature {
29         params: vec![
30             AbiParam::new(jit_module.target_config().pointer_type()),
31             AbiParam::new(jit_module.target_config().pointer_type()),
32         ],
33         returns: vec![AbiParam::new(
34             jit_module.target_config().pointer_type(), /*isize*/
35         )],
36         call_conv: CallConv::triple_default(&crate::target_triple(tcx.sess)),
37     };
38     let main_func_id = jit_module
39         .declare_function("main", Linkage::Import, &sig)
40         .unwrap();
41
42     if !tcx.sess.opts.output_types.should_codegen() {
43         tcx.sess.fatal("JIT mode doesn't work with `cargo check`.");
44     }
45
46     let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
47     let mono_items = cgus
48         .iter()
49         .map(|cgu| cgu.items_in_deterministic_order(tcx).into_iter())
50         .flatten()
51         .collect::<FxHashMap<_, (_, _)>>()
52         .into_iter()
53         .collect::<Vec<(_, (_, _))>>();
54
55     // FIXME register with unwind runtime
56     let mut unwind_context = UnwindContext::new(tcx, &mut jit_module);
57
58     super::time(tcx, "codegen mono items", || {
59         super::codegen_mono_items(tcx, &mut jit_module, None, &mut unwind_context, mono_items);
60     });
61     crate::main_shim::maybe_create_entry_wrapper(tcx, &mut jit_module);
62     crate::allocator::codegen(tcx, &mut jit_module);
63
64     jit_module.finalize_definitions();
65
66     tcx.sess.abort_if_errors();
67
68     let finalized_main: *const u8 = jit_module.get_finalized_function(main_func_id);
69
70     println!("Rustc codegen cranelift will JIT run the executable, because the CG_CLIF_JIT env var is set");
71
72     let f: extern "C" fn(c_int, *const *const c_char) -> c_int =
73         unsafe { ::std::mem::transmute(finalized_main) };
74
75     let args = ::std::env::var("CG_CLIF_JIT_ARGS").unwrap_or_else(|_| String::new());
76     let args = args
77         .split(" ")
78         .chain(Some(&*tcx.crate_name(LOCAL_CRATE).as_str().to_string()))
79         .map(|arg| CString::new(arg).unwrap())
80         .collect::<Vec<_>>();
81     let argv = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<_>>();
82     // TODO: Rust doesn't care, but POSIX argv has a NULL sentinel at the end
83
84     let ret = f(args.len() as c_int, argv.as_ptr());
85
86     jit_module.finish();
87     std::process::exit(ret);
88 }
89
90 fn load_imported_symbols_for_jit(tcx: TyCtxt<'_>) -> Vec<(String, *const u8)> {
91     use rustc_middle::middle::dependency_format::Linkage;
92
93     let mut dylib_paths = Vec::new();
94
95     let crate_info = CrateInfo::new(tcx);
96     let formats = tcx.dependency_formats(LOCAL_CRATE);
97     let data = &formats
98         .iter()
99         .find(|(crate_type, _data)| *crate_type == rustc_session::config::CrateType::Executable)
100         .unwrap()
101         .1;
102     for &(cnum, _) in &crate_info.used_crates_dynamic {
103         let src = &crate_info.used_crate_source[&cnum];
104         match data[cnum.as_usize() - 1] {
105             Linkage::NotLinked | Linkage::IncludedFromDylib => {}
106             Linkage::Static => {
107                 let name = tcx.crate_name(cnum);
108                 let mut err = tcx
109                     .sess
110                     .struct_err(&format!("Can't load static lib {}", name.as_str()));
111                 err.note("rustc_codegen_cranelift can only load dylibs in JIT mode.");
112                 err.emit();
113             }
114             Linkage::Dynamic => {
115                 dylib_paths.push(src.dylib.as_ref().unwrap().0.clone());
116             }
117         }
118     }
119
120     let mut imported_symbols = Vec::new();
121     for path in dylib_paths {
122         use object::Object;
123         let lib = libloading::Library::new(&path).unwrap();
124         let obj = std::fs::read(path).unwrap();
125         let obj = object::File::parse(&obj).unwrap();
126         imported_symbols.extend(obj.dynamic_symbols().filter_map(|(_idx, symbol)| {
127             let name = symbol.name().unwrap().to_string();
128             if name.is_empty() || !symbol.is_global() || symbol.is_undefined() {
129                 return None;
130             }
131             let dlsym_name = if cfg!(target_os = "macos") {
132                 // On macOS `dlsym` expects the name without leading `_`.
133                 assert!(name.starts_with("_"), "{:?}", name);
134                 &name[1..]
135             } else {
136                 &name
137             };
138             let symbol: libloading::Symbol<'_, *const u8> =
139                 unsafe { lib.get(dlsym_name.as_bytes()) }.unwrap();
140             Some((name, *symbol))
141         }));
142         std::mem::forget(lib)
143     }
144
145     tcx.sess.abort_if_errors();
146
147     imported_symbols
148 }