1 use rustc_attr as attr;
2 use rustc_data_structures::fx::FxHashSet;
3 use rustc_errors::struct_span_err;
5 use rustc_hir::itemlikevisit::ItemLikeVisitor;
6 use rustc_middle::middle::cstore::NativeLib;
7 use rustc_middle::ty::TyCtxt;
8 use rustc_session::parse::feature_err;
9 use rustc_session::utils::NativeLibKind;
10 use rustc_session::Session;
11 use rustc_span::source_map::Span;
12 use rustc_span::symbol::{kw, sym, Symbol};
13 use rustc_target::spec::abi::Abi;
15 crate fn collect(tcx: TyCtxt<'_>) -> Vec<NativeLib> {
16 let mut collector = Collector { tcx, libs: Vec::new() };
17 tcx.hir().krate().visit_all_item_likes(&mut collector);
18 collector.process_command_line();
22 crate fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
24 Some(ref cfg) => attr::cfg_matches(cfg, &sess.parse_sess, None),
29 struct Collector<'tcx> {
34 impl ItemLikeVisitor<'tcx> for Collector<'tcx> {
35 fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
36 let fm = match it.kind {
37 hir::ItemKind::ForeignMod(ref fm) => fm,
41 if fm.abi == Abi::Rust || fm.abi == Abi::RustIntrinsic || fm.abi == Abi::PlatformIntrinsic {
45 // Process all of the #[link(..)]-style arguments
46 for m in it.attrs.iter().filter(|a| a.check_name(sym::link)) {
47 let items = match m.meta_item_list() {
51 let mut lib = NativeLib {
53 kind: NativeLibKind::Unspecified,
55 foreign_module: Some(self.tcx.hir().local_def_id(it.hir_id).to_def_id()),
56 wasm_import_module: None,
58 let mut kind_specified = false;
60 for item in items.iter() {
61 if item.check_name(sym::kind) {
62 kind_specified = true;
63 let kind = match item.value_str() {
65 None => continue, // skip like historical compilers
67 lib.kind = match &*kind.as_str() {
68 "static" => NativeLibKind::StaticBundle,
69 "static-nobundle" => NativeLibKind::StaticNoBundle,
70 "dylib" => NativeLibKind::Dylib,
71 "framework" => NativeLibKind::Framework,
72 "raw-dylib" => NativeLibKind::RawDylib,
81 .span_label(item.span(), "unknown kind")
82 .span_label(m.span, "")
84 NativeLibKind::Unspecified
87 } else if item.check_name(sym::name) {
88 lib.name = item.value_str();
89 } else if item.check_name(sym::cfg) {
90 let cfg = match item.meta_item_list() {
92 None => continue, // skip like historical compilers
95 self.tcx.sess.span_err(item.span(), "`cfg()` must have an argument");
96 } else if let cfg @ Some(..) = cfg[0].meta_item() {
97 lib.cfg = cfg.cloned();
99 self.tcx.sess.span_err(cfg[0].span(), "invalid argument for `cfg(..)`");
101 } else if item.check_name(sym::wasm_import_module) {
102 match item.value_str() {
103 Some(s) => lib.wasm_import_module = Some(s),
105 let msg = "must be of the form `#[link(wasm_import_module = \"...\")]`";
106 self.tcx.sess.span_err(item.span(), msg);
110 // currently, like past compilers, ignore unknown
115 // In general we require #[link(name = "...")] but we allow
116 // #[link(wasm_import_module = "...")] without the `name`.
117 let requires_name = kind_specified || lib.wasm_import_module.is_none();
118 if lib.name.is_none() && requires_name {
123 "`#[link(...)]` specified without \
126 .span_label(m.span, "missing `name` argument")
129 self.register_native_lib(Some(m.span), lib);
133 fn visit_trait_item(&mut self, _it: &'tcx hir::TraitItem<'tcx>) {}
134 fn visit_impl_item(&mut self, _it: &'tcx hir::ImplItem<'tcx>) {}
137 impl Collector<'tcx> {
138 fn register_native_lib(&mut self, span: Option<Span>, lib: NativeLib) {
139 if lib.name.as_ref().map(|&s| s == kw::Invalid).unwrap_or(false) {
146 "`#[link(name = \"\")]` given with empty name"
148 .span_label(span, "empty name given")
152 self.tcx.sess.err("empty library name given via `-l`");
157 let is_osx = self.tcx.sess.target.target.options.is_like_osx;
158 if lib.kind == NativeLibKind::Framework && !is_osx {
159 let msg = "native frameworks are only available on macOS targets";
161 Some(span) => struct_span_err!(self.tcx.sess, span, E0455, "{}", msg).emit(),
162 None => self.tcx.sess.err(msg),
165 if lib.cfg.is_some() && !self.tcx.features().link_cfg {
167 &self.tcx.sess.parse_sess,
170 "kind=\"link_cfg\" is unstable",
174 if lib.kind == NativeLibKind::StaticNoBundle && !self.tcx.features().static_nobundle {
176 &self.tcx.sess.parse_sess,
177 sym::static_nobundle,
178 span.unwrap_or_else(|| rustc_span::DUMMY_SP),
179 "kind=\"static-nobundle\" is unstable",
183 if lib.kind == NativeLibKind::RawDylib && !self.tcx.features().raw_dylib {
185 &self.tcx.sess.parse_sess,
187 span.unwrap_or_else(|| rustc_span::DUMMY_SP),
188 "kind=\"raw-dylib\" is unstable",
195 // Process libs passed on the command line
196 fn process_command_line(&mut self) {
197 // First, check for errors
198 let mut renames = FxHashSet::default();
199 for &(ref name, ref new_name, _) in &self.tcx.sess.opts.libs {
200 if let &Some(ref new_name) = new_name {
201 let any_duplicate = self
204 .filter_map(|lib| lib.name.as_ref())
205 .any(|n| n.as_str() == *name);
206 if new_name.is_empty() {
207 self.tcx.sess.err(&format!(
208 "an empty renaming target was specified for library `{}`",
211 } else if !any_duplicate {
212 self.tcx.sess.err(&format!(
213 "renaming of the library `{}` was specified, \
214 however this crate contains no `#[link(...)]` \
215 attributes referencing this library.",
218 } else if !renames.insert(name) {
219 self.tcx.sess.err(&format!(
220 "multiple renamings were \
221 specified for library `{}` .",
228 // Update kind and, optionally, the name of all native libraries
229 // (there may be more than one) with the specified name. If any
230 // library is mentioned more than once, keep the latest mention
231 // of it, so that any possible dependent libraries appear before
232 // it. (This ensures that the linker is able to see symbols from
233 // all possible dependent libraries before linking in the library
235 for &(ref name, ref new_name, kind) in &self.tcx.sess.opts.libs {
236 // If we've already added any native libraries with the same
237 // name, they will be pulled out into `existing`, so that we
238 // can move them to the end of the list below.
239 let mut existing = self
241 .drain_filter(|lib| {
242 if let Some(lib_name) = lib.name {
243 if lib_name.as_str() == *name {
244 if kind != NativeLibKind::Unspecified {
247 if let &Some(ref new_name) = new_name {
248 lib.name = Some(Symbol::intern(new_name));
255 .collect::<Vec<_>>();
256 if existing.is_empty() {
258 let new_name = new_name.as_ref().map(|s| &**s); // &Option<String> -> Option<&str>
259 let lib = NativeLib {
260 name: Some(Symbol::intern(new_name.unwrap_or(name))),
263 foreign_module: None,
264 wasm_import_module: None,
266 self.register_native_lib(None, lib);
268 // Move all existing libraries with the same name to the
269 // end of the command line.
270 self.libs.append(&mut existing);