]> git.lizzy.rs Git - rust.git/blob - src/driver/jit.rs
Enable the rust_2018_idioms and unused_lifetimes lints and fix all warnings
[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     let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
43     let mono_items = cgus
44         .iter()
45         .map(|cgu| cgu.items_in_deterministic_order(tcx).into_iter())
46         .flatten()
47         .collect::<FxHashMap<_, (_, _)>>()
48         .into_iter()
49         .collect::<Vec<(_, (_, _))>>();
50
51     super::time(tcx, "codegen mono items", || {
52         super::codegen_mono_items(tcx, &mut jit_module, None, mono_items);
53     });
54     crate::main_shim::maybe_create_entry_wrapper(tcx, &mut jit_module);
55     crate::allocator::codegen(tcx, &mut jit_module);
56
57     jit_module.finalize_definitions();
58
59     tcx.sess.abort_if_errors();
60
61     let finalized_main: *const u8 = jit_module.get_finalized_function(main_func_id);
62
63     println!("Rustc codegen cranelift will JIT run the executable, because the CG_CLIF_JIT env var is set");
64
65     let f: extern "C" fn(c_int, *const *const c_char) -> c_int =
66         unsafe { ::std::mem::transmute(finalized_main) };
67
68     let args = ::std::env::var("CG_CLIF_JIT_ARGS").unwrap_or_else(|_| String::new());
69     let args = args
70         .split(" ")
71         .chain(Some(&*tcx.crate_name(LOCAL_CRATE).as_str().to_string()))
72         .map(|arg| CString::new(arg).unwrap())
73         .collect::<Vec<_>>();
74     let argv = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<_>>();
75     // TODO: Rust doesn't care, but POSIX argv has a NULL sentinel at the end
76
77     let ret = f(args.len() as c_int, argv.as_ptr());
78
79     jit_module.finish();
80     std::process::exit(ret);
81 }
82
83 fn load_imported_symbols_for_jit(tcx: TyCtxt<'_>) -> Vec<(String, *const u8)> {
84     use rustc_middle::middle::dependency_format::Linkage;
85
86     let mut dylib_paths = Vec::new();
87
88     let crate_info = CrateInfo::new(tcx);
89     let formats = tcx.dependency_formats(LOCAL_CRATE);
90     let data = &formats
91         .iter()
92         .find(|(crate_type, _data)| *crate_type == rustc_session::config::CrateType::Executable)
93         .unwrap()
94         .1;
95     for &(cnum, _) in &crate_info.used_crates_dynamic {
96         let src = &crate_info.used_crate_source[&cnum];
97         match data[cnum.as_usize() - 1] {
98             Linkage::NotLinked | Linkage::IncludedFromDylib => {}
99             Linkage::Static => {
100                 let name = tcx.crate_name(cnum);
101                 let mut err = tcx
102                     .sess
103                     .struct_err(&format!("Can't load static lib {}", name.as_str()));
104                 err.note("rustc_codegen_cranelift can only load dylibs in JIT mode.");
105                 err.emit();
106             }
107             Linkage::Dynamic => {
108                 dylib_paths.push(src.dylib.as_ref().unwrap().0.clone());
109             }
110         }
111     }
112
113     let mut imported_symbols = Vec::new();
114     for path in dylib_paths {
115         use object::Object;
116         let lib = libloading::Library::new(&path).unwrap();
117         let obj = std::fs::read(path).unwrap();
118         let obj = object::File::parse(&obj).unwrap();
119         imported_symbols.extend(obj.dynamic_symbols().filter_map(|(_idx, symbol)| {
120             let name = symbol.name().unwrap().to_string();
121             if name.is_empty() || !symbol.is_global() || symbol.is_undefined() {
122                 return None;
123             }
124             let dlsym_name = if cfg!(target_os = "macos") {
125                 // On macOS `dlsym` expects the name without leading `_`.
126                 assert!(name.starts_with("_"), "{:?}", name);
127                 &name[1..]
128             } else {
129                 &name
130             };
131             let symbol: libloading::Symbol<'_, *const u8> =
132                 unsafe { lib.get(dlsym_name.as_bytes()) }.unwrap();
133             Some((name, *symbol))
134         }));
135         std::mem::forget(lib)
136     }
137
138     tcx.sess.abort_if_errors();
139
140     imported_symbols
141 }