Hello,
I'm currently interacting with a C application via a shared library written in Rust. The C application expects a global const char* plugin_name;
in the .so
file, which I am trying to define as a top level pub static _: &[u8]
object in my rust project. However, the C application fails to load the string via dlsym()
and only invalid memory is being read out.
An example application would be:
// src/application.c
#include <dlfcn.h>
#include <stdio.h>
void info(void *handle, const char *name)
{
const char *value = (const char *)dlsym(handle, name);
printf("%s: \"%s\"\n", name, value);
}
int main(int argc, char **argv)
{
const char *target = argv[1];
// load the shared library
void *handle = dlopen(target, RTLD_GLOBAL | RTLD_NOW);
// lookup plugin info
info(handle, "plugin_name");
info(handle, "plugin_description");
return dlclose(handle);
}
The Rust symbols I currently define via:
// src/plugin.rs
#[allow(non_upper_case_globals)]
#[no_mangle]
pub static plugin_name: &[u8] = c"plugin name".to_bytes();
#[allow(non_upper_case_globals)]
#[no_mangle]
pub static plugin_description: &[u8] = c"plugin description".to_bytes();
Compile e.g. via make like:
.PHONY: all
all: libplugin.so application
application: src/application.c Makefile
gcc -g -o $@ $<
libplugin.so: src/plugin.rs Makefile
rustc --edition 2021 --crate-type cdylib -C relocation-model=pic -o $@ $<
.PHONY: run
run: all
./application ./libplugin.so
My rustc version is: 1.82.0 (f6e511eec 2024-10-15)
Running this, the loaded symbols from dlsym
just point to empty/random memory:
> make run
./application ./libplugin.so
plugin_name: ""
plugin_description: "
0t��|"
> make run
./application ./libplugin.so
plugin_name: ""
plugin_description: "
� r"
> make run
./application ./libplugin.so
plugin_name: ""
plugin_description: "
��3_~"
Looking at it via nm
or rust-gdb
shows however, that the symbols are well defined in the library:
(gdb) print (char*) plugin_name
$1 = 0x2000 "plugin name"
(gdb) print (char*) plugin_description
$2 = 0x200c "plugin description"
Any ideas what I'm doing wrong, what could be the issue here?