5151//! Additionally, the algorithm is geared towards finding *any* solution rather
5252//! than finding a number of solutions (there are normally quite a few).
5353
54- use rustc_data_structures:: fx:: FxHashMap ;
54+ use rustc_data_structures:: fx:: { FxHashMap , FxHashSet } ;
5555use rustc_hir:: def_id:: CrateNum ;
5656use rustc_middle:: bug;
5757use rustc_middle:: middle:: dependency_format:: { Dependencies , DependencyList , Linkage } ;
@@ -160,18 +160,43 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList {
160160 Linkage :: Dynamic | Linkage :: IncludedFromDylib => { }
161161 }
162162
163+ let all_dylibs = || {
164+ tcx. crates ( ( ) ) . iter ( ) . filter ( |& & cnum| {
165+ !tcx. dep_kind ( cnum) . macros_only ( ) && tcx. used_crate_source ( cnum) . dylib . is_some ( )
166+ } )
167+ } ;
168+
169+ let mut upstream_in_dylibs = FxHashSet :: default ( ) ;
170+
171+ if tcx. features ( ) . rustc_private {
172+ // We need this to prevent users of `rustc_driver` from linking dynamically to `std`
173+ // which does not work as `std` is also statically linked into `rustc_driver`.
174+
175+ // Find all libraries statically linked to upstream dylibs.
176+ for & cnum in all_dylibs ( ) {
177+ let deps = tcx. dylib_dependency_formats ( cnum) ;
178+ for & ( depnum, style) in deps. iter ( ) {
179+ if let RequireStatic = style {
180+ upstream_in_dylibs. insert ( depnum) ;
181+ }
182+ }
183+ }
184+ }
185+
163186 let mut formats = FxHashMap :: default ( ) ;
164187
165188 // Sweep all crates for found dylibs. Add all dylibs, as well as their
166189 // dependencies, ensuring there are no conflicts. The only valid case for a
167190 // dependency to be relied upon twice is for both cases to rely on a dylib.
168- for & cnum in tcx. crates ( ( ) ) . iter ( ) {
169- if tcx. dep_kind ( cnum) . macros_only ( ) {
191+ for & cnum in all_dylibs ( ) {
192+ if upstream_in_dylibs. contains ( & cnum) {
193+ info ! ( "skipping dylib: {}" , tcx. crate_name( cnum) ) ;
194+ // If this dylib is also available statically linked to another dylib
195+ // we try to use that instead.
170196 continue ;
171197 }
198+
172199 let name = tcx. crate_name ( cnum) ;
173- let src = tcx. used_crate_source ( cnum) ;
174- if src. dylib . is_some ( ) {
175200 info ! ( "adding dylib: {}" , name) ;
176201 add_library ( tcx, cnum, RequireDynamic , & mut formats, & mut unavailable_as_static) ;
177202 let deps = tcx. dylib_dependency_formats ( cnum) ;
@@ -180,7 +205,6 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList {
180205 add_library ( tcx, depnum, style, & mut formats, & mut unavailable_as_static) ;
181206 }
182207 }
183- }
184208
185209 // Collect what we've got so far in the return vector.
186210 let last_crate = tcx. crates ( ( ) ) . len ( ) ;
0 commit comments