]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_metadata/src/native_libs.rs
New upstream version 1.54.0+dfsg1
[rustc.git] / compiler / rustc_metadata / src / native_libs.rs
1 use rustc_attr as attr;
2 use rustc_data_structures::fx::FxHashSet;
3 use rustc_errors::struct_span_err;
4 use rustc_hir as hir;
5 use rustc_hir::itemlikevisit::ItemLikeVisitor;
6 use rustc_middle::middle::cstore::{DllImport, 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};
12 use rustc_span::Span;
13 use rustc_target::spec::abi::Abi;
14
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();
19 collector.libs
20 }
21
22 crate fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
23 match lib.cfg {
24 Some(ref cfg) => attr::cfg_matches(cfg, &sess.parse_sess, None),
25 None => true,
26 }
27 }
28
29 struct Collector<'tcx> {
30 tcx: TyCtxt<'tcx>,
31 libs: Vec<NativeLib>,
32 }
33
34 impl ItemLikeVisitor<'tcx> for Collector<'tcx> {
35 fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
36 let (abi, foreign_mod_items) = match it.kind {
37 hir::ItemKind::ForeignMod { abi, items } => (abi, items),
38 _ => return,
39 };
40
41 if abi == Abi::Rust || abi == Abi::RustIntrinsic || abi == Abi::PlatformIntrinsic {
42 return;
43 }
44
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))
48 {
49 let items = match m.meta_item_list() {
50 Some(item) => item,
51 None => continue,
52 };
53 let mut lib = NativeLib {
54 name: None,
55 kind: NativeLibKind::Unspecified,
56 cfg: None,
57 foreign_module: Some(it.def_id.to_def_id()),
58 wasm_import_module: None,
59 verbatim: None,
60 dll_imports: Vec::new(),
61 };
62 let mut kind_specified = false;
63
64 for item in items.iter() {
65 if item.has_name(sym::kind) {
66 kind_specified = true;
67 let kind = match item.value_str() {
68 Some(name) => name,
69 None => continue, // skip like historical compilers
70 };
71 lib.kind = match &*kind.as_str() {
72 "static" => NativeLibKind::Static { bundle: None, whole_archive: None },
73 "static-nobundle" => {
74 sess.struct_span_warn(
75 item.span(),
76 "library kind `static-nobundle` has been superseded by specifying \
77 modifier `-bundle` with library kind `static`",
78 )
79 .emit();
80 NativeLibKind::Static { bundle: Some(false), whole_archive: None }
81 }
82 "dylib" => NativeLibKind::Dylib { as_needed: None },
83 "framework" => NativeLibKind::Framework { as_needed: None },
84 "raw-dylib" => NativeLibKind::RawDylib,
85 k => {
86 struct_span_err!(sess, item.span(), E0458, "unknown kind: `{}`", k)
87 .span_label(item.span(), "unknown kind")
88 .span_label(m.span, "")
89 .emit();
90 NativeLibKind::Unspecified
91 }
92 };
93 } else if item.has_name(sym::name) {
94 lib.name = item.value_str();
95 } else if item.has_name(sym::cfg) {
96 let cfg = match item.meta_item_list() {
97 Some(list) => list,
98 None => continue, // skip like historical compilers
99 };
100 if cfg.is_empty() {
101 sess.span_err(item.span(), "`cfg()` must have an argument");
102 } else if let cfg @ Some(..) = cfg[0].meta_item() {
103 lib.cfg = cfg.cloned();
104 } else {
105 sess.span_err(cfg[0].span(), "invalid argument for `cfg(..)`");
106 }
107 } else if item.has_name(sym::wasm_import_module) {
108 match item.value_str() {
109 Some(s) => lib.wasm_import_module = Some(s),
110 None => {
111 let msg = "must be of the form `#[link(wasm_import_module = \"...\")]`";
112 sess.span_err(item.span(), msg);
113 }
114 }
115 } else {
116 // currently, like past compilers, ignore unknown
117 // directives here.
118 }
119 }
120
121 // Do this outside the above loop so we don't depend on modifiers coming
122 // after kinds
123 if let Some(item) = items.iter().find(|item| item.has_name(sym::modifiers)) {
124 if let Some(modifiers) = item.value_str() {
125 let span = item.name_value_literal_span().unwrap();
126 for modifier in modifiers.as_str().split(',') {
127 let (modifier, value) = match modifier.strip_prefix(&['+', '-'][..]) {
128 Some(m) => (m, modifier.starts_with('+')),
129 None => {
130 sess.span_err(
131 span,
132 "invalid linking modifier syntax, expected '+' or '-' prefix \
133 before one of: bundle, verbatim, whole-archive, as-needed",
134 );
135 continue;
136 }
137 };
138
139 match (modifier, &mut lib.kind) {
140 ("bundle", NativeLibKind::Static { bundle, .. }) => {
141 *bundle = Some(value);
142 }
143 ("bundle", _) => sess.span_err(
144 span,
145 "bundle linking modifier is only compatible with \
146 `static` linking kind",
147 ),
148
149 ("verbatim", _) => lib.verbatim = Some(value),
150
151 ("whole-archive", NativeLibKind::Static { whole_archive, .. }) => {
152 *whole_archive = Some(value);
153 }
154 ("whole-archive", _) => sess.span_err(
155 span,
156 "whole-archive linking modifier is only compatible with \
157 `static` linking kind",
158 ),
159
160 ("as-needed", NativeLibKind::Dylib { as_needed })
161 | ("as-needed", NativeLibKind::Framework { as_needed }) => {
162 *as_needed = Some(value);
163 }
164 ("as-needed", _) => sess.span_err(
165 span,
166 "as-needed linking modifier is only compatible with \
167 `dylib` and `framework` linking kinds",
168 ),
169
170 _ => sess.span_err(
171 span,
172 &format!(
173 "unrecognized linking modifier `{}`, expected one \
174 of: bundle, verbatim, whole-archive, as-needed",
175 modifier
176 ),
177 ),
178 }
179 }
180 } else {
181 let msg = "must be of the form `#[link(modifiers = \"...\")]`";
182 sess.span_err(item.span(), msg);
183 }
184 }
185
186 // In general we require #[link(name = "...")] but we allow
187 // #[link(wasm_import_module = "...")] without the `name`.
188 let requires_name = kind_specified || lib.wasm_import_module.is_none();
189 if lib.name.is_none() && requires_name {
190 struct_span_err!(
191 sess,
192 m.span,
193 E0459,
194 "`#[link(...)]` specified without \
195 `name = \"foo\"`"
196 )
197 .span_label(m.span, "missing `name` argument")
198 .emit();
199 }
200
201 if lib.kind == NativeLibKind::RawDylib {
202 match abi {
203 Abi::C { .. } => (),
204 Abi::Cdecl => (),
205 _ => {
206 if sess.target.arch == "x86" {
207 sess.span_fatal(
208 it.span,
209 r#"`#[link(kind = "raw-dylib")]` only supports C and Cdecl ABIs"#,
210 );
211 }
212 }
213 };
214 lib.dll_imports.extend(
215 foreign_mod_items
216 .iter()
217 .map(|child_item| DllImport { name: child_item.ident.name, ordinal: None }),
218 );
219 }
220
221 self.register_native_lib(Some(m.span), lib);
222 }
223 }
224
225 fn visit_trait_item(&mut self, _it: &'tcx hir::TraitItem<'tcx>) {}
226 fn visit_impl_item(&mut self, _it: &'tcx hir::ImplItem<'tcx>) {}
227 fn visit_foreign_item(&mut self, _it: &'tcx hir::ForeignItem<'tcx>) {}
228 }
229
230 impl Collector<'tcx> {
231 fn register_native_lib(&mut self, span: Option<Span>, lib: NativeLib) {
232 if lib.name.as_ref().map_or(false, |&s| s == kw::Empty) {
233 match span {
234 Some(span) => {
235 struct_span_err!(
236 self.tcx.sess,
237 span,
238 E0454,
239 "`#[link(name = \"\")]` given with empty name"
240 )
241 .span_label(span, "empty name given")
242 .emit();
243 }
244 None => {
245 self.tcx.sess.err("empty library name given via `-l`");
246 }
247 }
248 return;
249 }
250 let is_osx = self.tcx.sess.target.is_like_osx;
251 if matches!(lib.kind, NativeLibKind::Framework { .. }) && !is_osx {
252 let msg = "native frameworks are only available on macOS targets";
253 match span {
254 Some(span) => struct_span_err!(self.tcx.sess, span, E0455, "{}", msg).emit(),
255 None => self.tcx.sess.err(msg),
256 }
257 }
258 if lib.cfg.is_some() && !self.tcx.features().link_cfg {
259 feature_err(
260 &self.tcx.sess.parse_sess,
261 sym::link_cfg,
262 span.unwrap(),
263 "kind=\"link_cfg\" is unstable",
264 )
265 .emit();
266 }
267 if matches!(lib.kind, NativeLibKind::Static { bundle: Some(false), .. })
268 && !self.tcx.features().static_nobundle
269 {
270 feature_err(
271 &self.tcx.sess.parse_sess,
272 sym::static_nobundle,
273 span.unwrap_or(rustc_span::DUMMY_SP),
274 "kind=\"static-nobundle\" is unstable",
275 )
276 .emit();
277 }
278 // this just unwraps lib.name; we already established that it isn't empty above.
279 if let (NativeLibKind::RawDylib, Some(lib_name)) = (lib.kind, lib.name) {
280 let span = match span {
281 Some(s) => s,
282 None => {
283 bug!("raw-dylib libraries are not supported on the command line");
284 }
285 };
286
287 if !self.tcx.sess.target.options.is_like_windows {
288 self.tcx.sess.span_fatal(
289 span,
290 "`#[link(...)]` with `kind = \"raw-dylib\"` only supported on Windows",
291 );
292 } else if !self.tcx.sess.target.options.is_like_msvc {
293 self.tcx.sess.span_warn(
294 span,
295 "`#[link(...)]` with `kind = \"raw-dylib\"` not supported on windows-gnu",
296 );
297 }
298
299 if lib_name.as_str().contains('\0') {
300 self.tcx.sess.span_err(span, "library name may not contain NUL characters");
301 }
302
303 if !self.tcx.features().raw_dylib {
304 feature_err(
305 &self.tcx.sess.parse_sess,
306 sym::raw_dylib,
307 span,
308 "kind=\"raw-dylib\" is unstable",
309 )
310 .emit();
311 }
312 }
313
314 self.libs.push(lib);
315 }
316
317 // Process libs passed on the command line
318 fn process_command_line(&mut self) {
319 // First, check for errors
320 let mut renames = FxHashSet::default();
321 for lib in &self.tcx.sess.opts.libs {
322 if let Some(ref new_name) = lib.new_name {
323 let any_duplicate = self
324 .libs
325 .iter()
326 .filter_map(|lib| lib.name.as_ref())
327 .any(|n| &n.as_str() == &lib.name);
328 if new_name.is_empty() {
329 self.tcx.sess.err(&format!(
330 "an empty renaming target was specified for library `{}`",
331 lib.name
332 ));
333 } else if !any_duplicate {
334 self.tcx.sess.err(&format!(
335 "renaming of the library `{}` was specified, \
336 however this crate contains no `#[link(...)]` \
337 attributes referencing this library.",
338 lib.name
339 ));
340 } else if !renames.insert(&lib.name) {
341 self.tcx.sess.err(&format!(
342 "multiple renamings were \
343 specified for library `{}` .",
344 lib.name
345 ));
346 }
347 }
348 }
349
350 // Update kind and, optionally, the name of all native libraries
351 // (there may be more than one) with the specified name. If any
352 // library is mentioned more than once, keep the latest mention
353 // of it, so that any possible dependent libraries appear before
354 // it. (This ensures that the linker is able to see symbols from
355 // all possible dependent libraries before linking in the library
356 // in question.)
357 for passed_lib in &self.tcx.sess.opts.libs {
358 // If we've already added any native libraries with the same
359 // name, they will be pulled out into `existing`, so that we
360 // can move them to the end of the list below.
361 let mut existing = self
362 .libs
363 .drain_filter(|lib| {
364 if let Some(lib_name) = lib.name {
365 if lib_name.as_str() == passed_lib.name {
366 if passed_lib.kind != NativeLibKind::Unspecified {
367 lib.kind = passed_lib.kind;
368 }
369 if let Some(new_name) = &passed_lib.new_name {
370 lib.name = Some(Symbol::intern(new_name));
371 }
372 lib.verbatim = passed_lib.verbatim;
373 return true;
374 }
375 }
376 false
377 })
378 .collect::<Vec<_>>();
379 if existing.is_empty() {
380 // Add if not found
381 let new_name = passed_lib.new_name.as_ref().map(|s| &**s); // &Option<String> -> Option<&str>
382 let lib = NativeLib {
383 name: Some(Symbol::intern(new_name.unwrap_or(&passed_lib.name))),
384 kind: passed_lib.kind,
385 cfg: None,
386 foreign_module: None,
387 wasm_import_module: None,
388 verbatim: passed_lib.verbatim,
389 dll_imports: Vec::new(),
390 };
391 self.register_native_lib(None, lib);
392 } else {
393 // Move all existing libraries with the same name to the
394 // end of the command line.
395 self.libs.append(&mut existing);
396 }
397 }
398 }
399 }