2 use std::os::raw::{c_char, c_int};
4 use rustc_codegen_ssa::CrateInfo;
8 pub(super) fn run_jit(tcx: TyCtxt<'_>) -> ! {
9 use cranelift_simplejit::{SimpleJITBackend, SimpleJITBuilder};
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());
18 let imported_symbols = load_imported_symbols_for_jit(tcx);
20 let mut jit_builder = SimpleJITBuilder::with_isa(
21 crate::build_isa(tcx.sess, false),
22 cranelift_module::default_libcall_names(),
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());
30 AbiParam::new(jit_module.target_config().pointer_type()),
31 AbiParam::new(jit_module.target_config().pointer_type()),
33 returns: vec![AbiParam::new(
34 jit_module.target_config().pointer_type(), /*isize*/
36 call_conv: CallConv::triple_default(&crate::target_triple(tcx.sess)),
38 let main_func_id = jit_module
39 .declare_function("main", Linkage::Import, &sig)
42 let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
45 .map(|cgu| cgu.items_in_deterministic_order(tcx).into_iter())
47 .collect::<FxHashMap<_, (_, _)>>()
49 .collect::<Vec<(_, (_, _))>>();
51 super::time(tcx, "codegen mono items", || {
52 super::codegen_mono_items(tcx, &mut jit_module, None, mono_items);
54 crate::main_shim::maybe_create_entry_wrapper(tcx, &mut jit_module);
55 crate::allocator::codegen(tcx, &mut jit_module);
57 jit_module.finalize_definitions();
59 tcx.sess.abort_if_errors();
61 let finalized_main: *const u8 = jit_module.get_finalized_function(main_func_id);
63 println!("Rustc codegen cranelift will JIT run the executable, because the CG_CLIF_JIT env var is set");
65 let f: extern "C" fn(c_int, *const *const c_char) -> c_int =
66 unsafe { ::std::mem::transmute(finalized_main) };
68 let args = ::std::env::var("CG_CLIF_JIT_ARGS").unwrap_or_else(|_| String::new());
71 .chain(Some(&*tcx.crate_name(LOCAL_CRATE).as_str().to_string()))
72 .map(|arg| CString::new(arg).unwrap())
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
77 let ret = f(args.len() as c_int, argv.as_ptr());
80 std::process::exit(ret);
83 fn load_imported_symbols_for_jit(tcx: TyCtxt<'_>) -> Vec<(String, *const u8)> {
84 use rustc_middle::middle::dependency_format::Linkage;
86 let mut dylib_paths = Vec::new();
88 let crate_info = CrateInfo::new(tcx);
89 let formats = tcx.dependency_formats(LOCAL_CRATE);
92 .find(|(crate_type, _data)| *crate_type == rustc_session::config::CrateType::Executable)
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 => {}
100 let name = tcx.crate_name(cnum);
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.");
107 Linkage::Dynamic => {
108 dylib_paths.push(src.dylib.as_ref().unwrap().0.clone());
113 let mut imported_symbols = Vec::new();
114 for path in dylib_paths {
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() {
124 let dlsym_name = if cfg!(target_os = "macos") {
125 // On macOS `dlsym` expects the name without leading `_`.
126 assert!(name.starts_with("_"), "{:?}", name);
131 let symbol: libloading::Symbol<'_, *const u8> =
132 unsafe { lib.get(dlsym_name.as_bytes()) }.unwrap();
133 Some((name, *symbol))
135 std::mem::forget(lib)
138 tcx.sess.abort_if_errors();