1 //! Used by `rustc` when loading a plugin.
4 use rustc::middle::cstore::MetadataLoader;
5 use rustc::session::Session;
6 use rustc_error_codes::*;
7 use rustc_errors::struct_span_err;
8 use rustc_metadata::locator;
9 use rustc_span::symbol::sym;
11 use syntax::ast::{Crate, 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.check_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 registrar = locator::find_plugin_registrar(sess, metadata_loader, ident.span, ident.name);
61 if let Some((lib, disambiguator)) = registrar {
62 let symbol = sess.generate_plugin_registrar_symbol(disambiguator);
63 let fun = dylink_registrar(sess, ident.span, lib, symbol);
68 // Dynamically link a registrar function into the compiler process.
74 ) -> PluginRegistrarFn {
75 use rustc_metadata::dynamic_lib::DynamicLibrary;
77 // Make sure the path contains a / or the linker will search for it.
78 let path = env::current_dir().unwrap().join(&path);
80 let lib = match DynamicLibrary::open(Some(&path)) {
82 // this is fatal: there are almost certainly macros we need
83 // inside this crate, so continue would spew "macro undefined"
85 Err(err) => sess.span_fatal(span, &err),
89 let registrar = match lib.symbol(&symbol) {
90 Ok(registrar) => mem::transmute::<*mut u8, PluginRegistrarFn>(registrar),
91 // again fatal if we can't register macros
92 Err(err) => sess.span_fatal(span, &err),
95 // Intentionally leak the dynamic library. We can't ever unload it
96 // since the library can make things that will live arbitrarily long
97 // (e.g., an @-box cycle or a thread).