Skip to main content

libdd_crashtracker/
common.rs

1// Copyright 2024-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4use alloc::ffi::CString;
5use libc::c_void;
6use std::path::Path;
7use std::path::PathBuf;
8
9pub fn get_tests_folder_path() -> std::io::Result<PathBuf> {
10    Path::new(&env!("CARGO_MANIFEST_DIR"))
11        .join("tests")
12        .canonicalize()
13}
14
15pub struct SharedLibrary {
16    handle: *mut c_void,
17}
18
19impl SharedLibrary {
20    pub fn open(lib_path: &str) -> Result<Self, String> {
21        let cstr = CString::new(lib_path).map_err(|e| e.to_string())?;
22        // Use RTLD_NOW or another flag
23        let handle = unsafe { libc::dlopen(cstr.as_ptr(), libc::RTLD_NOW) };
24        if handle.is_null() {
25            Err("Failed to open library".to_string())
26        } else {
27            Ok(Self { handle })
28        }
29    }
30
31    pub fn get_symbol_address(&self, symbol: &str) -> Result<String, String> {
32        let cstr = CString::new(symbol).map_err(|e| e.to_string())?;
33        let sym = unsafe { libc::dlsym(self.handle, cstr.as_ptr()) };
34        if sym.is_null() {
35            Err(format!("Failed to find symbol: {symbol}"))
36        } else {
37            Ok(format!("{sym:p}"))
38        }
39    }
40}
41
42impl Drop for SharedLibrary {
43    fn drop(&mut self) {
44        if !self.handle.is_null() {
45            unsafe { libc::dlclose(self.handle) };
46        }
47    }
48}