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