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 if !tcx.sess.opts.output_types.should_codegen() {
43 tcx.sess.fatal("JIT mode doesn't work with `cargo check`.");
46 let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
49 .map(|cgu| cgu.items_in_deterministic_order(tcx).into_iter())
51 .collect::<FxHashMap<_, (_, _)>>()
53 .collect::<Vec<(_, (_, _))>>();
55 let mut cx = crate::CodegenCx::new(tcx, jit_module, false);
57 let (mut jit_module, global_asm, _debug, mut unwind_context) = super::time(tcx, "codegen mono items", || {
58 super::codegen_mono_items(&mut cx, mono_items);
59 tcx.sess.time("finalize CodegenCx", || cx.finalize())
61 if !global_asm.is_empty() {
62 tcx.sess.fatal("Global asm is not supported in JIT mode");
64 crate::main_shim::maybe_create_entry_wrapper(tcx, &mut jit_module, &mut unwind_context);
65 crate::allocator::codegen(tcx, &mut jit_module, &mut unwind_context);
67 jit_module.finalize_definitions();
69 let _unwind_register_guard = unsafe { unwind_context.register_jit(&mut jit_module) };
71 tcx.sess.abort_if_errors();
73 let finalized_main: *const u8 = jit_module.get_finalized_function(main_func_id);
75 println!("Rustc codegen cranelift will JIT run the executable, because the CG_CLIF_JIT env var is set");
77 let f: extern "C" fn(c_int, *const *const c_char) -> c_int =
78 unsafe { ::std::mem::transmute(finalized_main) };
80 let args = ::std::env::var("CG_CLIF_JIT_ARGS").unwrap_or_else(|_| String::new());
81 let args = std::iter::once(&*tcx.crate_name(LOCAL_CRATE).as_str().to_string())
82 .chain(args.split(" "))
83 .map(|arg| CString::new(arg).unwrap())
85 let argv = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<_>>();
86 // TODO: Rust doesn't care, but POSIX argv has a NULL sentinel at the end
88 let ret = f(args.len() as c_int, argv.as_ptr());
91 std::process::exit(ret);
94 fn load_imported_symbols_for_jit(tcx: TyCtxt<'_>) -> Vec<(String, *const u8)> {
95 use rustc_middle::middle::dependency_format::Linkage;
97 let mut dylib_paths = Vec::new();
99 let crate_info = CrateInfo::new(tcx);
100 let formats = tcx.dependency_formats(LOCAL_CRATE);
103 .find(|(crate_type, _data)| *crate_type == rustc_session::config::CrateType::Executable)
106 for &(cnum, _) in &crate_info.used_crates_dynamic {
107 let src = &crate_info.used_crate_source[&cnum];
108 match data[cnum.as_usize() - 1] {
109 Linkage::NotLinked | Linkage::IncludedFromDylib => {}
111 let name = tcx.crate_name(cnum);
114 .struct_err(&format!("Can't load static lib {}", name.as_str()));
115 err.note("rustc_codegen_cranelift can only load dylibs in JIT mode.");
118 Linkage::Dynamic => {
119 dylib_paths.push(src.dylib.as_ref().unwrap().0.clone());
124 let mut imported_symbols = Vec::new();
125 for path in dylib_paths {
127 let lib = libloading::Library::new(&path).unwrap();
128 let obj = std::fs::read(path).unwrap();
129 let obj = object::File::parse(&obj).unwrap();
130 imported_symbols.extend(obj.dynamic_symbols().filter_map(|(_idx, symbol)| {
131 let name = symbol.name().unwrap().to_string();
132 if name.is_empty() || !symbol.is_global() || symbol.is_undefined() {
135 let dlsym_name = if cfg!(target_os = "macos") {
136 // On macOS `dlsym` expects the name without leading `_`.
137 assert!(name.starts_with("_"), "{:?}", name);
142 let symbol: libloading::Symbol<'_, *const u8> =
143 unsafe { lib.get(dlsym_name.as_bytes()) }.unwrap();
144 Some((name, *symbol))
146 std::mem::forget(lib)
149 tcx.sess.abort_if_errors();