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