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::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 abi = match it.kind {
37 hir::ItemKind::ForeignMod { abi, .. } => abi,
41 if abi == Abi::Rust || abi == Abi::RustIntrinsic || abi == Abi::PlatformIntrinsic {
45 // Process all of the #[link(..)]-style arguments
46 let sess = &self.tcx.sess;
47 for m in self.tcx.hir().attrs(it.hir_id()).iter().filter(|a| sess.check_name(a, sym::link))
49 let items = match m.meta_item_list() {
53 let mut lib = NativeLib {
55 kind: NativeLibKind::Unspecified,
57 foreign_module: Some(it.def_id.to_def_id()),
58 wasm_import_module: None,
61 let mut kind_specified = false;
63 for item in items.iter() {
64 if item.has_name(sym::kind) {
65 kind_specified = true;
66 let kind = match item.value_str() {
68 None => continue, // skip like historical compilers
70 lib.kind = match &*kind.as_str() {
71 "static" => NativeLibKind::Static { bundle: None, whole_archive: None },
72 "static-nobundle" => {
73 sess.struct_span_warn(
75 "library kind `static-nobundle` has been superseded by specifying \
76 modifier `-bundle` with library kind `static`",
79 NativeLibKind::Static { bundle: Some(false), whole_archive: None }
81 "dylib" => NativeLibKind::Dylib { as_needed: None },
82 "framework" => NativeLibKind::Framework { as_needed: None },
83 "raw-dylib" => NativeLibKind::RawDylib,
85 struct_span_err!(sess, item.span(), E0458, "unknown kind: `{}`", k)
86 .span_label(item.span(), "unknown kind")
87 .span_label(m.span, "")
89 NativeLibKind::Unspecified
92 } else if item.has_name(sym::name) {
93 lib.name = item.value_str();
94 } else if item.has_name(sym::cfg) {
95 let cfg = match item.meta_item_list() {
97 None => continue, // skip like historical compilers
100 sess.span_err(item.span(), "`cfg()` must have an argument");
101 } else if let cfg @ Some(..) = cfg[0].meta_item() {
102 lib.cfg = cfg.cloned();
104 sess.span_err(cfg[0].span(), "invalid argument for `cfg(..)`");
106 } else if item.has_name(sym::wasm_import_module) {
107 match item.value_str() {
108 Some(s) => lib.wasm_import_module = Some(s),
110 let msg = "must be of the form `#[link(wasm_import_module = \"...\")]`";
111 sess.span_err(item.span(), msg);
115 // currently, like past compilers, ignore unknown
120 // Do this outside the above loop so we don't depend on modifiers coming
122 if let Some(item) = items.iter().find(|item| item.has_name(sym::modifiers)) {
123 if let Some(modifiers) = item.value_str() {
124 let span = item.name_value_literal_span().unwrap();
125 for modifier in modifiers.as_str().split(',') {
126 let (modifier, value) = match modifier.strip_prefix(&['+', '-'][..]) {
127 Some(m) => (m, modifier.starts_with('+')),
131 "invalid linking modifier syntax, expected '+' or '-' prefix \
132 before one of: bundle, verbatim, whole-archive, as-needed",
138 match (modifier, &mut lib.kind) {
139 ("bundle", NativeLibKind::Static { bundle, .. }) => {
140 *bundle = Some(value);
142 ("bundle", _) => sess.span_err(
144 "bundle linking modifier is only compatible with \
145 `static` linking kind",
148 ("verbatim", _) => lib.verbatim = Some(value),
150 ("whole-archive", NativeLibKind::Static { whole_archive, .. }) => {
151 *whole_archive = Some(value);
153 ("whole-archive", _) => sess.span_err(
155 "whole-archive linking modifier is only compatible with \
156 `static` linking kind",
159 ("as-needed", NativeLibKind::Dylib { as_needed })
160 | ("as-needed", NativeLibKind::Framework { as_needed }) => {
161 *as_needed = Some(value);
163 ("as-needed", _) => sess.span_err(
165 "as-needed linking modifier is only compatible with \
166 `dylib` and `framework` linking kinds",
172 "unrecognized linking modifier `{}`, expected one \
173 of: bundle, verbatim, whole-archive, as-needed",
180 let msg = "must be of the form `#[link(modifiers = \"...\")]`";
181 sess.span_err(item.span(), msg);
185 // In general we require #[link(name = "...")] but we allow
186 // #[link(wasm_import_module = "...")] without the `name`.
187 let requires_name = kind_specified || lib.wasm_import_module.is_none();
188 if lib.name.is_none() && requires_name {
193 "`#[link(...)]` specified without \
196 .span_label(m.span, "missing `name` argument")
199 self.register_native_lib(Some(m.span), lib);
203 fn visit_trait_item(&mut self, _it: &'tcx hir::TraitItem<'tcx>) {}
204 fn visit_impl_item(&mut self, _it: &'tcx hir::ImplItem<'tcx>) {}
205 fn visit_foreign_item(&mut self, _it: &'tcx hir::ForeignItem<'tcx>) {}
208 impl Collector<'tcx> {
209 fn register_native_lib(&mut self, span: Option<Span>, lib: NativeLib) {
210 if lib.name.as_ref().map_or(false, |&s| s == kw::Empty) {
217 "`#[link(name = \"\")]` given with empty name"
219 .span_label(span, "empty name given")
223 self.tcx.sess.err("empty library name given via `-l`");
228 let is_osx = self.tcx.sess.target.is_like_osx;
229 if matches!(lib.kind, NativeLibKind::Framework { .. }) && !is_osx {
230 let msg = "native frameworks are only available on macOS targets";
232 Some(span) => struct_span_err!(self.tcx.sess, span, E0455, "{}", msg).emit(),
233 None => self.tcx.sess.err(msg),
236 if lib.cfg.is_some() && !self.tcx.features().link_cfg {
238 &self.tcx.sess.parse_sess,
241 "kind=\"link_cfg\" is unstable",
245 if matches!(lib.kind, NativeLibKind::Static { bundle: Some(false), .. })
246 && !self.tcx.features().static_nobundle
249 &self.tcx.sess.parse_sess,
250 sym::static_nobundle,
251 span.unwrap_or(rustc_span::DUMMY_SP),
252 "kind=\"static-nobundle\" is unstable",
256 if lib.kind == NativeLibKind::RawDylib && !self.tcx.features().raw_dylib {
258 &self.tcx.sess.parse_sess,
260 span.unwrap_or(rustc_span::DUMMY_SP),
261 "kind=\"raw-dylib\" is unstable",
268 // Process libs passed on the command line
269 fn process_command_line(&mut self) {
270 // First, check for errors
271 let mut renames = FxHashSet::default();
272 for lib in &self.tcx.sess.opts.libs {
273 if let Some(ref new_name) = lib.new_name {
274 let any_duplicate = self
277 .filter_map(|lib| lib.name.as_ref())
278 .any(|n| &n.as_str() == &lib.name);
279 if new_name.is_empty() {
280 self.tcx.sess.err(&format!(
281 "an empty renaming target was specified for library `{}`",
284 } else if !any_duplicate {
285 self.tcx.sess.err(&format!(
286 "renaming of the library `{}` was specified, \
287 however this crate contains no `#[link(...)]` \
288 attributes referencing this library.",
291 } else if !renames.insert(&lib.name) {
292 self.tcx.sess.err(&format!(
293 "multiple renamings were \
294 specified for library `{}` .",
301 // Update kind and, optionally, the name of all native libraries
302 // (there may be more than one) with the specified name. If any
303 // library is mentioned more than once, keep the latest mention
304 // of it, so that any possible dependent libraries appear before
305 // it. (This ensures that the linker is able to see symbols from
306 // all possible dependent libraries before linking in the library
308 for passed_lib in &self.tcx.sess.opts.libs {
309 // If we've already added any native libraries with the same
310 // name, they will be pulled out into `existing`, so that we
311 // can move them to the end of the list below.
312 let mut existing = self
314 .drain_filter(|lib| {
315 if let Some(lib_name) = lib.name {
316 if lib_name.as_str() == passed_lib.name {
317 if passed_lib.kind != NativeLibKind::Unspecified {
318 lib.kind = passed_lib.kind;
320 if let Some(new_name) = &passed_lib.new_name {
321 lib.name = Some(Symbol::intern(new_name));
323 lib.verbatim = passed_lib.verbatim;
329 .collect::<Vec<_>>();
330 if existing.is_empty() {
332 let new_name = passed_lib.new_name.as_ref().map(|s| &**s); // &Option<String> -> Option<&str>
333 let lib = NativeLib {
334 name: Some(Symbol::intern(new_name.unwrap_or(&passed_lib.name))),
335 kind: passed_lib.kind,
337 foreign_module: None,
338 wasm_import_module: None,
339 verbatim: passed_lib.verbatim,
341 self.register_native_lib(None, lib);
343 // Move all existing libraries with the same name to the
344 // end of the command line.
345 self.libs.append(&mut existing);