Apollo
Apollo

Reputation: 9064

How to detect dynamic library loads

Is there a way to detect what dynamic libraries an app loads at runtime? I've looked through Apple's documentation for dynamic libraries but it doesn't seem to discuss this.

Upvotes: 2

Views: 3354

Answers (2)

Mark Bessey
Mark Bessey

Reputation: 19782

To get a list of all libraries loaded at runtime by your application:

// import the dynamic linker API
#import <mach-o/dyld.h>

// After your application finishes launching, maybe in 
// -application:didFinishLaunchingWithOptions:
int imageCount = _dyld_image_count();
for (int i=0; i < imageCount; i++) {
    NSLog(@"%d - %s", i, _dyld_get_image_name(i));
}

If you want to call a function each time a library is loaded, you can use _dyld_register_func_for_add_image() or _dyld_register_func_for_link_module()

Important note I only checked this in the simulator. I believe it should work on-device, but I have other things I need to work on right now.

Apple Documentation starts here: https://developer.apple.com/library/prerelease/mac/documentation/DeveloperTools/Reference/MachOReference/

There's an interesting blog article about walking the mach header information here:

http://ddeville.me/2014/04/dynamic-linking/

Upvotes: 4

Amin Negm-Awad
Amin Negm-Awad

Reputation: 16660

A.

You can log the loading event as described here.

This article identifies the environment variables you can set and the type of dynamic loader logging they activate.

You can set the env with the Product | Scheme | Edit Scheme… menu and then in the sheet Run | Environment.

So you cannot "access" it in your app. The app (to be more precise: the runtime environment) simply logs the event without any code in your app.

B.

A dynamic library itself can detect its loading through the +load method on a per class resp. per category basis.

I do not think that there is a notification or something like this for the app itself to get notified, when a call leads to a dynamic load.

Upvotes: 1

Related Questions