Skip to content

Commit cf296c0

Browse files
Rollup merge of rust-lang#87092 - ricobbe:fix-raw-dylib-multiple-definitions, r=petrochenkov
Remove nondeterminism in multiple-definitions test Compare all fields in `DllImport` when sorting to avoid nondeterminism in the error for multiple inconsistent definitions of an extern function. Restore the multiple-definitions test. Resolves rust-lang#87084.
2 parents 8662723 + ce59f1a commit cf296c0

File tree

7 files changed

+91
-75
lines changed

7 files changed

+91
-75
lines changed

compiler/rustc_codegen_cranelift/src/lib.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -221,9 +221,7 @@ impl CodegenBackend for CraneliftCodegenBackend {
221221
sess,
222222
&codegen_results,
223223
outputs,
224-
);
225-
226-
Ok(())
224+
)
227225
}
228226
}
229227

compiler/rustc_codegen_llvm/src/lib.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -292,9 +292,7 @@ impl CodegenBackend for LlvmCodegenBackend {
292292

293293
// Run the linker on any artifacts that resulted from the LLVM run.
294294
// This should produce either a finished executable or library.
295-
link_binary::<LlvmArchiveBuilder<'_>>(sess, &codegen_results, outputs);
296-
297-
Ok(())
295+
link_binary::<LlvmArchiveBuilder<'_>>(sess, &codegen_results, outputs)
298296
}
299297
}
300298

compiler/rustc_codegen_ssa/src/back/link.rs

+49-65
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
1+
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
22
use rustc_data_structures::temp_dir::MaybeTempDir;
3-
use rustc_errors::Handler;
3+
use rustc_errors::{ErrorReported, Handler};
44
use rustc_fs_util::fix_windows_verbatim_for_gcc;
55
use rustc_hir::def_id::CrateNum;
6-
use rustc_middle::middle::cstore::{DllCallingConvention, DllImport};
6+
use rustc_middle::middle::cstore::DllImport;
77
use rustc_middle::middle::dependency_format::Linkage;
88
use rustc_session::config::{self, CFGuard, CrateType, DebugInfo, LdImpl, Strip};
99
use rustc_session::config::{OutputFilenames, OutputType, PrintRequest};
@@ -35,7 +35,6 @@ use object::{Architecture, BinaryFormat, Endianness, FileFlags, SectionFlags, Se
3535
use tempfile::Builder as TempFileBuilder;
3636

3737
use std::ffi::OsString;
38-
use std::iter::FromIterator;
3938
use std::path::{Path, PathBuf};
4039
use std::process::{ExitStatus, Output, Stdio};
4140
use std::{ascii, char, env, fmt, fs, io, mem, str};
@@ -54,7 +53,7 @@ pub fn link_binary<'a, B: ArchiveBuilder<'a>>(
5453
sess: &'a Session,
5554
codegen_results: &CodegenResults,
5655
outputs: &OutputFilenames,
57-
) {
56+
) -> Result<(), ErrorReported> {
5857
let _timer = sess.timer("link_binary");
5958
let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
6059
for &crate_type in sess.crate_types().iter() {
@@ -95,11 +94,17 @@ pub fn link_binary<'a, B: ArchiveBuilder<'a>>(
9594
match crate_type {
9695
CrateType::Rlib => {
9796
let _timer = sess.timer("link_rlib");
98-
link_rlib::<B>(sess, codegen_results, RlibFlavor::Normal, &out_filename, &path)
99-
.build();
97+
link_rlib::<B>(
98+
sess,
99+
codegen_results,
100+
RlibFlavor::Normal,
101+
&out_filename,
102+
&path,
103+
)?
104+
.build();
100105
}
101106
CrateType::Staticlib => {
102-
link_staticlib::<B>(sess, codegen_results, &out_filename, &path);
107+
link_staticlib::<B>(sess, codegen_results, &out_filename, &path)?;
103108
}
104109
_ => {
105110
link_natively::<B>(
@@ -145,6 +150,8 @@ pub fn link_binary<'a, B: ArchiveBuilder<'a>>(
145150
}
146151
}
147152
});
153+
154+
Ok(())
148155
}
149156

150157
pub fn each_linked_rlib(
@@ -220,7 +227,7 @@ fn link_rlib<'a, B: ArchiveBuilder<'a>>(
220227
flavor: RlibFlavor,
221228
out_filename: &Path,
222229
tmpdir: &MaybeTempDir,
223-
) -> B {
230+
) -> Result<B, ErrorReported> {
224231
info!("preparing rlib to {:?}", out_filename);
225232
let mut ab = <B as ArchiveBuilder>::new(sess, out_filename, None);
226233

@@ -259,7 +266,7 @@ fn link_rlib<'a, B: ArchiveBuilder<'a>>(
259266
}
260267

261268
for (raw_dylib_name, raw_dylib_imports) in
262-
collate_raw_dylibs(sess, &codegen_results.crate_info.used_libraries)
269+
collate_raw_dylibs(sess, &codegen_results.crate_info.used_libraries)?
263270
{
264271
ab.inject_dll_import_lib(&raw_dylib_name, &raw_dylib_imports, tmpdir);
265272
}
@@ -312,7 +319,7 @@ fn link_rlib<'a, B: ArchiveBuilder<'a>>(
312319
}
313320
}
314321
}
315-
return ab;
322+
return Ok(ab);
316323

317324
// For rlibs we "pack" rustc metadata into a dummy object file. When rustc
318325
// creates a dylib crate type it will pass `--whole-archive` (or the
@@ -454,65 +461,40 @@ fn link_rlib<'a, B: ArchiveBuilder<'a>>(
454461
fn collate_raw_dylibs(
455462
sess: &Session,
456463
used_libraries: &[NativeLib],
457-
) -> Vec<(String, Vec<DllImport>)> {
458-
let mut dylib_table: FxHashMap<String, FxHashSet<DllImport>> = FxHashMap::default();
464+
) -> Result<Vec<(String, Vec<DllImport>)>, ErrorReported> {
465+
// Use index maps to preserve original order of imports and libraries.
466+
let mut dylib_table = FxIndexMap::<String, FxIndexMap<Symbol, &DllImport>>::default();
459467

460468
for lib in used_libraries {
461469
if lib.kind == NativeLibKind::RawDylib {
462-
let name = lib.name.unwrap_or_else(||
463-
bug!("`link` attribute with kind = \"raw-dylib\" and no name should have caused error earlier")
464-
);
465-
let name = if matches!(lib.verbatim, Some(true)) {
466-
name.to_string()
467-
} else {
468-
format!("{}.dll", name)
469-
};
470-
dylib_table.entry(name).or_default().extend(lib.dll_imports.iter().cloned());
471-
}
472-
}
473-
474-
// Rustc already signals an error if we have two imports with the same name but different
475-
// calling conventions (or function signatures), so we don't have pay attention to those
476-
// when ordering.
477-
// FIXME: when we add support for ordinals, figure out if we need to do anything if we
478-
// have two DllImport values with the same name but different ordinals.
479-
let mut result: Vec<(String, Vec<DllImport>)> = dylib_table
480-
.into_iter()
481-
.map(|(lib_name, import_table)| {
482-
let mut imports = Vec::from_iter(import_table.into_iter());
483-
imports.sort_unstable_by_key(|x: &DllImport| x.name.as_str());
484-
(lib_name, imports)
485-
})
486-
.collect::<Vec<_>>();
487-
result.sort_unstable_by(|a: &(String, Vec<DllImport>), b: &(String, Vec<DllImport>)| {
488-
a.0.cmp(&b.0)
489-
});
490-
let result = result;
491-
492-
// Check for multiple imports with the same name but different calling conventions or
493-
// (when relevant) argument list sizes. Rustc only signals an error for this if the
494-
// declarations are at the same scope level; if one shadows the other, we only get a lint
495-
// warning.
496-
for (library, imports) in &result {
497-
let mut import_table: FxHashMap<Symbol, DllCallingConvention> = FxHashMap::default();
498-
for import in imports {
499-
if let Some(old_convention) =
500-
import_table.insert(import.name, import.calling_convention)
501-
{
502-
if import.calling_convention != old_convention {
503-
sess.span_fatal(
504-
import.span,
505-
&format!(
506-
"multiple definitions of external function `{}` from library `{}` have different calling conventions",
507-
import.name,
508-
library,
509-
));
470+
let ext = if matches!(lib.verbatim, Some(true)) { "" } else { ".dll" };
471+
let name = format!("{}{}", lib.name.expect("unnamed raw-dylib library"), ext);
472+
let imports = dylib_table.entry(name.clone()).or_default();
473+
for import in &lib.dll_imports {
474+
if let Some(old_import) = imports.insert(import.name, import) {
475+
// FIXME: when we add support for ordinals, figure out if we need to do anything
476+
// if we have two DllImport values with the same name but different ordinals.
477+
if import.calling_convention != old_import.calling_convention {
478+
sess.span_err(
479+
import.span,
480+
&format!(
481+
"multiple declarations of external function `{}` from \
482+
library `{}` have different calling conventions",
483+
import.name, name,
484+
),
485+
);
486+
}
510487
}
511488
}
512489
}
513490
}
514-
515-
result
491+
sess.compile_status()?;
492+
Ok(dylib_table
493+
.into_iter()
494+
.map(|(name, imports)| {
495+
(name, imports.into_iter().map(|(_, import)| import.clone()).collect())
496+
})
497+
.collect())
516498
}
517499

518500
/// Create a static archive.
@@ -531,9 +513,9 @@ fn link_staticlib<'a, B: ArchiveBuilder<'a>>(
531513
codegen_results: &CodegenResults,
532514
out_filename: &Path,
533515
tempdir: &MaybeTempDir,
534-
) {
516+
) -> Result<(), ErrorReported> {
535517
let mut ab =
536-
link_rlib::<B>(sess, codegen_results, RlibFlavor::StaticlibBase, out_filename, tempdir);
518+
link_rlib::<B>(sess, codegen_results, RlibFlavor::StaticlibBase, out_filename, tempdir)?;
537519
let mut all_native_libs = vec![];
538520

539521
let res = each_linked_rlib(&codegen_results.crate_info, &mut |cnum, path| {
@@ -581,6 +563,8 @@ fn link_staticlib<'a, B: ArchiveBuilder<'a>>(
581563
print_native_static_libs(sess, &all_native_libs);
582564
}
583565
}
566+
567+
Ok(())
584568
}
585569

586570
fn escape_stdout_stderr_string(s: &[u8]) -> String {

compiler/rustc_metadata/src/rmeta/encoder.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1581,7 +1581,7 @@ impl EncodeContext<'a, 'tcx> {
15811581
fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> {
15821582
empty_proc_macro!(self);
15831583
let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1584-
self.lazy(used_libraries.iter().cloned())
1584+
self.lazy(used_libraries.iter())
15851585
}
15861586

15871587
fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {

compiler/rustc_middle/src/middle/cstore.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ pub enum LinkagePreference {
6464
RequireStatic,
6565
}
6666

67-
#[derive(Clone, Debug, Encodable, Decodable, HashStable)]
67+
#[derive(Debug, Encodable, Decodable, HashStable)]
6868
pub struct NativeLib {
6969
pub kind: NativeLibKind,
7070
pub name: Option<Symbol>,
@@ -75,7 +75,7 @@ pub struct NativeLib {
7575
pub dll_imports: Vec<DllImport>,
7676
}
7777

78-
#[derive(Clone, Debug, PartialEq, Eq, Encodable, Decodable, Hash, HashStable)]
78+
#[derive(Clone, Debug, Encodable, Decodable, HashStable)]
7979
pub struct DllImport {
8080
pub name: Symbol,
8181
pub ordinal: Option<u16>,
@@ -92,7 +92,7 @@ pub struct DllImport {
9292
///
9393
/// The usize value, where present, indicates the size of the function's argument list
9494
/// in bytes.
95-
#[derive(Copy, Clone, Debug, PartialEq, Eq, Encodable, Decodable, Hash, HashStable)]
95+
#[derive(Clone, PartialEq, Debug, Encodable, Decodable, HashStable)]
9696
pub enum DllCallingConvention {
9797
C,
9898
Stdcall(usize),
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// only-i686-pc-windows-msvc
2+
// compile-flags: --crate-type lib --emit link
3+
#![allow(clashing_extern_declarations)]
4+
#![feature(raw_dylib)]
5+
//~^ WARN the feature `raw_dylib` is incomplete
6+
#[link(name = "foo", kind = "raw-dylib")]
7+
extern "C" {
8+
fn f(x: i32);
9+
}
10+
11+
pub fn lib_main() {
12+
#[link(name = "foo", kind = "raw-dylib")]
13+
extern "stdcall" {
14+
fn f(x: i32);
15+
//~^ ERROR multiple declarations of external function `f` from library `foo.dll` have different calling conventions
16+
}
17+
18+
unsafe { f(42); }
19+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
warning: the feature `raw_dylib` is incomplete and may not be safe to use and/or cause compiler crashes
2+
--> $DIR/multiple-declarations.rs:4:12
3+
|
4+
LL | #![feature(raw_dylib)]
5+
| ^^^^^^^^^
6+
|
7+
= note: `#[warn(incomplete_features)]` on by default
8+
= note: see issue #58713 <https://github.com/rust-lang/rust/issues/58713> for more information
9+
10+
error: multiple declarations of external function `f` from library `foo.dll` have different calling conventions
11+
--> $DIR/multiple-declarations.rs:14:9
12+
|
13+
LL | fn f(x: i32);
14+
| ^^^^^^^^^^^^^
15+
16+
error: aborting due to previous error; 1 warning emitted
17+

0 commit comments

Comments
 (0)