1 //! Used by `rustc` when loading a plugin.
4 use rustc::middle::cstore::MetadataLoader;
5 use rustc::session::Session;
6 use rustc_metadata::locator;
9 use std::borrow::ToOwned;
12 use std::path::PathBuf;
13 use syntax::ast::{Crate, Ident};
14 use syntax::struct_span_err;
15 use syntax::symbol::sym;
17 use rustc_error_codes::*;
19 /// Pointer to a registrar function.
20 type PluginRegistrarFn = fn(&mut Registry<'_>);
22 fn call_malformed_plugin_attribute(sess: &Session, span: Span) {
23 struct_span_err!(sess, span, E0498, "malformed `plugin` attribute")
24 .span_label(span, "malformed attribute")
28 /// Read plugin metadata and dynamically load registrar functions.
31 metadata_loader: &dyn MetadataLoader,
33 ) -> Vec<PluginRegistrarFn> {
34 let mut plugins = Vec::new();
36 for attr in &krate.attrs {
37 if !attr.check_name(sym::plugin) {
41 for plugin in attr.meta_item_list().unwrap_or_default() {
42 match plugin.ident() {
43 Some(ident) if plugin.is_word() => {
44 load_plugin(&mut plugins, sess, metadata_loader, ident)
46 _ => call_malformed_plugin_attribute(sess, plugin.span()),
55 plugins: &mut Vec<PluginRegistrarFn>,
57 metadata_loader: &dyn MetadataLoader,
60 let registrar = locator::find_plugin_registrar(sess, metadata_loader, ident.span, ident.name);
62 if let Some((lib, disambiguator)) = registrar {
63 let symbol = sess.generate_plugin_registrar_symbol(disambiguator);
64 let fun = dylink_registrar(sess, ident.span, lib, symbol);
69 // Dynamically link a registrar function into the compiler process.
75 ) -> PluginRegistrarFn {
76 use rustc_metadata::dynamic_lib::DynamicLibrary;
78 // Make sure the path contains a / or the linker will search for it.
79 let path = env::current_dir().unwrap().join(&path);
81 let lib = match DynamicLibrary::open(Some(&path)) {
83 // this is fatal: there are almost certainly macros we need
84 // inside this crate, so continue would spew "macro undefined"
86 Err(err) => sess.span_fatal(span, &err),
90 let registrar = match lib.symbol(&symbol) {
91 Ok(registrar) => mem::transmute::<*mut u8, PluginRegistrarFn>(registrar),
92 // again fatal if we can't register macros
93 Err(err) => sess.span_fatal(span, &err),
96 // Intentionally leak the dynamic library. We can't ever unload it
97 // since the library can make things that will live arbitrarily long
98 // (e.g., an @-box cycle or a thread).