Debian Codegraph @

debian/rust-vendor/clang-sys/tests/build.rs

raw
1 #![allow(dead_code)]
2
3 use core::fmt;
4 use std::collections::HashMap;
5 use std::env;
6 use std::fs;
7 use std::path::PathBuf;
8 use std::sync::Arc;
9 use std::sync::Mutex;
10
11 use tempfile::TempDir;
12
13 #[macro_use]
14 #[path = "../build/macros.rs"]
15 mod macros;
16
17 #[path = "../build/common.rs"]
18 mod common;
19 #[path = "../build/dynamic.rs"]
20 mod dynamic;
21 #[path = "../build/static.rs"]
22 mod r#static;
23
24 #[derive(Debug, Default)]
25 struct RunCommandMock {
26 invocations: Vec<(String, String, Vec<String>)>,
27 responses: HashMap<Vec<String>, String>,
28 }
29
30 #[derive(Copy, Clone, Debug)]
31 enum Arch {
32 ARM64,
33 X86,
34 X86_64,
35 }
36
37 impl Arch {
38 fn pe_machine_type(self) -> u16 {
39 match self {
40 Arch::ARM64 => 0xAA64,
41 Arch::X86 => 0x014C,
42 Arch::X86_64 => 0x8664,
43 }
44 }
45 }
46
47 impl fmt::Display for Arch {
48 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
49 match self {
50 Arch::ARM64 => write!(f, "aarch64"),
51 Arch::X86 => write!(f, "x86"),
52 Arch::X86_64 => write!(f, "x86_64"),
53 }
54 }
55 }
56
57 #[derive(Debug)]
58 struct Env {
59 os: String,
60 arch: Arch,
61 pointer_width: String,
62 env: Option<String>,
63 vars: HashMap<String, (Option<String>, Option<String>)>,
64 cwd: PathBuf,
65 tmp: TempDir,
66 files: Vec<String>,
67 commands: Arc<Mutex<RunCommandMock>>,
68 }
69
70 impl Env {
71 fn new(os: &str, arch: Arch, pointer_width: &str) -> Self {
72 Env {
73 os: os.into(),
74 arch,
75 pointer_width: pointer_width.into(),
76 env: None,
77 vars: HashMap::new(),
78 cwd: env::current_dir().unwrap(),
79 tmp: tempfile::Builder::new()
80 .prefix("clang_sys_test")
81 .tempdir()
82 .unwrap(),
83 files: vec![],
84 commands: Default::default(),
85 }
86 .var("CLANG_PATH", None)
87 .var("LD_LIBRARY_PATH", None)
88 .var("LIBCLANG_PATH", None)
89 .var("LIBCLANG_STATIC_PATH", None)
90 .var("LLVM_CONFIG_PATH", None)
91 .var("PATH", None)
92 }
93
94 fn env(mut self, env: &str) -> Self {
95 self.env = Some(env.into());
96 self
97 }
98
99 fn var(mut self, name: &str, value: Option<&str>) -> Self {
100 let previous = env::var(name).ok();
101 self.vars
102 .insert(name.into(), (value.map(|v| v.into()), previous));
103 self
104 }
105
106 fn dir(mut self, path: &str) -> Self {
107 self.files.push(path.into());
108 let path = self.tmp.path().join(path);
109 fs::create_dir_all(path).unwrap();
110 self
111 }
112
113 fn file(mut self, path: &str, contents: &[u8]) -> Self {
114 self.files.push(path.into());
115 let path = self.tmp.path().join(path);
116 fs::create_dir_all(path.parent().unwrap()).unwrap();
117 fs::write(self.tmp.path().join(path), contents).unwrap();
118 self
119 }
120
121 fn dll(self, path: &str, arch: Arch, pointer_width: &str) -> Self {
122 // PE header.
123 let mut contents = [0; 64];
124 contents[0x3C..0x3C + 4].copy_from_slice(&i32::to_le_bytes(10));
125 contents[10..14].copy_from_slice(&[b'P', b'E', 0, 0]);
126 contents[14..16].copy_from_slice(&u16::to_le_bytes(arch.pe_machine_type()));
127 let magic = if pointer_width == "64" { 523 } else { 267 };
128 contents[34..36].copy_from_slice(&u16::to_le_bytes(magic));
129
130 self.file(path, &contents)
131 }
132
133 fn so(self, path: &str, pointer_width: &str) -> Self {
134 // ELF header.
135 let class = if pointer_width == "64" { 2 } else { 1 };
136 let contents = [127, 69, 76, 70, class];
137
138 self.file(path, &contents)
139 }
140
141 fn command(self, command: &str, args: &[&str], response: &str) -> Self {
142 let command = command.to_string();
143 let args = args.iter().map(|a| a.to_string()).collect::<Vec<_>>();
144
145 let mut key = vec![command];
146 key.extend(args);
147 self.commands
148 .lock()
149 .unwrap()
150 .responses
151 .insert(key, response.into());
152
153 self
154 }
155
156 fn enable(self) -> Self {
157 env::set_var("_CLANG_SYS_TEST", "yep");
158 env::set_var("_CLANG_SYS_TEST_OS", &self.os);
159 env::set_var("_CLANG_SYS_TEST_ARCH", &format!("{}", self.arch));
160 env::set_var("_CLANG_SYS_TEST_POINTER_WIDTH", &self.pointer_width);
161 if let Some(env) = &self.env {
162 env::set_var("_CLANG_SYS_TEST_ENV", env);
163 }
164
165 for (name, (value, _)) in &self.vars {
166 if let Some(value) = value {
167 env::set_var(name, value);
168 } else {
169 env::remove_var(name);
170 }
171 }
172
173 env::set_current_dir(&self.tmp).unwrap();
174
175 let commands = self.commands.clone();
176 let mock = &mut *common::RUN_COMMAND_MOCK.lock().unwrap();
177 *mock = Some(Box::new(move |command, path, args| {
178 let command = command.to_string();
179 let path = path.to_string();
180 let args = args.iter().map(|a| a.to_string()).collect::<Vec<_>>();
181
182 let mut commands = commands.lock().unwrap();
183 commands
184 .invocations
185 .push((command.clone(), path, args.clone()));
186
187 let mut key = vec![command];
188 key.extend(args);
189 commands.responses.get(&key).cloned()
190 }));
191
192 self
193 }
194 }
195
196 impl Drop for Env {
197 fn drop(&mut self) {
198 env::remove_var("_CLANG_SYS_TEST");
199 env::remove_var("_CLANG_SYS_TEST_OS");
200 env::remove_var("_CLANG_SYS_TEST_ARCH");
201 env::remove_var("_CLANG_SYS_TEST_POINTER_WIDTH");
202 env::remove_var("_CLANG_SYS_TEST_ENV");
203
204 for (name, (_, previous)) in &self.vars {
205 if let Some(previous) = previous {
206 env::set_var(name, previous);
207 } else {
208 env::remove_var(name);
209 }
210 }
211
212 if let Err(error) = env::set_current_dir(&self.cwd) {
213 println!("Failed to reset working directory: {:?}", error);
214 }
215 }
216 }
217
218 #[test]
219 fn test_all() {
220 // Run tests serially since they alter the environment.
221
222 test_linux_directory_preference();
223 test_linux_version_preference();
224 test_linux_directory_and_version_preference();
225
226 #[cfg(target_os = "windows")]
227 {
228 test_windows_bin_sibling();
229 test_windows_mingw_gnu();
230 test_windows_mingw_msvc();
231 test_windows_arm64_on_x86_64();
232 test_windows_x86_64_on_arm64();
233 }
234 }
235
236 macro_rules! assert_error {
237 ($result:expr, $contents:expr $(,)?) => {
238 if let Err(error) = $result {
239 if !error.contains($contents) {
240 panic!(
241 "expected error to contain {:?}, received: {error:?}",
242 $contents
243 );
244 }
245 } else {
246 panic!("expected error, received: {:?}", $result);
247 }
248 };
249 }
250
251 //================================================
252 // Dynamic
253 //================================================
254
255 // Linux -----------------------------------------
256
257 fn test_linux_directory_preference() {
258 let _env = Env::new("linux", Arch::X86_64, "64")
259 .so("usr/lib/libclang.so.1", "64")
260 .so("usr/local/lib/libclang.so.1", "64")
261 .enable();
262
263 assert_eq!(
264 dynamic::find(true),
265 Ok(("usr/local/lib".into(), "libclang.so.1".into())),
266 );
267 }
268
269 fn test_linux_version_preference() {
270 let _env = Env::new("linux", Arch::X86_64, "64")
271 .so("usr/lib/libclang-3.so", "64")
272 .so("usr/lib/libclang-3.5.so", "64")
273 .so("usr/lib/libclang-3.5.0.so", "64")
274 .enable();
275
276 assert_eq!(
277 dynamic::find(true),
278 Ok(("usr/lib".into(), "libclang-3.5.0.so".into())),
279 );
280 }
281
282 fn test_linux_directory_and_version_preference() {
283 let _env = Env::new("linux", Arch::X86_64, "64")
284 .so("usr/local/llvm/lib/libclang-3.so", "64")
285 .so("usr/local/lib/libclang-3.5.so", "64")
286 .so("usr/lib/libclang-3.5.0.so", "64")
287 .enable();
288
289 assert_eq!(
290 dynamic::find(true),
291 Ok(("usr/lib".into(), "libclang-3.5.0.so".into())),
292 );
293 }
294
295 // Windows ---------------------------------------
296
297 #[cfg(target_os = "windows")]
298 fn test_windows_bin_sibling() {
299 let _env = Env::new("windows", Arch::X86_64, "64")
300 .dir("Program Files\\LLVM\\lib")
301 .dll("Program Files\\LLVM\\bin\\libclang.dll", Arch::X86_64, "64")
302 .enable();
303
304 assert_eq!(
305 dynamic::find(true),
306 Ok(("Program Files\\LLVM\\bin".into(), "libclang.dll".into())),
307 );
308 }
309
310 #[cfg(target_os = "windows")]
311 fn test_windows_mingw_gnu() {
312 let _env = Env::new("windows", Arch::X86_64, "64")
313 .env("gnu")
314 .dir("MSYS\\MinGW\\lib")
315 .dll("MSYS\\MinGW\\bin\\clang.dll", Arch::X86_64, "64")
316 .dir("Program Files\\LLVM\\lib")
317 .dll("Program Files\\LLVM\\bin\\libclang.dll", Arch::X86_64, "64")
318 .enable();
319
320 assert_eq!(
321 dynamic::find(true),
322 Ok(("MSYS\\MinGW\\bin".into(), "clang.dll".into())),
323 );
324 }
325
326 #[cfg(target_os = "windows")]
327 fn test_windows_mingw_msvc() {
328 let _env = Env::new("windows", Arch::X86_64, "64")
329 .env("msvc")
330 .dir("MSYS\\MinGW\\lib")
331 .dll("MSYS\\MinGW\\bin\\clang.dll", Arch::X86_64, "64")
332 .dir("Program Files\\LLVM\\lib")
333 .dll("Program Files\\LLVM\\bin\\libclang.dll", Arch::X86_64, "64")
334 .enable();
335
336 assert_eq!(
337 dynamic::find(true),
338 Ok(("Program Files\\LLVM\\bin".into(), "libclang.dll".into())),
339 );
340 }
341
342 #[cfg(target_os = "windows")]
343 fn test_windows_arm64_on_x86_64() {
344 let _env = Env::new("windows", Arch::X86_64, "64")
345 .env("msvc")
346 .dir("Program Files\\LLVM\\lib")
347 .dll("Program Files\\LLVM\\bin\\libclang.dll", Arch::ARM64, "64")
348 .enable();
349
350 assert_error!(
351 dynamic::find(true),
352 "invalid: [(Program Files\\LLVM\\bin\\libclang.dll: invalid DLL (ARM64)",
353 );
354 }
355
356 #[cfg(target_os = "windows")]
357 fn test_windows_x86_64_on_arm64() {
358 let _env = Env::new("windows", Arch::ARM64, "64")
359 .env("msvc")
360 .dir("Program Files\\LLVM\\lib")
361 .dll("Program Files\\LLVM\\bin\\libclang.dll", Arch::X86_64, "64")
362 .enable();
363
364 assert_error!(
365 dynamic::find(true),
366 "invalid: [(Program Files\\LLVM\\bin\\libclang.dll: invalid DLL (x86-64)",
367 );
368 }