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
273
274
275
276
277
278
279
use crate::d::{self, ast::Names};
use std::{
env,
fs::{read_to_string, File},
io::prelude::*,
path::{Path, PathBuf},
process::Command,
};
const SONDE_RUST_API_FILE_ENV_NAME: &str = "SONDE_RUST_API_FILE";
#[derive(Default)]
pub struct Builder {
d_files: Vec<PathBuf>,
keep_h_file: bool,
keep_c_file: bool,
}
impl Builder {
pub fn new() -> Self {
Self {
..Default::default()
}
}
pub fn file<P>(&mut self, path: P) -> &mut Self
where
P: AsRef<Path>,
{
self.d_files.push(path.as_ref().to_path_buf());
self
}
pub fn files<P>(&mut self, paths: P) -> &mut Self
where
P: IntoIterator,
P::Item: AsRef<Path>,
{
for path in paths.into_iter() {
self.file(path);
}
self
}
pub fn keep_h_file(&mut self, keep: bool) -> &mut Self {
self.keep_h_file = keep;
self
}
pub fn keep_c_file(&mut self, keep: bool) -> &mut Self {
self.keep_c_file = keep;
self
}
pub fn compile(&self) {
let out_dir = env::var("OUT_DIR")
.map_err(|_| "The Cargo `OUT_DIR` variable is missing")
.unwrap();
let mut contents = String::new();
let mut providers = Vec::with_capacity(self.d_files.len());
// Tell Cargo to rerun the build script if one of the `.d` files has changed.
{
for d_file in &self.d_files {
println!(
"cargo:rerun-if-changed={file}",
file = d_file.as_path().display()
);
}
}
// Collect all contents of the `.d` files, and parse the declared providers.
{
for d_file in &self.d_files {
let content = read_to_string(d_file).unwrap();
contents.push_str(&content);
let script = d::parser::parse(&content).unwrap();
for provider in script.providers {
providers.push(provider);
}
}
}
// Let's get a unique `.h` file from the `.d` files.
let h_file = tempfile::Builder::new()
.prefix("sonde-")
.suffix(".h")
.tempfile_in(&out_dir)
.unwrap();
let h_file_name = h_file.path();
{
let mut d_file = tempfile::Builder::new()
.prefix("sonde-")
.suffix(".d")
.tempfile_in(&out_dir)
.unwrap();
d_file.write_all(contents.as_bytes()).unwrap();
Command::new("dtrace")
.arg("-arch")
.arg(match env::var("CARGO_CFG_TARGET_ARCH").unwrap().as_str() {
"aarch64" => "arm64",
arch => arch,
})
.arg("-o")
.arg(h_file_name.as_os_str())
.arg("-h")
.arg("-s")
.arg(&d_file.path().as_os_str())
.status()
.unwrap();
}
// Generate the FFI `.c` file. The probes are defined behind C
// macros; they can't be call from Rust, so we need to wrap
// them inside C functions.
let mut ffi_file = tempfile::Builder::new()
.prefix("sonde-ffi")
.suffix(".c")
.tempfile_in(&out_dir)
.unwrap();
{
let ffi = format!(
r#"#include {header_file:?}
{wrappers}"#,
header_file = h_file_name,
wrappers = providers
.iter()
.map(|provider| {
provider
.probes
.iter()
.map(|probe| {
format!(
r#"
void {prefix}_probe_{suffix}({arguments}) {{
{macro_prefix}_{macro_suffix}({argument_names});
}}
"#,
prefix = provider.name_for_c(),
suffix = probe.name_for_c(),
macro_prefix = provider.name_for_c_macro(),
macro_suffix = probe.name_for_c_macro(),
arguments = probe.arguments_for_c(),
argument_names = probe
.arguments
.iter()
.enumerate()
.map(|(nth, _)| { format!("arg{nth}", nth = nth) })
.collect::<Vec<String>>()
.join(", ")
)
})
.collect::<Vec<String>>()
.join("")
})
.collect::<Vec<String>>()
.join("\n")
);
ffi_file.write_all(ffi.as_bytes()).unwrap();
}
// Let's compile the FFI `.c` file to a `.a` file.
{
cc::Build::new().file(&ffi_file).compile("sonde-ffi");
}
// Finally, let's generate the nice API for Rust.
let mut rs_path = PathBuf::new();
rs_path.push(&out_dir);
rs_path.push("sonde.rs");
let mut rs_file = File::create(&rs_path).unwrap();
{
let rs = format!(
r#"/// Bindings from Rust to the C FFI small library that calls the
/// probes.
#[allow(unused)]
use std::os::raw::*;
extern "C" {{
{externs}
}}
{wrappers}
"#,
externs = providers
.iter()
.map(|provider| {
provider
.probes
.iter()
.map(|probe| {
format!(
r#" #[doc(hidden)]
fn {ffi_prefix}_probe_{ffi_suffix}({arguments});"#,
ffi_prefix = provider.name_for_c(),
ffi_suffix = probe.name_for_c(),
arguments = probe.arguments_for_c_from_rust(),
)
})
.collect::<Vec<String>>()
.join("\n\n")
})
.collect::<Vec<String>>()
.join("\n\n"),
wrappers = providers
.iter()
.map(|provider| {
format!(
r#"/// Probes for the `{provider_name}` provider.
pub mod r#{provider_name} {{
#[allow(unused)]
use std::os::raw::*;
{probes}
}}"#,
provider_name = provider.name_for_rust(),
probes = provider
.probes
.iter()
.map(|probe| {
format!(
r#" /// Call the `{probe_name}` probe of the `{provider_name}` provider.
pub fn r#{probe_name}({arguments}) {{
unsafe {{ super::{ffi_prefix}_probe_{ffi_suffix}({argument_names}) }};
}}"#,
provider_name = provider.name_for_rust(),
probe_name = probe.name_for_rust(),
ffi_prefix = provider.name_for_c(),
ffi_suffix = probe.name_for_c(),
arguments = probe.arguments_for_c_from_rust(),
argument_names = probe
.arguments
.iter()
.enumerate()
.map(|(nth, _)| { format!("arg{nth}", nth = nth) })
.collect::<Vec<String>>()
.join(", ")
)
})
.collect::<Vec<String>>()
.join("\n\n")
)
})
.collect::<Vec<String>>()
.join("\n\n")
);
println!(
"cargo:rustc-env={name}={value}",
name = SONDE_RUST_API_FILE_ENV_NAME,
value = rs_path.as_path().display(),
);
rs_file.write_all(rs.as_bytes()).unwrap();
}
if self.keep_h_file {
h_file.keep().unwrap();
}
if self.keep_c_file {
ffi_file.keep().unwrap();
}
}
}