1 //! Used by `rustc` when loading a plugin.
4 use rustc::middle::cstore::MetadataLoader;
5 use rustc::session::Session;
6 use rustc_ast::ast::{Crate, Ident};
7 use rustc_errors::struct_span_err;
8 use rustc_metadata::locator;
9 use rustc_span::symbol::sym;
12 use std::borrow::ToOwned;
15 use std::path::PathBuf;
17 /// Pointer to a registrar function.
18 type PluginRegistrarFn = fn(&mut Registry<'_>);
20 fn call_malformed_plugin_attribute(sess: &Session, span: Span) {
21 struct_span_err!(sess, span, E0498, "malformed `plugin` attribute")
22 .span_label(span, "malformed attribute")
26 /// Read plugin metadata and dynamically load registrar functions.
29 metadata_loader: &dyn MetadataLoader,
31 ) -> Vec<PluginRegistrarFn> {
32 let mut plugins = Vec::new();
34 for attr in &krate.attrs {
35 if !attr.check_name(sym::plugin) {
39 for plugin in attr.meta_item_list().unwrap_or_default() {
40 match plugin.ident() {
41 Some(ident) if plugin.is_word() => {
42 load_plugin(&mut plugins, sess, metadata_loader, ident)
44 _ => call_malformed_plugin_attribute(sess, plugin.span()),
53 plugins: &mut Vec<PluginRegistrarFn>,
55 metadata_loader: &dyn MetadataLoader,
58 let registrar = locator::find_plugin_registrar(sess, metadata_loader, ident.span, ident.name);
60 if let Some((lib, disambiguator)) = registrar {
61 let symbol = sess.generate_plugin_registrar_symbol(disambiguator);
62 let fun = dylink_registrar(sess, ident.span, lib, symbol);
67 // Dynamically link a registrar function into the compiler process.
73 ) -> PluginRegistrarFn {
74 use rustc_metadata::dynamic_lib::DynamicLibrary;
76 // Make sure the path contains a / or the linker will search for it.
77 let path = env::current_dir().unwrap().join(&path);
79 let lib = match DynamicLibrary::open(Some(&path)) {
81 // this is fatal: there are almost certainly macros we need
82 // inside this crate, so continue would spew "macro undefined"
84 Err(err) => sess.span_fatal(span, &err),
88 let registrar = match lib.symbol(&symbol) {
89 Ok(registrar) => mem::transmute::<*mut u8, PluginRegistrarFn>(registrar),
90 // again fatal if we can't register macros
91 Err(err) => sess.span_fatal(span, &err),
94 // Intentionally leak the dynamic library. We can't ever unload it
95 // since the library can make things that will live arbitrarily long
96 // (e.g., an @-box cycle or a thread).