Skip to main content

cuda_interposer_build/
lib.rs

1use anyhow::{Context, Result};
2use cfg_expr::{Expression, Predicate};
3use std::collections::HashMap;
4use std::env;
5use std::fs;
6use std::io::Write;
7use std::path::{Path, PathBuf};
8use tree_sitter::StreamingIterator;
9use walkdir::WalkDir;
10
11pub struct InterposerBuilder {
12    src_dir: PathBuf,
13    out_dir: PathBuf,
14    manifest_dir: PathBuf,
15}
16
17impl InterposerBuilder {
18    pub fn new() -> Self {
19        let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
20        Self {
21            src_dir: manifest_dir.join("src"),
22            out_dir: PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR not set")),
23            manifest_dir,
24        }
25    }
26
27    /// Sets the source directory to scan for manual hooks (default: ./src)
28    pub fn with_src(mut self, path: impl Into<PathBuf>) -> Self {
29        self.src_dir = path.into();
30        self
31    }
32
33    /// Run the build process.
34    pub fn build(self) -> Result<()> {
35        println!("cargo:rerun-if-changed={}", self.src_dir.display());
36
37        let mut manual_hooks = scan_local_hooks(&self.src_dir)?;
38
39        // Manually inject the core hooking functions into the hook map.
40        // These are defined by the `install_hooks!` macro in the library.
41        manual_hooks.insert(
42            "cuGetProcAddress".to_string(),
43            "cuGetProcAddress".to_string(),
44        );
45        manual_hooks.insert(
46            "cuGetProcAddress_v2".to_string(),
47            "cuGetProcAddress_v2".to_string(),
48        );
49
50        for hook in manual_hooks.keys() {
51            println!("cargo:warning=Detected manual hook: {}", hook);
52        }
53
54        generate_hook_map(&self.out_dir, &manual_hooks)?;
55
56        let target_dir = find_target_dir(&self.out_dir);
57
58        // Scan both driver and runtime prototypes
59        let all_protos =
60            scan_bindgen_prototypes(&target_dir, &["driver_internal_sys.rs", "runtime_sys.rs"])?;
61
62        if all_protos.is_empty() {
63            println!(
64                "cargo:warning=No CUDA prototypes found. Ensure cuda_interposer_sys is in dependencies."
65            );
66        }
67
68        let mut driver_passthroughs = Vec::new();
69        let mut runtime_passthroughs = Vec::new();
70
71        for proto in all_protos {
72            // Skip functions explicitly hooked by the user
73            if manual_hooks.contains_key(&proto.name) {
74                continue;
75            }
76
77            // Distinguish between Runtime (cuda*) and Driver (cu*)
78            // Note: 'cuda' technically starts with 'cu', so we check cuda first.
79            if proto.name.starts_with("cuda") || proto.name.starts_with("__cuda") {
80                runtime_passthroughs.push(proto);
81            } else if proto.name.starts_with("cu") {
82                driver_passthroughs.push(proto);
83            }
84        }
85
86        emit_passthroughs(
87            &self.out_dir.join("passthroughs_driver.rs"),
88            &driver_passthroughs,
89        )?;
90
91        emit_passthroughs(
92            &self.out_dir.join("passthroughs_runtime.rs"),
93            &runtime_passthroughs,
94        )?;
95
96        Ok(())
97    }
98}
99
100#[derive(Clone, Debug)]
101struct Prototype {
102    name: String,
103    aliases: Vec<String>,
104    args: Vec<(String, String)>, // (Name, Type)
105    ret: String,
106}
107
108fn is_node_cfg_enabled(mut node: tree_sitter::Node, src: &str) -> bool {
109    // Simple string scan for file-level configs
110    if src.contains("#![cfg(feature = \"primary\")]") && std::env::var("CARGO_FEATURE_PRIMARY").is_err() {
111        return false;
112    }
113    if src.contains("#![cfg(feature = \"secondary\")]") && std::env::var("CARGO_FEATURE_SECONDARY").is_err() {
114        return false;
115    }
116
117    loop {
118        let mut n = node.prev_sibling();
119        while let Some(sib) = n {
120            if sib.kind() == "attribute_item" {
121                let attr_text = &src[sib.byte_range()];
122                if attr_text.starts_with("#[cfg(") && attr_text.ends_with(")]") {
123                    let inner = &attr_text[6..attr_text.len() - 2];
124                    if let Ok(expr) = cfg_expr::Expression::parse(inner) {
125                        let res = expr.eval(|pred| match pred {
126                            cfg_expr::Predicate::Feature(feat) => {
127                                let env_var = format!(
128                                    "CARGO_FEATURE_{}",
129                                    feat.to_uppercase().replace("-", "_")
130                                );
131                                std::env::var(&env_var).is_ok()
132                            }
133                            _ => true,
134                        });
135                        if !res {
136                            return false;
137                        }
138                    }
139                }
140            } else if sib.kind() == "line_comment" || sib.kind() == "block_comment" {
141                // ignore
142            } else {
143                break;
144            }
145            n = sib.prev_sibling();
146        }
147        if let Some(parent) = node.parent() {
148            node = parent;
149        } else {
150            break;
151        }
152    }
153    true
154}
155
156fn scan_local_hooks(root: &Path) -> Result<HashMap<String, String>> {
157    let mut hooks = HashMap::new();
158    let mut parser = create_rust_parser();
159
160    let macro_query = tree_sitter::Query::new(
161        &tree_sitter_rust::LANGUAGE.into(),
162        r#"(macro_invocation
163        (identifier) @macro_name (#eq? @macro_name "cuda_hook")
164        (token_tree) @tt
165        )"#,
166    )?;
167
168    let func_query = tree_sitter::Query::new(
169        &tree_sitter_rust::LANGUAGE.into(),
170        r#"(function_item
171        name: (identifier) @func_name
172        )"#,
173    )?;
174
175    for entry in WalkDir::new(root) {
176        let entry = entry?;
177        if entry.path().extension().map_or(false, |e| e == "rs") {
178            let src = fs::read_to_string(entry.path())?;
179            let tree = parser
180                .parse(&src, None)
181                .context("Failed to parse rust file")?;
182            let mut cursor = tree_sitter::QueryCursor::new();
183
184            let mut matches = cursor.matches(&macro_query, tree.root_node(), src.as_bytes());
185
186            while let Some(m) = matches.next() {
187                let macro_name_node = m.captures.iter().find(|c| c.index == 0).unwrap().node;
188                if let Some(macro_invocation_node) = macro_name_node.parent() {
189                    if !is_node_cfg_enabled(macro_invocation_node, &src) {
190                        continue;
191                    }
192                }
193
194                let tt_node = m.captures.iter().find(|c| c.index == 1).unwrap().node;
195                let tt_text = &src[tt_node.byte_range()];
196
197                if tt_text.len() < 2 {
198                    continue;
199                }
200
201                let inner_src = &tt_text[1..tt_text.len() - 1];
202
203                // Double Parse: Macro body
204                let mut inner_parser = create_rust_parser();
205                if let Some(inner_tree) = inner_parser.parse(inner_src, None) {
206                    let mut inner_cursor = tree_sitter::QueryCursor::new();
207                    let mut inner_matches = inner_cursor.matches(
208                        &func_query,
209                        inner_tree.root_node(),
210                        inner_src.as_bytes(),
211                    );
212                    while let Some(im) = inner_matches.next() {
213                        let name_node = im.captures[0].node;
214                        let name = &inner_src[name_node.byte_range()];
215                        hooks.insert(name.to_string(), name.to_string());
216                    }
217                }
218            }
219        }
220    }
221    Ok(hooks)
222}
223
224fn scan_bindgen_prototypes(root: &Path, filenames: &[&str]) -> Result<Vec<Prototype>> {
225    let mut prototypes = HashMap::new();
226    let mut parser = create_rust_parser();
227
228    // Find the bindgen output files in target dir
229    let valid_files: Vec<PathBuf> = WalkDir::new(root)
230        .into_iter()
231        .filter_map(|e| e.ok())
232        .filter(|e| {
233            filenames
234                .iter()
235                .any(|f| e.file_name().to_string_lossy() == *f)
236        })
237        .map(|e| e.path().to_path_buf())
238        .collect();
239
240    for file in valid_files {
241        let src = fs::read_to_string(&file)?;
242        let tree = parser.parse(&src, None).context("Parse bindgen file")?;
243
244        let query = tree_sitter::Query::new(
245            &tree_sitter_rust::LANGUAGE.into(),
246            r#"(function_signature_item
247            name: (identifier) @name
248            parameters: (parameters) @params
249            return_type: (_)? @ret
250            )"#,
251        )?;
252
253        let mut cursor = tree_sitter::QueryCursor::new();
254        let mut matches = cursor.matches(&query, tree.root_node(), src.as_bytes());
255
256        while let Some(m) = matches.next() {
257            let name_node = m.captures.iter().find(|c| c.index == 0).unwrap().node;
258            let name = get_text(&src, name_node);
259
260            // Filter for Driver (cu*) and Runtime (cuda*)
261            // Also include internal __cuda symbols if necessary
262            if !name.starts_with("cu") && !name.starts_with("__cuda") {
263                continue;
264            }
265
266            let params_node = m.captures.iter().find(|c| c.index == 1).unwrap().node;
267            let ret_node = m.captures.iter().find(|c| c.index == 2).map(|c| c.node);
268
269            let args = parse_params(&src, params_node);
270            let ret = match ret_node {
271                Some(n) => get_text(&src, n).trim().to_string(),
272                None => "()".to_string(),
273            };
274
275            prototypes.entry(name.to_string()).or_insert(Prototype {
276                name: name.to_string(),
277                aliases: vec![],
278                args,
279                ret,
280            });
281        }
282    }
283
284    Ok(prototypes.into_values().collect())
285}
286
287fn generate_hook_map(out_dir: &Path, hooks: &HashMap<String, String>) -> Result<()> {
288    let mut f = fs::File::create(out_dir.join("hook_map.rs"))?;
289
290    writeln!(f, "|name: &str| {{")?;
291    writeln!(f, "    match name {{")?;
292
293    for name in hooks.keys() {
294        writeln!(f, "        \"{}\" => {{", name)?;
295        writeln!(f, "            unsafe extern \"C\" {{ fn {}(); }}", name)?;
296        writeln!(
297            f,
298            "            Some({} as *const () as *mut std::os::raw::c_void)",
299            name
300        )?;
301        writeln!(f, "        }},")?;
302    }
303
304    writeln!(f, "        _ => None,")?;
305    writeln!(f, "    }}")?;
306    writeln!(f, "}}")?;
307
308    Ok(())
309}
310
311fn emit_passthroughs(path: &Path, protos: &[Prototype]) -> Result<()> {
312    let mut f = fs::File::create(path)?;
313    for p in protos {
314        let args_str = p
315            .args
316            .iter()
317            .map(|(n, t)| format!("({}: {})", n, t))
318            .collect::<Vec<_>>()
319            .join(", ");
320
321        let aliases_str = if p.aliases.is_empty() {
322            String::new()
323        } else {
324            format!(", aliases: {}", p.aliases.join(", "))
325        };
326
327        writeln!(
328            f,
329            "cuda_interposer::generate_proxy! {{ fn {}([{}]) -> {}; name: {}{} }}",
330            p.name, args_str, p.ret, p.name, aliases_str
331        )?;
332    }
333    Ok(())
334}
335
336fn create_rust_parser() -> tree_sitter::Parser {
337    let mut parser = tree_sitter::Parser::new();
338    parser
339        .set_language(&tree_sitter_rust::LANGUAGE.into())
340        .unwrap();
341    parser
342}
343
344fn get_text<'a>(src: &'a str, node: tree_sitter::Node) -> &'a str {
345    &src[node.byte_range()]
346}
347
348fn parse_params(src: &str, node: tree_sitter::Node) -> Vec<(String, String)> {
349    let mut out = Vec::new();
350    let mut cursor = node.walk();
351
352    for child in node.named_children(&mut cursor) {
353        if child.kind() == "parameter" {
354            let pat = child
355                .child_by_field_name("pattern")
356                .map(|n| get_text(src, n))
357                .unwrap_or("_");
358            let ty = child
359                .child_by_field_name("type")
360                .map(|n| get_text(src, n))
361                .unwrap_or("c_void");
362            out.push((pat.to_string(), ty.to_string()));
363        }
364    }
365    out
366}
367
368fn find_target_dir(out_dir: &Path) -> PathBuf {
369    let mut p = out_dir.to_path_buf();
370    for _ in 0..3 {
371        p.pop();
372    }
373    p
374}