Skip to content

Commit 17ad504

Browse files
committed
rustc: Topographically sort rust dependencies
This commit starts to topographically sort rust dependencies on the linker command line. The reason for this is that linkers use right-hand libraries to resolve left-hand libraries symbols, which is especially crucial for us because we're using --as-needed on linux.
1 parent 0b3df19 commit 17ad504

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

src/librustc/metadata/cstore.rs

+30-2
Original file line numberDiff line numberDiff line change
@@ -143,16 +143,44 @@ impl CStore {
143143
self.used_link_args.with_mut(|s| s.clear());
144144
}
145145

146+
// This method is used when generating the command line to pass through to
147+
// system linker. The linker expects undefined symbols on the left of the
148+
// command line to be defined in libraries on the right, not the other way
149+
// around. For more info, see some comments in the add_used_library function
150+
// below.
151+
//
152+
// In order to get this left-to-right dependency ordering, we perform a
153+
// topological sort of all crates putting the leaves at the right-most
154+
// positions.
146155
pub fn get_used_crates(&self, prefer: LinkagePreference)
147156
-> Vec<(ast::CrateNum, Option<Path>)> {
157+
let mut ordering = Vec::new();
158+
fn visit(cstore: &CStore, cnum: ast::CrateNum,
159+
ordering: &mut Vec<ast::CrateNum>) {
160+
if ordering.as_slice().contains(&cnum) { return }
161+
let meta = cstore.get_crate_data(cnum);
162+
for (_, &dep) in meta.cnum_map.borrow().get().iter() {
163+
visit(cstore, dep, ordering);
164+
}
165+
ordering.push(cnum);
166+
};
167+
for (&num, _) in self.metas.borrow().get().iter() {
168+
visit(self, num, &mut ordering);
169+
}
170+
ordering.as_mut_slice().reverse();
171+
let ordering = ordering.as_slice();
148172
let used_crate_sources = self.used_crate_sources.borrow();
149-
used_crate_sources.get()
173+
let mut libs = used_crate_sources.get()
150174
.iter()
151175
.map(|src| (src.cnum, match prefer {
152176
RequireDynamic => src.dylib.clone(),
153177
RequireStatic => src.rlib.clone(),
154178
}))
155-
.collect()
179+
.collect();
180+
libs.sort_by(|&(a, _), &(b, _)| {
181+
ordering.position_elem(&a).cmp(&ordering.position_elem(&b))
182+
});
183+
libs
156184
}
157185

158186
pub fn add_used_library(&self, lib: ~str, kind: NativeLibaryKind) {

0 commit comments

Comments
 (0)