```std``` global state in shared libraries

⚓ rust    📅 2025-05-27    👤 surdeus    👁️ 4      

surdeus

Warning

This post was published 32 days ago. The information described in this article may have changed.

Hello everyone!

Recently, I've made an experiment, creating two shared libraries in Rust (on Linux), one of which had a function that called fill_buf() on std::io::stdin().lock() object and printed it to stdout, and the other read (consumed) one byte from it and returned it. I've found something strange -- when called from a C application, the first library function read and printed a chunk of file and the second library function read a byte after that chunk. Calling the first function printed the previously-read buffer without any changes, as if two libraries had separate global states. When these libraries were used from Rust application, the app itself seemed to have its own global state that weren't used by libraries. Just wanted to note it, that shared libraries (like PAM modules) need to be careful to use unbuffered stdin reading (because the unconsumed buffer content may become inaccessible if the library is never called again) and stdout/stderr writing, or use stdio (however, it should be done carefully, because streams may be wide-oriented or -- for some implementations -- in text mode). As far as I understand, it also means that it's not safe to allocate and then Box::leak() in one shared library and get the Box in another (or the main app), so shared libraries should either provide C API constructors/destructors for such allocations (like fopen()/fclose() in stdio), or use special Box types (like one in stabby, which stores a pointer to the allocator with the allocated memory area).

1 post - 1 participant

Read full topic

🏷️ rust_feed