1 // Copyright 2018 Kyle Mayes
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 use std::env;
16 use std::fs::File;
17 use std::io::{self, Error, ErrorKind, Read, Seek, SeekFrom};
18 use std::path::{Path, PathBuf};
19 
20 use super::common;
21 
22 /// Returns the ELF class from the ELF header in the supplied file.
parse_elf_header(path: &Path) -> io::Result<u8>23 fn parse_elf_header(path: &Path) -> io::Result<u8> {
24     let mut file = File::open(path)?;
25     let mut buffer = [0; 5];
26     file.read_exact(&mut buffer)?;
27     if buffer[..4] == [127, 69, 76, 70] {
28         Ok(buffer[4])
29     } else {
30         Err(Error::new(ErrorKind::InvalidData, "invalid ELF header"))
31     }
32 }
33 
34 /// Returns the magic number from the PE header in the supplied file.
parse_pe_header(path: &Path) -> io::Result<u16>35 fn parse_pe_header(path: &Path) -> io::Result<u16> {
36     let mut file = File::open(path)?;
37 
38     // Determine the header offset.
39     let mut buffer = [0; 4];
40     let start = SeekFrom::Start(0x3C);
41     file.seek(start)?;
42     file.read_exact(&mut buffer)?;
43     let offset = i32::from_le_bytes(buffer);
44 
45     // Determine the validity of the header.
46     file.seek(SeekFrom::Start(offset as u64))?;
47     file.read_exact(&mut buffer)?;
48     if buffer != [80, 69, 0, 0] {
49         return Err(Error::new(ErrorKind::InvalidData, "invalid PE header"));
50     }
51 
52     // Find the magic number.
53     let mut buffer = [0; 2];
54     file.seek(SeekFrom::Current(20))?;
55     file.read_exact(&mut buffer)?;
56     Ok(u16::from_le_bytes(buffer))
57 }
58 
59 /// Validates the header for the supplied `libclang` shared library.
validate_header(path: &Path) -> Result<(), String>60 fn validate_header(path: &Path) -> Result<(), String> {
61     if cfg!(any(target_os = "freebsd", target_os = "linux")) {
62         let class = parse_elf_header(path).map_err(|e| e.to_string())?;
63 
64         if cfg!(target_pointer_width = "32") && class != 1 {
65             return Err("invalid ELF class (64-bit)".into());
66         }
67 
68         if cfg!(target_pointer_width = "64") && class != 2 {
69             return Err("invalid ELF class (32-bit)".into());
70         }
71 
72         Ok(())
73     } else if cfg!(target_os = "windows") {
74         let magic = parse_pe_header(path).map_err(|e| e.to_string())?;
75 
76         if cfg!(target_pointer_width = "32") && magic != 267 {
77             return Err("invalid DLL (64-bit)".into());
78         }
79 
80         if cfg!(target_pointer_width = "64") && magic != 523 {
81             return Err("invalid DLL (32-bit)".into());
82         }
83 
84         Ok(())
85     } else {
86         Ok(())
87     }
88 }
89 
90 /// Returns the components of the version in the supplied `libclang` shared
91 // library filename.
parse_version(filename: &str) -> Vec<u32>92 fn parse_version(filename: &str) -> Vec<u32> {
93     let version = if filename.starts_with("libclang.so.") {
94         &filename[12..]
95     } else if filename.starts_with("libclang-") {
96         &filename[9..filename.len() - 3]
97     } else {
98         return vec![];
99     };
100 
101     version.split('.').map(|s| s.parse().unwrap_or(0)).collect()
102 }
103 
104 /// Returns the paths to, the filenames, and the versions of the `libclang`
105 // shared libraries.
search_libclang_directories(runtime: bool) -> Result<Vec<(PathBuf, String, Vec<u32>)>, String>106 fn search_libclang_directories(runtime: bool) -> Result<Vec<(PathBuf, String, Vec<u32>)>, String> {
107     let mut files = vec![format!(
108         "{}clang{}",
109         env::consts::DLL_PREFIX,
110         env::consts::DLL_SUFFIX
111     )];
112 
113     if cfg!(target_os = "linux") {
114         // Some Linux distributions don't create a `libclang.so` symlink, so we
115         // need to look for versioned files (e.g., `libclang-3.9.so`).
116         files.push("libclang-*.so".into());
117 
118         // Some Linux distributions don't create a `libclang.so` symlink and
119         // don't have versioned files as described above, so we need to look for
120         // suffix versioned files (e.g., `libclang.so.1`). However, `ld` cannot
121         // link to these files, so this will only be included when linking at
122         // runtime.
123         if runtime {
124             files.push("libclang.so.*".into());
125         }
126     }
127 
128     if cfg!(any(
129         target_os = "openbsd",
130         target_os = "freebsd",
131         target_os = "netbsd"
132     )) {
133         // Some BSD distributions don't create a `libclang.so` symlink either,
134         // but use a different naming scheme for versioned files (e.g.,
135         // `libclang.so.7.0`).
136         files.push("libclang.so.*".into());
137     }
138 
139     if cfg!(target_os = "windows") {
140         // The official LLVM build uses `libclang.dll` on Windows instead of
141         // `clang.dll`. However, unofficial builds such as MinGW use `clang.dll`.
142         files.push("libclang.dll".into());
143     }
144 
145     // Validate the `libclang` shared libraries and collect the versions.
146     let mut valid = vec![];
147     let mut invalid = vec![];
148     for (directory, filename) in common::search_libclang_directories(&files, "LIBCLANG_PATH") {
149         let path = directory.join(&filename);
150         match validate_header(&path) {
151             Ok(()) => {
152                 let version = parse_version(&filename);
153                 valid.push((directory, filename, version))
154             }
155             Err(message) => invalid.push(format!("({}: {})", path.display(), message)),
156         }
157     }
158 
159     if !valid.is_empty() {
160         return Ok(valid);
161     }
162 
163     let message = format!(
164         "couldn't find any valid shared libraries matching: [{}], set the \
165          `LIBCLANG_PATH` environment variable to a path where one of these files \
166          can be found (invalid: [{}])",
167         files
168             .iter()
169             .map(|f| format!("'{}'", f))
170             .collect::<Vec<_>>()
171             .join(", "),
172         invalid.join(", "),
173     );
174 
175     Err(message)
176 }
177 
178 /// Returns the directory and filename of the "best" available `libclang` shared
179 /// library.
find(runtime: bool) -> Result<(PathBuf, String), String>180 pub fn find(runtime: bool) -> Result<(PathBuf, String), String> {
181     search_libclang_directories(runtime)?
182         .iter()
183         .max_by_key(|f| &f.2)
184         .cloned()
185         .map(|(path, filename, _)| (path, filename))
186         .ok_or_else(|| "unreachable".into())
187 }
188 
189 /// Find and link to `libclang` dynamically.
190 #[cfg(not(feature = "runtime"))]
link()191 pub fn link() {
192     use std::fs;
193 
194     let (directory, filename) = find(false).unwrap();
195     println!("cargo:rustc-link-search={}", directory.display());
196 
197     if cfg!(all(target_os = "windows", target_env = "msvc")) {
198         // Find the `libclang` stub static library required for the MSVC
199         // toolchain.
200         let lib = if !directory.ends_with("bin") {
201             directory.to_owned()
202         } else {
203             directory.parent().unwrap().join("lib")
204         };
205 
206         if lib.join("libclang.lib").exists() {
207             println!("cargo:rustc-link-search={}", lib.display());
208         } else if lib.join("libclang.dll.a").exists() {
209             // MSYS and MinGW use `libclang.dll.a` instead of `libclang.lib`.
210             // It is linkable with the MSVC linker, but Rust doesn't recognize
211             // the `.a` suffix, so we need to copy it with a different name.
212             //
213             // FIXME: Maybe we can just hardlink or symlink it?
214             let out = env::var("OUT_DIR").unwrap();
215             fs::copy(
216                 lib.join("libclang.dll.a"),
217                 Path::new(&out).join("libclang.lib"),
218             )
219             .unwrap();
220             println!("cargo:rustc-link-search=native={}", out);
221         } else {
222             panic!(
223                 "using '{}', so 'libclang.lib' or 'libclang.dll.a' must be \
224                  available in {}",
225                 filename,
226                 lib.display(),
227             );
228         }
229 
230         println!("cargo:rustc-link-lib=dylib=libclang");
231     } else {
232         let name = filename.trim_start_matches("lib");
233 
234         // Strip extensions and trailing version numbers (e.g., the `.so.7.0` in
235         // `libclang.so.7.0`).
236         let name = match name.find(".dylib").or(name.find(".so")) {
237             Some(index) => &name[0..index],
238             None => &name,
239         };
240 
241         println!("cargo:rustc-link-lib=dylib={}", name);
242     }
243 }
244