Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load dynamic library from memory

Is it possible to load a library from memory instead of from the filesystem on mac/gcc?

With windows I'm using MemoryModule but it's obviously not cross-platform compatible.

like image 436
Qix - MONICA WAS MISTREATED Avatar asked Aug 06 '12 02:08

Qix - MONICA WAS MISTREATED


1 Answers

First things first, to do this I advise you use read the OS X ABI Dynamic Loader Reference.

To do this, you must use the NSCreateObjectFileImageFromMemory API.

Given a pointer to a Mach-O file in memory, this function creates and returns an NSObjectFileImage reference. The current implementation works only with bundles, so you must build the Mach-O executable file using the -bundle linker option.

The memory block that address points to, must be allocated with vm_allocate (/usr/include/mach/vm_map.h).

Make sure to abide by the requirement that vm_allocate is used for the memory block containing the module.

Once you acquire the object file image, you must use NSLinkModule function to link the module into the program.

When you call this function, all libraries referenced by the given module are added to the library search list. Unless you pass the NSLINKMODULE_OPTION_PRIVATE, NSLinkModule adds all global symbols in the module to the global symbol list.

After linking, don't forget to clean up by calling the NSDestroyObjectFileImage function.

When this function is called, the dynamic loader calls vm_deallocate (/usr/include/mach/vm_map.h) on the memory pointed to by the objectFileImage parameter.

Note that while these functions are deprecated, there is no substitute (to the best of my knowledge) using the suggested alternative dlopen et. al.

like image 115
obataku Avatar answered Sep 30 '22 16:09

obataku