Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling function by name using dlsym in iOS

Tags:

ios

dlopen

dlsym

Can't I call a function by name in iOS? I have a C function called getstring. I am calling it as follows:

void* handle = dlopen(NULL, RTLD_NOW);
if (handle)
{
fp func = dlsym(handle, "getstring");
if (!func)
    responseField.text = [NSString stringWithUTF8String:dlerror()];
else {
    char* tmpStr = func();
    responseField.text = [NSString stringWithUTF8String:tmpStr];        
}
}
else {
responseField.text = [NSString stringWithUTF8String:dlerror()];
}

When this executes, responseFiled.text is set to dlsym(...): symbol not found. This means dlopen works but not dlsym. I dumped the symbols in the binary using nm and saw that _getstring is present. I checked the manual for dlsym and it says I should not add an underscore to the name. Adding it does not solve the issue anyway. What am I doing wrong?

I had asked a similar question here about calling functions by name in Objective-C and then tried it successfully on a Mac following the answers, so this problem seems to be specific to iOS.

like image 424
341008 Avatar asked Sep 10 '25 23:09

341008


2 Answers

I believe the problem is that dlopen is not supported on iOS, even if you statically link your libraries. You should be able to use

dlsym(RTLD_SELF, "getstring");

because RTLD_SELF means 'start looking in the image that called dlsym'. Based on how you're using dlopen() it should accomplish the same thing.

like image 60
Scott K. Avatar answered Sep 12 '25 12:09

Scott K.


I've actually had some successful experiences in a case similar to yours. I used dlsym(RTLD_MAIN_ONLY, "getstring") to get the function pointer.

Note that your getstring symbol must be suitable for dynamic linking: this can be checked using

nm -m <application>

Your symbol must be external (not non-external).

I'm not yet too sure about the procedure to ensure that symbols are marked as external.

like image 29
rotoglup Avatar answered Sep 12 '25 14:09

rotoglup



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!