1 //! The JIT driver uses [`cranelift_jit`] to JIT execute programs without writing any object
2 //! files.
3
4 use std::cell::RefCell;
5 use std::ffi::CString;
6 use std::lazy::{Lazy, SyncOnceCell};
7 use std::os::raw::{c_char, c_int};
8 use std::sync::{mpsc, Mutex};
9
10 use cranelift_codegen::binemit::{NullStackMapSink, NullTrapSink};
11 use rustc_codegen_ssa::CrateInfo;
12 use rustc_middle::mir::mono::MonoItem;
13 use rustc_session::Session;
14
15 use cranelift_jit::{JITBuilder, JITModule};
16
17 use crate::{prelude::*, BackendConfig};
18 use crate::{CodegenCx, CodegenMode};
19
20 struct JitState {
21 backend_config: BackendConfig,
22 jit_module: JITModule,
23 }
24
25 thread_local! {
26 static LAZY_JIT_STATE: RefCell<Option<JitState>> = RefCell::new(None);
27 }
28
29 /// The Sender owned by the rustc thread
30 static GLOBAL_MESSAGE_SENDER: SyncOnceCell<Mutex<mpsc::Sender<UnsafeMessage>>> =
31 SyncOnceCell::new();
32
33 /// A message that is sent from the jitted runtime to the rustc thread.
34 /// Senders are responsible for upholding `Send` semantics.
35 enum UnsafeMessage {
36 /// Request that the specified `Instance` be lazily jitted.
37 ///
38 /// Nothing accessible through `instance_ptr` may be moved or mutated by the sender after
39 /// this message is sent.
40 JitFn {
41 instance_ptr: *const Instance<'static>,
42 trampoline_ptr: *const u8,
43 tx: mpsc::Sender<*const u8>,
44 },
45 }
46 unsafe impl Send for UnsafeMessage {}
47
48 impl UnsafeMessage {
49 /// Send the message.
send(self) -> Result<(), mpsc::SendError<UnsafeMessage>>50 fn send(self) -> Result<(), mpsc::SendError<UnsafeMessage>> {
51 thread_local! {
52 /// The Sender owned by the local thread
53 static LOCAL_MESSAGE_SENDER: Lazy<mpsc::Sender<UnsafeMessage>> = Lazy::new(||
54 GLOBAL_MESSAGE_SENDER
55 .get().unwrap()
56 .lock().unwrap()
57 .clone()
58 );
59 }
60 LOCAL_MESSAGE_SENDER.with(|sender| sender.send(self))
61 }
62 }
63
create_jit_module<'tcx>( tcx: TyCtxt<'tcx>, backend_config: &BackendConfig, hotswap: bool, ) -> (JITModule, CodegenCx<'tcx>)64 fn create_jit_module<'tcx>(
65 tcx: TyCtxt<'tcx>,
66 backend_config: &BackendConfig,
67 hotswap: bool,
68 ) -> (JITModule, CodegenCx<'tcx>) {
69 let crate_info = CrateInfo::new(tcx, "dummy_target_cpu".to_string());
70 let imported_symbols = load_imported_symbols_for_jit(tcx.sess, crate_info);
71
72 let isa = crate::build_isa(tcx.sess, backend_config);
73 let mut jit_builder = JITBuilder::with_isa(isa, cranelift_module::default_libcall_names());
74 jit_builder.hotswap(hotswap);
75 crate::compiler_builtins::register_functions_for_jit(&mut jit_builder);
76 jit_builder.symbols(imported_symbols);
77 let mut jit_module = JITModule::new(jit_builder);
78
79 let mut cx = crate::CodegenCx::new(tcx, backend_config.clone(), jit_module.isa(), false);
80
81 crate::allocator::codegen(tcx, &mut jit_module, &mut cx.unwind_context);
82 crate::main_shim::maybe_create_entry_wrapper(
83 tcx,
84 &mut jit_module,
85 &mut cx.unwind_context,
86 true,
87 true,
88 );
89
90 (jit_module, cx)
91 }
92
run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> !93 pub(crate) fn run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> ! {
94 if !tcx.sess.opts.output_types.should_codegen() {
95 tcx.sess.fatal("JIT mode doesn't work with `cargo check`");
96 }
97
98 if !tcx.sess.crate_types().contains(&rustc_session::config::CrateType::Executable) {
99 tcx.sess.fatal("can't jit non-executable crate");
100 }
101
102 let (mut jit_module, mut cx) = create_jit_module(
103 tcx,
104 &backend_config,
105 matches!(backend_config.codegen_mode, CodegenMode::JitLazy),
106 );
107
108 let (_, cgus) = tcx.collect_and_partition_mono_items(());
109 let mono_items = cgus
110 .iter()
111 .map(|cgu| cgu.items_in_deterministic_order(tcx).into_iter())
112 .flatten()
113 .collect::<FxHashMap<_, (_, _)>>()
114 .into_iter()
115 .collect::<Vec<(_, (_, _))>>();
116
117 super::time(tcx, backend_config.display_cg_time, "codegen mono items", || {
118 super::predefine_mono_items(tcx, &mut jit_module, &mono_items);
119 for (mono_item, _) in mono_items {
120 match mono_item {
121 MonoItem::Fn(inst) => match backend_config.codegen_mode {
122 CodegenMode::Aot => unreachable!(),
123 CodegenMode::Jit => {
124 cx.tcx.sess.time("codegen fn", || {
125 crate::base::codegen_fn(&mut cx, &mut jit_module, inst)
126 });
127 }
128 CodegenMode::JitLazy => codegen_shim(&mut cx, &mut jit_module, inst),
129 },
130 MonoItem::Static(def_id) => {
131 crate::constant::codegen_static(tcx, &mut jit_module, def_id);
132 }
133 MonoItem::GlobalAsm(item_id) => {
134 let item = tcx.hir().item(item_id);
135 tcx.sess.span_fatal(item.span, "Global asm is not supported in JIT mode");
136 }
137 }
138 }
139 });
140
141 if !cx.global_asm.is_empty() {
142 tcx.sess.fatal("Inline asm is not supported in JIT mode");
143 }
144
145 tcx.sess.abort_if_errors();
146
147 jit_module.finalize_definitions();
148 unsafe { cx.unwind_context.register_jit(&jit_module) };
149
150 println!(
151 "Rustc codegen cranelift will JIT run the executable, because -Cllvm-args=mode=jit was passed"
152 );
153
154 let args = std::iter::once(&*tcx.crate_name(LOCAL_CRATE).as_str().to_string())
155 .chain(backend_config.jit_args.iter().map(|arg| &**arg))
156 .map(|arg| CString::new(arg).unwrap())
157 .collect::<Vec<_>>();
158
159 let start_sig = Signature {
160 params: vec![
161 AbiParam::new(jit_module.target_config().pointer_type()),
162 AbiParam::new(jit_module.target_config().pointer_type()),
163 ],
164 returns: vec![AbiParam::new(jit_module.target_config().pointer_type() /*isize*/)],
165 call_conv: jit_module.target_config().default_call_conv,
166 };
167 let start_func_id = jit_module.declare_function("main", Linkage::Import, &start_sig).unwrap();
168 let finalized_start: *const u8 = jit_module.get_finalized_function(start_func_id);
169
170 LAZY_JIT_STATE.with(|lazy_jit_state| {
171 let mut lazy_jit_state = lazy_jit_state.borrow_mut();
172 assert!(lazy_jit_state.is_none());
173 *lazy_jit_state = Some(JitState { backend_config, jit_module });
174 });
175
176 let f: extern "C" fn(c_int, *const *const c_char) -> c_int =
177 unsafe { ::std::mem::transmute(finalized_start) };
178
179 let (tx, rx) = mpsc::channel();
180 GLOBAL_MESSAGE_SENDER.set(Mutex::new(tx)).unwrap();
181
182 // Spawn the jitted runtime in a new thread so that this rustc thread can handle messages
183 // (eg to lazily JIT further functions as required)
184 std::thread::spawn(move || {
185 let mut argv = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<_>>();
186
187 // Push a null pointer as a terminating argument. This is required by POSIX and
188 // useful as some dynamic linkers use it as a marker to jump over.
189 argv.push(std::ptr::null());
190
191 let ret = f(args.len() as c_int, argv.as_ptr());
192 std::process::exit(ret);
193 });
194
195 // Handle messages
196 loop {
197 match rx.recv().unwrap() {
198 // lazy JIT compilation request - compile requested instance and return pointer to result
199 UnsafeMessage::JitFn { instance_ptr, trampoline_ptr, tx } => {
200 tx.send(jit_fn(instance_ptr, trampoline_ptr))
201 .expect("jitted runtime hung up before response to lazy JIT request was sent");
202 }
203 }
204 }
205 }
206
207 #[no_mangle]
__clif_jit_fn( instance_ptr: *const Instance<'static>, trampoline_ptr: *const u8, ) -> *const u8208 extern "C" fn __clif_jit_fn(
209 instance_ptr: *const Instance<'static>,
210 trampoline_ptr: *const u8,
211 ) -> *const u8 {
212 // send the JIT request to the rustc thread, with a channel for the response
213 let (tx, rx) = mpsc::channel();
214 UnsafeMessage::JitFn { instance_ptr, trampoline_ptr, tx }
215 .send()
216 .expect("rustc thread hung up before lazy JIT request was sent");
217
218 // block on JIT compilation result
219 rx.recv().expect("rustc thread hung up before responding to sent lazy JIT request")
220 }
221
jit_fn(instance_ptr: *const Instance<'static>, trampoline_ptr: *const u8) -> *const u8222 fn jit_fn(instance_ptr: *const Instance<'static>, trampoline_ptr: *const u8) -> *const u8 {
223 rustc_middle::ty::tls::with(|tcx| {
224 // lift is used to ensure the correct lifetime for instance.
225 let instance = tcx.lift(unsafe { *instance_ptr }).unwrap();
226
227 LAZY_JIT_STATE.with(|lazy_jit_state| {
228 let mut lazy_jit_state = lazy_jit_state.borrow_mut();
229 let lazy_jit_state = lazy_jit_state.as_mut().unwrap();
230 let jit_module = &mut lazy_jit_state.jit_module;
231 let backend_config = lazy_jit_state.backend_config.clone();
232
233 let name = tcx.symbol_name(instance).name;
234 let sig = crate::abi::get_function_sig(tcx, jit_module.isa().triple(), instance);
235 let func_id = jit_module.declare_function(name, Linkage::Export, &sig).unwrap();
236
237 let current_ptr = jit_module.read_got_entry(func_id);
238
239 // If the function's GOT entry has already been updated to point at something other
240 // than the shim trampoline, don't re-jit but just return the new pointer instead.
241 // This does not need synchronization as this code is executed only by a sole rustc
242 // thread.
243 if current_ptr != trampoline_ptr {
244 return current_ptr;
245 }
246
247 jit_module.prepare_for_function_redefine(func_id).unwrap();
248
249 let mut cx = crate::CodegenCx::new(tcx, backend_config, jit_module.isa(), false);
250 tcx.sess.time("codegen fn", || crate::base::codegen_fn(&mut cx, jit_module, instance));
251
252 assert!(cx.global_asm.is_empty());
253 jit_module.finalize_definitions();
254 unsafe { cx.unwind_context.register_jit(&jit_module) };
255 jit_module.get_finalized_function(func_id)
256 })
257 })
258 }
259
load_imported_symbols_for_jit( sess: &Session, crate_info: CrateInfo, ) -> Vec<(String, *const u8)>260 fn load_imported_symbols_for_jit(
261 sess: &Session,
262 crate_info: CrateInfo,
263 ) -> Vec<(String, *const u8)> {
264 use rustc_middle::middle::dependency_format::Linkage;
265
266 let mut dylib_paths = Vec::new();
267
268 let data = &crate_info
269 .dependency_formats
270 .iter()
271 .find(|(crate_type, _data)| *crate_type == rustc_session::config::CrateType::Executable)
272 .unwrap()
273 .1;
274 for &cnum in &crate_info.used_crates {
275 let src = &crate_info.used_crate_source[&cnum];
276 match data[cnum.as_usize() - 1] {
277 Linkage::NotLinked | Linkage::IncludedFromDylib => {}
278 Linkage::Static => {
279 let name = &crate_info.crate_name[&cnum];
280 let mut err = sess.struct_err(&format!("Can't load static lib {}", name.as_str()));
281 err.note("rustc_codegen_cranelift can only load dylibs in JIT mode.");
282 err.emit();
283 }
284 Linkage::Dynamic => {
285 dylib_paths.push(src.dylib.as_ref().unwrap().0.clone());
286 }
287 }
288 }
289
290 let mut imported_symbols = Vec::new();
291 for path in dylib_paths {
292 use object::{Object, ObjectSymbol};
293 let lib = libloading::Library::new(&path).unwrap();
294 let obj = std::fs::read(path).unwrap();
295 let obj = object::File::parse(&*obj).unwrap();
296 imported_symbols.extend(obj.dynamic_symbols().filter_map(|symbol| {
297 let name = symbol.name().unwrap().to_string();
298 if name.is_empty() || !symbol.is_global() || symbol.is_undefined() {
299 return None;
300 }
301 if name.starts_with("rust_metadata_") {
302 // The metadata is part of a section that is not loaded by the dynamic linker in
303 // case of cg_llvm.
304 return None;
305 }
306 let dlsym_name = if cfg!(target_os = "macos") {
307 // On macOS `dlsym` expects the name without leading `_`.
308 assert!(name.starts_with('_'), "{:?}", name);
309 &name[1..]
310 } else {
311 &name
312 };
313 let symbol: libloading::Symbol<'_, *const u8> =
314 unsafe { lib.get(dlsym_name.as_bytes()) }.unwrap();
315 Some((name, *symbol))
316 }));
317 std::mem::forget(lib)
318 }
319
320 sess.abort_if_errors();
321
322 imported_symbols
323 }
324
codegen_shim<'tcx>(cx: &mut CodegenCx<'tcx>, module: &mut JITModule, inst: Instance<'tcx>)325 fn codegen_shim<'tcx>(cx: &mut CodegenCx<'tcx>, module: &mut JITModule, inst: Instance<'tcx>) {
326 let tcx = cx.tcx;
327
328 let pointer_type = module.target_config().pointer_type();
329
330 let name = tcx.symbol_name(inst).name;
331 let sig = crate::abi::get_function_sig(tcx, module.isa().triple(), inst);
332 let func_id = module.declare_function(name, Linkage::Export, &sig).unwrap();
333
334 let instance_ptr = Box::into_raw(Box::new(inst));
335
336 let jit_fn = module
337 .declare_function(
338 "__clif_jit_fn",
339 Linkage::Import,
340 &Signature {
341 call_conv: module.target_config().default_call_conv,
342 params: vec![AbiParam::new(pointer_type), AbiParam::new(pointer_type)],
343 returns: vec![AbiParam::new(pointer_type)],
344 },
345 )
346 .unwrap();
347
348 cx.cached_context.clear();
349 let trampoline = &mut cx.cached_context.func;
350 trampoline.signature = sig.clone();
351
352 let mut builder_ctx = FunctionBuilderContext::new();
353 let mut trampoline_builder = FunctionBuilder::new(trampoline, &mut builder_ctx);
354
355 let trampoline_fn = module.declare_func_in_func(func_id, trampoline_builder.func);
356 let jit_fn = module.declare_func_in_func(jit_fn, trampoline_builder.func);
357 let sig_ref = trampoline_builder.func.import_signature(sig);
358
359 let entry_block = trampoline_builder.create_block();
360 trampoline_builder.append_block_params_for_function_params(entry_block);
361 let fn_args = trampoline_builder.func.dfg.block_params(entry_block).to_vec();
362
363 trampoline_builder.switch_to_block(entry_block);
364 let instance_ptr = trampoline_builder.ins().iconst(pointer_type, instance_ptr as u64 as i64);
365 let trampoline_ptr = trampoline_builder.ins().func_addr(pointer_type, trampoline_fn);
366 let jitted_fn = trampoline_builder.ins().call(jit_fn, &[instance_ptr, trampoline_ptr]);
367 let jitted_fn = trampoline_builder.func.dfg.inst_results(jitted_fn)[0];
368 let call_inst = trampoline_builder.ins().call_indirect(sig_ref, jitted_fn, &fn_args);
369 let ret_vals = trampoline_builder.func.dfg.inst_results(call_inst).to_vec();
370 trampoline_builder.ins().return_(&ret_vals);
371
372 module
373 .define_function(
374 func_id,
375 &mut cx.cached_context,
376 &mut NullTrapSink {},
377 &mut NullStackMapSink {},
378 )
379 .unwrap();
380 }
381