Chih-Hung Hsieh | fab4380 | 2020-04-07 14:24:01 -0700 | [diff] [blame^] | 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. |
| 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. |
| 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. |
| 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. |
| 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. |
| 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 | files.push("libclang-*.so.*".into()); |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | if cfg!(any( |
| 130 | target_os = "openbsd", |
| 131 | target_os = "freebsd", |
| 132 | target_os = "netbsd" |
| 133 | )) { |
| 134 | // Some BSD distributions don't create a `libclang.so` symlink either, |
| 135 | // but use a different naming scheme for versioned files (e.g., |
| 136 | // `libclang.so.7.0`). |
| 137 | files.push("libclang.so.*".into()); |
| 138 | } |
| 139 | |
| 140 | if cfg!(target_os = "windows") { |
| 141 | // The official LLVM build uses `libclang.dll` on Windows instead of |
| 142 | // `clang.dll`. However, unofficial builds such as MinGW use `clang.dll`. |
| 143 | files.push("libclang.dll".into()); |
| 144 | } |
| 145 | |
| 146 | // Validate the `libclang` shared libraries and collect the versions. |
| 147 | let mut valid = vec![]; |
| 148 | let mut invalid = vec![]; |
| 149 | for (directory, filename) in common::search_libclang_directories(&files, "LIBCLANG_PATH") { |
| 150 | let path = directory.join(&filename); |
| 151 | match validate_header(&path) { |
| 152 | Ok(()) => { |
| 153 | let version = parse_version(&filename); |
| 154 | valid.push((directory, filename, version)) |
| 155 | } |
| 156 | Err(message) => invalid.push(format!("({}: {})", path.display(), message)), |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | if !valid.is_empty() { |
| 161 | return Ok(valid); |
| 162 | } |
| 163 | |
| 164 | let message = format!( |
| 165 | "couldn't find any valid shared libraries matching: [{}], set the \ |
| 166 | `LIBCLANG_PATH` environment variable to a path where one of these files \ |
| 167 | can be found (invalid: [{}])", |
| 168 | files |
| 169 | .iter() |
| 170 | .map(|f| format!("'{}'", f)) |
| 171 | .collect::<Vec<_>>() |
| 172 | .join(", "), |
| 173 | invalid.join(", "), |
| 174 | ); |
| 175 | |
| 176 | Err(message) |
| 177 | } |
| 178 | |
| 179 | /// Returns the directory and filename of the "best" available `libclang` shared |
| 180 | /// library. |
| 181 | pub fn find(runtime: bool) -> Result<(PathBuf, String), String> { |
| 182 | search_libclang_directories(runtime)? |
| 183 | .iter() |
| 184 | .max_by_key(|f| &f.2) |
| 185 | .cloned() |
| 186 | .map(|(path, filename, _)| (path, filename)) |
| 187 | .ok_or_else(|| "unreachable".into()) |
| 188 | } |
| 189 | |
| 190 | /// Find and link to `libclang` dynamically. |
| 191 | #[cfg(not(feature = "runtime"))] |
| 192 | pub fn link() { |
| 193 | use std::fs; |
| 194 | |
| 195 | let (directory, filename) = find(false).unwrap(); |
| 196 | println!("cargo:rustc-link-search={}", directory.display()); |
| 197 | |
| 198 | if cfg!(all(target_os = "windows", target_env = "msvc")) { |
| 199 | // Find the `libclang` stub static library required for the MSVC |
| 200 | // toolchain. |
| 201 | let lib = if !directory.ends_with("bin") { |
| 202 | directory |
| 203 | } else { |
| 204 | directory.parent().unwrap().join("lib") |
| 205 | }; |
| 206 | |
| 207 | if lib.join("libclang.lib").exists() { |
| 208 | println!("cargo:rustc-link-search={}", lib.display()); |
| 209 | } else if lib.join("libclang.dll.a").exists() { |
| 210 | // MSYS and MinGW use `libclang.dll.a` instead of `libclang.lib`. |
| 211 | // It is linkable with the MSVC linker, but Rust doesn't recognize |
| 212 | // the `.a` suffix, so we need to copy it with a different name. |
| 213 | // |
| 214 | // FIXME: Maybe we can just hardlink or symlink it? |
| 215 | let out = env::var("OUT_DIR").unwrap(); |
| 216 | fs::copy( |
| 217 | lib.join("libclang.dll.a"), |
| 218 | Path::new(&out).join("libclang.lib"), |
| 219 | ) |
| 220 | .unwrap(); |
| 221 | println!("cargo:rustc-link-search=native={}", out); |
| 222 | } else { |
| 223 | panic!( |
| 224 | "using '{}', so 'libclang.lib' or 'libclang.dll.a' must be \ |
| 225 | available in {}", |
| 226 | filename, |
| 227 | lib.display(), |
| 228 | ); |
| 229 | } |
| 230 | |
| 231 | println!("cargo:rustc-link-lib=dylib=libclang"); |
| 232 | } else { |
| 233 | let name = filename.trim_start_matches("lib"); |
| 234 | |
| 235 | // Strip extensions and trailing version numbers (e.g., the `.so.7.0` in |
| 236 | // `libclang.so.7.0`). |
| 237 | let name = match name.find(".dylib").or_else(|| name.find(".so")) { |
| 238 | Some(index) => &name[0..index], |
| 239 | None => &name, |
| 240 | }; |
| 241 | |
| 242 | println!("cargo:rustc-link-lib=dylib={}", name); |
| 243 | } |
| 244 | } |