Skip to main content

lsplt_rs/
lib.rs

1//! LSPlt - PLT hooking library for Rust
2//!
3//! This module provides a safe Rust interface to the LSPlt hooking functionality,
4//! allowing for function hooking in shared libraries.
5
6pub type DeviceId = lsplt_sys::dev_t;
7pub type Inode = lsplt_sys::ino_t;
8
9#[derive(Debug, Clone)]
10/// An entry that describes a line in /proc/self/maps. You can obtain a list of these entries
11/// by calling [`scan()`](MapInfo::scan) or [`scan_self()`](MapInfo::scan_self).
12pub struct MapInfo {
13    /// The start address of the memory region.
14    pub start: usize,
15    /// The end address of the memory region.
16    pub end: usize,
17    /// The permissions of the memory region. This is a bit mask of the following values:
18    /// - PROT_READ
19    /// - PROT_WRITE  
20    /// - PROT_EXEC
21    pub perms: u8,
22    /// Whether the memory region is private.
23    pub is_private: bool,
24    /// The offset of the memory region.
25    pub offset: usize,
26    /// The device number of the memory region.
27    /// Major can be obtained by `major()`
28    /// Minor can be obtained by `minor()`
29    pub dev: DeviceId,
30    /// The inode number of the memory region.
31    pub inode: Inode,
32    /// The path of the memory region.
33    pub pathname: Option<String>,
34}
35
36impl MapInfo {
37    fn new(
38        start: usize,
39        end: usize,
40        perms: u8,
41        is_private: bool,
42        offset: usize,
43        dev: DeviceId,
44        inode: Inode,
45        pathname: Option<String>,
46    ) -> Self {
47        MapInfo {
48            start,
49            end,
50            perms,
51            is_private,
52            offset,
53            dev,
54            inode,
55            pathname,
56        }
57    }
58
59    fn from_map_info(mi: &lsplt_sys::lsplt_map_info_t) -> Self {
60        let pathname = if mi.path.is_null() {
61            None
62        } else {
63            unsafe {
64                Some(std::ffi::CStr::from_ptr(mi.path).to_string_lossy().into_owned())
65            }
66        };
67        MapInfo::new(
68            mi.start,
69            mi.end,
70            mi.perms,
71            mi.is_private,
72            mi.offset,
73            mi.dev,
74            mi.inode,
75            pathname,
76        )
77    }
78
79    // Preserve this function for potential future use
80    #[allow(dead_code)]
81    fn to_map_info(&self) -> lsplt_sys::lsplt_map_info_t {
82        lsplt_sys::lsplt_map_info_t {
83            start: self.start,
84            end: self.end,
85            perms: self.perms,
86            is_private: self.is_private,
87            offset: self.offset,
88            dev: self.dev,
89            inode: self.inode,
90            path: match &self.pathname {
91                Some(s) => std::ffi::CString::new(s.as_str()).unwrap().into_raw(),
92                None => std::ptr::null_mut(),
93            },
94        }
95    }
96
97    /// Scans /proc/self/maps and returns a list of [`MapInfo`] entries.
98    /// This is useful to find out the inode of the library to hook.
99    pub fn scan_self() -> Vec<MapInfo> {
100        Self::scan("self")
101    }
102
103    /// Scans /proc/[pid]/maps and returns a list of [`MapInfo`] entries.
104    /// This is useful to find out the inode of the library to hook.
105    ///
106    /// # Arguments
107    /// * `pid` - The process id to scan. Use "self" for the current process.
108    ///
109    /// # Returns
110    /// A vector of [`MapInfo`] entries describing the memory maps.
111    pub fn scan(pid: &str) -> Vec<MapInfo> {
112        let c_pid = std::ffi::CString::new(pid).unwrap();
113        unsafe {
114            let array = lsplt_sys::lsplt_scan(c_pid.as_ptr());
115            let slice = std::slice::from_raw_parts(array.data, array.size);
116            let mut result = Vec::with_capacity(array.size);
117            for mi in slice {
118                result.push(MapInfo::from_map_info(mi));
119            }
120            lsplt_sys::lsplt_free_map_info_array(&array as *const _ as *mut _);
121            result
122        }
123    }
124}
125
126/// Register a hook to a function by inode.
127///
128/// For shared objects within an archive, you should use
129/// [`register_hook_with_offset`] instead.
130///
131/// # Arguments
132/// * `dev` - The device number of the memory region.
133/// * `inode` - The inode of the library to hook. You can obtain the inode by `stat()` or by finding
134///             the library in the list returned by [`MapInfo::scan`].
135/// * `symbol` - The function symbol to hook.
136/// * `callback` - The callback function pointer to call when the function is called.
137/// * `backup` - Optional backup function pointer which can call the original function.
138///
139/// # Returns
140/// `Ok(())` if the hook was successfully registered, or an `io::Error` on failure.
141///
142/// # Notes
143/// - This function is thread-safe.
144/// - The backup will not be available until [`commit_hook`] is called.
145/// - The backup will be `None` if the hook fails.
146/// - You can unhook the function by calling this function with `callback` set to the backup
147///   from a previous call.
148/// - LSPlt will backup the hook memory region and restore it when the hook is restored to its
149///   original function pointer to avoid dirty pages. LSPlt will do hooks on a copied memory region
150///   so that the original memory region will not be modified. You can invalidate this behavior
151///   and hook the original memory region by calling [`invalidate_backup`].
152///
153/// # See Also
154/// - [`commit_hook`]
155/// - [`invalidate_backup`]
156pub fn register_hook(
157    dev: DeviceId,
158    inode: Inode,
159    symbol: &str,
160    callback: *mut std::ffi::c_void,
161    backup: Option<&mut *mut std::ffi::c_void>,
162) -> std::io::Result<()> {
163    let c_symbol = std::ffi::CString::new(symbol).unwrap();
164    let result = unsafe {
165        lsplt_sys::lsplt_register_hook(
166            dev,
167            inode,
168            c_symbol.as_ptr(),
169            callback,
170            match backup {
171                Some(b) => b as *mut *mut std::ffi::c_void,
172                None => std::ptr::null_mut(),
173            },
174        )
175    };
176
177    if result {
178        Ok(())
179    } else {
180        Err(std::io::Error::other("Failed to register hook"))
181    }
182}
183
184/// Register a hook to a function by inode with offset range.
185///
186/// This is useful when hooking a library that is directly loaded from an archive without extraction.
187///
188/// # Arguments
189/// * `dev` - The device number of the memory region.
190/// * `inode` - The inode of the library to hook. You can obtain the inode by `stat()` or by finding
191///             the library in the list returned by [`MapInfo::scan`].
192/// * `offset` - The offset to the library in the file.
193/// * `size` - The upper bound size to the library in the file.
194/// * `symbol` - The function symbol to hook.
195/// * `callback` - The callback function to call when the function is called.
196/// * `backup` - Optional backup function pointer which can call the original function.
197///
198/// # Returns
199/// `Ok(())` if the hook was successfully registered, or an `io::Error` on failure.
200///
201/// # Notes
202/// - This function is thread-safe.
203/// - The backup will not be available until [`commit_hook`] is called.
204/// - The backup will be `None` if the hook fails.
205/// - You can unhook the function by calling this function with `callback` set to the backup
206///   from a previous call.
207/// - LSPlt will backup the hook memory region and restore it when the hook is restored to its
208///   original function pointer to avoid dirty pages. LSPlt will do hooks on a copied memory region
209///   so that the original memory region will not be modified. You can invalidate this behavior
210///   and hook the original memory region by calling [`invalidate_backup`].
211/// - You can get the offset range of the library by getting its entry offset and size in the
212///   zip file.
213/// - According to the Android linker specification, the `offset` must be page aligned.
214/// - The `offset` must be accurate, otherwise the hook may fail because the ELF header
215///   cannot be found.
216/// - The `size` can be inaccurate but should be larger or equal to the library size,
217///   otherwise the hook may fail when the hook pointer is beyond the range.
218/// - The behavior of this function is undefined if `offset + size` is larger than the
219///   maximum value of `usize`.
220///
221/// # See Also
222/// - [`commit_hook`]
223/// - [`invalidate_backup`]
224pub fn register_hook_with_offset(
225    dev: DeviceId,
226    inode: Inode,
227    offset: usize,
228    size: usize,
229    symbol: &str,
230    callback: extern "C" fn(),
231    backup: Option<&mut *mut std::ffi::c_void>,
232) -> std::io::Result<()> {
233    let c_symbol = std::ffi::CString::new(symbol).unwrap();
234    let result = unsafe {
235        lsplt_sys::lsplt_register_hook_with_offset(
236            dev,
237            inode,
238            offset,
239            size,
240            c_symbol.as_ptr(),
241            callback as usize as *mut std::ffi::c_void,
242            match backup {
243                Some(b) => b as *mut *mut std::ffi::c_void,
244                None => std::ptr::null_mut(),
245            },
246        )
247    };
248
249    if result {
250        Ok(())
251    } else {
252        Err(std::io::Error::other("Failed to register hook with offset"))
253    }
254}
255
256/// Commit all registered hooks.
257///
258/// # Returns
259/// `Ok(())` if all hooks were successfully committed, or an `io::Error` if any hook failed.
260///
261/// # Notes
262/// - This function is thread-safe.
263/// - The return value indicates whether all hooks are successfully committed. You can
264///   determine which hook fails by checking the backup function pointer of [`register_hook`].
265///
266/// # See Also
267/// - [`register_hook`]
268/// - [`register_hook_with_offset`]
269pub fn commit_hook() -> std::io::Result<()> {
270    if unsafe {
271        lsplt_sys::lsplt_commit_hook()
272    } {
273        Ok(())
274    } else {
275        Err(std::io::Error::other("Failed to commit hook"))
276    }
277}
278
279/// Invalidate backup memory regions.
280///
281/// Normally LSPlt will backup the hooked memory region and do hook on a copied anonymous memory
282/// region, and restore the original memory region when the hook is unregistered
283/// (when the callback of [`register_hook`] is the original function). This function will restore
284/// the backup memory region and do all existing hooks on the original memory region.
285///
286/// # Returns
287/// `Ok(())` if all hooks were successfully invalidated, or an `io::Error` if any hook failed.
288///
289/// # Notes
290/// - This function is thread-safe.
291/// - This will be automatically called when the library is unloaded.
292///
293/// # See Also
294/// - [`register_hook`]
295pub fn invalidate_backup() -> std::io::Result<()> {
296    if unsafe {
297        lsplt_sys::lsplt_invalidate_backup()
298    } {
299        Ok(())
300    } else {
301        Err(std::io::Error::other("Failed to invalidate backup"))
302    }
303}