Skip to content

Commit 63fc57b

Browse files
committed
Auto merge of #106560 - bjorn3:support_staticlib_dylib_linking, r=pnkfelix
Support linking to rust dylib with --crate-type staticlib This allows for example dynamically linking libstd, while statically linking the user crate into an executable or C dynamic library. For this two unstable flags (`-Z staticlib-allow-rdylib-deps` and `-Z staticlib-prefer-dynamic`) are introduced. Without the former you get an error. The latter is the equivalent to `-C prefer-dynamic` for the staticlib crate type to indicate that dynamically linking is preferred when both options are available, like for libstd. Care must be taken to ensure that no crate ends up being merged into two distinct staticlibs that are linked together. Doing so will cause a linker error at best and undefined behavior at worst. In addition two distinct staticlibs compiled by different rustc may not be combined under any circumstances due to some rustc private symbols not being mangled. To successfully link a staticlib, `--print native-static-libs` can be used while compiling to ask rustc for the linker flags necessary when linking the staticlib. This is an existing flag which previously only listed native libraries. It has been extended to list rust dylibs too. Trying to locate libstd yourself to link against it is not supported and may break if for example the libstd of multiple rustc versions are put in the same directory. For an example on how to use this see the `src/test/run-make-fulldeps/staticlib-dylib-linkage/` test.
2 parents 65dfca8 + 47be060 commit 63fc57b

File tree

7 files changed

+144
-15
lines changed

7 files changed

+144
-15
lines changed

compiler/rustc_codegen_ssa/src/back/link.rs

+70-5
Original file line numberDiff line numberDiff line change
@@ -546,12 +546,38 @@ fn link_staticlib<'a>(
546546

547547
ab.build(out_filename);
548548

549-
if !all_native_libs.is_empty() {
550-
if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
551-
print_native_static_libs(sess, &all_native_libs);
549+
let crates = codegen_results.crate_info.used_crates.iter();
550+
551+
let fmts = codegen_results
552+
.crate_info
553+
.dependency_formats
554+
.iter()
555+
.find_map(|&(ty, ref list)| if ty == CrateType::Staticlib { Some(list) } else { None })
556+
.expect("no dependency formats for staticlib");
557+
558+
let mut all_rust_dylibs = vec![];
559+
for &cnum in crates {
560+
match fmts.get(cnum.as_usize() - 1) {
561+
Some(&Linkage::Dynamic) => {}
562+
_ => continue,
563+
}
564+
let crate_name = codegen_results.crate_info.crate_name[&cnum];
565+
let used_crate_source = &codegen_results.crate_info.used_crate_source[&cnum];
566+
if let Some((path, _)) = &used_crate_source.dylib {
567+
all_rust_dylibs.push(&**path);
568+
} else {
569+
if used_crate_source.rmeta.is_some() {
570+
sess.emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
571+
} else {
572+
sess.emit_fatal(errors::LinkRlibError::NotFound { crate_name });
573+
}
552574
}
553575
}
554576

577+
if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
578+
print_native_static_libs(sess, &all_native_libs, &all_rust_dylibs);
579+
}
580+
555581
Ok(())
556582
}
557583

@@ -1370,8 +1396,12 @@ enum RlibFlavor {
13701396
StaticlibBase,
13711397
}
13721398

1373-
fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLib]) {
1374-
let lib_args: Vec<_> = all_native_libs
1399+
fn print_native_static_libs(
1400+
sess: &Session,
1401+
all_native_libs: &[NativeLib],
1402+
all_rust_dylibs: &[&Path],
1403+
) {
1404+
let mut lib_args: Vec<_> = all_native_libs
13751405
.iter()
13761406
.filter(|l| relevant_lib(sess, l))
13771407
.filter_map(|lib| {
@@ -1401,6 +1431,41 @@ fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLib]) {
14011431
}
14021432
})
14031433
.collect();
1434+
for path in all_rust_dylibs {
1435+
// FIXME deduplicate with add_dynamic_crate
1436+
1437+
// Just need to tell the linker about where the library lives and
1438+
// what its name is
1439+
let parent = path.parent();
1440+
if let Some(dir) = parent {
1441+
let dir = fix_windows_verbatim_for_gcc(dir);
1442+
if sess.target.is_like_msvc {
1443+
let mut arg = String::from("/LIBPATH:");
1444+
arg.push_str(&dir.display().to_string());
1445+
lib_args.push(arg);
1446+
} else {
1447+
lib_args.push("-L".to_owned());
1448+
lib_args.push(dir.display().to_string());
1449+
}
1450+
}
1451+
let stem = path.file_stem().unwrap().to_str().unwrap();
1452+
// Convert library file-stem into a cc -l argument.
1453+
let prefix = if stem.starts_with("lib") && !sess.target.is_like_windows { 3 } else { 0 };
1454+
let lib = &stem[prefix..];
1455+
let path = parent.unwrap_or_else(|| Path::new(""));
1456+
if sess.target.is_like_msvc {
1457+
// When producing a dll, the MSVC linker may not actually emit a
1458+
// `foo.lib` file if the dll doesn't actually export any symbols, so we
1459+
// check to see if the file is there and just omit linking to it if it's
1460+
// not present.
1461+
let name = format!("{}.dll.lib", lib);
1462+
if path.join(&name).exists() {
1463+
lib_args.push(name);
1464+
}
1465+
} else {
1466+
lib_args.push(format!("-l{}", lib));
1467+
}
1468+
}
14041469
if !lib_args.is_empty() {
14051470
sess.emit_note(errors::StaticLibraryNativeArtifacts);
14061471
// Prefix for greppability

compiler/rustc_metadata/src/dependency_format.rs

+21-10
Original file line numberDiff line numberDiff line change
@@ -89,11 +89,25 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList {
8989
// to try to eagerly statically link all dependencies. This is normally
9090
// done for end-product dylibs, not intermediate products.
9191
//
92-
// Treat cdylibs similarly. If `-C prefer-dynamic` is set, the caller may
93-
// be code-size conscious, but without it, it makes sense to statically
94-
// link a cdylib.
95-
CrateType::Dylib | CrateType::Cdylib if !sess.opts.cg.prefer_dynamic => Linkage::Static,
96-
CrateType::Dylib | CrateType::Cdylib => Linkage::Dynamic,
92+
// Treat cdylibs and staticlibs similarly. If `-C prefer-dynamic` is set,
93+
// the caller may be code-size conscious, but without it, it makes sense
94+
// to statically link a cdylib or staticlib. For staticlibs we use
95+
// `-Z staticlib-prefer-dynamic` for now. This may be merged into
96+
// `-C prefer-dynamic` in the future.
97+
CrateType::Dylib | CrateType::Cdylib => {
98+
if sess.opts.cg.prefer_dynamic {
99+
Linkage::Dynamic
100+
} else {
101+
Linkage::Static
102+
}
103+
}
104+
CrateType::Staticlib => {
105+
if sess.opts.unstable_opts.staticlib_prefer_dynamic {
106+
Linkage::Dynamic
107+
} else {
108+
Linkage::Static
109+
}
110+
}
97111

98112
// If the global prefer_dynamic switch is turned off, or the final
99113
// executable will be statically linked, prefer static crate linkage.
@@ -108,9 +122,6 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList {
108122
// No linkage happens with rlibs, we just needed the metadata (which we
109123
// got long ago), so don't bother with anything.
110124
CrateType::Rlib => Linkage::NotLinked,
111-
112-
// staticlibs must have all static dependencies.
113-
CrateType::Staticlib => Linkage::Static,
114125
};
115126

116127
match preferred_linkage {
@@ -123,9 +134,9 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList {
123134
return v;
124135
}
125136

126-
// Staticlibs and static executables must have all static dependencies.
137+
// Static executables must have all static dependencies.
127138
// If any are not found, generate some nice pretty errors.
128-
if ty == CrateType::Staticlib
139+
if (ty == CrateType::Staticlib && !sess.opts.unstable_opts.staticlib_allow_rdylib_deps)
129140
|| (ty == CrateType::Executable
130141
&& sess.crt_static(Some(ty))
131142
&& !sess.target.crt_static_allows_dylibs)

compiler/rustc_session/src/options.rs

+4
Original file line numberDiff line numberDiff line change
@@ -1720,6 +1720,10 @@ options! {
17201720
#[rustc_lint_opt_deny_field_access("use `Session::stack_protector` instead of this field")]
17211721
stack_protector: StackProtector = (StackProtector::None, parse_stack_protector, [TRACKED],
17221722
"control stack smash protection strategy (`rustc --print stack-protector-strategies` for details)"),
1723+
staticlib_allow_rdylib_deps: bool = (false, parse_bool, [TRACKED],
1724+
"allow staticlibs to have rust dylib dependencies"),
1725+
staticlib_prefer_dynamic: bool = (false, parse_bool, [TRACKED],
1726+
"prefer dynamic linking to static linking for staticlibs (default: no)"),
17231727
strict_init_checks: bool = (false, parse_bool, [TRACKED],
17241728
"control if mem::uninitialized and mem::zeroed panic on more UB"),
17251729
strip: Strip = (Strip::None, parse_strip, [UNTRACKED],
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
include ../tools.mk
2+
3+
# ignore-cross-compile
4+
# ignore-msvc FIXME(bjorn3) can't figure out how to link with the MSVC toolchain
5+
# ignore-wasm wasm doesn't support dynamic libraries
6+
7+
all:
8+
$(RUSTC) -C prefer-dynamic bar.rs
9+
$(RUSTC) foo.rs --crate-type staticlib --print native-static-libs \
10+
-Z staticlib-allow-rdylib-deps 2>&1 | grep 'note: native-static-libs: ' \
11+
| sed 's/note: native-static-libs: \(.*\)/\1/' > $(TMPDIR)/libs.txt
12+
cat $(TMPDIR)/libs.txt
13+
14+
ifdef IS_MSVC
15+
$(CC) $(CFLAGS) /c foo.c /Fo:$(TMPDIR)/foo.o
16+
$(RUSTC_LINKER) $(TMPDIR)/foo.o $(TMPDIR)/foo.lib $$(cat $(TMPDIR)/libs.txt) $(call OUT_EXE,foo)
17+
else
18+
$(CC) $(CFLAGS) foo.c -L $(TMPDIR) -lfoo $$(cat $(TMPDIR)/libs.txt) -o $(call RUN_BINFILE,foo)
19+
endif
20+
21+
$(call RUN,foo)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#![crate_type = "dylib"]
2+
3+
pub fn bar() {
4+
println!("hello!");
5+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#include <assert.h>
2+
3+
extern void foo();
4+
extern unsigned bar(unsigned a, unsigned b);
5+
6+
int main() {
7+
foo();
8+
assert(bar(1, 2) == 3);
9+
return 0;
10+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#![crate_type = "staticlib"]
2+
3+
extern crate bar;
4+
5+
#[no_mangle]
6+
pub extern "C" fn foo() {
7+
bar::bar();
8+
}
9+
10+
#[no_mangle]
11+
pub extern "C" fn bar(a: u32, b: u32) -> u32 {
12+
a + b
13+
}

0 commit comments

Comments
 (0)