1 //! Used by `rustc` when loading a plugin.
4 use libloading::Library;
6 use rustc_errors::struct_span_err;
7 use rustc_metadata::locator;
8 use rustc_session::cstore::MetadataLoader;
9 use rustc_session::Session;
10 use rustc_span::symbol::{sym, Ident};
13 use std::borrow::ToOwned;
16 use std::path::PathBuf;
18 /// Pointer to a registrar function.
19 type PluginRegistrarFn = fn(&mut Registry<'_>);
21 fn call_malformed_plugin_attribute(sess: &Session, span: Span) {
22 struct_span_err!(sess, span, E0498, "malformed `plugin` attribute")
23 .span_label(span, "malformed attribute")
27 /// Read plugin metadata and dynamically load registrar functions.
30 metadata_loader: &dyn MetadataLoader,
32 ) -> Vec<PluginRegistrarFn> {
33 let mut plugins = Vec::new();
35 for attr in &krate.attrs {
36 if !attr.has_name(sym::plugin) {
40 for plugin in attr.meta_item_list().unwrap_or_default() {
41 match plugin.ident() {
42 Some(ident) if plugin.is_word() => {
43 load_plugin(&mut plugins, sess, metadata_loader, ident)
45 _ => call_malformed_plugin_attribute(sess, plugin.span()),
54 plugins: &mut Vec<PluginRegistrarFn>,
56 metadata_loader: &dyn MetadataLoader,
59 let lib = locator::find_plugin_registrar(sess, metadata_loader, ident.span, ident.name);
60 let fun = dylink_registrar(lib).unwrap_or_else(|err| {
61 // This is fatal: there are almost certainly macros we need inside this crate, so
62 // continuing would spew "macro undefined" errors.
63 sess.span_fatal(ident.span, &err.to_string());
68 /// Dynamically link a registrar function into the compiler process.
69 fn dylink_registrar(lib_path: PathBuf) -> Result<PluginRegistrarFn, libloading::Error> {
70 // Make sure the path contains a / or the linker will search for it.
71 let lib_path = env::current_dir().unwrap().join(&lib_path);
73 let lib = unsafe { Library::new(&lib_path) }?;
75 let registrar_sym = unsafe { lib.get::<PluginRegistrarFn>(b"__rustc_plugin_registrar") }?;
77 // Intentionally leak the dynamic library. We can't ever unload it
78 // since the library can make things that will live arbitrarily long
79 // (e.g., an Rc cycle or a thread).
80 let registrar_sym = unsafe { registrar_sym.into_raw() };