user282909
user282909

Reputation: 135

Can I load symbols with dlsym from memory

I'm trying to load symbols from a library file read into memory (I've made the buffer PAGE aligned with mprotect PROT_EXEC flag). I'm trying to use dlsym on this buffer since I CANNOT use the disk to dump this and then dlopen.

For example,

char* buffer; // retrieved from external sources and saved at a page aligned heap area.
mprotect(...); // mark buffer as executable.
void* handle = &buf;
// it segfaults below
void (*symbol_i_want)(void) = (void(*)(void)) dlsym(handle, "symbol_i_want");

Things I noticed:
dlopen() mmaps the library into multiple memory segments. If I know what exactly it maps I can recreate it just so dlsym works the way I want it to.

Either this or a way to dlopen on a buffer. Since it calls open and read internally.

Is there any way to make dlsym work on a buffer containing the shared library rather than a file on disk?

Thank you.

Upvotes: 0

Views: 1159

Answers (1)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215259

No, you can't. Loading an ELF image requires the ability to map pages arbitrarily, possibly mapping the same page more than once, so starting with the file in memory is a non-starter in the general case; this is (part of) why there's no dynamic loader function to "load" a library from memory.

If you have an image which you know already is arranged correctly in memory, you can perform the needed relocations on it yourself and lookup symbols in it yourself via following the tables. This will not integrate it with the global symbol table (making its symbols available to other libraries and making other libraries' symbols available to it), and may be problematic to get working if the library uses thread-local storage (you'll need to provide a special version of __tls_get_addr for it), but it's possible and may meet your needs. The structure and macro definitions in <elf.h> are all you need to do this.

Probably the better option is just making a temp file. You haven't clearly stated why you can't, so it's possible that the reason you think you can't isn't even accurate.

Upvotes: 2

Related Questions