#include <stdbool.h> // fprintf(), NULL
#include <stdio.h> // fprintf(), NULL
#include <stdlib.h> // exit(), EXIT_SUCCESS
#include <stdbool.h>
#include <string.h>
#include <mach-o/dyld.h>
#include <mach-o/dyld_priv.h>
#include <dlfcn.h>
#include "test.h" // PASS(), FAIL(), XPASS(), XFAIL()
#if __MAC_OS_X_VERSION_MIN_REQUIRED
static bool doneRegistering = false;
static const char* batchMappedHandler(enum dyld_image_states state, uint32_t infoCount, const struct dyld_image_info info[])
{
for (uint32_t i=0; i < infoCount; ++i) {
if ( strstr(info[i].imageFilePath, "bar") != NULL )
return "can't load bar";
}
return NULL;
}
static const char* singleMappedHandler(enum dyld_image_states state, uint32_t infoCount, const struct dyld_image_info info[])
{
if ( strstr(info[0].imageFilePath, "bar") != NULL )
return "can't load bar";
return NULL;
}
static const char* singleInitializedHandler(enum dyld_image_states state, uint32_t infoCount, const struct dyld_image_info info[])
{
if ( doneRegistering ) {
FAIL("image-state-deny something loaded");
exit(0);
}
return NULL;
}
static void load(const char* name)
{
NSObjectFileImage ofi;
if ( NSCreateObjectFileImageFromFile(name, &ofi) == NSObjectFileImageSuccess ) {
NSModule mod = NSLinkModule(ofi, name, NSLINKMODULE_OPTION_PRIVATE | NSLINKMODULE_OPTION_RETURN_ON_ERROR);
if ( mod != NULL ) {
FAIL("neither NSCreateObjectFileImageFromFile nor NSLinkModule failed but should have");
if ( !NSDestroyObjectFileImage(ofi) ) {
FAIL("NSDestroyObjectFileImage failed");
}
exit(0);
}
else {
NSDestroyObjectFileImage(ofi);
}
}
}
#endif
int main(int argc, const char* argv[])
{
#if __MAC_OS_X_VERSION_MIN_REQUIRED
dyld_register_image_state_change_handler(dyld_image_state_initialized, false, singleInitializedHandler);
doneRegistering = true;
if ( argc > 1 )
dyld_register_image_state_change_handler(dyld_image_state_dependents_mapped, true, batchMappedHandler);
else
dyld_register_image_state_change_handler(dyld_image_state_mapped, false, singleMappedHandler);
NSObjectFileImage ofi;
if ( NSCreateObjectFileImageFromFile("foo2.bundle", &ofi) != NSObjectFileImageSuccess ) {
FAIL("NSCreateObjectFileImageFromFile failed for foo2.bundle");
exit(0);
}
load("foo.bundle");
load("bar.bundle");
if ( !NSDestroyObjectFileImage(ofi) ) {
FAIL("NSDestroyObjectFileImage failed for foo2.bundle");
exit(0);
}
#endif
PASS("image-state-deny");
return EXIT_SUCCESS;
}