summary refs log tree commit diff
path: root/src/librustc/metadata/filesearch.rs
blob: 5313473739ff7ce25e02b1c40ff5e65ebdde3d6f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![allow(non_camel_case_types)]

use std::cell::RefCell;
use std::os;
use std::io::fs;
use collections::HashSet;

pub enum FileMatch { FileMatches, FileDoesntMatch }

// A module for searching for libraries
// FIXME (#2658): I'm not happy how this module turned out. Should
// probably just be folded into cstore.

/// Functions with type `pick` take a parent directory as well as
/// a file found in that directory.
pub type pick<'a> = 'a |path: &Path| -> FileMatch;

pub struct FileSearch<'a> {
    sysroot: &'a Path,
    addl_lib_search_paths: &'a RefCell<HashSet<Path>>,
    target_triple: &'a str
}

impl<'a> FileSearch<'a> {
    pub fn for_each_lib_search_path(&self, f: |&Path| -> FileMatch) {
        let mut visited_dirs = HashSet::new();
        let mut found = false;

        debug!("filesearch: searching additional lib search paths [{:?}]",
               self.addl_lib_search_paths.borrow().len());
        for path in self.addl_lib_search_paths.borrow().iter() {
            match f(path) {
                FileMatches => found = true,
                FileDoesntMatch => ()
            }
            visited_dirs.insert(path.as_vec().to_owned());
        }

        debug!("filesearch: searching target lib path");
        let tlib_path = make_target_lib_path(self.sysroot,
                                    self.target_triple);
        if !visited_dirs.contains_equiv(&tlib_path.as_vec()) {
            match f(&tlib_path) {
                FileMatches => found = true,
                FileDoesntMatch => ()
            }
        }
        visited_dirs.insert(tlib_path.as_vec().to_owned());
        // Try RUST_PATH
        if !found {
            let rustpath = rust_path();
            for path in rustpath.iter() {
                let tlib_path = make_rustpkg_target_lib_path(
                    self.sysroot, path, self.target_triple);
                debug!("is {} in visited_dirs? {:?}", tlib_path.display(),
                        visited_dirs.contains_equiv(&tlib_path.as_vec().to_owned()));

                if !visited_dirs.contains_equiv(&tlib_path.as_vec()) {
                    visited_dirs.insert(tlib_path.as_vec().to_owned());
                    // Don't keep searching the RUST_PATH if one match turns up --
                    // if we did, we'd get a "multiple matching crates" error
                    match f(&tlib_path) {
                       FileMatches => {
                           break;
                       }
                       FileDoesntMatch => ()
                    }
                }
            }
        }
    }

    pub fn get_target_lib_path(&self) -> Path {
        make_target_lib_path(self.sysroot, self.target_triple)
    }

    pub fn get_target_lib_file_path(&self, file: &Path) -> Path {
        let mut p = self.get_target_lib_path();
        p.push(file);
        p
    }

    pub fn search(&self, pick: pick) {
        self.for_each_lib_search_path(|lib_search_path| {
            debug!("searching {}", lib_search_path.display());
            match fs::readdir(lib_search_path) {
                Ok(files) => {
                    let mut rslt = FileDoesntMatch;
                    let is_rlib = |p: & &Path| {
                        p.extension_str() == Some("rlib")
                    };
                    // Reading metadata out of rlibs is faster, and if we find both
                    // an rlib and a dylib we only read one of the files of
                    // metadata, so in the name of speed, bring all rlib files to
                    // the front of the search list.
                    let files1 = files.iter().filter(|p| is_rlib(p));
                    let files2 = files.iter().filter(|p| !is_rlib(p));
                    for path in files1.chain(files2) {
                        debug!("testing {}", path.display());
                        let maybe_picked = pick(path);
                        match maybe_picked {
                            FileMatches => {
                                debug!("picked {}", path.display());
                                rslt = FileMatches;
                            }
                            FileDoesntMatch => {
                                debug!("rejected {}", path.display());
                            }
                        }
                    }
                    rslt
                }
                Err(..) => FileDoesntMatch,
            }
        });
    }

    pub fn new(sysroot: &'a Path,
               target_triple: &'a str,
               addl_lib_search_paths: &'a RefCell<HashSet<Path>>) -> FileSearch<'a> {
        debug!("using sysroot = {}", sysroot.display());
        FileSearch {
            sysroot: sysroot,
            addl_lib_search_paths: addl_lib_search_paths,
            target_triple: target_triple
        }
    }
}

pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path {
    let mut p = Path::new(find_libdir(sysroot));
    assert!(p.is_relative());
    p.push(rustlibdir());
    p.push(target_triple);
    p.push("lib");
    p
}

fn make_target_lib_path(sysroot: &Path,
                        target_triple: &str) -> Path {
    sysroot.join(&relative_target_lib_path(sysroot, target_triple))
}

fn make_rustpkg_target_lib_path(sysroot: &Path,
                                dir: &Path,
                                target_triple: &str) -> Path {
    let mut p = dir.join(find_libdir(sysroot));
    p.push(target_triple);
    p
}

pub fn get_or_default_sysroot() -> Path {
    // Follow symlinks.  If the resolved path is relative, make it absolute.
    fn canonicalize(path: Option<Path>) -> Option<Path> {
        path.and_then(|mut path|
            match fs::readlink(&path) {
                Ok(canon) => {
                    if canon.is_absolute() {
                        Some(canon)
                    } else {
                        path.pop();
                        Some(path.join(canon))
                    }
                },
                Err(..) => Some(path),
            })
    }

    match canonicalize(os::self_exe_name()) {
        Some(mut p) => { p.pop(); p.pop(); p }
        None => fail!("can't determine value for sysroot")
    }
}

#[cfg(windows)]
static PATH_ENTRY_SEPARATOR: &'static str = ";";
#[cfg(not(windows))]
static PATH_ENTRY_SEPARATOR: &'static str = ":";

/// Returns RUST_PATH as a string, without default paths added
pub fn get_rust_path() -> Option<~str> {
    os::getenv("RUST_PATH")
}

/// Returns the value of RUST_PATH, as a list
/// of Paths. Includes default entries for, if they exist:
/// $HOME/.rust
/// DIR/.rust for any DIR that's the current working directory
/// or an ancestor of it
pub fn rust_path() -> Vec<Path> {
    let mut env_rust_path: Vec<Path> = match get_rust_path() {
        Some(env_path) => {
            let env_path_components =
                env_path.split_str(PATH_ENTRY_SEPARATOR);
            env_path_components.map(|s| Path::new(s)).collect()
        }
        None => Vec::new()
    };
    let mut cwd = os::getcwd();
    // now add in default entries
    let cwd_dot_rust = cwd.join(".rust");
    if !env_rust_path.contains(&cwd_dot_rust) {
        env_rust_path.push(cwd_dot_rust);
    }
    if !env_rust_path.contains(&cwd) {
        env_rust_path.push(cwd.clone());
    }
    loop {
        if { let f = cwd.filename(); f.is_none() || f.unwrap() == bytes!("..") } {
            break
        }
        cwd.set_filename(".rust");
        if !env_rust_path.contains(&cwd) && cwd.exists() {
            env_rust_path.push(cwd.clone());
        }
        cwd.pop();
    }
    let h = os::homedir();
    for h in h.iter() {
        let p = h.join(".rust");
        if !env_rust_path.contains(&p) && p.exists() {
            env_rust_path.push(p);
        }
    }
    env_rust_path
}

// The name of the directory rustc expects libraries to be located.
// On Unix should be "lib", on windows "bin"
#[cfg(unix)]
fn find_libdir(sysroot: &Path) -> ~str {
    // FIXME: This is a quick hack to make the rustc binary able to locate
    // Rust libraries in Linux environments where libraries might be installed
    // to lib64/lib32. This would be more foolproof by basing the sysroot off
    // of the directory where librustc is located, rather than where the rustc
    // binary is.

    if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() {
        return primary_libdir_name();
    } else {
        return secondary_libdir_name();
    }

    #[cfg(target_word_size = "64")]
    fn primary_libdir_name() -> ~str { ~"lib64" }

    #[cfg(target_word_size = "32")]
    fn primary_libdir_name() -> ~str { ~"lib32" }

    fn secondary_libdir_name() -> ~str { ~"lib" }
}

#[cfg(windows)]
fn find_libdir(_sysroot: &Path) -> ~str {
    ~"bin"
}

// The name of rustc's own place to organize libraries.
// Used to be "rustc", now the default is "rustlib"
pub fn rustlibdir() -> ~str {
    ~"rustlib"
}