itsi-scheduler 0.1.5 → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of itsi-scheduler might be problematic. Click here for more details.

Files changed (125) hide show
  1. checksums.yaml +4 -4
  2. data/CODE_OF_CONDUCT.md +7 -0
  3. data/Cargo.lock +90 -22
  4. data/README.md +5 -0
  5. data/_index.md +7 -0
  6. data/ext/itsi_error/Cargo.toml +1 -0
  7. data/ext/itsi_error/src/lib.rs +106 -7
  8. data/ext/itsi_error/target/debug/build/clang-sys-da71b0344e568175/out/common.rs +355 -0
  9. data/ext/itsi_error/target/debug/build/clang-sys-da71b0344e568175/out/dynamic.rs +276 -0
  10. data/ext/itsi_error/target/debug/build/clang-sys-da71b0344e568175/out/macros.rs +49 -0
  11. data/ext/itsi_error/target/debug/build/rb-sys-49f554618693db24/out/bindings-0.9.110-mri-arm64-darwin23-3.4.2.rs +8865 -0
  12. data/ext/itsi_error/target/debug/incremental/itsi_error-1mmt5sux7jb0i/s-h510z7m8v9-0bxu7yd.lock +0 -0
  13. data/ext/itsi_error/target/debug/incremental/itsi_error-2vn3jey74oiw0/s-h5113n0e7e-1v5qzs6.lock +0 -0
  14. data/ext/itsi_error/target/debug/incremental/itsi_error-37uv9dicz7awp/s-h510ykifhe-0tbnep2.lock +0 -0
  15. data/ext/itsi_error/target/debug/incremental/itsi_error-37uv9dicz7awp/s-h510yyocpj-0tz7ug7.lock +0 -0
  16. data/ext/itsi_error/target/debug/incremental/itsi_error-37uv9dicz7awp/s-h510z0xc8g-14ol18k.lock +0 -0
  17. data/ext/itsi_error/target/debug/incremental/itsi_error-3g5qf4y7d54uj/s-h5113n0e7d-1trk8on.lock +0 -0
  18. data/ext/itsi_error/target/debug/incremental/itsi_error-3lpfftm45d3e2/s-h510z7m8r3-1pxp20o.lock +0 -0
  19. data/ext/itsi_error/target/debug/incremental/itsi_error-3o4qownhl3d7n/s-h510ykifek-1uxasnk.lock +0 -0
  20. data/ext/itsi_error/target/debug/incremental/itsi_error-3o4qownhl3d7n/s-h510yyocki-11u37qm.lock +0 -0
  21. data/ext/itsi_error/target/debug/incremental/itsi_error-3o4qownhl3d7n/s-h510z0xc93-0pmy0zm.lock +0 -0
  22. data/ext/itsi_rb_helpers/Cargo.toml +1 -0
  23. data/ext/itsi_rb_helpers/src/heap_value.rs +18 -0
  24. data/ext/itsi_rb_helpers/src/lib.rs +59 -9
  25. data/ext/itsi_rb_helpers/target/debug/build/clang-sys-da71b0344e568175/out/common.rs +355 -0
  26. data/ext/itsi_rb_helpers/target/debug/build/clang-sys-da71b0344e568175/out/dynamic.rs +276 -0
  27. data/ext/itsi_rb_helpers/target/debug/build/clang-sys-da71b0344e568175/out/macros.rs +49 -0
  28. data/ext/itsi_rb_helpers/target/debug/build/rb-sys-eb9ed4ff3a60f995/out/bindings-0.9.110-mri-arm64-darwin23-3.4.2.rs +8865 -0
  29. data/ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-040pxg6yhb3g3/s-h5113n7a1b-03bwlt4.lock +0 -0
  30. data/ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-131g1u4dzkt1a/s-h51113xnh3-1eik1ip.lock +0 -0
  31. data/ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-131g1u4dzkt1a/s-h5111704jj-0g4rj8x.lock +0 -0
  32. data/ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-1q2d3drtxrzs5/s-h5113n79yl-0bxcqc5.lock +0 -0
  33. data/ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-374a9h7ovycj0/s-h51113xoox-10de2hp.lock +0 -0
  34. data/ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-374a9h7ovycj0/s-h5111704w7-0vdq7gq.lock +0 -0
  35. data/ext/itsi_scheduler/src/itsi_scheduler.rs +1 -1
  36. data/ext/itsi_server/Cargo.lock +2956 -0
  37. data/ext/itsi_server/Cargo.toml +72 -28
  38. data/ext/itsi_server/src/default_responses/mod.rs +11 -0
  39. data/ext/itsi_server/src/env.rs +43 -0
  40. data/ext/itsi_server/src/lib.rs +113 -75
  41. data/ext/itsi_server/src/prelude.rs +2 -0
  42. data/ext/itsi_server/src/{body_proxy → ruby_types/itsi_body_proxy}/big_bytes.rs +10 -5
  43. data/ext/itsi_server/src/{body_proxy/itsi_body_proxy.rs → ruby_types/itsi_body_proxy/mod.rs} +29 -8
  44. data/ext/itsi_server/src/ruby_types/itsi_grpc_call.rs +344 -0
  45. data/ext/itsi_server/src/ruby_types/itsi_grpc_response_stream/mod.rs +264 -0
  46. data/ext/itsi_server/src/ruby_types/itsi_http_request.rs +345 -0
  47. data/ext/itsi_server/src/{response/itsi_response.rs → ruby_types/itsi_http_response.rs} +84 -40
  48. data/ext/itsi_server/src/ruby_types/itsi_server/file_watcher.rs +225 -0
  49. data/ext/itsi_server/src/ruby_types/itsi_server/itsi_server_config.rs +375 -0
  50. data/ext/itsi_server/src/ruby_types/itsi_server.rs +83 -0
  51. data/ext/itsi_server/src/ruby_types/mod.rs +48 -0
  52. data/ext/itsi_server/src/server/{bind.rs → binds/bind.rs} +56 -24
  53. data/ext/itsi_server/src/server/{listener.rs → binds/listener.rs} +218 -113
  54. data/ext/itsi_server/src/server/binds/mod.rs +4 -0
  55. data/ext/itsi_server/src/server/{tls → binds/tls}/locked_dir_cache.rs +55 -17
  56. data/ext/itsi_server/src/server/{tls.rs → binds/tls.rs} +109 -28
  57. data/ext/itsi_server/src/server/byte_frame.rs +32 -0
  58. data/ext/itsi_server/src/server/http_message_types.rs +97 -0
  59. data/ext/itsi_server/src/server/io_stream.rs +2 -1
  60. data/ext/itsi_server/src/server/lifecycle_event.rs +3 -0
  61. data/ext/itsi_server/src/server/middleware_stack/middleware.rs +165 -0
  62. data/ext/itsi_server/src/server/middleware_stack/middlewares/allow_list.rs +56 -0
  63. data/ext/itsi_server/src/server/middleware_stack/middlewares/auth_api_key.rs +87 -0
  64. data/ext/itsi_server/src/server/middleware_stack/middlewares/auth_basic.rs +86 -0
  65. data/ext/itsi_server/src/server/middleware_stack/middlewares/auth_jwt.rs +285 -0
  66. data/ext/itsi_server/src/server/middleware_stack/middlewares/cache_control.rs +142 -0
  67. data/ext/itsi_server/src/server/middleware_stack/middlewares/compression.rs +289 -0
  68. data/ext/itsi_server/src/server/middleware_stack/middlewares/cors.rs +292 -0
  69. data/ext/itsi_server/src/server/middleware_stack/middlewares/deny_list.rs +55 -0
  70. data/ext/itsi_server/src/server/middleware_stack/middlewares/error_response/default_responses.rs +190 -0
  71. data/ext/itsi_server/src/server/middleware_stack/middlewares/error_response.rs +157 -0
  72. data/ext/itsi_server/src/server/middleware_stack/middlewares/etag.rs +195 -0
  73. data/ext/itsi_server/src/server/middleware_stack/middlewares/header_interpretation.rs +82 -0
  74. data/ext/itsi_server/src/server/middleware_stack/middlewares/intrusion_protection.rs +201 -0
  75. data/ext/itsi_server/src/server/middleware_stack/middlewares/log_requests.rs +82 -0
  76. data/ext/itsi_server/src/server/middleware_stack/middlewares/max_body.rs +47 -0
  77. data/ext/itsi_server/src/server/middleware_stack/middlewares/mod.rs +87 -0
  78. data/ext/itsi_server/src/server/middleware_stack/middlewares/proxy.rs +414 -0
  79. data/ext/itsi_server/src/server/middleware_stack/middlewares/rate_limit.rs +131 -0
  80. data/ext/itsi_server/src/server/middleware_stack/middlewares/redirect.rs +76 -0
  81. data/ext/itsi_server/src/server/middleware_stack/middlewares/request_headers.rs +44 -0
  82. data/ext/itsi_server/src/server/middleware_stack/middlewares/response_headers.rs +36 -0
  83. data/ext/itsi_server/src/server/middleware_stack/middlewares/ruby_app.rs +126 -0
  84. data/ext/itsi_server/src/server/middleware_stack/middlewares/static_assets.rs +180 -0
  85. data/ext/itsi_server/src/server/middleware_stack/middlewares/static_response.rs +55 -0
  86. data/ext/itsi_server/src/server/middleware_stack/middlewares/string_rewrite.rs +163 -0
  87. data/ext/itsi_server/src/server/middleware_stack/middlewares/token_source.rs +12 -0
  88. data/ext/itsi_server/src/server/middleware_stack/mod.rs +347 -0
  89. data/ext/itsi_server/src/server/mod.rs +6 -5
  90. data/ext/itsi_server/src/server/process_worker.rs +65 -14
  91. data/ext/itsi_server/src/server/request_job.rs +11 -0
  92. data/ext/itsi_server/src/server/serve_strategy/cluster_mode.rs +137 -49
  93. data/ext/itsi_server/src/server/serve_strategy/mod.rs +9 -6
  94. data/ext/itsi_server/src/server/serve_strategy/single_mode.rs +338 -164
  95. data/ext/itsi_server/src/server/signal.rs +32 -26
  96. data/ext/itsi_server/src/server/size_limited_incoming.rs +101 -0
  97. data/ext/itsi_server/src/server/thread_worker.rs +214 -107
  98. data/ext/itsi_server/src/services/cache_store.rs +74 -0
  99. data/ext/itsi_server/src/services/itsi_http_service.rs +239 -0
  100. data/ext/itsi_server/src/services/mime_types.rs +1416 -0
  101. data/ext/itsi_server/src/services/mod.rs +6 -0
  102. data/ext/itsi_server/src/services/password_hasher.rs +83 -0
  103. data/ext/itsi_server/src/services/rate_limiter.rs +569 -0
  104. data/ext/itsi_server/src/services/static_file_server.rs +1324 -0
  105. data/ext/itsi_tracing/Cargo.toml +1 -0
  106. data/ext/itsi_tracing/src/lib.rs +312 -34
  107. data/ext/itsi_tracing/target/debug/incremental/itsi_tracing-0994n8rpvvt9m/s-h510hfz1f6-1kbycmq.lock +0 -0
  108. data/ext/itsi_tracing/target/debug/incremental/itsi_tracing-0bob7bf4yq34i/s-h5113125h5-0lh4rag.lock +0 -0
  109. data/ext/itsi_tracing/target/debug/incremental/itsi_tracing-2fcodulrxbbxo/s-h510h2infk-0hp5kjw.lock +0 -0
  110. data/ext/itsi_tracing/target/debug/incremental/itsi_tracing-2iak63r1woi1l/s-h510h2in4q-0kxfzw1.lock +0 -0
  111. data/ext/itsi_tracing/target/debug/incremental/itsi_tracing-2kk4qj9gn5dg2/s-h5113124kv-0enwon2.lock +0 -0
  112. data/ext/itsi_tracing/target/debug/incremental/itsi_tracing-2mwo0yas7dtw4/s-h510hfz1ha-1udgpei.lock +0 -0
  113. data/lib/itsi/scheduler/version.rb +1 -1
  114. data/lib/itsi/scheduler.rb +2 -2
  115. metadata +93 -21
  116. data/ext/itsi_error/src/from.rs +0 -71
  117. data/ext/itsi_server/extconf.rb +0 -6
  118. data/ext/itsi_server/src/body_proxy/mod.rs +0 -2
  119. data/ext/itsi_server/src/request/itsi_request.rs +0 -277
  120. data/ext/itsi_server/src/request/mod.rs +0 -1
  121. data/ext/itsi_server/src/response/mod.rs +0 -1
  122. data/ext/itsi_server/src/server/itsi_ca/itsi_ca.crt +0 -13
  123. data/ext/itsi_server/src/server/itsi_ca/itsi_ca.key +0 -5
  124. data/ext/itsi_server/src/server/itsi_server.rs +0 -244
  125. /data/ext/itsi_server/src/server/{bind_protocol.rs → binds/bind_protocol.rs} +0 -0
@@ -8,3 +8,4 @@ cfg-if = "1.0.0"
8
8
  magnus = { version = "0.7.1", features = ["rb-sys", "bytes"] }
9
9
  nix = "0.29.0"
10
10
  rb-sys = "0.9.105"
11
+ serde = "1.0.219"
@@ -23,6 +23,24 @@ where
23
23
  }
24
24
  }
25
25
 
26
+ impl<T> HeapValue<T>
27
+ where
28
+ T: ReprValue,
29
+ {
30
+ pub fn into_inner(self) -> T {
31
+ *self.0
32
+ }
33
+ }
34
+
35
+ impl<T> HeapValue<T>
36
+ where
37
+ T: ReprValue,
38
+ {
39
+ pub fn cloned(&self) -> T {
40
+ *self.0
41
+ }
42
+ }
43
+
26
44
  impl<T> Deref for HeapValue<T>
27
45
  where
28
46
  T: ReprValue,
@@ -1,13 +1,14 @@
1
- use std::{os::raw::c_void, ptr::null_mut, sync::Arc};
1
+ use std::{ffi::c_int, os::raw::c_void, ptr::null_mut};
2
2
 
3
3
  use magnus::{
4
- RArray, Ruby, Thread, Value,
5
- rb_sys::FromRawValue,
6
- value::{LazyId, ReprValue},
4
+ ArgList, RArray, Ruby, Thread, Value,
5
+ block::Proc,
6
+ rb_sys::{AsRawId, FromRawValue, protect},
7
+ value::{IntoId, LazyId, ReprValue},
7
8
  };
8
9
  use rb_sys::{
9
- rb_thread_call_with_gvl, rb_thread_call_without_gvl, rb_thread_create, rb_thread_schedule,
10
- rb_thread_wakeup,
10
+ VALUE, rb_funcallv, rb_thread_call_with_gvl, rb_thread_call_without_gvl, rb_thread_create,
11
+ rb_thread_schedule, rb_thread_wakeup,
11
12
  };
12
13
 
13
14
  mod heap_value;
@@ -17,6 +18,7 @@ static ID_LIST: LazyId = LazyId::new("list");
17
18
  static ID_EQ: LazyId = LazyId::new("==");
18
19
  static ID_ALIVE: LazyId = LazyId::new("alive?");
19
20
  static ID_THREAD_VARIABLE_GET: LazyId = LazyId::new("thread_variable_get");
21
+ static ID_BACKTRACE: LazyId = LazyId::new("backtrace");
20
22
 
21
23
  pub fn schedule_thread() {
22
24
  unsafe {
@@ -120,20 +122,30 @@ where
120
122
  *result_box
121
123
  }
122
124
 
123
- pub fn fork(after_fork: Arc<Option<impl Fn()>>) -> Option<i32> {
125
+ pub fn fork(after_fork: Option<HeapValue<Proc>>) -> Option<i32> {
124
126
  let ruby = Ruby::get().unwrap();
125
127
  let fork_result = ruby
126
128
  .module_kernel()
127
129
  .funcall::<_, _, Option<i32>>(*ID_FORK, ())
128
130
  .unwrap();
129
131
  if fork_result.is_none() {
130
- if let Some(f) = &*after_fork {
131
- f()
132
+ if let Some(proc) = after_fork {
133
+ call_proc_and_log_errors(proc)
132
134
  }
133
135
  }
134
136
  fork_result
135
137
  }
136
138
 
139
+ pub fn call_proc_and_log_errors(proc: HeapValue<Proc>) {
140
+ if let Err(e) = proc.call::<_, Value>(()) {
141
+ if let Some(value) = e.value() {
142
+ print_rb_backtrace(value);
143
+ } else {
144
+ eprintln!("Error occurred {:?}", e);
145
+ }
146
+ }
147
+ }
148
+
137
149
  pub fn kill_threads<T>(threads: Vec<T>)
138
150
  where
139
151
  T: ReprValue,
@@ -176,3 +188,41 @@ pub fn terminate_non_fork_safe_threads() {
176
188
 
177
189
  kill_threads(non_fork_safe_threads);
178
190
  }
191
+
192
+ pub fn print_rb_backtrace(rb_err: Value) {
193
+ let backtrace = rb_err
194
+ .funcall::<_, _, Vec<String>>(*ID_BACKTRACE, ())
195
+ .unwrap_or_default();
196
+ let rust_backtrace = std::backtrace::Backtrace::capture().to_string();
197
+ eprintln!("Ruby exception {:?}", rb_err);
198
+ for line in backtrace {
199
+ eprintln!("{}", line);
200
+ }
201
+ for line in rust_backtrace.lines() {
202
+ eprintln!("{}", line);
203
+ }
204
+ }
205
+
206
+ pub fn funcall_no_ret<T, M, A>(target: T, method: M, args: A) -> magnus::error::Result<()>
207
+ where
208
+ T: ReprValue,
209
+ M: IntoId,
210
+ A: ArgList,
211
+ {
212
+ protect(|| {
213
+ let handle = Ruby::get().unwrap();
214
+ let method = method.into_id_with(&handle);
215
+ let args = args.into_arg_list_with(&handle);
216
+ let slice = args.as_ref();
217
+ unsafe {
218
+ rb_funcallv(
219
+ target.as_rb_value(),
220
+ method.as_raw(),
221
+ slice.len() as c_int,
222
+ slice.as_ptr() as *const VALUE,
223
+ );
224
+ }
225
+ 0
226
+ })?;
227
+ Ok(())
228
+ }
@@ -0,0 +1,355 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ use std::cell::RefCell;
4
+ use std::collections::HashMap;
5
+ use std::env;
6
+ use std::path::{Path, PathBuf};
7
+ use std::process::Command;
8
+
9
+ use glob::{MatchOptions, Pattern};
10
+
11
+ //================================================
12
+ // Commands
13
+ //================================================
14
+
15
+ thread_local! {
16
+ /// The errors encountered by the build script while executing commands.
17
+ static COMMAND_ERRORS: RefCell<HashMap<String, Vec<String>>> = RefCell::default();
18
+ }
19
+
20
+ /// Adds an error encountered by the build script while executing a command.
21
+ fn add_command_error(name: &str, path: &str, arguments: &[&str], message: String) {
22
+ COMMAND_ERRORS.with(|e| {
23
+ e.borrow_mut()
24
+ .entry(name.into())
25
+ .or_default()
26
+ .push(format!(
27
+ "couldn't execute `{} {}` (path={}) ({})",
28
+ name,
29
+ arguments.join(" "),
30
+ path,
31
+ message,
32
+ ))
33
+ });
34
+ }
35
+
36
+ /// A struct that prints the errors encountered by the build script while
37
+ /// executing commands when dropped (unless explictly discarded).
38
+ ///
39
+ /// This is handy because we only want to print these errors when the build
40
+ /// script fails to link to an instance of `libclang`. For example, if
41
+ /// `llvm-config` couldn't be executed but an instance of `libclang` was found
42
+ /// anyway we don't want to pollute the build output with irrelevant errors.
43
+ #[derive(Default)]
44
+ pub struct CommandErrorPrinter {
45
+ discard: bool,
46
+ }
47
+
48
+ impl CommandErrorPrinter {
49
+ pub fn discard(mut self) {
50
+ self.discard = true;
51
+ }
52
+ }
53
+
54
+ impl Drop for CommandErrorPrinter {
55
+ fn drop(&mut self) {
56
+ if self.discard {
57
+ return;
58
+ }
59
+
60
+ let errors = COMMAND_ERRORS.with(|e| e.borrow().clone());
61
+
62
+ if let Some(errors) = errors.get("llvm-config") {
63
+ println!(
64
+ "cargo:warning=could not execute `llvm-config` one or more \
65
+ times, if the LLVM_CONFIG_PATH environment variable is set to \
66
+ a full path to valid `llvm-config` executable it will be used \
67
+ to try to find an instance of `libclang` on your system: {}",
68
+ errors
69
+ .iter()
70
+ .map(|e| format!("\"{}\"", e))
71
+ .collect::<Vec<_>>()
72
+ .join("\n "),
73
+ )
74
+ }
75
+
76
+ if let Some(errors) = errors.get("xcode-select") {
77
+ println!(
78
+ "cargo:warning=could not execute `xcode-select` one or more \
79
+ times, if a valid instance of this executable is on your PATH \
80
+ it will be used to try to find an instance of `libclang` on \
81
+ your system: {}",
82
+ errors
83
+ .iter()
84
+ .map(|e| format!("\"{}\"", e))
85
+ .collect::<Vec<_>>()
86
+ .join("\n "),
87
+ )
88
+ }
89
+ }
90
+ }
91
+
92
+ #[cfg(test)]
93
+ lazy_static::lazy_static! {
94
+ pub static ref RUN_COMMAND_MOCK: std::sync::Mutex<
95
+ Option<Box<dyn Fn(&str, &str, &[&str]) -> Option<String> + Send + Sync + 'static>>,
96
+ > = std::sync::Mutex::new(None);
97
+ }
98
+
99
+ /// Executes a command and returns the `stdout` output if the command was
100
+ /// successfully executed (errors are added to `COMMAND_ERRORS`).
101
+ fn run_command(name: &str, path: &str, arguments: &[&str]) -> Option<String> {
102
+ #[cfg(test)]
103
+ if let Some(command) = &*RUN_COMMAND_MOCK.lock().unwrap() {
104
+ return command(name, path, arguments);
105
+ }
106
+
107
+ let output = match Command::new(path).args(arguments).output() {
108
+ Ok(output) => output,
109
+ Err(error) => {
110
+ let message = format!("error: {}", error);
111
+ add_command_error(name, path, arguments, message);
112
+ return None;
113
+ }
114
+ };
115
+
116
+ if output.status.success() {
117
+ Some(String::from_utf8_lossy(&output.stdout).into_owned())
118
+ } else {
119
+ let message = format!("exit code: {}", output.status);
120
+ add_command_error(name, path, arguments, message);
121
+ None
122
+ }
123
+ }
124
+
125
+ /// Executes the `llvm-config` command and returns the `stdout` output if the
126
+ /// command was successfully executed (errors are added to `COMMAND_ERRORS`).
127
+ pub fn run_llvm_config(arguments: &[&str]) -> Option<String> {
128
+ let path = env::var("LLVM_CONFIG_PATH").unwrap_or_else(|_| "llvm-config".into());
129
+ run_command("llvm-config", &path, arguments)
130
+ }
131
+
132
+ /// Executes the `xcode-select` command and returns the `stdout` output if the
133
+ /// command was successfully executed (errors are added to `COMMAND_ERRORS`).
134
+ pub fn run_xcode_select(arguments: &[&str]) -> Option<String> {
135
+ run_command("xcode-select", "xcode-select", arguments)
136
+ }
137
+
138
+ //================================================
139
+ // Search Directories
140
+ //================================================
141
+ // These search directories are listed in order of
142
+ // preference, so if multiple `libclang` instances
143
+ // are found when searching matching directories,
144
+ // the `libclang` instances from earlier
145
+ // directories will be preferred (though version
146
+ // takes precedence over location).
147
+ //================================================
148
+
149
+ /// `libclang` directory patterns for Haiku.
150
+ const DIRECTORIES_HAIKU: &[&str] = &[
151
+ "/boot/home/config/non-packaged/develop/lib",
152
+ "/boot/home/config/non-packaged/lib",
153
+ "/boot/system/non-packaged/develop/lib",
154
+ "/boot/system/non-packaged/lib",
155
+ "/boot/system/develop/lib",
156
+ "/boot/system/lib",
157
+ ];
158
+
159
+ /// `libclang` directory patterns for Linux (and FreeBSD).
160
+ const DIRECTORIES_LINUX: &[&str] = &[
161
+ "/usr/local/llvm*/lib*",
162
+ "/usr/local/lib*/*/*",
163
+ "/usr/local/lib*/*",
164
+ "/usr/local/lib*",
165
+ "/usr/lib*/*/*",
166
+ "/usr/lib*/*",
167
+ "/usr/lib*",
168
+ ];
169
+
170
+ /// `libclang` directory patterns for macOS.
171
+ const DIRECTORIES_MACOS: &[&str] = &[
172
+ "/usr/local/opt/llvm*/lib/llvm*/lib",
173
+ "/Library/Developer/CommandLineTools/usr/lib",
174
+ "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib",
175
+ "/usr/local/opt/llvm*/lib",
176
+ ];
177
+
178
+ /// `libclang` directory patterns for Windows.
179
+ ///
180
+ /// The boolean indicates whether the directory pattern should be used when
181
+ /// compiling for an MSVC target environment.
182
+ const DIRECTORIES_WINDOWS: &[(&str, bool)] = &[
183
+ // LLVM + Clang can be installed using Scoop (https://scoop.sh).
184
+ // Other Windows package managers install LLVM + Clang to other listed
185
+ // system-wide directories.
186
+ ("C:\\Users\\*\\scoop\\apps\\llvm\\current\\lib", true),
187
+ ("C:\\MSYS*\\MinGW*\\lib", false),
188
+ ("C:\\Program Files*\\LLVM\\lib", true),
189
+ ("C:\\LLVM\\lib", true),
190
+ // LLVM + Clang can be installed as a component of Visual Studio.
191
+ // https://github.com/KyleMayes/clang-sys/issues/121
192
+ ("C:\\Program Files*\\Microsoft Visual Studio\\*\\VC\\Tools\\Llvm\\**\\lib", true),
193
+ ];
194
+
195
+ /// `libclang` directory patterns for illumos
196
+ const DIRECTORIES_ILLUMOS: &[&str] = &[
197
+ "/opt/ooce/llvm-*/lib",
198
+ "/opt/ooce/clang-*/lib",
199
+ ];
200
+
201
+ //================================================
202
+ // Searching
203
+ //================================================
204
+
205
+ /// Finds the files in a directory that match one or more filename glob patterns
206
+ /// and returns the paths to and filenames of those files.
207
+ fn search_directory(directory: &Path, filenames: &[String]) -> Vec<(PathBuf, String)> {
208
+ // Escape the specified directory in case it contains characters that have
209
+ // special meaning in glob patterns (e.g., `[` or `]`).
210
+ let directory = Pattern::escape(directory.to_str().unwrap());
211
+ let directory = Path::new(&directory);
212
+
213
+ // Join the escaped directory to the filename glob patterns to obtain
214
+ // complete glob patterns for the files being searched for.
215
+ let paths = filenames
216
+ .iter()
217
+ .map(|f| directory.join(f).to_str().unwrap().to_owned());
218
+
219
+ // Prevent wildcards from matching path separators to ensure that the search
220
+ // is limited to the specified directory.
221
+ let mut options = MatchOptions::new();
222
+ options.require_literal_separator = true;
223
+
224
+ paths
225
+ .map(|p| glob::glob_with(&p, options))
226
+ .filter_map(Result::ok)
227
+ .flatten()
228
+ .filter_map(|p| {
229
+ let path = p.ok()?;
230
+ let filename = path.file_name()?.to_str().unwrap();
231
+
232
+ // The `libclang_shared` library has been renamed to `libclang-cpp`
233
+ // in Clang 10. This can cause instances of this library (e.g.,
234
+ // `libclang-cpp.so.10`) to be matched by patterns looking for
235
+ // instances of `libclang`.
236
+ if filename.contains("-cpp.") {
237
+ return None;
238
+ }
239
+
240
+ Some((path.parent().unwrap().to_owned(), filename.into()))
241
+ })
242
+ .collect::<Vec<_>>()
243
+ }
244
+
245
+ /// Finds the files in a directory (and any relevant sibling directories) that
246
+ /// match one or more filename glob patterns and returns the paths to and
247
+ /// filenames of those files.
248
+ fn search_directories(directory: &Path, filenames: &[String]) -> Vec<(PathBuf, String)> {
249
+ let mut results = search_directory(directory, filenames);
250
+
251
+ // On Windows, `libclang.dll` is usually found in the LLVM `bin` directory
252
+ // while `libclang.lib` is usually found in the LLVM `lib` directory. To
253
+ // keep things consistent with other platforms, only LLVM `lib` directories
254
+ // are included in the backup search directory globs so we need to search
255
+ // the LLVM `bin` directory here.
256
+ if target_os!("windows") && directory.ends_with("lib") {
257
+ let sibling = directory.parent().unwrap().join("bin");
258
+ results.extend(search_directory(&sibling, filenames));
259
+ }
260
+
261
+ results
262
+ }
263
+
264
+ /// Finds the `libclang` static or dynamic libraries matching one or more
265
+ /// filename glob patterns and returns the paths to and filenames of those files.
266
+ pub fn search_libclang_directories(filenames: &[String], variable: &str) -> Vec<(PathBuf, String)> {
267
+ // Search only the path indicated by the relevant environment variable
268
+ // (e.g., `LIBCLANG_PATH`) if it is set.
269
+ if let Ok(path) = env::var(variable).map(|d| Path::new(&d).to_path_buf()) {
270
+ // Check if the path is a matching file.
271
+ if let Some(parent) = path.parent() {
272
+ let filename = path.file_name().unwrap().to_str().unwrap();
273
+ let libraries = search_directories(parent, filenames);
274
+ if libraries.iter().any(|(_, f)| f == filename) {
275
+ return vec![(parent.into(), filename.into())];
276
+ }
277
+ }
278
+
279
+ // Check if the path is directory containing a matching file.
280
+ return search_directories(&path, filenames);
281
+ }
282
+
283
+ let mut found = vec![];
284
+
285
+ // Search the `bin` and `lib` directories in the directory returned by
286
+ // `llvm-config --prefix`.
287
+ if let Some(output) = run_llvm_config(&["--prefix"]) {
288
+ let directory = Path::new(output.lines().next().unwrap()).to_path_buf();
289
+ found.extend(search_directories(&directory.join("bin"), filenames));
290
+ found.extend(search_directories(&directory.join("lib"), filenames));
291
+ found.extend(search_directories(&directory.join("lib64"), filenames));
292
+ }
293
+
294
+ // Search the toolchain directory in the directory returned by
295
+ // `xcode-select --print-path`.
296
+ if target_os!("macos") {
297
+ if let Some(output) = run_xcode_select(&["--print-path"]) {
298
+ let directory = Path::new(output.lines().next().unwrap()).to_path_buf();
299
+ let directory = directory.join("Toolchains/XcodeDefault.xctoolchain/usr/lib");
300
+ found.extend(search_directories(&directory, filenames));
301
+ }
302
+ }
303
+
304
+ // Search the directories in the `LD_LIBRARY_PATH` environment variable.
305
+ if let Ok(path) = env::var("LD_LIBRARY_PATH") {
306
+ for directory in env::split_paths(&path) {
307
+ found.extend(search_directories(&directory, filenames));
308
+ }
309
+ }
310
+
311
+ // Determine the `libclang` directory patterns.
312
+ let directories: Vec<&str> = if target_os!("haiku") {
313
+ DIRECTORIES_HAIKU.into()
314
+ } else if target_os!("linux") || target_os!("freebsd") {
315
+ DIRECTORIES_LINUX.into()
316
+ } else if target_os!("macos") {
317
+ DIRECTORIES_MACOS.into()
318
+ } else if target_os!("windows") {
319
+ let msvc = target_env!("msvc");
320
+ DIRECTORIES_WINDOWS
321
+ .iter()
322
+ .filter(|d| d.1 || !msvc)
323
+ .map(|d| d.0)
324
+ .collect()
325
+ } else if target_os!("illumos") {
326
+ DIRECTORIES_ILLUMOS.into()
327
+ } else {
328
+ vec![]
329
+ };
330
+
331
+ // We use temporary directories when testing the build script so we'll
332
+ // remove the prefixes that make the directories absolute.
333
+ let directories = if test!() {
334
+ directories
335
+ .iter()
336
+ .map(|d| d.strip_prefix('/').or_else(|| d.strip_prefix("C:\\")).unwrap_or(d))
337
+ .collect::<Vec<_>>()
338
+ } else {
339
+ directories
340
+ };
341
+
342
+ // Search the directories provided by the `libclang` directory patterns.
343
+ let mut options = MatchOptions::new();
344
+ options.case_sensitive = false;
345
+ options.require_literal_separator = true;
346
+ for directory in directories.iter() {
347
+ if let Ok(directories) = glob::glob_with(directory, options) {
348
+ for directory in directories.filter_map(Result::ok).filter(|p| p.is_dir()) {
349
+ found.extend(search_directories(&directory, filenames));
350
+ }
351
+ }
352
+ }
353
+
354
+ found
355
+ }