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
Related
I have been trying to implement a small simulation to understand memory allocation of malloc(). I created a shared library called mem.c. I am linking the library to the main but cannot pass the correct address of the simulated "heap". Heap is created by a malloc() call in the shared library.
Address in the shared library: 0x55ddaff662a0
Address in the main: 0xffffffffaff662a0
Only last 4 bytes seem to be correct. Rest is set to 0xf.
However, when I #include "mem.c" in the main it works correctly. How can I achieve the same result without including the mem.c. I am trying to solve this without including mem.c or mem.h. I create shared library as this:
gcc -c -fpic mem.c
gcc -shared -o libmem.so mem.o
gcc main.c -lmem -L. -o main
From your comments
I am trying to implement without using #include mem.h or mem.c.
Then you must provide by other means a prototype for the function you're calling. Without an explicit function prototype, following the tradition of K&R and then later ANSI C, undeclared functions are assumed to return an int and take parameters of type int.
EDIT: Essentially you need to write what'd you normally find in a header, somewhere before you make first use of the function. Or of it's a function pointer you need an appropriate variable to store the function pointer.
For example to declare a function that returns an untyped pointer, and an arbitrary, unspecified number of arguments you'd write
void *getAddr();
Note that using the extern keyword here is not required, since extern linkage is always implied for non-static function declarations.
In case you want to dynamically link at runtime (using dlopen / LoadLibrary → dlsym / GetProcAddress), you'd define a function pointer variable
void* (*getAddr_fptr)();
You can set it using dlsym with
*(void**)(&getAddr_fptr) = dlsym(…)
This awkward way of writing it comes due to function pointers being allowed to have a different size and alignment as data pointers (see the dlsym manpage for details).
These days on the majority of platforms int is a 4 byte type and the most common calling convention pass the first few function arguments by register. On x86 (and x86_64) the registers are AX, BX, CX and DX and may be accessed in different sizes, but may read and write with different size (to allow size conversion). This explains why only the first 4 bytes are passed: It's passed via register and only the write to the register is done as a 4 byte wide write. When the function then reads from the register, it does so with a wider type, with the higher value bits set to all 1.
From the comments:
Do you have a declaration for getAddr in your main code?
No I don't have but I am trying to implement without a declaration, is it possible?
Then that's your problem. Without a declaration, the compiler falls back to a default declaration of int getAddr(). This is incompatible with the actual definition which returns a void *, and calling a function through an incompatible declaration triggers undefined behavior.
What probably happened is that when the return value of the function was actually returned you only got back the 4 low-order bytes. Assuming your system is little-endian, and int is 4 bytes, and a void * is 8 bytes, this would explain the low bits being the same.
You must include a valid declaration before the function is called. It doesn't necessarily have to reside in a header file, but it has to be visible at the point the call happens.
I'm assuming you're trying to accomplish something like this? For mem.c
#include <stdlib.h>
#include <stdio.h>
void* getAddr() {
char *heap = (char *)malloc(10);
printf("%p\n", (void*)heap);
return heap;
}
And then without including any headers for the mem.c functions, you'd probably create a library out of mem.c as you've already mentioned in the question and have something as follows in main.c
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
typedef void* (*getAddr)(); //prototype for getAddr() in mem.c
int main() {
void* handle = dlopen("./libmem.so", RTLD_LAZY);
if(handle) {
void* fn = dlsym(handle, "getAddr");
if(fn) {
void* addr = ((getAddr)(fn))();
printf("%p\n", addr);
free(addr);
addr = NULL;
} else {
printf("Failed to dlsym %s\n", dlerror());
}
} else {
printf("Failed to dlopen %s\n", dlerror());
}
}
EDIT: For OP's purpose as #Zilog80 mentioned, since the library is being linked with main executable, the dlopen() part can be gotten rid of and main.c can be simplified as
#include <stdio.h>
#include <stdlib.h>
extern void* getAddr(); //prototype for getAddr() in mem.c
int main() {
void* addr = getAddr();
printf("%p\n", addr);
free(addr);
addr = NULL;
}
And used similar compilation commands as OP i.e.
gcc -shared -o libmem.so -fpic mem.c
gcc main.c -lmem -L . -o main
while executing
LD_LIBRARY_PATH=. ./main
I am trying to make sense of a program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
int main(int argc, char** argv) {
volatile double fShared = 0.0;
// create pthread structures - one for each thread
pthread_t t0;
pthread_t t1;
//Arbitrary pointer variables - void* is a pointer to anything
void *thread_res0;
void *thread_res1;
int res0,res1;
//create a new thread AND run each function
// we pass the ADDRESS of the thread structure as the first argument
// we pass a function name as the third argument - this is known as a FUNCTION pointer
// you might want to look at the man pages for pthread_create
res0 = pthread_create(&t0, NULL, do_this, (void*)"");
res1 = pthread_create(&t1, NULL, do_that, (void*)"");
// Two threads are now running independently of each other and this main function
// the function main is said to run in the main thread, so we are actually running
// The main code can now continue while the threads run - so we can simply block
res0 = pthread_join(t0, &thread_res0);
res1 = pthread_join(t1, &thread_res1);
printf ("\n\nFinal result is fShared = %f\n",fShared);
return (EXIT_SUCCESS);
}
It should be noted that do_this and do_that are functions created earlier in the program. I am getting the following errors:
seed#ubuntu:~/Programs$ Homework2OS.c
/tmp/cceiRtg8.O: in function 'main'
Undefined reference to 'pthread_create'
Undefined reference to 'pthread_create'
Undefined reference to 'pthread_join'
Undefined reference to 'pthread_join'
We were given this bit of code to fix. I have found elsewhere the format for the pthread_create constructor. Do I need to actually define it above the main? I was under the impression it was imported with the library.
I would also venture to guess that it has something to do with the fourth parameter? I understand that the first parameter is the location of the thread (defined above), the second is NULLed, the third is the function call but I do not quite understand what the fourth parameter is supposed to be.
What's wrong?
all the code imports is the header for the pthread library. (pthread.h)
What is missing is the linker needs to actually include the library for gcc the parameter -pthread is needed (AT THE END of the list of parameters to gcc.)
It needs to be at the end because the linker processes parameters in the order given on the command line and if the object files are not already processed, then there will not be any unresolved references for the linker to try to resolve via browsing the pthread library.
I.E. this is wrong:
gcc -g -o myprogram -lpthread myprogram.o
This is correct:
gcc -g -o myprogram myprogram.o -lpthread
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;
}
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.
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#.