Loading...
--- dyld/dyld-95.3/src/dyld.cpp
+++ dyld/dyld-44.4/src/dyld.cpp
@@ -1,6 +1,6 @@
/* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
*
- * Copyright (c) 2004-2007 Apple Inc. All rights reserved.
+ * Copyright (c) 2004-2005 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
@@ -25,7 +25,6 @@
#include <stdint.h>
#include <string.h>
#include <unistd.h>
-#include <errno.h>
#include <fcntl.h>
#include <sys/param.h>
#include <mach/mach_time.h> // mach_absolute_time()
@@ -33,60 +32,35 @@
#include <sys/stat.h>
#include <mach-o/fat.h>
#include <mach-o/loader.h>
-#include <mach-o/ldsyms.h>
#include <libkern/OSByteOrder.h>
#include <mach/mach.h>
#include <sys/sysctl.h>
-#include <sys/mman.h>
-#include <sys/dtrace.h>
#include <vector>
-#include <algorithm>
#include "mach-o/dyld_gdb.h"
#include "dyld.h"
#include "ImageLoader.h"
#include "ImageLoaderMachO.h"
-#include "dyldLibSystemInterface.h"
-#include "dyld_cache_format.h"
-
-// from _simple.h in libc
-typedef struct _SIMPLE* _SIMPLE_STRING;
-extern "C" void _simple_vdprintf(int __fd, const char *__fmt, va_list __ap);
-extern "C" void _simple_dprintf(int __fd, const char *__fmt, ...);
-extern "C" _SIMPLE_STRING _simple_salloc(void);
-extern "C" int _simple_vsprintf(_SIMPLE_STRING __b, const char *__fmt, va_list __ap);
-extern "C" void _simple_sfree(_SIMPLE_STRING __b);
-extern "C" char * _simple_string(_SIMPLE_STRING __b);
-
-
-
-// 32-bit ppc is only architecture that uses cpu-sub-types
-#define CPU_SUBTYPES_SUPPORTED __ppc__
-
-
-#define OLD_GDB_DYLD_INTERFACE __ppc__ || __i386__
+#include "dyldLibSystemThreadHelpers.h"
#define CPU_TYPE_MASK 0x00FFFFFF /* complement of CPU_ARCH_MASK */
/* implemented in dyld_gdb.cpp */
-extern void addImagesToAllImages(uint32_t infoCount, const dyld_image_info info[]);
-extern void removeImageFromAllImages(const mach_header* mh);
+void addImagesToAllImages(uint32_t infoCount, const dyld_image_info info[]);
+void removeImageFromAllImages(const mach_header* mh);
#if OLD_GDB_DYLD_INTERFACE
-extern void addImageForgdb(const mach_header* mh, uintptr_t slide, const char* physicalPath, const char* logicalPath);
-extern void removeImageForgdb(const struct mach_header* mh);
+void addImageForgdb(const mach_header* mh, uintptr_t slide, const char* physicalPath, const char* logicalPath);
+void removeImageForgdb(const struct mach_header* mh);
#endif
// magic so CrashReporter logs message
extern "C" {
char error_string[1024];
}
-// implemented in dyldStartup.s for CrashReporter
-extern "C" void dyld_fatal_error(const char* errString) __attribute__((noreturn));
-
//
@@ -119,7 +93,6 @@
bool DYLD_PRINT_STATISTICS;
bool DYLD_PRINT_OPTS;
bool DYLD_PRINT_ENV;
- bool DYLD_DISABLE_DOFS;
// DYLD_IMAGE_SUFFIX ==> gLinkContext.imageSuffix
// DYLD_PRINT_OPTS ==> gLinkContext.verboseOpts
// DYLD_PRINT_ENV ==> gLinkContext.verboseEnv
@@ -128,17 +101,14 @@
// DYLD_PRINT_SEGMENTS ==> gLinkContext.verboseMapping
// DYLD_PRINT_BINDINGS ==> gLinkContext.verboseBind
// DYLD_PRINT_REBASINGS ==> gLinkContext.verboseRebase
- // DYLD_PRINT_DOFS ==> gLinkContext.verboseDOF
// DYLD_PRINT_APIS ==> gLogAPIs
// DYLD_IGNORE_PREBINDING ==> gLinkContext.prebindUsage
// DYLD_PREBIND_DEBUG ==> gLinkContext.verbosePrebinding
// DYLD_NEW_LOCAL_SHARED_REGIONS ==> gLinkContext.sharedRegionMode
// DYLD_SHARED_REGION ==> gLinkContext.sharedRegionMode
+ // DYLD_SLIDE_AND_PACK_DYLIBS ==> gLinkContext.slideAndPackDylibs
// DYLD_PRINT_WARNINGS ==> gLinkContext.verboseWarnings
};
-
-typedef std::vector<dyld_image_state_change_handler> StateHandlers;
-struct RegisteredDOF { const mach_header* mh; int registrationID; };
// all global state
static const char* sExecPath = NULL;
@@ -146,19 +116,13 @@
static cpu_type_t sHostCPU;
static cpu_subtype_t sHostCPUsubtype;
static ImageLoader* sMainExecutable = NULL;
-static bool sMainExecutableIsSetuid = false;
-static unsigned int sInsertedDylibCount = 0;
+static bool sAllImagesMightContainUnlinkedImages; // necessary until will support dylib unloading
static std::vector<ImageLoader*> sAllImages;
static std::vector<ImageLoader*> sImageRoots;
static std::vector<ImageLoader*> sImageFilesNeedingTermination;
-static std::vector<RegisteredDOF> sImageFilesNeedingDOFUnregistration;
-#if IMAGE_NOTIFY_SUPPORT
static std::vector<ImageLoader*> sImagesToNotifyAboutOtherImages;
-#endif
static std::vector<ImageCallback> sAddImageCallbacks;
static std::vector<ImageCallback> sRemoveImageCallbacks;
-static StateHandlers sSingleHandlers[7];
-static StateHandlers sBatchHandlers[7];
static ImageLoader* sLastImageByAddressCache;
static EnvironmentVariables sEnv;
static const char* sFrameworkFallbackPaths[] = { "$HOME/Library/Frameworks", "/Library/Frameworks", "/Network/Library/Frameworks", "/System/Library/Frameworks", NULL };
@@ -166,67 +130,10 @@
static BundleNotificationCallBack sBundleNotifier = NULL;
static BundleLocatorCallBack sBundleLocation = NULL;
static UndefinedHandler sUndefinedHandler = NULL;
-static ImageLoader* sBundleBeingLoaded = NULL; // hack until OFI is reworked
-#if DYLD_SHARED_CACHE_SUPPORT
-static const dyld_cache_header* sSharedCache = NULL;
-bool gSharedCacheNotFound = false;
-bool gSharedCacheNeedsUpdating = false;
-bool gSharedCacheDontNotify = false;
-#endif
ImageLoader::LinkContext gLinkContext;
bool gLogAPIs = false;
-const struct LibSystemHelpers* gLibSystemHelpers = NULL;
-#if SUPPORT_OLD_CRT_INITIALIZATION
-bool gRunInitializersOldWay = false;
-#endif
-#if __i386__
-static uint32_t sImportSegmentsStart = 0;
-static uint32_t sImportSegmentsSize = 0;
-#endif
-
-
-
-const char* mkstringf(const char* format, ...)
-{
- va_list list;
- va_start(list, format);
- _SIMPLE_STRING buf = _simple_salloc();
- _simple_vsprintf(buf, format, list);
- va_end(list);
- const char* t = strdup(_simple_string(buf));
- _simple_sfree(buf);
- return t;
-}
-
-
-void throwf(const char* format, ...)
-{
- va_list list;
- va_start(list, format);
- _SIMPLE_STRING buf = _simple_salloc();
- _simple_vsprintf(buf, format, list);
- va_end(list);
- const char* t = strdup(_simple_string(buf));
- _simple_sfree(buf);
- throw t;
-}
-
-void log(const char* format, ...)
-{
- va_list list;
- va_start(list, format);
- _simple_vdprintf(STDERR_FILENO, format, list);
- va_end(list);
-}
-
-void warn(const char* format, ...)
-{
- _simple_dprintf(STDERR_FILENO, "dyld: warning, ");
- va_list list;
- va_start(list, format);
- _simple_vdprintf(STDERR_FILENO, format, list);
- va_end(list);
-}
+const struct ThreadingHelpers* gThreadHelpers = NULL;
+
// utility class to assure files are closed when an exception is thrown
@@ -240,250 +147,60 @@
};
FileOpener::FileOpener(const char* path)
- : fd(-1)
{
fd = open(path, O_RDONLY, 0);
}
FileOpener::~FileOpener()
{
- if ( fd != -1 )
- close(fd);
-}
-
-
-// forward declaration
-#if __ppc__ || __i386__
-bool isRosetta();
-#endif
-
-
-static void registerDOFs(const std::vector<ImageLoader::DOFInfo>& dofs)
-{
-#if __ppc__
- // can't dtrace a program running emulated under rosetta rdar://problem/5179640
- if ( isRosetta() )
- return;
-#endif
- const unsigned int dofSectionCount = dofs.size();
- if ( !sEnv.DYLD_DISABLE_DOFS && (dofSectionCount != 0) ) {
- int fd = open("/dev/" DTRACEMNR_HELPER, O_RDWR);
- if ( fd < 0 ) {
- //dyld::warn("can't open /dev/" DTRACEMNR_HELPER " to register dtrace DOF sections\n");
- }
- else {
- // allocate a buffer on the stack for the variable length dof_ioctl_data_t type
- uint8_t buffer[sizeof(dof_ioctl_data_t) + dofSectionCount*sizeof(dof_helper_t)];
- dof_ioctl_data_t* ioctlData = (dof_ioctl_data_t*)buffer;
-
- // fill in buffer with one dof_helper_t per DOF section
- ioctlData->dofiod_count = dofSectionCount;
- for (unsigned int i=0; i < dofSectionCount; ++i) {
- strlcpy(ioctlData->dofiod_helpers[i].dofhp_mod, dofs[i].imageShortName, DTRACE_MODNAMELEN);
- ioctlData->dofiod_helpers[i].dofhp_dof = (uintptr_t)(dofs[i].dof);
- ioctlData->dofiod_helpers[i].dofhp_addr = (uintptr_t)(dofs[i].dof);
- }
-
- // tell kernel about all DOF sections en mas
- // pass pointer to ioctlData because ioctl() only copies a fixed size amount of data into kernel
- user_addr_t val = (user_addr_t)(unsigned long)ioctlData;
- if ( ioctl(fd, DTRACEHIOC_ADDDOF, &val) != -1 ) {
- // kernel returns a unique identifier for each section in the dofiod_helpers[].dofhp_dof field.
- for (unsigned int i=0; i < dofSectionCount; ++i) {
- RegisteredDOF info;
- info.mh = dofs[i].imageHeader;
- info.registrationID = (int)(ioctlData->dofiod_helpers[i].dofhp_dof);
- sImageFilesNeedingDOFUnregistration.push_back(info);
- if ( gLinkContext.verboseDOF ) {
- dyld::log("dyld: registering DOF section 0x%p in %s with dtrace, ID=0x%08X\n",
- dofs[i].dof, dofs[i].imageShortName, info.registrationID);
- }
- }
- }
- else {
- dyld::log( "dyld: ioctl to register dtrace DOF section failed\n");
- }
- close(fd);
- }
- }
-}
-
-static void unregisterDOF(int registrationID)
-{
- int fd = open("/dev/" DTRACEMNR_HELPER, O_RDWR);
- if ( fd < 0 ) {
- dyld::warn("can't open /dev/" DTRACEMNR_HELPER " to unregister dtrace DOF section\n");
- }
- else {
- ioctl(fd, DTRACEHIOC_REMOVE, registrationID);
- close(fd);
- if ( gLinkContext.verboseInit )
- dyld::warn("unregistering DOF section ID=0x%08X with dtrace\n", registrationID);
- }
-}
-
-
-//
-// _dyld_register_func_for_add_image() is implemented as part of the general image state change notification
-//
-static void notifyAddImageCallbacks(ImageLoader* image)
-{
- for (std::vector<ImageCallback>::iterator it=sAddImageCallbacks.begin(); it != sAddImageCallbacks.end(); it++)
- (*it)(image->machHeader(), image->getSlide());
-}
-
-
-// notify gdb about these new images
-static const char* notifyGDB(enum dyld_image_states state, uint32_t infoCount, const struct dyld_image_info info[])
-{
- addImagesToAllImages(infoCount, info);
- return NULL;
-}
-
-#if IMAGE_NOTIFY_SUPPORT
-// notify objc about these new images
-static void notifyAdding(const ImageLoader* const * images, unsigned int count)
+ close(fd);
+}
+
+
+
+// Objective-C installs an addImage hook to dyld to get notified about new images
+// The callback needs to be run after the image is rebased and bound, but before its initializers are called
+static uint32_t imageNotification(ImageLoader* image, uint32_t startIndex)
+{
+ // tell all register add image handlers about this
+ const uint32_t callbackCount = sAddImageCallbacks.size();
+ for (uint32_t i=startIndex; i < callbackCount; ++i) {
+ ImageCallback cb = sAddImageCallbacks[i];
+ //fprintf(stderr, "dyld: calling add-image-callback[%d]=%p for %s\n", i, cb, image->getPath());
+ (cb)(image->machHeader(), image->getSlide());
+ }
+ return callbackCount;
+}
+
+
+
+// notify gdb et al about these new images
+static void notifyAdding(std::vector<ImageLoader*>& images)
{
// build array
- if ( count != 0 ) {
- dyld_image_info infos[count];
- for (unsigned int i=0; i < count; ++i) {
+ unsigned int len = images.size();
+ if ( len != 0 ) {
+ dyld_image_info infos[len];
+ for (unsigned int i=0; i < len; ++i) {
dyld_image_info* p = &infos[i];
- const ImageLoader* image = images[i];
+ ImageLoader* image = images[i];
p->imageLoadAddress = image->machHeader();
p->imageFilePath = image->getPath();
p->imageFileModDate = image->lastModified();
- //dyld::log("notifying objc about %s\n", image->getPath());
+ //fprintf(stderr, "notifying objc about %s\n", image->getPath());
}
+ // tell gdb
+ addImagesToAllImages(len, infos);
+
// tell all interested images (after gdb, so you can debug anything the notification does)
for (std::vector<ImageLoader*>::iterator it=sImagesToNotifyAboutOtherImages.begin(); it != sImagesToNotifyAboutOtherImages.end(); it++) {
- (*it)->doNotification(dyld_image_adding, count, infos);
- }
- }
-}
-#endif
-
-static StateHandlers* stateToHandlers(dyld_image_states state, StateHandlers handlersArray[8])
-{
- switch ( state ) {
- case dyld_image_state_mapped:
- return &handlersArray[0];
-
- case dyld_image_state_dependents_mapped:
- return &handlersArray[1];
-
- case dyld_image_state_rebased:
- return &handlersArray[2];
-
- case dyld_image_state_bound:
- return &handlersArray[3];
-
- case dyld_image_state_dependents_initialized:
- return &handlersArray[4];
-
- case dyld_image_state_initialized:
- return &handlersArray[5];
-
- case dyld_image_state_terminated:
- return &handlersArray[6];
- }
- return NULL;
-}
-
-static void notifySingle(dyld_image_states state, const struct mach_header* mh, const char* path, time_t modDate)
-{
- std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sSingleHandlers);
- if ( handlers != NULL ) {
- dyld_image_info info;
- info.imageLoadAddress = mh;
- info.imageFilePath = path;
- info.imageFileModDate = modDate;
- for (std::vector<dyld_image_state_change_handler>::iterator it = handlers->begin(); it != handlers->end(); ++it) {
- const char* result = (*it)(state, 1, &info);
- if ( (result != NULL) && (state == dyld_image_state_mapped) ) {
- //fprintf(stderr, " image rejected by handler=%p\n", *it);
- // make copy of thrown string so that later catch clauses can free it
- const char* str = strdup(result);
- throw str;
- }
- }
- }
-}
-
-
-
-static int imageSorter(const void* l, const void* r)
-{
- const ImageLoader* left = *((ImageLoader**)l);
- const ImageLoader* right= *((ImageLoader**)r);
- return left->compare(right);
-}
-
-static void notifyBatchPartial(dyld_image_states state, bool orLater, dyld_image_state_change_handler onlyHandler)
-{
- std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sBatchHandlers);
- if ( handlers != NULL ) {
- // don't use a vector because it will use malloc/free and we want notifcation to be low cost
- ImageLoader* images[sAllImages.size()+1];
- ImageLoader** end = images;
- for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
- dyld_image_states imageState = (*it)->getState();
- if ( (imageState == state) || (orLater && (imageState > state)) )
- *end++ = *it;
- }
- if ( sBundleBeingLoaded != NULL ) {
- dyld_image_states imageState = sBundleBeingLoaded->getState();
- if ( (imageState == state) || (orLater && (imageState > state)) )
- *end++ = sBundleBeingLoaded;
- }
- unsigned int count = end-images;
- if ( end != images ) {
- // sort bottom up
- qsort(images, count, sizeof(ImageLoader*), &imageSorter);
- // build info array
- dyld_image_info infos[count];
- for (unsigned int i=0; i < count; ++i) {
- dyld_image_info* p = &infos[i];
- ImageLoader* image = images[i];
- //dyld::log(" state=%d, name=%s\n", state, image->getPath());
- p->imageLoadAddress = image->machHeader();
- p->imageFilePath = image->getPath();
- p->imageFileModDate = image->lastModified();
- // special case for add_image hook
- if ( state == dyld_image_state_bound )
- notifyAddImageCallbacks(image);
- }
-
- if ( onlyHandler != NULL ) {
- const char* result = (*onlyHandler)(state, count, infos);
- if ( (result != NULL) && (state == dyld_image_state_dependents_mapped) ) {
- //fprintf(stderr, " images rejected by handler=%p\n", onlyHandler);
- // make copy of thrown string so that later catch clauses can free it
- const char* str = strdup(result);
- throw str;
- }
- }
- else {
- // call each handler with whole array
- for (std::vector<dyld_image_state_change_handler>::iterator it = handlers->begin(); it != handlers->end(); ++it) {
- const char* result = (*it)(state, count, infos);
- if ( (result != NULL) && (state == dyld_image_state_dependents_mapped) ) {
- //fprintf(stderr, " images rejected by handler=%p\n", *it);
- // make copy of thrown string so that later catch clauses can free it
- const char* str = strdup(result);
- throw str;
- }
- }
- }
- }
- }
-}
-
-static void notifyBatch(dyld_image_states state)
-{
- notifyBatchPartial(state, false, NULL);
-}
+ (*it)->doNotification(dyld_image_adding, len, infos);
+ }
+ }
+}
+
+
// In order for register_func_for_add_image() callbacks to to be called bottom up,
// we need to maintain a list of root images. The main executable is usally the
@@ -491,73 +208,17 @@
// If DYLD_INSERT_LIBRARIES is used, those libraries are first.
static void addRootImage(ImageLoader* image)
{
- //dyld::log("addRootImage(%p, %s)\n", image, image->getPath());
+ //fprintf(stderr, "addRootImage(%p, %s)\n", image, image->getPath());
// add to list of roots
sImageRoots.push_back(image);
}
-#if IMAGE_NOTIFY_SUPPORT
// Objective-C will contain a __DATA/__image_notify section which contains pointers to a function to call
// whenever any new image is loaded.
static void addImageNeedingNotification(ImageLoader* image)
{
sImagesToNotifyAboutOtherImages.push_back(image);
}
-#endif
-
-static void clearAllDepths()
-{
- for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++)
- (*it)->clearDepth();
-}
-
-static unsigned int imageCount()
-{
- return sAllImages.size();
-}
-
-static void notifySharedCacheInvalid()
-{
- gSharedCacheNeedsUpdating = true;
-}
-
-
-
-#if __i386__
-static void makeSharedCacheImportSegmentsWritable(bool writable)
-{
- // if cache was built with read-only __IMPORT segments
- if ( sImportSegmentsSize != 0 ) {
- vm_prot_t prot = VM_PROT_EXECUTE | PROT_READ;
- if ( writable )
- prot |= VM_PROT_WRITE;
- vm_protect(mach_task_self(), sImportSegmentsStart, sImportSegmentsSize, false, prot);
- if ( gLinkContext.verboseMapping ) {
- dyld::log("%18s at %p->%p altered permissions to %c%c%c\n", "", (char*)sImportSegmentsStart, (char*)sImportSegmentsStart+sImportSegmentsSize-1,
- (prot & PROT_READ) ? 'r' : '.', (prot & PROT_WRITE) ? 'w' : '.', (prot & PROT_EXEC) ? 'x' : '.' );
- }
- }
-}
-#endif
-
-static void setNewProgramVars(const ProgramVars& newVars)
-{
- // make a copy of the pointers to program variables
- gLinkContext.programVars = newVars;
-
- // now set each program global to their initial value
- *gLinkContext.programVars.NXArgcPtr = gLinkContext.argc;
- *gLinkContext.programVars.NXArgvPtr = gLinkContext.argv;
- *gLinkContext.programVars.environPtr = gLinkContext.envp;
- *gLinkContext.programVars.__prognamePtr = gLinkContext.progname;
-}
-
-#if SUPPORT_OLD_CRT_INITIALIZATION
-static void setRunInitialzersOldWay()
-{
- gRunInitializersOldWay = true;
-}
-#endif
static void addImage(ImageLoader* image)
{
@@ -565,7 +226,11 @@
sAllImages.push_back(image);
if ( sEnv.DYLD_PRINT_LIBRARIES || (sEnv.DYLD_PRINT_LIBRARIES_POST_LAUNCH && (sMainExecutable!=NULL) && sMainExecutable->isLinked()) ) {
- dyld::log("dyld: loaded: %s\n", image->getPath());
+ uint64_t offset = image->getOffsetInFatFile();
+ if ( offset == 0 )
+ fprintf(stderr, "dyld: loaded: %s\n", image->getPath());
+ else
+ fprintf(stderr, "dyld: loaded: %s, cpu-sub-type: %d\n", image->getPath(), image->machHeader()->cpusubtype);
}
#if OLD_GDB_DYLD_INTERFACE
@@ -576,6 +241,10 @@
void removeImage(ImageLoader* image)
{
+ // flush find-by-address cache
+ if ( sLastImageByAddressCache == image )
+ sLastImageByAddressCache = NULL;
+
// if in termination list, pull it out and run terminator
for (std::vector<ImageLoader*>::iterator it=sImageFilesNeedingTermination.begin(); it != sImageFilesNeedingTermination.end(); it++) {
if ( *it == image ) {
@@ -585,27 +254,12 @@
}
}
- // if has dtrace DOF section, tell dtrace it is going away, then remove from sImageFilesNeedingDOFUnregistration
- for (std::vector<RegisteredDOF>::iterator it=sImageFilesNeedingDOFUnregistration.begin(); it != sImageFilesNeedingDOFUnregistration.end(); ) {
- if ( it->mh == image->machHeader() ) {
- unregisterDOF(it->registrationID);
- sImageFilesNeedingDOFUnregistration.erase(it);
- // don't increment iterator, the erase caused next element to be copied to where this iterator points
- }
- else {
- ++it;
- }
- }
-
// tell all register add image handlers about this
- // do this before removing image from internal data structures so that the callback can query dyld about the image
- if ( image->getState() >= dyld_image_state_bound ) {
- for (std::vector<ImageCallback>::iterator it=sRemoveImageCallbacks.begin(); it != sRemoveImageCallbacks.end(); it++) {
- (*it)(image->machHeader(), image->getSlide());
- }
- }
-
-#if IMAGE_NOTIFY_SUPPORT
+ // do this before removing image from internal data structures so that the callback can querey dyld about the image
+ for (std::vector<ImageCallback>::iterator it=sRemoveImageCallbacks.begin(); it != sRemoveImageCallbacks.end(); it++) {
+ (*it)(image->machHeader(), image->getSlide());
+ }
+
// tell all interested images
for (std::vector<ImageLoader*>::iterator it=sImagesToNotifyAboutOtherImages.begin(); it != sImagesToNotifyAboutOtherImages.end(); it++) {
dyld_image_info info;
@@ -614,7 +268,6 @@
info.imageFileModDate = image->lastModified();
(*it)->doNotification(dyld_image_removing, 1, &info);
}
-#endif
// remove from master list
for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
@@ -624,11 +277,6 @@
}
}
- // flush find-by-address cache (do this after removed from master list, so there is no chance it can come back)
- if ( sLastImageByAddressCache == image )
- sLastImageByAddressCache = NULL;
-
-#if IMAGE_NOTIFY_SUPPORT
// if in announcement list, pull it out
for (std::vector<ImageLoader*>::iterator it=sImagesToNotifyAboutOtherImages.begin(); it != sImagesToNotifyAboutOtherImages.end(); it++) {
if ( *it == image ) {
@@ -636,7 +284,6 @@
break;
}
}
-#endif
// if in root list, pull it out
for (std::vector<ImageLoader*>::iterator it=sImageRoots.begin(); it != sImageRoots.end(); it++) {
@@ -646,11 +293,6 @@
}
}
- // log if requested
- if ( sEnv.DYLD_PRINT_LIBRARIES || (sEnv.DYLD_PRINT_LIBRARIES_POST_LAUNCH && (sMainExecutable!=NULL) && sMainExecutable->isLinked()) ) {
- dyld::log("dyld: unloaded: %s\n", image->getPath());
- }
-
// tell gdb, new way
removeImageFromAllImages(image->machHeader());
@@ -675,28 +317,22 @@
void initializeMainExecutable()
{
-
-#if __i386__
- // make all __IMPORT segments in the shared cache read-only
- // before executing any code
- makeSharedCacheImportSegmentsWritable(false);
-#endif
-
- // run initialzers for any inserted dylibs
const int rootCount = sImageRoots.size();
- if ( rootCount > 1 ) {
- for(int i=1; i < rootCount; ++i)
- sImageRoots[i]->runInitializers(gLinkContext);
- }
-
- // run initializers for main executable and everything it brings up
- sMainExecutable->runInitializers(gLinkContext);
-
- // register atexit() handler to run terminators in all loaded images when this process exits
- if ( gLibSystemHelpers != NULL )
- (*gLibSystemHelpers->cxa_atexit)(&runTerminators, NULL, NULL);
-
- // dump info if requested
+ for(int i=0; i < rootCount; ++i) {
+ ImageLoader* image = sImageRoots[i];
+ //fprintf(stderr, "initializeMainExecutable: image = %p\n", image);
+ image->runInitializers(gLinkContext);
+ }
+/*
+ // this does not work???
+ for (std::vector<ImageLoader*>::iterator it=sImageRoots.begin(); it != sImageRoots.end(); it++) {
+ ImageLoader* image = *it;
+ fprintf(stderr, "initializeMainExecutable: image = %p\n", image);
+ // don't know why vector sometimes starts with NULL element???
+ if ( image != NULL )
+ image->runInitializers(gLinkContext);
+ }
+*/
if ( sEnv.DYLD_PRINT_STATISTICS )
ImageLoaderMachO::printStatistics(sAllImages.size());
}
@@ -712,16 +348,14 @@
}
-void runTerminators(void* extra)
+void runTerminators()
{
const unsigned int imageCount = sImageFilesNeedingTermination.size();
for(unsigned int i=imageCount; i > 0; --i){
ImageLoader* image = sImageFilesNeedingTermination[i-1];
image->doTermination(gLinkContext);
- notifySingle(dyld_image_state_terminated, image->machHeader(), image->getPath(), image->lastModified());
}
sImageFilesNeedingTermination.clear();
- notifyBatch(dyld_image_state_terminated);
}
@@ -763,7 +397,37 @@
return (const char**)result;
}
+/*
+ * Library path searching is not done for setuid programs
+ * which are not run by the real user. Futher the
+ * evironment varaible for the library path is cleared so
+ * that if this program executes a non-set uid program this
+ * part of the evironment will not be passed along so that
+ * that program also will not have it's libraries searched
+ * for.
+ */
+ static bool riskyUser()
+ {
+ static bool checked = false;
+ static bool risky = false;
+ if ( !checked ) {
+ risky = ( getuid() != 0 && (getuid() != geteuid() || getgid() != getegid()) );
+ checked = true;
+ }
+ return risky;
+ }
+
+static bool disableIfBadUser(char* rhs)
+{
+ bool didDisable = false;
+ if ( riskyUser() ) {
+ *rhs ='\0';
+ didDisable = true;
+ }
+ return didDisable;
+}
+
static void paths_expand_roots(const char **paths, const char *key, const char *val)
{
// assert(val != NULL);
@@ -784,18 +448,13 @@
static void removePathWithPrefix(const char* paths[], const char* prefix)
{
- size_t prefixLen = strlen(prefix);
- int skip = 0;
- int i;
- for(i = 0; paths[i] != NULL; ++i) {
- if ( strncmp(paths[i], prefix, prefixLen) == 0 )
- ++skip;
- else
- paths[i-skip] = paths[i];
- }
- paths[i-skip] = NULL;
-}
-
+ size_t prefixLen = strlen(prefix);
+ for(int s=0,d=0; (paths[d] != NULL) && (paths[s] != NULL); ++s, ++d) {
+ if ( strncmp(paths[s], prefix, prefixLen) == 0 )
+ ++s;
+ paths[d] = paths[s];
+ }
+}
#if 0
static void paths_dump(const char **paths)
@@ -804,7 +463,7 @@
const char **strs = paths;
while(*strs != NULL)
{
- dyld::log("\"%s\"\n", *strs);
+ fprintf(stderr, "\"%s\"\n", *strs);
strs++;
}
return;
@@ -815,7 +474,7 @@
{
uint32_t i = 0;
while ( NULL != argv[i] ) {
- dyld::log("opt[%i] = \"%s\"\n", i, argv[i]);
+ fprintf(stderr, "opt[%i] = \"%s\"\n", i, argv[i]);
i++;
}
}
@@ -823,49 +482,58 @@
static void printEnvironmentVariables(const char* envp[])
{
while ( NULL != *envp ) {
- dyld::log("%s\n", *envp);
+ fprintf(stderr, "%s\n", *envp);
envp++;
}
}
+
+
void processDyldEnvironmentVarible(const char* key, const char* value)
{
if ( strcmp(key, "DYLD_FRAMEWORK_PATH") == 0 ) {
- sEnv.DYLD_FRAMEWORK_PATH = parseColonList(value);
- gSharedCacheDontNotify = true;
+ if ( !disableIfBadUser((char*)value) )
+ sEnv.DYLD_FRAMEWORK_PATH = parseColonList(value);
}
else if ( strcmp(key, "DYLD_FALLBACK_FRAMEWORK_PATH") == 0 ) {
- sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = parseColonList(value);
- gSharedCacheDontNotify = true;
+ if ( !disableIfBadUser((char*)value) )
+ sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = parseColonList(value);
}
else if ( strcmp(key, "DYLD_LIBRARY_PATH") == 0 ) {
- sEnv.DYLD_LIBRARY_PATH = parseColonList(value);
- gSharedCacheDontNotify = true;
+ if ( !disableIfBadUser((char*)value) )
+ sEnv.DYLD_LIBRARY_PATH = parseColonList(value);
}
else if ( strcmp(key, "DYLD_FALLBACK_LIBRARY_PATH") == 0 ) {
- sEnv.DYLD_FALLBACK_LIBRARY_PATH = parseColonList(value);
- gSharedCacheDontNotify = true;
+ if ( !disableIfBadUser((char*)value) )
+ sEnv.DYLD_FALLBACK_LIBRARY_PATH = parseColonList(value);
}
else if ( (strcmp(key, "DYLD_ROOT_PATH") == 0) || (strcmp(key, "DYLD_PATHS_ROOT") == 0) ) {
- gSharedCacheDontNotify = true;
- if ( strcmp(value, "/") != 0 ) {
- sEnv.DYLD_ROOT_PATH = parseColonList(value);
- for (int i=0; sEnv.DYLD_ROOT_PATH[i] != NULL; ++i) {
- if ( sEnv.DYLD_ROOT_PATH[i][0] != '/' ) {
- dyld::warn("DYLD_ROOT_PATH not used because it contains a non-absolute path\n");
- sEnv.DYLD_ROOT_PATH = NULL;
- break;
+ if ( !disableIfBadUser((char*)value) ) {
+ if ( strcmp(value, "/") != 0 ) {
+ sEnv.DYLD_ROOT_PATH = parseColonList(value);
+ for (int i=0; sEnv.DYLD_ROOT_PATH[i] != NULL; ++i) {
+ if ( sEnv.DYLD_ROOT_PATH[i][0] != '/' ) {
+ fprintf(stderr, "dyld: warning DYLD_ROOT_PATH not used because it contains a non-absolute path\n");
+ sEnv.DYLD_ROOT_PATH = NULL;
+ break;
+ }
}
}
}
}
else if ( strcmp(key, "DYLD_IMAGE_SUFFIX") == 0 ) {
- gSharedCacheDontNotify = true;
- gLinkContext.imageSuffix = value;
+ if ( !disableIfBadUser((char*)value) )
+ gLinkContext.imageSuffix = value;
}
else if ( strcmp(key, "DYLD_INSERT_LIBRARIES") == 0 ) {
- sEnv.DYLD_INSERT_LIBRARIES = parseColonList(value);
- gSharedCacheDontNotify = true;
+ if ( !disableIfBadUser((char*)value) )
+ sEnv.DYLD_INSERT_LIBRARIES = parseColonList(value);
+ }
+ else if ( strcmp(key, "DYLD_DEBUG_TRACE") == 0 ) {
+ fprintf(stderr, "dyld: warning DYLD_DEBUG_TRACE not supported\n");
+ }
+ else if ( strcmp(key, "DYLD_ERROR_PRINT") == 0 ) {
+ fprintf(stderr, "dyld: warning DYLD_ERROR_PRINT not supported\n");
}
else if ( strcmp(key, "DYLD_PRINT_OPTS") == 0 ) {
sEnv.DYLD_PRINT_OPTS = true;
@@ -873,39 +541,61 @@
else if ( strcmp(key, "DYLD_PRINT_ENV") == 0 ) {
sEnv.DYLD_PRINT_ENV = true;
}
- else if ( strcmp(key, "DYLD_DISABLE_DOFS") == 0 ) {
- sEnv.DYLD_DISABLE_DOFS = true;
- }
- else if ( strcmp(key, "DYLD_DISABLE_PREFETCH") == 0 ) {
- gLinkContext.preFetchDisabled = true;
- }
else if ( strcmp(key, "DYLD_PRINT_LIBRARIES") == 0 ) {
sEnv.DYLD_PRINT_LIBRARIES = true;
}
else if ( strcmp(key, "DYLD_PRINT_LIBRARIES_POST_LAUNCH") == 0 ) {
sEnv.DYLD_PRINT_LIBRARIES_POST_LAUNCH = true;
}
+ else if ( strcmp(key, "DYLD_TRACE") == 0 ) {
+ fprintf(stderr, "dyld: warning DYLD_TRACE not supported\n");
+ }
+ else if ( strcmp(key, "DYLD_EBADEXEC_ONLY") == 0 ) {
+ fprintf(stderr, "dyld: warning DYLD_EBADEXEC_ONLY not supported\n");
+ }
else if ( strcmp(key, "DYLD_BIND_AT_LAUNCH") == 0 ) {
sEnv.DYLD_BIND_AT_LAUNCH = true;
}
else if ( strcmp(key, "DYLD_FORCE_FLAT_NAMESPACE") == 0 ) {
gLinkContext.bindFlat = true;
}
+ else if ( strcmp(key, "DYLD_DEAD_LOCK_HANG") == 0 ) {
+ fprintf(stderr, "dyld: warning DYLD_DEAD_LOCK_HANG not supported\n");
+ }
+ else if ( strcmp(key, "DYLD_ABORT_MULTIPLE_INITS") == 0 ) {
+ fprintf(stderr, "dyld: warning DYLD_ABORT_MULTIPLE_INITS not supported\n");
+ }
else if ( strcmp(key, "DYLD_NEW_LOCAL_SHARED_REGIONS") == 0 ) {
- // ignore, no longer relevant but some scripts still set it
+ gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
+ }
+ else if ( strcmp(key, "DYLD_SLIDE_AND_PACK_DYLIBS") == 0 ) {
+ gLinkContext.slideAndPackDylibs = true;
}
else if ( strcmp(key, "DYLD_NO_FIX_PREBINDING") == 0 ) {
- gSharedCacheDontNotify = true;
+ // since the new dyld never runs fix_prebinding, no need to warn if someone does not want it run
+ //fprintf(stderr, "dyld: warning DYLD_NO_FIX_PREBINDING not supported\n");
}
else if ( strcmp(key, "DYLD_PREBIND_DEBUG") == 0 ) {
gLinkContext.verbosePrebinding = true;
}
+ else if ( strcmp(key, "DYLD_HINTS_DEBUG") == 0 ) {
+ fprintf(stderr, "dyld: warning DYLD_HINTS_DEBUG not supported\n");
+ }
+ else if ( strcmp(key, "DYLD_SAMPLE_DEBUG") == 0 ) {
+ fprintf(stderr, "dyld: warning DYLD_SAMPLE_DEBUG not supported\n");
+ }
+ else if ( strcmp(key, "DYLD_EXECUTABLE_PATH_DEBUG") == 0 ) {
+ fprintf(stderr, "dyld: warning DYLD_EXECUTABLE_PATH_DEBUG not supported\n");
+ }
+ else if ( strcmp(key, "DYLD_TWO_LEVEL_DEBUG") == 0 ) {
+ fprintf(stderr, "dyld: warning DYLD_TWO_LEVEL_DEBUG not supported\n");
+ }
+ else if ( strcmp(key, "DYLD_LAZY_INITIALIZERS") == 0 ) {
+ fprintf(stderr, "dyld: warning DYLD_LAZY_INITIALIZERS not supported\n");
+ }
else if ( strcmp(key, "DYLD_PRINT_INITIALIZERS") == 0 ) {
gLinkContext.verboseInit = true;
}
- else if ( strcmp(key, "DYLD_PRINT_DOFS") == 0 ) {
- gLinkContext.verboseDOF = true;
- }
else if ( strcmp(key, "DYLD_PRINT_STATISTICS") == 0 ) {
sEnv.DYLD_PRINT_STATISTICS = true;
}
@@ -925,7 +615,6 @@
gLinkContext.verboseWarnings = true;
}
else if ( strcmp(key, "DYLD_SHARED_REGION") == 0 ) {
- gSharedCacheDontNotify = true;
if ( strcmp(value, "private") == 0 ) {
gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
}
@@ -939,11 +628,10 @@
gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
}
else {
- dyld::warn("unknown option to DYLD_SHARED_REGION. Valid options are: use, private, avoid\n");
+ fprintf(stderr, "dyld: warning unknown option to DYLD_SHARED_REGION. Valid options are: use, private, avoid\n");
}
}
else if ( strcmp(key, "DYLD_IGNORE_PREBINDING") == 0 ) {
- gSharedCacheDontNotify = true;
if ( strcmp(value, "all") == 0 ) {
gLinkContext.prebindUsage = ImageLoader::kUseNoPrebinding;
}
@@ -957,51 +645,13 @@
gLinkContext.prebindUsage = ImageLoader::kUseSplitSegPrebinding;
}
else {
- dyld::warn("unknown option to DYLD_IGNORE_PREBINDING. Valid options are: all, app, nonsplit\n");
+ fprintf(stderr, "dyld: warning unknown option to DYLD_IGNORE_PREBINDING. Valid options are: all, app, nonsplit\n");
}
}
else {
- dyld::warn("unknown environment variable: %s\n", key);
- }
-}
-
-
-//
-// For security, setuid programs ignore DYLD_* environment variables.
-// Additionally, the DYLD_* enviroment variables are removed
-// from the environment, so that any child processes don't see them.
-//
-static void pruneEnvironmentVariables(const char* envp[], const char*** applep)
-{
- // setuit binaries don't trigger a cache rebuild
- gSharedCacheDontNotify = true;
-
- // delete all DYLD_* and LD_LIBRARY_PATH environment variables
- int removedCount = 0;
- const char** d = envp;
- for(const char** s = envp; *s != NULL; s++) {
- if ( (strncmp(*s, "DYLD_", 5) != 0) && (strncmp(*s, "LD_LIBRARY_PATH=", 16) != 0) ) {
- *d++ = *s;
- }
- else {
- ++removedCount;
- }
- }
- *d++ = NULL;
-
- // slide apple parameters
- if ( removedCount > 0 ) {
- *applep = d;
- do {
- *d = d[removedCount];
- } while ( *d++ != NULL );
- }
-
- // disable framework and library fallback paths for setuid binaries rdar://problem/4589305
- sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = NULL;
- sEnv.DYLD_FALLBACK_LIBRARY_PATH = NULL;
-}
-
+ fprintf(stderr, "dyld: warning, unknown environment variable: %s\n", key);
+ }
+}
static void checkEnvironmentVariables(const char* envp[], bool ignoreEnviron)
{
@@ -1025,27 +675,32 @@
}
else if ( strncmp(keyEqualsValue, "LD_LIBRARY_PATH=", 16) == 0 ) {
const char* path = &keyEqualsValue[16];
- sEnv.LD_LIBRARY_PATH = parseColonList(path);
+ if ( !disableIfBadUser((char*)path) )
+ sEnv.LD_LIBRARY_PATH = parseColonList(path);
}
}
// default value for DYLD_FALLBACK_FRAMEWORK_PATH, if not set in environment
if ( sEnv.DYLD_FALLBACK_FRAMEWORK_PATH == NULL ) {
const char** paths = sFrameworkFallbackPaths;
- if ( home == NULL )
- removePathWithPrefix(paths, "$HOME");
- else
- paths_expand_roots(paths, "$HOME", home);
+ if ( home != NULL ) {
+ if ( riskyUser() )
+ removePathWithPrefix(paths, "$HOME");
+ else
+ paths_expand_roots(paths, "$HOME", home);
+ }
sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = paths;
}
// default value for DYLD_FALLBACK_LIBRARY_PATH, if not set in environment
if ( sEnv.DYLD_FALLBACK_LIBRARY_PATH == NULL ) {
const char** paths = sLibraryFallbackPaths;
- if ( home == NULL )
- removePathWithPrefix(paths, "$HOME");
- else
- paths_expand_roots(paths, "$HOME", home);
+ if ( home != NULL ) {
+ if ( riskyUser() )
+ removePathWithPrefix(paths, "$HOME");
+ else
+ paths_expand_roots(paths, "$HOME", home);
+ }
sEnv.DYLD_FALLBACK_LIBRARY_PATH = paths;
}
}
@@ -1053,7 +708,7 @@
static void getHostInfo()
{
-#if 1
+#if 0
struct host_basic_info info;
mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
mach_port_t hostPort = mach_host_self();
@@ -1064,30 +719,17 @@
sHostCPU = info.cpu_type;
sHostCPUsubtype = info.cpu_subtype;
-#else
+#endif
+
size_t valSize = sizeof(sHostCPU);
if (sysctlbyname ("hw.cputype", &sHostCPU, &valSize, NULL, 0) != 0)
throw "sysctlbyname(hw.cputype) failed";
valSize = sizeof(sHostCPUsubtype);
if (sysctlbyname ("hw.cpusubtype", &sHostCPUsubtype, &valSize, NULL, 0) != 0)
throw "sysctlbyname(hw.cpusubtype) failed";
-#endif
-}
-
-static void checkSharedRegionDisable()
-{
- #if __ppc__ || __i386__
- // if main executable has segments that overlap the shared region,
- // then disable using the shared region
- if ( sMainExecutable->overlapsWithAddressRange((void*)0x90000000, (void*)0xAFFFFFFF) ) {
- gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
- if ( gLinkContext.verboseMapping )
- dyld::warn("disabling shared region because main executable overlaps\n");
- }
- #endif
-}
-
-bool validImage(const ImageLoader* possibleImage)
+}
+
+bool validImage(ImageLoader* possibleImage)
{
const unsigned int imageCount = sAllImages.size();
for(unsigned int i=0; i < imageCount; ++i) {
@@ -1100,13 +742,35 @@
uint32_t getImageCount()
{
- return sAllImages.size();
+ if ( sAllImagesMightContainUnlinkedImages ) {
+ uint32_t count = 0;
+ for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
+ if ( (*it)->isLinked() )
+ ++count;
+ }
+ return count;
+ }
+ else {
+ return sAllImages.size();
+ }
}
ImageLoader* getIndexedImage(unsigned int index)
{
- if ( index < sAllImages.size() )
- return sAllImages[index];
+ if ( sAllImagesMightContainUnlinkedImages ) {
+ uint32_t count = 0;
+ for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
+ if ( (*it)->isLinked() ) {
+ if ( index == count )
+ return *it;
+ ++count;
+ }
+ }
+ }
+ else {
+ if ( index < sAllImages.size() )
+ return sAllImages[index];
+ }
return NULL;
}
@@ -1129,7 +793,7 @@
static int cacheMiss = 0;
static int cacheNotMacho = 0;
if ( ((cacheHit+cacheMiss+cacheNotMacho) % 100) == 0 )
- dyld::log("findImageContainingAddress(): cache hit = %d, miss = %d, unknown = %d\n", cacheHit, cacheMiss, cacheNotMacho);
+ fprintf(stderr, "findImageContainingAddress(): cache hit = %d, miss = %d, unknown = %d\n", cacheHit, cacheMiss, cacheNotMacho);
#endif
// first look in image where last address was found rdar://problem/3685517
if ( (sLastImageByAddressCache != NULL) && sLastImageByAddressCache->containsAddress(addr) ) {
@@ -1154,20 +818,6 @@
#if FIND_STATS
++cacheNotMacho;
#endif
- return NULL;
-}
-
-ImageLoader* findImageContainingAddressThreadSafe(const void* addr)
-{
- // do exhastive search
- // todo: consider maintaining a list sorted by address ranges and do a binary search on that
- const unsigned int imageCount = sAllImages.size();
- for(unsigned int i=0; i < imageCount; ++i) {
- ImageLoader* anImage = sAllImages[i];
- if ( anImage->containsAddress(addr) ) {
- return anImage;
- }
- }
return NULL;
}
@@ -1259,8 +909,6 @@
}
-// only for architectures that use cpu-sub-types
-#if CPU_SUBTYPES_SUPPORTED
const cpu_subtype_t CPU_SUBTYPE_END_OF_LIST = -1;
@@ -1295,6 +943,23 @@
};
+//
+// 64-bit PowerPC sub-type lists
+//
+const int kPPC64_RowCount = 1;
+static const cpu_subtype_t kPPC64[kPPC64_RowCount][3] = {
+ // G5 can run any 64-bit code
+ { CPU_SUBTYPE_POWERPC_970, CPU_SUBTYPE_POWERPC_ALL, CPU_SUBTYPE_END_OF_LIST },
+};
+
+
+
+//
+// 32-bit x86 sub-type lists
+//
+// TO-DO
+
+
// scan the tables above to find the cpu-sub-type-list for this machine
static const cpu_subtype_t* findCPUSubtypeList(cpu_type_t cpu, cpu_subtype_t subtype)
@@ -1306,6 +971,15 @@
return kPPC32[i];
}
break;
+ case CPU_TYPE_POWERPC64:
+ for (int i=0; i < kPPC64_RowCount ; ++i) {
+ if ( kPPC64[i][0] == subtype )
+ return kPPC64[i];
+ }
+ break;
+ case CPU_TYPE_I386:
+ // To do
+ break;
}
return NULL;
}
@@ -1320,7 +994,7 @@
for (uint32_t subTypeIndex=0; list[subTypeIndex] != CPU_SUBTYPE_END_OF_LIST; ++subTypeIndex) {
for(uint32_t fatIndex=0; fatIndex < OSSwapBigToHostInt32(fh->nfat_arch); ++fatIndex) {
if ( ((cpu_type_t)OSSwapBigToHostInt32(archs[fatIndex].cputype) == cpu)
- && (list[subTypeIndex] == (cpu_subtype_t)OSSwapBigToHostInt32(archs[fatIndex].cpusubtype)) ) {
+ && (list[subTypeIndex] == archs[fatIndex].cpusubtype) ) {
*offset = OSSwapBigToHostInt32(archs[fatIndex].offset);
*len = OSSwapBigToHostInt32(archs[fatIndex].size);
return true;
@@ -1353,19 +1027,26 @@
if ( (cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == cpu) {
switch (cpu) {
case CPU_TYPE_POWERPC:
+ case CPU_TYPE_POWERPC64:
if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_POWERPC_ALL ) {
*offset = OSSwapBigToHostInt32(archs[i].offset);
*len = OSSwapBigToHostInt32(archs[i].size);
return true;
}
break;
+ case CPU_TYPE_I386:
+ if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_I386_ALL ) {
+ *offset = OSSwapBigToHostInt32(archs[i].offset);
+ *len = OSSwapBigToHostInt32(archs[i].size);
+ return true;
+ }
+ break;
}
}
}
return false;
}
-#endif // CPU_SUBTYPES_SUPPORTED
//
// A fat file may contain multiple sub-images for the same cpu-type,
@@ -1374,7 +1055,6 @@
//
static bool fatFindBest(const fat_header* fh, uint64_t* offset, uint64_t* len)
{
-#if CPU_SUBTYPES_SUPPORTED
// assume all dylibs loaded must have same cpu type as main executable
const cpu_type_t cpu = sMainExecutableMachHeader->cputype;
@@ -1394,32 +1074,20 @@
// running on an uknown cpu, can only load generic code
return fatFindRunsOnAllCPUs(cpu, fh, offset, len);
-#else
- // just find first slice with matching architecture
- const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
- for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
- if ( (cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == sMainExecutableMachHeader->cputype) {
- *offset = OSSwapBigToHostInt32(archs[i].offset);
- *len = OSSwapBigToHostInt32(archs[i].size);
- return true;
- }
- }
- return false;
-#endif
}
//
// This is used to validate if a non-fat (aka thin or raw) mach-o file can be used
-// on the current processor. //
+// on the current processor. It is deemed compatible if any of the following are true:
+// 1) mach_header subtype is in list of compatible subtypes for running processor
+// 2) mach_header subtype is same as running processor subtype
+// 3) mach_header subtype runs on all processor variants
+//
+//
bool isCompatibleMachO(const uint8_t* firstPage)
{
-#if CPU_SUBTYPES_SUPPORTED
- // It is deemed compatible if any of the following are true:
- // 1) mach_header subtype is in list of compatible subtypes for running processor
- // 2) mach_header subtype is same as running processor subtype
- // 3) mach_header subtype runs on all processor variants
const mach_header* mh = (mach_header*)firstPage;
if ( mh->magic == sMainExecutableMachHeader->magic ) {
if ( mh->cputype == sMainExecutableMachHeader->cputype ) {
@@ -1440,135 +1108,64 @@
return true;
}
- // cpu type has no ordered list of subtypes
+ // cpu unknown, so don't know if subtype is compatible
+ // only load _ALL variant
switch (mh->cputype) {
case CPU_TYPE_POWERPC:
- // allow _ALL to be used by any client
+ case CPU_TYPE_POWERPC64:
if ( mh->cpusubtype == CPU_SUBTYPE_POWERPC_ALL )
return true;
break;
- case CPU_TYPE_POWERPC64:
case CPU_TYPE_I386:
- case CPU_TYPE_X86_64:
- // subtypes are not used or these architectures
- return true;
- }
- }
- }
-#else
- // For architectures that don't support cpu-sub-types
- // this just check the cpu type.
- const mach_header* mh = (mach_header*)firstPage;
- if ( mh->magic == sMainExecutableMachHeader->magic ) {
- if ( mh->cputype == sMainExecutableMachHeader->cputype ) {
- return true;
- }
- }
-#endif
+ if ( mh->cpusubtype == CPU_SUBTYPE_I386_ALL )
+ return true;
+ break;
+ }
+ }
+ }
return false;
}
-
-
// The kernel maps in main executable before dyld gets control. We need to
// make an ImageLoader* for the already mapped in main executable.
-static ImageLoader* instantiateFromLoadedImage(const struct mach_header* mh, uintptr_t slide, const char* path)
+static ImageLoader* instantiateFromLoadedImage(const struct mach_header* mh, const char* path)
{
// try mach-o loader
if ( isCompatibleMachO((const uint8_t*)mh) ) {
- ImageLoader* image = new ImageLoaderMachO(mh, slide, path, gLinkContext);
+ ImageLoader* image = new ImageLoaderMachO(path, mh, 0, gLinkContext);
addImage(image);
return image;
}
- throw "main executable not a known format";
-}
-
-#if DYLD_SHARED_CACHE_SUPPORT
-static ImageLoader* findSharedCacheImage(const struct stat& stat_buf, const char* path)
-{
- if ( sSharedCache != NULL ) {
- // walk shared cache to see if there is a cached image that matches the inode/mtime/path desired
- const dyld_cache_image_info* const start = (dyld_cache_image_info*)((uint8_t*)sSharedCache + sSharedCache->imagesOffset);
- const dyld_cache_image_info* const end = &start[sSharedCache->imagesCount];
- for( const dyld_cache_image_info* p = start; p != end; ++p) {
- // check mtime and inode first because it is fast
- if ( ((time_t)p->modTime == stat_buf.st_mtime) && ((ino_t)p->inode == stat_buf.st_ino) ) {
- // mod-time and inode match an image in the shared cache, now check path
- const char* pathInCache = (char*)sSharedCache + p->pathFileOffset;
- bool cacheHit = (strcmp(path, pathInCache) == 0);
- if ( ! cacheHit ) {
- // path does not match install name of dylib in cache, but inode and mtime does match
- // perhaps path is a symlink to the cached dylib
- struct stat pathInCacheStatBuf;
- if ( stat(pathInCache, &pathInCacheStatBuf) != -1 )
- cacheHit = ( (pathInCacheStatBuf.st_dev == stat_buf.st_dev) && (pathInCacheStatBuf.st_ino == stat_buf.st_ino) );
- }
- if ( cacheHit ) {
- // found image in cache, instantiate an ImageLoader with it
- return new ImageLoaderMachO((struct mach_header*)(p->address), pathInCache, stat_buf, gLinkContext);
- }
- }
- }
- }
return NULL;
}
-#endif
-
-static ImageLoader* checkandAddImage(ImageLoader* image, const LoadContext& context)
-{
- // now sanity check that this loaded image does not have the same install path as any existing image
- const char* loadedImageInstallPath = image->getInstallPath();
- if ( image->isDylib() && (loadedImageInstallPath != NULL) && (loadedImageInstallPath[0] == '/') ) {
- for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
- ImageLoader* anImage = *it;
- const char* installPath = anImage->getInstallPath();
- if ( installPath != NULL) {
- if ( strcmp(loadedImageInstallPath, installPath) == 0 ) {
- //dyld::log("duplicate(%s) => %p\n", installPath, anImage);
- delete image;
- return anImage;
- }
- }
- }
- }
-
- // some API's restrict what they can load
- if ( context.mustBeBundle && !image->isBundle() )
- throw "not a bundle";
- if ( context.mustBeDylib && !image->isDylib() )
- throw "not a dylib";
-
- // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
- if ( ! image->isBundle() )
- addImage(image);
-
- return image;
-}
+
+
+
// map in file and instantiate an ImageLoader
static ImageLoader* loadPhase6(int fd, struct stat& stat_buf, const char* path, const LoadContext& context)
{
- //dyld::log("%s(%s)\n", __func__ , path);
+ //fprintf(stderr, "%s(%s)\n", __func__ , path);
uint64_t fileOffset = 0;
uint64_t fileLength = stat_buf.st_size;
+#if __ppc64__
+ if ( *((uint32_t*)((char*)(&stat_buf)+0x60)) == 0xFEFEFEFE )
+ fileLength = *((uint64_t*)((char*)(&stat_buf)+0x30)); // HACK work around for kernel stat bug rdar://problem/3845883
+#endif
// validate it is a file (not directory)
if ( (stat_buf.st_mode & S_IFMT) != S_IFREG )
throw "not a file";
+ // min file is 4K
+ if ( fileLength < 4096 ) {
+ throw "file to short";
+ }
+
uint8_t firstPage[4096];
- bool shortPage = false;
-
- // min mach-o file is 4K
- if ( fileLength < 4096 ) {
- pread(fd, firstPage, fileLength, 0);
- shortPage = true;
- }
- else {
- pread(fd, firstPage, 4096,0);
- }
+ pread(fd, firstPage, 4096,0);
// if fat wrapper, find usable sub-file
const fat_header* fileStartAsFat = (fat_header*)firstPage;
@@ -1583,17 +1180,46 @@
// try mach-o loader
if ( isCompatibleMachO(firstPage) ) {
- if ( shortPage )
- throw "file too short";
+ char realFilePath[PATH_MAX];
+ if ( gLinkContext.slideAndPackDylibs ) {
+ // when prebinding, we always want to track the real path of images
+ if ( realpath(path, realFilePath) != NULL )
+ path = realFilePath;
+ }
// instantiate an image
ImageLoader* image = new ImageLoaderMachO(path, fd, firstPage, fileOffset, fileLength, stat_buf, gLinkContext);
- // validate
- return checkandAddImage(image, context);
- }
-
- // try other file formats here...
+ // now sanity check that this loaded image does not have the same install path as any existing image
+ const char* loadedImageInstallPath = image->getInstallPath();
+ if ( image->isDylib() && (loadedImageInstallPath != NULL) && (loadedImageInstallPath[0] == '/') ) {
+ for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
+ ImageLoader* anImage = *it;
+ const char* installPath = anImage->getInstallPath();
+ if ( installPath != NULL) {
+ if ( strcmp(loadedImageInstallPath, installPath) == 0 ) {
+ //fprintf(stderr, "duplicate(%s) => %p\n", installPath, anImage);
+ delete image;
+ return anImage;
+ }
+ }
+ }
+ }
+
+ // some API's restrict what they can load
+ if ( context.mustBeBundle && !image->isBundle() )
+ throw "not a bundle";
+ if ( context.mustBeDylib && !image->isDylib() )
+ throw "not a dylib";
+
+ // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
+ if ( ! image->isBundle() )
+ addImage(image);
+
+ return image;
+ }
+
+ // try other file formats...
// throw error about what was found
@@ -1613,50 +1239,40 @@
// try to open file
static ImageLoader* loadPhase5open(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
{
- //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
+ //fprintf(stdout, "%s(%s)\n", __func__, path);
ImageLoader* image = NULL;
- // just return NULL if file not found, but record any other errors
+ // open file (automagically closed when this function exits)
+ FileOpener file(path);
+
+ //fprintf(stderr, "open(%s) => %d\n", path, file.getFileDescriptor() );
+
+ if ( file.getFileDescriptor() == -1 )
+ return NULL;
+
struct stat stat_buf;
- if ( stat(path, &stat_buf) == -1 ) {
- int err = errno;
- if ( err != ENOENT ) {
- exceptions->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path, err));
- }
- return NULL;
- }
+#if __ppc64__
+ memset(&stat_buf, 254, sizeof(struct stat)); // hack until rdar://problem/3845883 is fixed
+#endif
+ if ( fstat(file.getFileDescriptor(), &stat_buf) == -1)
+ throw "stat error";
// in case image was renamed or found via symlinks, check for inode match
image = findLoadedImage(stat_buf);
if ( image != NULL )
return image;
- // do nothing if not already loaded and if RTLD_NOLOAD or NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
+ // needed to implement NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
if ( context.dontLoad )
return NULL;
-
-#if DYLD_SHARED_CACHE_SUPPORT
- // see if this image is in shared cache
- image = findSharedCacheImage(stat_buf, path);
- if ( image != NULL ) {
- return checkandAddImage(image, context);
- }
-#endif
-
- // open file (automagically closed when this function exits)
- FileOpener file(path);
-
- // just return NULL if file not found
- if ( file.getFileDescriptor() == -1 )
- return NULL;
-
+
try {
return loadPhase6(file.getFileDescriptor(), stat_buf, path, context);
}
catch (const char* msg) {
- const char* newMsg = dyld::mkstringf("%s: %s", path, msg);
+ char* newMsg = new char[strlen(msg) + strlen(path) + 8];
+ sprintf(newMsg, "%s: %s", path, msg);
exceptions->push_back(newMsg);
- free((void*)msg);
return NULL;
}
}
@@ -1664,7 +1280,7 @@
// look for path match with existing loaded images
static ImageLoader* loadPhase5check(const char* path, const LoadContext& context)
{
- //dyld::log("%s(%s)\n", __func__ , path);
+ //fprintf(stderr, "%s(%s)\n", __func__ , path);
// search path against load-path and install-path of all already loaded images
uint32_t hash = ImageLoader::hash(path);
for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
@@ -1688,7 +1304,7 @@
}
}
- //dyld::log("%s(%s) => NULL\n", __func__, path);
+ //fprintf(stderr, "check(%s) => NULL\n", path);
return NULL;
}
@@ -1696,7 +1312,7 @@
// open or check existing
static ImageLoader* loadPhase5(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
{
- //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
+ //fprintf(stderr, "%s(%s)\n", __func__ , path);
if ( exceptions != NULL )
return loadPhase5open(path, context, exceptions);
else
@@ -1706,7 +1322,7 @@
// try with and without image suffix
static ImageLoader* loadPhase4(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
{
- //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
+ //fprintf(stderr, "%s(%s)\n", __func__ , path);
ImageLoader* image = NULL;
if ( gLinkContext.imageSuffix != NULL ) {
char pathWithSuffix[strlen(path)+strlen( gLinkContext.imageSuffix)+2];
@@ -1718,21 +1334,13 @@
return image;
}
-static ImageLoader* loadPhase2(const char* path, const LoadContext& context,
- const char* const frameworkPaths[], const char* const libraryPaths[],
- std::vector<const char*>* exceptions); // forward reference
-
// expand @ variables
static ImageLoader* loadPhase3(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
{
- //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
+ //fprintf(stderr, "%s(%s)\n", __func__ , path);
ImageLoader* image = NULL;
if ( strncmp(path, "@executable_path/", 17) == 0 ) {
- // executable_path cannot be in used in any binary in a setuid process rdar://problem/4589305
- if ( sMainExecutableIsSetuid ) {
- throwf("unsafe use of @executable_path in %s with setuid binary", context.origin);
- }
// handle @executable_path path prefix
const char* executablePath = sExecPath;
char newPath[strlen(executablePath) + strlen(path)];
@@ -1762,10 +1370,6 @@
}
}
else if ( (strncmp(path, "@loader_path/", 13) == 0) && (context.origin != NULL) ) {
- // @loader_path cannot be used from the main executable of a setuid process rdar://problem/4589305
- if ( sMainExecutableIsSetuid && (strcmp(context.origin, sExecPath) == 0) )
- throwf("unsafe use of @loader_path in %s with setuid binary", context.origin);
-
// handle @loader_path path prefix
char newPath[strlen(context.origin) + strlen(path)];
strcpy(newPath, context.origin);
@@ -1793,38 +1397,6 @@
return image;
}
}
- else if ( context.implicitRPath || (strncmp(path, "@rpath/", 7) == 0) ) {
- const char* trailingPath = (strncmp(path, "@rpath/", 7) == 0) ? &path[7] : path;
- // substitute @rpath with all -rpath paths up the load chain
- for(const ImageLoader::RPathChain* rp=context.rpath; rp != NULL; rp=rp->next) {
- if (rp->paths != NULL ) {
- for(std::vector<const char*>::iterator it=rp->paths->begin(); it != rp->paths->end(); ++it) {
- const char* anRPath = *it;
- char newPath[strlen(anRPath) + strlen(trailingPath)+2];
- strcpy(newPath, anRPath);
- strcat(newPath, "/");
- strcat(newPath, trailingPath);
- image = loadPhase4(newPath, context, exceptions);
- if ( image != NULL )
- return image;
- }
- }
- }
-
- // substitute @rpath with LD_LIBRARY_PATH
- if ( sEnv.LD_LIBRARY_PATH != NULL ) {
- image = loadPhase2(trailingPath, context, NULL, sEnv.LD_LIBRARY_PATH, exceptions);
- if ( image != NULL )
- return image;
- }
-
- // if this is the "open" pass, don't try to open @rpath/... as a relative path
- if ( (exceptions != NULL) && (trailingPath != path) )
- return NULL;
- }
- else if ( sMainExecutableIsSetuid && (path[0] != '/') ) {
- throwf("unsafe use of relative rpath %s in %s with setuid binary", path, context.origin);
- }
return loadPhase4(path, context, exceptions);
}
@@ -1835,7 +1407,7 @@
const char* const frameworkPaths[], const char* const libraryPaths[],
std::vector<const char*>* exceptions)
{
- //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
+ //fprintf(stderr, "%s(%s)\n", __func__ , path);
ImageLoader* image = NULL;
const char* frameworkPartialPath = getFrameworkPartialPath(path);
if ( frameworkPaths != NULL ) {
@@ -1846,7 +1418,7 @@
strcpy(npath, *fp);
strcat(npath, "/");
strcat(npath, frameworkPartialPath);
- //dyld::log("dyld: fallback framework path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, npath);
+ //fprintf(stderr, "dyld: fallback framework path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, npath);
image = loadPhase4(npath, context, exceptions);
if ( image != NULL )
return image;
@@ -1861,7 +1433,7 @@
strcpy(libpath, *lp);
strcat(libpath, "/");
strcat(libpath, libraryLeafName);
- //dyld::log("dyld: fallback library path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, libpath);
+ //fprintf(stderr, "dyld: fallback library path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, libpath);
image = loadPhase4(libpath, context, exceptions);
if ( image != NULL )
return image;
@@ -1873,7 +1445,7 @@
// try search overrides and fallbacks
static ImageLoader* loadPhase1(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
{
- //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
+ //fprintf(stderr, "%s(%s)\n", __func__ , path);
ImageLoader* image = NULL;
// handle LD_LIBRARY_PATH environment variables that force searching
@@ -1896,7 +1468,7 @@
return image;
// try fallback paths during second time (will open file)
- if ( !context.dontLoad && (exceptions != NULL) && ((sEnv.DYLD_FALLBACK_FRAMEWORK_PATH != NULL) || (sEnv.DYLD_FALLBACK_LIBRARY_PATH != NULL)) ) {
+ if ( (exceptions != NULL) && ((sEnv.DYLD_FALLBACK_FRAMEWORK_PATH != NULL) || (sEnv.DYLD_FALLBACK_LIBRARY_PATH != NULL)) ) {
image = loadPhase2(path, context, sEnv.DYLD_FALLBACK_FRAMEWORK_PATH, sEnv.DYLD_FALLBACK_LIBRARY_PATH, exceptions);
if ( image != NULL )
return image;
@@ -1908,8 +1480,8 @@
// try root substitutions
static ImageLoader* loadPhase0(const char* path, const LoadContext& context, std::vector<const char*>* exceptions)
{
- //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
-
+ //fprintf(stderr, "%s(%s)\n", __func__ , path);
+
// handle DYLD_ROOT_PATH which forces absolute paths to use a new root
if ( (sEnv.DYLD_ROOT_PATH != NULL) && (path[0] == '/') ) {
for(const char* const* rootPath = sEnv.DYLD_ROOT_PATH ; *rootPath != NULL; ++rootPath) {
@@ -1942,7 +1514,7 @@
//
ImageLoader* load(const char* path, const LoadContext& context)
{
- //dyld::log("%s(%s)\n", __func__ , path);
+ //fprintf(stderr, "%s(%s)\n", __func__ , path);
char realPath[PATH_MAX];
// when DYLD_IMAGE_SUFFIX is in used, do a realpath(), otherwise a load of "Foo.framework/Foo" will not match
if ( context.useSearchPaths && ( gLinkContext.imageSuffix != NULL) ) {
@@ -1954,12 +1526,14 @@
ImageLoader* image = loadPhase0(path, context, NULL);
if ( image != NULL )
return image;
-
+
// try all path permutations and try open() until first sucesss
std::vector<const char*> exceptions;
image = loadPhase0(path, context, &exceptions);
if ( image != NULL )
return image;
+ else if ( context.dontLoad )
+ return NULL;
else if ( exceptions.size() == 0 )
throw "image not found";
else {
@@ -1973,225 +1547,11 @@
for (unsigned int i=0; i < exceptions.size(); ++i) {
strcat(fullMsg, delim);
strcat(fullMsg, exceptions[i]);
- free((void*)exceptions[i]);
}
throw (const char*)fullMsg;
}
}
-
-
-
-#if DYLD_SHARED_CACHE_SUPPORT
-
-
-// hack until dyld no longer needs to run on Leopard kernels that don't have new shared region syscall
-static bool newSharedRegionSyscallAvailable()
-{
- int shreg_version;
- size_t buffer_size = sizeof(shreg_version);
- if ( sysctlbyname("vm.shared_region_version", &shreg_version, &buffer_size, NULL, 0) == 0 ) {
- if ( shreg_version == 3 )
- return true;
- }
- return false;
-}
-
-
-static int __attribute__((noinline)) _shared_region_check_np(uint64_t* start_address)
-{
- if ( (gLinkContext.sharedRegionMode == ImageLoader::kUseSharedRegion) && newSharedRegionSyscallAvailable() )
- return syscall(294, start_address);
- return -1;
-}
-
-
-static int __attribute__((noinline)) _shared_region_map_np(int fd, uint32_t count, const shared_file_mapping_np mappings[])
-{
- int result;
- if ( (gLinkContext.sharedRegionMode == ImageLoader::kUseSharedRegion) && newSharedRegionSyscallAvailable() ) {
- return syscall(295, fd, count, mappings);
- }
-
- // remove the shared region sub-map
-#if __ppc__ || __i386__
- vm_address_t addr = (vm_address_t)0x90000000;
- vm_deallocate(mach_task_self(), addr, 0x20000000);
-#elif __ppc64__ || __x86_64__
- vm_address_t addr = (vm_address_t)0x7FFF60000000;
- vm_deallocate(mach_task_self(), addr, 0x80000000);
-#endif
-
- // map cache just for this process with mmap()
- bool failed = false;
- const shared_file_mapping_np* start = mappings;
- const shared_file_mapping_np* end = &mappings[count];
- for (const shared_file_mapping_np* p = start; p < end; ++p ) {
- void* mmapAddress = (void*)(uintptr_t)(p->sfm_address);
- size_t size = p->sfm_size;
- int protection = 0;
- if ( p->sfm_init_prot & VM_PROT_EXECUTE )
- protection |= PROT_EXEC;
- if ( p->sfm_init_prot & VM_PROT_READ )
- protection |= PROT_READ;
- if ( p->sfm_init_prot & VM_PROT_WRITE )
- protection |= PROT_WRITE;
- off_t offset = p->sfm_file_offset;
- mmapAddress = mmap(mmapAddress, size, protection, MAP_FIXED | MAP_PRIVATE, fd, offset);
- if ( mmap(mmapAddress, size, protection, MAP_FIXED | MAP_PRIVATE, fd, offset) != mmapAddress )
- failed = true;
- }
- if ( !failed ) {
- result = 0;
- gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
- }
- else {
- result = -1;
- gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
- if ( gLinkContext.verboseMapping )
- dyld::log("dyld: shared cached cannot be mapped\n");
- }
-
- return result;
-}
-
-
-
-#if __ppc__
- #define ARCH_NAME "ppc"
- #define ARCH_NAME_ROSETTA "rosetta"
- #define ARCH_VALUE CPU_TYPE_POWERPC
- #define ARCH_CACHE_MAGIC "dyld_v1 ppc"
-#elif __ppc64__
- #define ARCH_NAME "ppc64"
- #define ARCH_VALUE CPU_TYPE_POWERPC64
- #define ARCH_CACHE_MAGIC "dyld_v1 ppc64"
-#elif __i386__
- #define ARCH_NAME "i386"
- #define ARCH_VALUE CPU_TYPE_I386
- #define ARCH_CACHE_MAGIC "dyld_v1 i386"
-#elif __x86_64__
- #define ARCH_NAME "x86_64"
- #define ARCH_VALUE CPU_TYPE_X86_64
- #define ARCH_CACHE_MAGIC "dyld_v1 x86_64"
-#endif
-
-
-static void mapSharedCache()
-{
- uint64_t cacheBaseAddress;
- // quick check if a cache is alreay mapped into shared region
- if ( _shared_region_check_np(&cacheBaseAddress) == 0 ) {
- sSharedCache = (dyld_cache_header*)cacheBaseAddress;
- // if we don't understand the currently mapped shared cache, then ignore
- if ( strcmp(sSharedCache->magic, ARCH_CACHE_MAGIC) != 0 ) {
- sSharedCache = NULL;
- if ( gLinkContext.verboseMapping )
- dyld::log("dyld: existing shared cached in memory is not compatible\n");
- }
- }
- else {
- // map in shared cache to shared region
- int fd;
-#if __ppc__
- // rosetta cannot handle optimized _ppc cache, so it use _rosetta cache instead, rdar://problem/5495438
- if ( isRosetta() )
- fd = open(DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME_ROSETTA, O_RDONLY);
- else
-#endif
- fd = open(DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME, O_RDONLY);
- if ( fd != -1 ) {
- uint8_t firstPage[4096];
- if ( ::read(fd, firstPage, 4096) == 4096 ) {
- dyld_cache_header* header = (dyld_cache_header*)firstPage;
- if ( strcmp(header->magic, ARCH_CACHE_MAGIC) == 0 ) {
- const shared_file_mapping_np* mappings = (shared_file_mapping_np*)&firstPage[header->mappingOffset];
- const shared_file_mapping_np* const end = &mappings[header->mappingCount];
- // validate that the cache file has not been truncated
- bool goodCache = false;
- struct stat stat_buf;
- if ( fstat(fd, &stat_buf) == 0 ) {
- goodCache = true;
- for (const shared_file_mapping_np* p = mappings; p < end; ++p) {
- if ( p->sfm_file_offset+p->sfm_size > (uint64_t)stat_buf.st_size )
- goodCache = false;
- }
- }
- if ( goodCache ) {
- const shared_file_mapping_np* mappings = (shared_file_mapping_np*)&firstPage[header->mappingOffset];
- if (_shared_region_map_np(fd, header->mappingCount, mappings) == 0) {
- // sucessfully mapped cache into shared region
- sSharedCache = (dyld_cache_header*)mappings[0].sfm_address;
- }
- }
- else {
- gSharedCacheNeedsUpdating = true;
- dyld::log("dyld: shared cached file is corrupt: " DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME ARCH_NAME "\n");
- }
- }
- else {
- gSharedCacheNeedsUpdating = true;
- if ( gLinkContext.verboseMapping )
- dyld::log("dyld: shared cached file is invalid\n");
- }
- }
- else {
- gSharedCacheNeedsUpdating = true;
- if ( gLinkContext.verboseMapping )
- dyld::log("dyld: shared cached file cannot be read\n");
- }
- close(fd);
- }
- else {
- gSharedCacheNotFound = true;
- if ( gLinkContext.verboseMapping )
- dyld::log("dyld: shared cached file cannot be opened\n");
- }
- }
-
- // remember if dyld loaded at same address as when cache built
- if ( sSharedCache != NULL ) {
- gLinkContext.dyldLoadedAtSameAddressNeededBySharedCache = ((uintptr_t)(sSharedCache->dyldBaseAddress) == (uintptr_t)&_mh_dylinker_header);
- }
-
- // tell gdb where the shared cache is
- if ( sSharedCache != NULL ) {
- const shared_file_mapping_np* const start = (shared_file_mapping_np*)((uint8_t*)sSharedCache + sSharedCache->mappingOffset);
- dyld_shared_cache_ranges.sharedRegionsCount = sSharedCache->mappingCount;
- // only room to tell gdb about first four regions
- if ( dyld_shared_cache_ranges.sharedRegionsCount > 4 )
- dyld_shared_cache_ranges.sharedRegionsCount = 4;
- if ( gLinkContext.verboseMapping ) {
- if ( gLinkContext.sharedRegionMode == ImageLoader::kUseSharedRegion )
- dyld::log("dyld: Mapping shared cache\n");
- else if ( gLinkContext.sharedRegionMode == ImageLoader::kUsePrivateSharedRegion )
- dyld::log("dyld: Mapping private shared cache\n");
- }
- const shared_file_mapping_np* const end = &start[dyld_shared_cache_ranges.sharedRegionsCount];
- int index = 0;
- for (const shared_file_mapping_np* p = start; p < end; ++p, ++index ) {
- dyld_shared_cache_ranges.ranges[index].start = p->sfm_address;
- dyld_shared_cache_ranges.ranges[index].length = p->sfm_size;
- if ( gLinkContext.verboseMapping ) {
- dyld::log(" 0x%08llX->0x%08llX %s%s%s init=%x, max=%x\n", p->sfm_address, p->sfm_address+p->sfm_size-1,
- ((p->sfm_init_prot & VM_PROT_READ) ? "read " : ""),
- ((p->sfm_init_prot & VM_PROT_WRITE) ? "write " : ""),
- ((p->sfm_init_prot & VM_PROT_EXECUTE) ? "execute " : ""), p->sfm_init_prot, p->sfm_max_prot);
- }
- #if __i386__
- // record if a non-writable and executable region is found in the R/W shared region
- // this is the __IMPORT segments. dyld will turn write protection on and off as needed
- if ( (p->sfm_init_prot == (VM_PROT_READ|VM_PROT_EXECUTE)) && ((p->sfm_address & 0xF0000000) == 0xA0000000) ) {
- sImportSegmentsStart = p->sfm_address;
- sImportSegmentsSize = p->sfm_size;
- makeSharedCacheImportSegmentsWritable(true);
- }
- #endif
- }
-
- }
-}
-#endif // #if DYLD_SHARED_CACHE_SUPPORT
@@ -2204,6 +1564,9 @@
FileOpener file(image->getPath());
struct stat stat_buf;
+#if __ppc64__
+ memset(&stat_buf, 254, sizeof(struct stat)); // hack until rdar://problem/3845883 is fixed
+#endif
if ( fstat(file.getFileDescriptor(), &stat_buf) == -1)
throw "stat error";
@@ -2244,7 +1607,7 @@
}
}
- // try each loader
+ // try mach-o each loader
if ( isCompatibleMachO(mem) ) {
ImageLoader* image = new ImageLoaderMachO(moduleName, (mach_header*)mem, len, gLinkContext);
// don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
@@ -2253,7 +1616,7 @@
return image;
}
- // try other file formats here...
+ // try other file formats...
// throw error about what was found
switch (*(uint32_t*)mem) {
@@ -2274,12 +1637,17 @@
// now add to list to get notified when any more images are added
sAddImageCallbacks.push_back(func);
- // call callback with all existing images
- for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
- ImageLoader* image = *it;
- if ( image->getState() >= dyld_image_state_bound && image->getState() < dyld_image_state_terminated )
- (*func)(image->machHeader(), image->getSlide());
- }
+ // call callback with all existing images, starting at roots
+ const int rootCount = sImageRoots.size();
+ for(int i=0; i < rootCount; ++i) {
+ ImageLoader* image = sImageRoots[i];
+ image->runNotification(gLinkContext, sAddImageCallbacks.size());
+ }
+
+// for (std::vector<ImageLoader*>::iterator it=sImageRoots.begin(); it != sImageRoots.end(); it++) {
+// ImageLoader* image = *it;
+// image->runNotification(gLinkContext, sAddImageCallbacks.size());
+// }
}
void registerRemoveCallback(ImageCallback func)
@@ -2304,14 +1672,21 @@
return error_string;
}
-
void halt(const char* message)
{
- dyld::log("dyld: %s\n", message);
+ fprintf(stderr, "dyld: %s\n", message);
setErrorMessage(message);
strncpy(error_string, message, sizeof(error_string)-1);
error_string[sizeof(error_string)-1] = '\0';
- dyld_fatal_error(error_string);
+
+#if __ppc__ || __ppc64__
+ __asm__ ("trap");
+#elif __i386__
+ __asm__ ("int3");
+#else
+ #error unknown architecture
+#endif
+ abort(); // needed to suppress warning that noreturn function returns
}
@@ -2320,34 +1695,25 @@
uintptr_t result = 0;
// acquire read-lock on dyld's data structures
#if 0 // rdar://problem/3811777 turn off locking until deadlock is resolved
- if ( gLibSystemHelpers != NULL )
- (*gLibSystemHelpers->lockForReading)();
+ if ( gThreadHelpers != NULL )
+ (*gThreadHelpers->lockForReading)();
#endif
// lookup and bind lazy pointer and get target address
try {
- ImageLoader* target;
- #if __i386__
- // fast stubs pass NULL for mh and image is instead found via the location of stub (aka lazyPointer)
- if ( mh == NULL )
- target = dyld::findImageContainingAddressThreadSafe(lazyPointer);
- else
- target = dyld::findImageByMachHeader(mh);
- #else
// note, target should always be mach-o, because only mach-o lazy handler wired up to this
- target = dyld::findImageByMachHeader(mh);
- #endif
+ ImageLoader* target = dyld::findImageByMachHeader(mh);
if ( target == NULL )
- throwf("image not found for lazy pointer at %p", lazyPointer);
+ throw "image not found for lazy pointer";
result = target->doBindLazySymbol(lazyPointer, gLinkContext);
}
catch (const char* message) {
- dyld::log("dyld: lazy symbol binding failed: %s\n", message);
+ fprintf(stderr, "dyld: lazy symbol binding failed: %s\n", message);
halt(message);
}
// release read-lock on dyld's data structures
#if 0
- if ( gLibSystemHelpers != NULL )
- (*gLibSystemHelpers->unlockForReading)();
+ if ( gThreadHelpers != NULL )
+ (*gThreadHelpers->unlockForReading)();
#endif
// return target address to glue which jumps to it with real parameters restored
return result;
@@ -2373,7 +1739,7 @@
}
}
-static bool findExportedSymbol(const char* name, bool onlyInCoalesced, const ImageLoader::Symbol** sym, const ImageLoader** image)
+static bool findExportedSymbol(const char* name, bool onlyInCoalesced, const ImageLoader::Symbol** sym, ImageLoader** image)
{
// try ZeroLink short cut to finding bundle which exports this symbol
if ( sBundleLocation != NULL ) {
@@ -2390,15 +1756,10 @@
return false;
if ( zlImage != NULL ) {
// ZeroLink cache knows where the symbol is
- if ( onlyInCoalesced ) {
- // but ZeroLink does not know about coalescing weak symbols, so ignore ZeroLink's hint when onlyInCoalesced==true
- }
- else {
- *sym = zlImage->findExportedSymbol(name, NULL, false, image);
- if ( *sym != NULL ) {
- *image = zlImage;
- return true;
- }
+ *sym = zlImage->findExportedSymbol(name, NULL, false, image);
+ if ( *sym != NULL ) {
+ *image = zlImage;
+ return true;
}
}
else {
@@ -2407,7 +1768,7 @@
for(unsigned int i=0; i < imageCount; ++i){
ImageLoader* anImage = sAllImages[i];
if ( anImage->isBundle() && !anImage->hasHiddenExports() ) {
- //dyld::log("dyld: search for %s in %s\n", name, anImage->getPath());
+ //fprintf(stderr, "dyld: search for %s in %s\n", name, anImage->getPath());
*sym = anImage->findExportedSymbol(name, NULL, false, image);
if ( *sym != NULL ) {
return true;
@@ -2418,19 +1779,11 @@
}
// search all images in order
- const ImageLoader* firstWeakImage = NULL;
+ ImageLoader* firstWeakImage = NULL;
const ImageLoader::Symbol* firstWeakSym = NULL;
const unsigned int imageCount = sAllImages.size();
- for(unsigned int i=0; i < imageCount; ++i) {
+ for(unsigned int i=0; i < imageCount; ++i){
ImageLoader* anImage = sAllImages[i];
- // the use of inserted libraries alters search order
- // so that inserted libraries are found before the main executable
- if ( sInsertedDylibCount > 0 ) {
- if ( i < sInsertedDylibCount )
- anImage = sAllImages[i+1];
- else if ( i == sInsertedDylibCount )
- anImage = sAllImages[0];
- }
if ( ! anImage->hasHiddenExports() && (!onlyInCoalesced || anImage->hasCoalescedExports()) ) {
*sym = anImage->findExportedSymbol(name, NULL, false, image);
if ( *sym != NULL ) {
@@ -2458,18 +1811,18 @@
return false;
}
-bool flatFindExportedSymbol(const char* name, const ImageLoader::Symbol** sym, const ImageLoader** image)
+bool flatFindExportedSymbol(const char* name, const ImageLoader::Symbol** sym, ImageLoader** image)
{
return findExportedSymbol(name, false, sym, image);
}
-bool findCoalescedExportedSymbol(const char* name, const ImageLoader::Symbol** sym, const ImageLoader** image)
+bool findCoalescedExportedSymbol(const char* name, const ImageLoader::Symbol** sym, ImageLoader** image)
{
return findExportedSymbol(name, true, sym, image);
}
-bool flatFindExportedSymbolWithHint(const char* name, const char* librarySubstring, const ImageLoader::Symbol** sym, const ImageLoader** image)
+bool flatFindExportedSymbolWithHint(const char* name, const char* librarySubstring, const ImageLoader::Symbol** sym, ImageLoader** image)
{
// search all images in order
const unsigned int imageCount = sAllImages.size();
@@ -2486,168 +1839,73 @@
return false;
}
-static ImageLoader::MappedRegion* getMappedRegions(ImageLoader::MappedRegion* regions)
-{
- ImageLoader::MappedRegion* end = regions;
- for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
- (*it)->getMappedRegions(end);
- }
- return end;
-}
-
-void registerImageStateSingleChangeHandler(dyld_image_states state, dyld_image_state_change_handler handler)
-{
- // mark the image that the handler is in as never-unload because dyld has a reference into it
- ImageLoader* handlerImage = findImageContainingAddress((void*)handler);
- if ( handlerImage != NULL )
- handlerImage->setNeverUnload();
-
- // add to list of handlers
- std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sSingleHandlers);
- if ( handlers != NULL ) {
- handlers->push_back(handler);
-
- // call callback with all existing images
- for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
- ImageLoader* image = *it;
- dyld_image_info info;
- info.imageLoadAddress = image->machHeader();
- info.imageFilePath = image->getPath();
- info.imageFileModDate = image->lastModified();
- // should only call handler if state == image->state
- if ( image->getState() == state )
- (*handler)(state, 1, &info);
- // ignore returned string, too late to do anything
- }
- }
-}
-
-void registerImageStateBatchChangeHandler(dyld_image_states state, dyld_image_state_change_handler handler)
-{
- // mark the image that the handler is in as never-unload because dyld has a reference into it
- ImageLoader* handlerImage = findImageContainingAddress((void*)handler);
- if ( handlerImage != NULL )
- handlerImage->setNeverUnload();
-
- // add to list of handlers
- std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sBatchHandlers);
- if ( handlers != NULL ) {
- // insert at front, so that gdb handler is always last
- handlers->insert(handlers->begin(), handler);
-
- // call callback with all existing images
- try {
- notifyBatchPartial(state, true, handler);
- }
- catch (const char* msg) {
- // ignore request to abort during registration
- }
- }
-}
-
-static ImageLoader* libraryLocator(const char* libraryName, bool search, bool findDLL, const char* origin, const ImageLoader::RPathChain* rpaths)
+static void getMappedRegions(ImageLoader::RegionsVector& regions)
+{
+ const unsigned int imageCount = sAllImages.size();
+ for(unsigned int i=0; i < imageCount; ++i){
+ ImageLoader* anImage = sAllImages[i];
+ anImage->addMappedRegions(regions);
+ }
+}
+
+
+static ImageLoader* libraryLocator(const char* libraryName, bool search, const char* origin, const char* rpath[])
{
dyld::LoadContext context;
context.useSearchPaths = search;
context.useLdLibraryPath = false;
- context.implicitRPath = false;
- context.matchByInstallName = false;
context.dontLoad = false;
context.mustBeBundle = false;
context.mustBeDylib = true;
- context.findDLL = findDLL;
+ context.matchByInstallName = false;
context.origin = origin;
- context.rpath = rpaths;
+ context.rpath = rpath;
return load(libraryName, context);
}
-static const char* basename(const char* path)
-{
- const char* last = path;
- for (const char* s = path; *s != '\0'; s++) {
- if (*s == '/')
- last = s+1;
- }
- return last;
-}
-
-static void setContext(const struct mach_header* mainExecutableMH, int argc, const char* argv[], const char* envp[], const char* apple[])
+
+static void setContext(int argc, const char* argv[], const char* envp[], const char* apple[])
{
gLinkContext.loadLibrary = &libraryLocator;
+ gLinkContext.imageNotification = &imageNotification;
gLinkContext.terminationRecorder = &terminationRecorder;
gLinkContext.flatExportFinder = &flatFindExportedSymbol;
gLinkContext.coalescedExportFinder = &findCoalescedExportedSymbol;
gLinkContext.undefinedHandler = &undefinedHandler;
-#if IMAGE_NOTIFY_SUPPORT
gLinkContext.addImageNeedingNotification = &addImageNeedingNotification;
gLinkContext.notifyAdding = ¬ifyAdding;
-#endif
gLinkContext.getAllMappedRegions = &getMappedRegions;
gLinkContext.bindingHandler = NULL;
- gLinkContext.notifySingle = ¬ifySingle;
- gLinkContext.notifyBatch = ¬ifyBatch;
- gLinkContext.removeImage = &removeImage;
- gLinkContext.registerDOFs = ®isterDOFs;
- gLinkContext.clearAllDepths = &clearAllDepths;
- gLinkContext.imageCount = &imageCount;
- gLinkContext.notifySharedCacheInvalid= ¬ifySharedCacheInvalid;
-#if __i386__
- gLinkContext.makeSharedCacheImportSegmentsWritable = &makeSharedCacheImportSegmentsWritable;
-#endif
- gLinkContext.setNewProgramVars = &setNewProgramVars;
-#if SUPPORT_OLD_CRT_INITIALIZATION
- gLinkContext.setRunInitialzersOldWay= &setRunInitialzersOldWay;
-#endif
gLinkContext.bindingOptions = ImageLoader::kBindingNone;
+ gLinkContext.mainExecutable = sMainExecutable;
gLinkContext.argc = argc;
gLinkContext.argv = argv;
gLinkContext.envp = envp;
gLinkContext.apple = apple;
- gLinkContext.progname = (argv[0] != NULL) ? basename(argv[0]) : "";
- gLinkContext.programVars.mh = mainExecutableMH;
- gLinkContext.programVars.NXArgcPtr = &gLinkContext.argc;
- gLinkContext.programVars.NXArgvPtr = &gLinkContext.argv;
- gLinkContext.programVars.environPtr = &gLinkContext.envp;
- gLinkContext.programVars.__prognamePtr=&gLinkContext.progname;
- gLinkContext.mainExecutable = NULL;
- gLinkContext.imageSuffix = NULL;
- gLinkContext.prebindUsage = ImageLoader::kUseAllPrebinding;
- gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
-}
-
-#if __ppc__ || __i386__
-bool isRosetta()
-{
+}
+
+static bool checkEmulation()
+{
+#if __i386__
int mib[] = { CTL_KERN, KERN_CLASSIC, getpid() };
int is_classic = 0;
size_t len = sizeof(int);
int ret = sysctl(mib, 3, &is_classic, &len, NULL, 0);
if ((ret != -1) && is_classic) {
- // we're running under Rosetta
+ // When a 32-bit ppc program is run under emulation on an Intel processor,
+ // we want any i386 dylibs (e.g. the emulator) to not load in the shared region
+ // because the shared region is being used by ppc dylibs
+ gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
return true;
}
+#endif
return false;
}
-#endif
-
-#if 0
-static void printAllImages()
-{
- dyld::log("printAllImages()\n");
- for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
- ImageLoader* image = *it;
- dyld_image_states imageState = image->getState();
- dyld::log(" state=%d, refcount=%d, name=%s\n", imageState, image->referenceCount(), image->getShortName());
- image->printReferenceCounts();
- }
-}
-#endif
-
-
-void link(ImageLoader* image, bool forceLazysBound, const ImageLoader::RPathChain& loaderRPaths)
+
+void link(ImageLoader* image, ImageLoader::BindingLaziness bindness, ImageLoader::InitializerRunning runInitializers)
{
// add to list of known images. This did not happen at creation time for bundles
- if ( image->isBundle() && !image->isLinked() )
+ if ( image->isBundle() )
addImage(image);
// we detect root images as those not linked in yet
@@ -2665,11 +1923,11 @@
// process images
try {
- image->link(gLinkContext, forceLazysBound, false, loaderRPaths);
+ image->link(gLinkContext, bindness, runInitializers, sAddImageCallbacks.size());
}
catch (const char* msg) {
- garbageCollectImages();
- throw;
+ sAllImagesMightContainUnlinkedImages = true;
+ throw msg;
}
#if OLD_GDB_DYLD_INTERFACE
@@ -2679,87 +1937,6 @@
}
-void runInitializers(ImageLoader* image)
-{
- // do bottom up initialization
- image->runInitializers(gLinkContext);
-}
-
-void garbageCollectImages()
-{
- // keep scanning list of images until entire list is scanned with no unreferenced images
- bool mightBeUnreferencedImages = true;
- while ( mightBeUnreferencedImages ) {
- mightBeUnreferencedImages = false;
- for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
- ImageLoader* image = *it;
- if ( (image->referenceCount() == 0) && !image->neverUnload() && !image->isBeingRemoved() ) {
- try {
- //dyld::log("garbageCollectImages: deleting %s\n", image->getPath());
- image->setBeingRemoved();
- removeImage(image);
- delete image;
- }
- catch (const char* msg) {
- dyld::warn("problem deleting image: %s\n", msg);
- }
- mightBeUnreferencedImages = true;
- break;
- }
- }
- }
- //printAllImages();
-}
-
-
-static void preflight_finally(ImageLoader* image)
-{
- if ( image->isBundle() ) {
- removeImageFromAllImages(image->machHeader());
- delete image;
- }
- sBundleBeingLoaded = NULL;
- dyld::garbageCollectImages();
-}
-
-
-void preflight(ImageLoader* image, const ImageLoader::RPathChain& loaderRPaths)
-{
- try {
- if ( image->isBundle() )
- sBundleBeingLoaded = image; // hack
- image->link(gLinkContext, false, true, loaderRPaths);
- }
- catch (const char* msg) {
- preflight_finally(image);
- throw;
- }
- preflight_finally(image);
-}
-
-static void loadInsertedDylib(const char* path)
-{
- ImageLoader* image = NULL;
- try {
- LoadContext context;
- context.useSearchPaths = false;
- context.useLdLibraryPath = false;
- context.implicitRPath = false;
- context.matchByInstallName = false;
- context.dontLoad = false;
- context.mustBeBundle = false;
- context.mustBeDylib = true;
- context.findDLL = false;
- context.origin = NULL; // can't use @loader_path with DYLD_INSERT_LIBRARIES
- context.rpath = NULL;
- image = load(path, context);
- image->setNeverUnload();
- }
- catch (...) {
- halt(dyld::mkstringf("could not load inserted library: %s\n", path));
- }
-}
-
//
// Entry point for dyld. The kernel loads dyld and jumps to __dyld_start which
// sets up some registers and call this function.
@@ -2767,23 +1944,10 @@
// Returns address of main() in target program which __dyld_start jumps to
//
uintptr_t
-_main(const struct mach_header* mainExecutableMH, uintptr_t mainExecutableSlide, int argc, const char* argv[], const char* envp[], const char* apple[])
+_main(const struct mach_header* mainExecutableMH, int argc, const char* argv[], const char* envp[], const char* apple[])
{
- setContext(mainExecutableMH, argc, argv, envp, apple);
-
// Pickup the pointer to the exec path.
sExecPath = apple[0];
- bool ignoreEnvironmentVariables = false;
-#if __i386__
- if ( isRosetta() ) {
- // under Rosetta (x86 side)
- // When a 32-bit ppc program is run under emulation on an Intel processor,
- // we want any i386 dylibs (e.g. any used by Rosetta) to not load in the shared region
- // because the shared region is being used by ppc dylibs
- gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
- ignoreEnvironmentVariables = true;
- }
-#endif
if ( sExecPath[0] != '/' ) {
// have relative path, use cwd to make absolute
char cwdbuff[MAXPATHLEN];
@@ -2798,79 +1962,81 @@
}
uintptr_t result = 0;
sMainExecutableMachHeader = mainExecutableMH;
- sMainExecutableIsSetuid = issetugid();
- if ( sMainExecutableIsSetuid )
- pruneEnvironmentVariables(envp, &apple);
- else
- checkEnvironmentVariables(envp, ignoreEnvironmentVariables);
+ bool isEmulated = checkEmulation();
+ checkEnvironmentVariables(envp, isEmulated);
if ( sEnv.DYLD_PRINT_OPTS )
printOptions(argv);
if ( sEnv.DYLD_PRINT_ENV )
printEnvironmentVariables(envp);
getHostInfo();
- // install gdb notifier
- stateToHandlers(dyld_image_state_dependents_mapped, sBatchHandlers)->push_back(notifyGDB);
- // make initial allocations large enough that it is unlikely to need to be re-alloced
- sAllImages.reserve(200);
- sImageRoots.reserve(16);
- sAddImageCallbacks.reserve(4);
- sRemoveImageCallbacks.reserve(4);
- sImageFilesNeedingTermination.reserve(16);
- sImageFilesNeedingDOFUnregistration.reserve(8);
-
+ setContext(argc, argv, envp, apple);
+ ImageLoader::BindingLaziness bindness = sEnv.DYLD_BIND_AT_LAUNCH ? ImageLoader::kLazyAndNonLazy : ImageLoader::kNonLazyOnly;
+
+ // load any inserted libraries before loading the main executable so that they are first in flat namespace
+ int insertLibrariesCount = 0;
+ if ( sEnv.DYLD_INSERT_LIBRARIES != NULL ) {
+ for (const char* const* lib = sEnv.DYLD_INSERT_LIBRARIES; *lib != NULL; ++lib) {
+ insertLibrariesCount++;
+ }
+ }
+ ImageLoader* insertedImages[insertLibrariesCount];
+ if ( insertLibrariesCount > 0 ) {
+ for (int i=0; i < insertLibrariesCount; ++i) {
+ try {
+ LoadContext context;
+ context.useSearchPaths = false;
+ context.useLdLibraryPath = false;
+ context.dontLoad = false;
+ context.mustBeBundle = false;
+ context.mustBeDylib = true;
+ context.matchByInstallName = false;
+ context.origin = NULL; // can't use @loader_path with DYLD_INSERT_LIBRARIES
+ context.rpath = NULL;
+ insertedImages[i] = load(sEnv.DYLD_INSERT_LIBRARIES[i], context);
+ }
+ catch (...) {
+ char buf[strlen(sEnv.DYLD_INSERT_LIBRARIES[i])+50];
+ sprintf(buf, "could not load inserted library: %s\n", sEnv.DYLD_INSERT_LIBRARIES[i]);
+ insertedImages[i] = NULL;
+ halt(buf);
+ }
+ }
+ }
+
+ // load and link main executable
try {
- // instantiate ImageLoader for main executable
- sMainExecutable = instantiateFromLoadedImage(mainExecutableMH, mainExecutableSlide, sExecPath);
- sMainExecutable->setNeverUnload();
+ sMainExecutable = instantiateFromLoadedImage(mainExecutableMH, sExecPath);
gLinkContext.mainExecutable = sMainExecutable;
- // load shared cache
- checkSharedRegionDisable();
- #if DYLD_SHARED_CACHE_SUPPORT
- if ( gLinkContext.sharedRegionMode != ImageLoader::kDontUseSharedRegion )
- mapSharedCache();
- #endif
- // load any inserted libraries
- if ( sEnv.DYLD_INSERT_LIBRARIES != NULL ) {
- for (const char* const* lib = sEnv.DYLD_INSERT_LIBRARIES; *lib != NULL; ++lib)
- loadInsertedDylib(*lib);
- }
- // record count of inserted libraries so that a flat search will look at
- // inserted libraries, then main, then others.
- sInsertedDylibCount = sAllImages.size()-1;
-
- // link main executable
- gLinkContext.linkingMainExecutable = true;
- link(sMainExecutable, sEnv.DYLD_BIND_AT_LAUNCH, ImageLoader::RPathChain(NULL, NULL));
- gLinkContext.linkingMainExecutable = false;
if ( sMainExecutable->forceFlat() ) {
gLinkContext.bindFlat = true;
gLinkContext.prebindUsage = ImageLoader::kUseNoPrebinding;
}
+ link(sMainExecutable, bindness, ImageLoader::kDontRunInitializers);
result = (uintptr_t)sMainExecutable->getMain();
-
- // link any inserted libraries
- // do this after linking main executable so that any dylibs pulled in by inserted
- // dylibs (e.g. libSystem) will not be in front of dylibs the program uses
- if ( sInsertedDylibCount > 0 ) {
- for(unsigned int i=0; i < sInsertedDylibCount; ++i) {
- ImageLoader* image = sAllImages[i+1];
- link(image, sEnv.DYLD_BIND_AT_LAUNCH, ImageLoader::RPathChain(NULL, NULL));
- }
- }
-
- #if SUPPORT_OLD_CRT_INITIALIZATION
- // Old way is to run initializers via a callback from crt1.o
- if ( ! gRunInitializersOldWay )
- #endif
- initializeMainExecutable(); // run all initializers
}
catch(const char* message) {
halt(message);
}
catch(...) {
- dyld::log("dyld: launch failed\n");
- }
-
+ fprintf(stderr, "dyld: launch failed\n");
+ }
+
+ // Link in any inserted libraries.
+ // Do this after link main executable so any extra libraries pulled in by inserted libraries are at end of flat namespace
+ if ( insertLibrariesCount > 0 ) {
+ for (int i=0; i < insertLibrariesCount; ++i) {
+ try {
+ if ( insertedImages[i] != NULL )
+ link(insertedImages[i], bindness, ImageLoader::kDontRunInitializers);
+ }
+ catch (const char* message) {
+ char buf[strlen(sEnv.DYLD_INSERT_LIBRARIES[i])+50+strlen(message)];
+ sprintf(buf, "could not link inserted library: %s\n%s\n", sEnv.DYLD_INSERT_LIBRARIES[i], message);
+ halt(buf);
+ }
+ }
+ }
+
return result;
}