dlopen issue(OSX) - c

I have a main application which dynamically loads a dylib, from inside that dylib I would like to call exported functions from my main program. I'm using dlopen(NULL,flag) to retrieve my main applications handle and dlsym(handle, symbol) to get the function.
dlopen gives no error but when I try to dlsym my function I get the following error:
dlerror dlsym(RTLD_NEXT, CallMe): symbol not found
The symbol is exported corrected confirmed by nm
I'm not sure why RTLD_NEXT is there? is this the result of dlopen(NULL,flag)?
How can I solve this problem or achieve my goal?
Or are there other ways to call the main application (preferably not by passing on function pointers to the dylib)?
Thanks in advance!
Added:
Export:
extern "C" {
void CallMe(char* test);
}
__attribute__((visibility("default")))
void CallMe(char* test)
{
NSLog(#"CallMe with: %s",test);
}
Result of nm
...
0000000000001922 T _CallMe
..
Code in dylib:
void * m_Handle;
typedef void CallMe(char* test);
CallMe* m_Function;
m_Handle = dlopen(NULL,RTLD_LAZY); //Also tried RTLD_NOW|RTLD_GLOBAL
if(!m_Handle)
return EC_ERROR;
m_Function = (CallMe*)dlsym(m_Handle, "CallMe");
if(!m_Function)
return EC_ERROR;
m_Function("Hallo");

I think a better approach might be to establish a proprietary protocol with your dynamic library where you initialise it by passing it a struct of function pointers. The dynamic library needs to simply provide some sort of init(const struct *myfuncs), or some such, function and this makes it simpler to implement the dynamic library.
This would also make the implementation more portable.

Related

Undefined reference to pointer to a function

I'm new to this topic. I'm trying to dynamically link a shared library in my c code, but I'm getting an error...
undefined reference to `func'
I've searched the web and I can't find anything wrong with my syntax...
void *handle;
int (*func)(char **);
handle = dlopen(argv[0], RTLD_LOCAL | RTLD_LAZY);
*(int **)&func = dlsym(handle, pluggin_method->FunctionName); //I might need to pass a string by first using strcpy
int func_ret_val = (func)(argv); //execute function
I'm banging my head against a wall trying to figure this out. Any help?
does the code have the statement:
#include <dlfcn.h>
Are you including the -ldl library in the link statement>
if the returned value from dlopen() is NULL, then call dlerror() to obtain the resulting error message.
NOTE: dlopen() loads the library and returns a 'opaque' handle for the library, not a pointer to the actual function.
After a successful call to dlopen() then need to call dlsym() to obtain the actual address in memory of the function.
check the returned value from dlsym() (!=NULL) to assure the op was successful

Is there a way to overwrite the malloc/free function in C?

Is there a way to hook the malloc/free function call from a C application it self?
malloc() and free() are defined in the standard library; when linking code, the linker will search the library only for symbols that are not already resolved by eailier encountered object code, and object files generated from compilation are always linked before any libraries.
So you can override any library function simply by defining it in your own code, ensuring that it has the correct signature (same name, same number and types of parameters and same return type).
Yes you can. Here's an example program. It compiles and builds with gcc 4.8.2 but does not do anything useful since the implementations are not functional.
#include <stdlib.h>
int main()
{
int* ip = malloc(sizeof(int));
double* dp = malloc(sizeof(double));
free(ip);
free(dp);
}
void* malloc(size_t s)
{
return NULL;
}
void free(void* p)
{
}
Not sure if this counts as "overwriting', but you can effectively change the behavior of code that calls malloc and free by using a macro:
#define malloc(x) my_malloc(x)
#define free(x) my_free(x)
void * my_malloc(size_t nbytes)
{
/* Do your magic here! */
}
void my_free(void *p)
{
/* Do your magic here! */
}
int main(void)
{
int *p = malloc(sizeof(int) * 4); /* calls my_malloc */
free(p); /* calls my_free */
}
You may need LD_PRELOAD mechanism to replace malloc and free.
As many mentioned already, this is very platform specific. Most "portable" way is described in an accepted answer to this question. A port to non-posix platforms requires finding an appropriate replacement to dlsym.
Since you mention Linux/gcc, hooks for malloc would probably serve you the best.
Depending on the platform you are using, you may be able to remove the default malloc/free from the library and add your own using the linker or librarian tools. I'd suggest you only do this in a private area and make sure you can't corrupt the original library.
On the Windows platform there is a Detour library. It basically patches any given function on the assembler level. This allows interception of any C library or OS call, like CreateThread, HeapAlloc, etc. I used this library for overriding memory allocation functions in a working application.
This library is Windows specific. On other platforms most likely there are similar libraries.
C does not provide function overloading. So you cannot override.

How to wrap a library function with custom code?

I have a library which implements malloc. I want to override this function with a custom malloc function that does something and then calls the malloc function of the library.
How can i redefine the symbol malloc without losing the function from the library?
The GNU linker provides the --wrap symbol flag to wrap a custom function around an existing function.
As you can read here, last flag: http://ieee.uwaterloo.ca/coldfire/gcc-doc/docs/ld_3.html#SEC3
--wrap symbol
Use a wrapper function for symbol. Any undefined reference to symbol will be resolved to __wrap_symbol. Any undefined reference to __real_symbol will be resolved to symbol. This can used to provide a wrapper for a system function. The wrapper function should be called __wrap_symbol. If it wishes to call the system function, it should call __real_symbol. Here is a trivial example:
void *
__wrap_malloc (int c) {
printf ("malloc called with %ld\n", c);
return __real_malloc (c);
}
If you link other code with this file using --wrap malloc, then all calls to malloc will call the function __wrap_malloc instead. The call to __real_malloc in __wrap_malloc will call the real malloc function. You may wish to provide a __real_malloc function as well, so that links without the --wrap option will succeed. If you do this, you should not put the definition of __real_malloc in the same file as __wrap_malloc; if you do, the assembler may resolve the call before the linker has a chance to wrap it to malloc.
it is not a good practice to create new functions with the names of library functions. If at all you want to create such a function, your new function will work fine but you can not use the library function. If you want to create your own version of printf(), you can do so but you can not use the original printf() function as you are overriding.
If both functions have the same prototype, you can use a function pointer
#include <stdlib.h>
void *my_malloc(size_t len) {
return malloc(len);
}
int main(void) {
void *(*malloc_pointer)(size_t);
malloc_pointer = my_malloc;
malloc_pointer(42); // uses my_malloc;
malloc_pointer = malloc;
malloc_pointer(42); // uses malloc;
return 0;
}

C functions before mainCRTStartup on Mingw?

void start() {
stuff(); //code before mainCRTStartup
mainCRTStartup();
}
int main()
{
//other code
}
In Visual C++,it compiles fine and function "stuff()" gets called before main. How would call "stuff()" before "mainCRTStartup()"? on Mingw(OS:Windows NT)? it seems to ignore "void start()".
You could use the -e argument to ld (the linker) to specify start as your entry point.
I'm not sure how to feed arguments to ld using mingw; perhaps someone can edit my answer to provide that.
The real entry point is always start().
start() calls mainCRTStartup() that initializes CRT functions and call main(), so in stuff(), you can not use CRT functions.

How to get function's name from function's pointer in Linux kernel?

How to get function's name from function's pointer in C?
Edit: The real case is: I'm writing a linux kernel module and I'm calling kernel functions. Some of these functions are pointers and I want to inspect the code of that function in the kernel source. But I don't know which function it is pointing to. I thought it could be done because, when the system fails (kernel panic) it prints out in the screen the current callstack with function's names. But, I guess I was wrong... am I?
I'm surprised why everybody says it is not possible. It is possible on Linux for non-static functions.
I know at least two ways to achieve this.
There are GNU functions for backtrace printing: backtrace() and backtrace_symbols() (See man). In your case you don't need backtrace() as you already have function pointer, you just pass it to backtrace_symbols().
Example (working code):
#include <stdio.h>
#include <execinfo.h>
void foo(void) {
printf("foo\n");
}
int main(int argc, char *argv[]) {
void *funptr = &foo;
backtrace_symbols_fd(&funptr, 1, 1);
return 0;
}
Compile with gcc test.c -rdynamic
Output: ./a.out(foo+0x0)[0x8048634]
It gives you binary name, function name, pointer offset from function start and pointer value so you can parse it.
Another way is to use dladdr() (another extension), I guess print_backtrace() uses dladdr(). dladdr() returns Dl_info structure that has function name in dli_sname field. I don't provide code example here but it is obvious - see man dladdr for details.
NB! Both approaches require function to be non-static!
Well, there is one more way - use debug information using libdwarf but it would require unstripped binary and not very easy to do so I don't recommend it.
That's not directly possible without additional assistance.
You could:
maintain a table in your program mapping function pointers to names
examine the executable's symbol table, if it has one.
The latter, however, is hard, and is not portable. The method will depend on the operating system's binary format (ELF, a.out, .exe, etc), and also on any relocation done by the linker.
EDIT: Since you've now explained what your real use case is, the answer is actually not that hard. The kernel symbol table is available in /proc/kallsyms, and there's an API for accessing it:
#include <linux/kallsyms.h>
const char *kallsyms_lookup(unsigned long addr, unsigned long *symbolsize,
unsigned long *ofset, char **modname, char *namebuf)
void print_symbol(const char *fmt, unsigned long addr)
For simple debug purposes the latter will probably do exactly what you need - it takes the address, formats it, and sends it to printk, or you can use printk with the %pF format specifier.
In the Linux kernel, you can use directly "%pF" format of printk !
void *func = &foo;
printk("func: %pF at address: %p\n", func, func);
The following works me on Linux:
printf the address of the function using %p
Then do an nm <program_path> | grep <address> (without the 0x prefix)
It should show you the function name.
It works only if the function in question is in the same program (not in a dynamically linked library or something).
If you can find out the load addresses of the loaded shared libraries, you can subtract the address from the printed number, and use nm on the library to find out the function name.
You can't diectly but you can implement a different approach to this problem if you want. You can make a struct pointer instead pointing to a function as well as a descriptive string you can set to whatever you want.
I also added a debugging posebilety since you problably do not want these vars to be printet forever.
// Define it like this
typedef struct
{
char *dec_text;
#ifdef _DEBUG_FUNC
void (*action)(char);
#endif
} func_Struct;
// Initialize it like this
func_Struct func[3]= {
#ifdef _DEBUG_FUNC
{"my_Set(char input)",&my_Set}};
{"my_Get(char input)",&my_Get}};
{"my_Clr(char input)",&my_Clr}};
#else
{&my_Set}};
{&my_Get}};
{&my_Clr}};
#endif
// And finally you can use it like this
func[0].action( 0x45 );
#ifdef _DEBUG_FUNC
printf("%s",func.dec_text);
#endif
There is no way how to do it in general.
If you compile the corresponding code into a DLL/Shared Library, you should be able to enlist all entry points and compare with the pointer you've got. Haven't tried it yet, but I've got some experience with DLLs/Shared Libs and would expect it to work. This could even be implemented to work cross-plarform.
Someone else mentioned already to compile with debug symbols, then you could try to find a way to analyse these from the running application, similiar to what a debugger would do.
But this is absolutely proprietary and not portable.
If the list of functions that can be pointed to is not too big or if you already suspect of a small group of functions you can print the addresses and compare them to the one used during execution. Ex:
typedef void (*simpleFP)();
typedef struct functionMETA {
simpleFP funcPtr;
char * funcName;
} functionMETA;
void f1() {/*do something*/}
void f2() {/*do something*/}
void f3() {/*do something*/}
int main()
{
void (*funPointer)() = f2; // you ignore this
funPointer(); // this is all you see
printf("f1 %p\n", f1);
printf("f2 %p\n", f2);
printf("f3 %p\n", f3);
printf("%p\n", funPointer);
// if you want to print the name
struct functionMETA arrFuncPtrs[3] = {{f1, "f1"}, {f2, "f2"} , {f3, "f3"}};
int i;
for(i=0; i<3; i++) {
if( funPointer == arrFuncPtrs[i].funcPtr )
printf("function name: %s\n", arrFuncPtrs[i].funcName);
}
}
Output:
f1 0x40051b
f2 0x400521
f3 0x400527
0x400521
function name: f2
This approach will work for static functions too.
Use kallsyms_lookup_name() to find the address of kallsyms_lookup.
Use a function pointer that points to kallsyms_lookup, to call it.
Check out Visual Leak Detector to see how they get their callstack printing working. This assumes you are using Windows, though.
Alnitak's answer is very helpful to me when I was looking for a workaround to print out function's name in kernel module. But there is one thing I want to supplyment, which is that you might want to use %pS instead of %pF to print function's name, becasue %pF not works anymore at some newer verions of kernel, for example 5.10.x.
Not exactly what the question is asking for but after reading the answers here
I though of this solution to a similar problem of mine:
/**
* search methods */
static int starts(const char *str, const char *c);
static int fuzzy(const char *str, const char *c);
int (*search_method)(const char *, const char *);
/* asign the search_method and do other stuff */
[...]
printf("The search method is %s\n", search_method == starts ? "starts" : "fuzzy")
If your program needs this a lot you could define the method names along with a string in an XMacro and use #define X(name, str) ... #undef X in the code to get the corresponding string from the function name.
You can't. The function name isn't attached to the function by the time it's compiled and linked. It's all by memory address at that point, not name.
You wouldn't know how you look like without a reflecting mirror. You'll have to use a reflection-capable language like C#.

Resources