The `cdylib` built with rust sometimes fails to get the original function by `dlsym`

Recently, I'm writing a stack based coroutine library , in which hook technology is used.

user code

use open_coroutine::{co, Yielder};
use std::os::raw::c_void;
use std::time::Duration;

extern "C" fn f1(
    _yielder: &Yielder<Option<&'static mut c_void>, (), Option<&'static mut c_void>>,
    _input: Option<&'static mut c_void>,
) -> Option<&'static mut c_void> {
    println!("[coroutine1] launched");
    None
}

extern "C" fn f2(
    _yielder: &Yielder<Option<&'static mut c_void>, (), Option<&'static mut c_void>>,
    _input: Option<&'static mut c_void>,
) -> Option<&'static mut c_void> {
    println!("[coroutine2] launched");
    None
}

fn main() {
    co(f1, None, 4096);
    co(f2, None, 4096);
    std::thread::sleep(Duration::from_millis(1));
    println!("scheduler finished successfully!");
}

output

[coroutine1] launched
[coroutine2] launched
scheduler finished successfully!

As you can see, I added hook to the underlying system call nanosleep.

When I continued to add some changes to code, a problem occurred: the new cdylib built through CI failed to get the original system function nanosleep.

I think there is no problem with the code, how can I fix this(to solve the painc system nanosleep not found ! completely) ?

For code changes, see Painc if not found original by dragon-zhang · Pull Request #46 · acl-dev/open-coroutine · GitHub , just need to focus on libhook/src/unix/mod.rs, the other changes are built by CI.

The command to build the dynamic link library is cargo build -- release - p libhook

Page where CI failed: Painc if not found original · acl-dev/open-coroutine@a56a36e · GitHub

let ptr = libc::dlsym(libc::RTLD_NEXT, "nanosleep".as_ptr() as _);

The dlsym() function takes a null-terminated C string as input, so you'll need to explicitly write "nanosleep\0" (or better yet b"nanosleep\0") to produce that from the Rust side. Same with the other strings like "connect" that you pass to libc functions.

Thanks a lot, pal.

For safely constructing C string literals, without the fear of forgetting the NUL terminator, you can use the zstr!() macro.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.