rust/src/librustc_metadata/native_libs.rs

270 lines
11 KiB
Rust
Raw Normal View History

use errors::struct_span_err;
use rustc::middle::cstore::{self, NativeLibrary};
use rustc::session::Session;
use rustc::ty::TyCtxt;
2019-12-24 05:02:53 +01:00
use rustc_data_structures::fx::FxHashSet;
use rustc_error_codes::*;
use rustc_hir as hir;
use rustc_hir::itemlikevisit::ItemLikeVisitor;
use rustc_span::source_map::Span;
2020-01-01 19:30:57 +01:00
use rustc_span::symbol::{kw, sym, Symbol};
use rustc_target::spec::abi::Abi;
use syntax::attr;
use syntax::feature_gate::feature_err;
crate fn collect(tcx: TyCtxt<'_>) -> Vec<NativeLibrary> {
2019-12-22 23:42:04 +01:00
let mut collector = Collector { tcx, libs: Vec::new() };
tcx.hir().krate().visit_all_item_likes(&mut collector);
collector.process_command_line();
return collector.libs;
}
crate fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
match lib.cfg {
Some(ref cfg) => attr::cfg_matches(cfg, &sess.parse_sess, None),
None => true,
}
}
struct Collector<'tcx> {
2019-06-13 23:48:52 +02:00
tcx: TyCtxt<'tcx>,
libs: Vec<NativeLibrary>,
}
impl ItemLikeVisitor<'tcx> for Collector<'tcx> {
2019-11-28 19:28:50 +01:00
fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
2019-09-26 18:51:36 +02:00
let fm = match it.kind {
2018-07-11 17:36:06 +02:00
hir::ItemKind::ForeignMod(ref fm) => fm,
_ => return,
};
2019-12-22 23:42:04 +01:00
if fm.abi == Abi::Rust || fm.abi == Abi::RustIntrinsic || fm.abi == Abi::PlatformIntrinsic {
return;
}
// Process all of the #[link(..)]-style arguments
for m in it.attrs.iter().filter(|a| a.check_name(sym::link)) {
let items = match m.meta_item_list() {
Some(item) => item,
None => continue,
};
let mut lib = NativeLibrary {
name: None,
kind: cstore::NativeUnknown,
cfg: None,
foreign_module: Some(self.tcx.hir().local_def_id(it.hir_id)),
wasm_import_module: None,
};
let mut kind_specified = false;
for item in items.iter() {
if item.check_name(sym::kind) {
kind_specified = true;
let kind = match item.value_str() {
Some(name) => name,
None => continue, // skip like historical compilers
};
lib.kind = match &*kind.as_str() {
"static" => cstore::NativeStatic,
"static-nobundle" => cstore::NativeStaticNobundle,
"dylib" => cstore::NativeUnknown,
"framework" => cstore::NativeFramework,
2019-08-27 16:42:44 +02:00
"raw-dylib" => cstore::NativeRawDylib,
k => {
2019-12-22 23:42:04 +01:00
struct_span_err!(
self.tcx.sess,
item.span(),
E0458,
"unknown kind: `{}`",
k
)
.span_label(item.span(), "unknown kind")
.span_label(m.span, "")
.emit();
cstore::NativeUnknown
}
};
} else if item.check_name(sym::name) {
lib.name = item.value_str();
} else if item.check_name(sym::cfg) {
let cfg = match item.meta_item_list() {
Some(list) => list,
None => continue, // skip like historical compilers
};
if cfg.is_empty() {
2019-12-22 23:42:04 +01:00
self.tcx.sess.span_err(item.span(), "`cfg()` must have an argument");
} else if let cfg @ Some(..) = cfg[0].meta_item() {
lib.cfg = cfg.cloned();
} else {
self.tcx.sess.span_err(cfg[0].span(), "invalid argument for `cfg(..)`");
}
} else if item.check_name(sym::wasm_import_module) {
match item.value_str() {
Some(s) => lib.wasm_import_module = Some(s),
None => {
let msg = "must be of the form `#[link(wasm_import_module = \"...\")]`";
self.tcx.sess.span_err(item.span(), msg);
}
}
} else {
// currently, like past compilers, ignore unknown
// directives here.
}
}
// In general we require #[link(name = "...")] but we allow
// #[link(wasm_import_module = "...")] without the `name`.
let requires_name = kind_specified || lib.wasm_import_module.is_none();
if lib.name.is_none() && requires_name {
2019-12-22 23:42:04 +01:00
struct_span_err!(
self.tcx.sess,
m.span,
E0459,
"`#[link(...)]` specified without \
`name = \"foo\"`"
)
.span_label(m.span, "missing `name` argument")
.emit();
}
self.register_native_lib(Some(m.span), lib);
}
}
2019-11-28 21:47:10 +01:00
fn visit_trait_item(&mut self, _it: &'tcx hir::TraitItem<'tcx>) {}
2019-11-28 22:16:44 +01:00
fn visit_impl_item(&mut self, _it: &'tcx hir::ImplItem<'tcx>) {}
}
impl Collector<'tcx> {
fn register_native_lib(&mut self, span: Option<Span>, lib: NativeLibrary) {
2019-09-05 03:54:01 +02:00
if lib.name.as_ref().map(|&s| s == kw::Invalid).unwrap_or(false) {
match span {
Some(span) => {
2019-12-22 23:42:04 +01:00
struct_span_err!(
self.tcx.sess,
span,
E0454,
"`#[link(name = \"\")]` given with empty name"
)
.span_label(span, "empty name given")
.emit();
}
None => {
self.tcx.sess.err("empty library name given via `-l`");
}
}
2019-12-22 23:42:04 +01:00
return;
}
let is_osx = self.tcx.sess.target.target.options.is_like_osx;
if lib.kind == cstore::NativeFramework && !is_osx {
let msg = "native frameworks are only available on macOS targets";
match span {
Some(span) => struct_span_err!(self.tcx.sess, span, E0455, "{}", msg).emit(),
None => self.tcx.sess.err(msg),
}
}
2018-02-14 16:11:02 +01:00
if lib.cfg.is_some() && !self.tcx.features().link_cfg {
feature_err(&self.tcx.sess.parse_sess, sym::link_cfg, span.unwrap(), "is unstable")
.emit();
}
2019-12-22 23:42:04 +01:00
if lib.kind == cstore::NativeStaticNobundle && !self.tcx.features().static_nobundle {
feature_err(
&self.tcx.sess.parse_sess,
sym::static_nobundle,
span.unwrap_or_else(|| rustc_span::DUMMY_SP),
2019-12-22 23:42:04 +01:00
"kind=\"static-nobundle\" is unstable",
)
.emit();
}
2019-12-22 23:42:04 +01:00
if lib.kind == cstore::NativeRawDylib && !self.tcx.features().raw_dylib {
feature_err(
&self.tcx.sess.parse_sess,
sym::raw_dylib,
span.unwrap_or_else(|| rustc_span::DUMMY_SP),
2019-12-22 23:42:04 +01:00
"kind=\"raw-dylib\" is unstable",
)
.emit();
2019-08-27 16:42:44 +02:00
}
self.libs.push(lib);
}
// Process libs passed on the command line
fn process_command_line(&mut self) {
// First, check for errors
let mut renames = FxHashSet::default();
for &(ref name, ref new_name, _) in &self.tcx.sess.opts.libs {
if let &Some(ref new_name) = new_name {
2019-12-22 23:42:04 +01:00
let any_duplicate = self
.libs
.iter()
.filter_map(|lib| lib.name.as_ref())
.any(|n| n.as_str() == *name);
if new_name.is_empty() {
2019-12-22 23:42:04 +01:00
self.tcx.sess.err(&format!(
"an empty renaming target was specified for library `{}`",
name
));
} else if !any_duplicate {
2019-12-22 23:42:04 +01:00
self.tcx.sess.err(&format!(
"renaming of the library `{}` was specified, \
however this crate contains no `#[link(...)]` \
2019-12-22 23:42:04 +01:00
attributes referencing this library.",
name
));
} else if !renames.insert(name) {
2019-12-22 23:42:04 +01:00
self.tcx.sess.err(&format!(
"multiple renamings were \
specified for library `{}` .",
2019-12-22 23:42:04 +01:00
name
));
}
}
}
2018-08-19 15:30:23 +02:00
// Update kind and, optionally, the name of all native libraries
// (there may be more than one) with the specified name. If any
// library is mentioned more than once, keep the latest mention
// of it, so that any possible dependent libraries appear before
// it. (This ensures that the linker is able to see symbols from
// all possible dependent libraries before linking in the library
// in question.)
for &(ref name, ref new_name, kind) in &self.tcx.sess.opts.libs {
// If we've already added any native libraries with the same
2018-12-20 22:19:55 +01:00
// name, they will be pulled out into `existing`, so that we
// can move them to the end of the list below.
2019-12-22 23:42:04 +01:00
let mut existing = self
.libs
.drain_filter(|lib| {
if let Some(lib_name) = lib.name {
if lib_name.as_str() == *name {
if let Some(k) = kind {
lib.kind = k;
}
if let &Some(ref new_name) = new_name {
lib.name = Some(Symbol::intern(new_name));
}
return true;
}
}
2019-12-22 23:42:04 +01:00
false
})
.collect::<Vec<_>>();
if existing.is_empty() {
// Add if not found
let new_name = new_name.as_ref().map(|s| &**s); // &Option<String> -> Option<&str>
let lib = NativeLibrary {
name: Some(Symbol::intern(new_name.unwrap_or(name))),
kind: if let Some(k) = kind { k } else { cstore::NativeUnknown },
cfg: None,
rustc: Add a `#[wasm_import_module]` attribute This commit adds a new attribute to the Rust compiler specific to the wasm target (and no other targets). The `#[wasm_import_module]` attribute is used to specify the module that a name is imported from, and is used like so: #[wasm_import_module = "./foo.js"] extern { fn some_js_function(); } Here the import of the symbol `some_js_function` is tagged with the `./foo.js` module in the wasm output file. Wasm-the-format includes two fields on all imports, a module and a field. The field is the symbol name (`some_js_function` above) and the module has historically unconditionally been `"env"`. I'm not sure if this `"env"` convention has asm.js or LLVM roots, but regardless we'd like the ability to configure it! The proposed ES module integration with wasm (aka a wasm module is "just another ES module") requires that the import module of wasm imports is interpreted as an ES module import, meaning that you'll need to encode paths, NPM packages, etc. As a result, we'll need this to be something other than `"env"`! Unfortunately neither our version of LLVM nor LLD supports custom import modules (aka anything not `"env"`). My hope is that by the time LLVM 7 is released both will have support, but in the meantime this commit adds some primitive encoding/decoding of wasm files to the compiler. This way rustc postprocesses the wasm module that LLVM emits to ensure it's got all the imports we'd like to have in it. Eventually I'd ideally like to unconditionally require this attribute to be placed on all `extern { ... }` blocks. For now though it seemed prudent to add it as an unstable attribute, so for now it's not required (as that'd force usage of a feature gate). Hopefully it doesn't take too long to "stabilize" this! cc rust-lang-nursery/rust-wasm#29
2018-02-10 23:28:17 +01:00
foreign_module: None,
wasm_import_module: None,
};
self.register_native_lib(None, lib);
} else {
// Move all existing libraries with the same name to the
// end of the command line.
self.libs.append(&mut existing);
}
}
}
}