#ifndef __IMAGELOADER__
#define __IMAGELOADER__
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <mach/mach_time.h> // struct mach_timebase_info
#include <mach/mach_init.h> // struct mach_thread_self
#include <mach/shared_region.h>
#include <mach-o/loader.h>
#include <mach-o/nlist.h>
#include <stdint.h>
#include <stdlib.h>
#include <TargetConditionals.h>
#include <vector>
#include <new>
#if __arm__
#include <mach/vm_page_size.h>
#endif
#if __x86_64__ || __i386__
#include <CrashReporterClient.h>
#else
#define CRSetCrashLogMessage(x)
#define CRSetCrashLogMessage2(x)
#endif
#ifndef SHARED_REGION_BASE_ARM64
#define SHARED_REGION_BASE_ARM64 0x7FFF80000000LL
#endif
#ifndef SHARED_REGION_SIZE_ARM64
#define SHARED_REGION_SIZE_ARM64 0x10000000LL
#endif
#define LOG_BINDINGS 0
#include "mach-o/dyld_images.h"
#include "mach-o/dyld_priv.h"
#if __i386__
#define SHARED_REGION_BASE SHARED_REGION_BASE_I386
#define SHARED_REGION_SIZE SHARED_REGION_SIZE_I386
#elif __x86_64__
#define SHARED_REGION_BASE SHARED_REGION_BASE_X86_64
#define SHARED_REGION_SIZE SHARED_REGION_SIZE_X86_64
#elif __arm__
#define SHARED_REGION_BASE SHARED_REGION_BASE_ARM
#define SHARED_REGION_SIZE SHARED_REGION_SIZE_ARM
#elif __arm64__
#define SHARED_REGION_BASE SHARED_REGION_BASE_ARM64
#define SHARED_REGION_SIZE SHARED_REGION_SIZE_ARM64
#endif
#ifndef EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
#define EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER 0x10
#endif
#ifndef EXPORT_SYMBOL_FLAGS_REEXPORT
#define EXPORT_SYMBOL_FLAGS_REEXPORT 0x08
#endif
#ifndef LC_MAIN
#define LC_MAIN (0x28|LC_REQ_DYLD)
struct entry_point_command {
uint32_t cmd;
uint32_t cmdsize;
uint64_t entryoff;
uint64_t stacksize;
};
#endif
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#define SPLIT_SEG_SHARED_REGION_SUPPORT 0
#define SPLIT_SEG_DYLIB_SUPPORT 0
#define PREBOUND_IMAGE_SUPPORT __arm__
#define TEXT_RELOC_SUPPORT __i386__
#define DYLD_SHARED_CACHE_SUPPORT (__arm__ || __arm64__)
#define SUPPORT_OLD_CRT_INITIALIZATION 0
#define SUPPORT_LC_DYLD_ENVIRONMENT 1
#define SUPPORT_VERSIONED_PATHS 1
#define SUPPORT_CLASSIC_MACHO __arm__
#define SUPPORT_ZERO_COST_EXCEPTIONS (!__USING_SJLJ_EXCEPTIONS__)
#define INITIAL_IMAGE_COUNT 256
#else
#define SPLIT_SEG_SHARED_REGION_SUPPORT 0
#define SPLIT_SEG_DYLIB_SUPPORT __i386__
#define PREBOUND_IMAGE_SUPPORT __i386__
#define TEXT_RELOC_SUPPORT __i386__
#define DYLD_SHARED_CACHE_SUPPORT 1
#define SUPPORT_OLD_CRT_INITIALIZATION __i386__
#define SUPPORT_LC_DYLD_ENVIRONMENT (__i386__ || __x86_64__)
#define SUPPORT_VERSIONED_PATHS 1
#define SUPPORT_CLASSIC_MACHO 1
#define SUPPORT_ZERO_COST_EXCEPTIONS 1
#define INITIAL_IMAGE_COUNT 200
#endif
#define VECTOR_NEVER_DESTRUCTED(type) \
namespace std { \
template <> \
__vector_base<type, std::allocator<type> >::~__vector_base() { } \
}
#define VECTOR_NEVER_DESTRUCTED_EXTERN(type) \
namespace std { \
template <> \
__vector_base<type, std::allocator<type> >::~__vector_base(); \
}
#define VECTOR_NEVER_DESTRUCTED_IMPL(type) \
namespace std { \
template <> \
__vector_base<type, std::allocator<type> >::~__vector_base() { } \
}
namespace dyld {
extern __attribute__((noreturn)) void throwf(const char* format, ...) __attribute__((format(printf, 1, 2)));
extern void log(const char* format, ...) __attribute__((format(printf, 1, 2)));
extern void warn(const char* format, ...) __attribute__((format(printf, 1, 2)));
extern const char* mkstringf(const char* format, ...) __attribute__((format(printf, 1, 2)));
#if LOG_BINDINGS
extern void logBindings(const char* format, ...) __attribute__((format(printf, 1, 2)));
#endif
}
extern "C" int vm_alloc(vm_address_t* addr, vm_size_t size, uint32_t flags);
extern "C" void* xmmap(void* addr, size_t len, int prot, int flags, int fd, off_t offset);
#if __LP64__
struct macho_header : public mach_header_64 {};
struct macho_nlist : public nlist_64 {};
#else
struct macho_header : public mach_header {};
struct macho_nlist : public nlist {};
#endif
#if __arm64__
#define dyld_page_trunc(__addr) (__addr & (-16384))
#define dyld_page_round(__addr) ((__addr + 16383) & (-16384))
#define dyld_page_size 16384
#elif __arm__
#define dyld_page_trunc(__addr) trunc_page_kernel(__addr)
#define dyld_page_round(__addr) round_page_kernel(__addr)
#define dyld_page_size vm_kernel_page_size
#else
#define dyld_page_trunc(__addr) (__addr & (-4096))
#define dyld_page_round(__addr) ((__addr + 4095) & (-4096))
#define dyld_page_size 4096
#endif
struct ProgramVars
{
const void* mh;
int* NXArgcPtr;
const char*** NXArgvPtr;
const char*** environPtr;
const char** __prognamePtr;
};
class ImageLoader {
public:
typedef uint32_t DefinitionFlags;
static const DefinitionFlags kNoDefinitionOptions = 0;
static const DefinitionFlags kWeakDefinition = 1;
typedef uint32_t ReferenceFlags;
static const ReferenceFlags kNoReferenceOptions = 0;
static const ReferenceFlags kWeakReference = 1;
static const ReferenceFlags kTentativeDefinition = 2;
enum PrebindMode { kUseAllPrebinding, kUseSplitSegPrebinding, kUseAllButAppPredbinding, kUseNoPrebinding };
enum BindingOptions { kBindingNone, kBindingLazyPointers, kBindingNeverSetLazyPointers };
enum SharedRegionMode { kUseSharedRegion, kUsePrivateSharedRegion, kDontUseSharedRegion, kSharedRegionIsSharedCache };
struct Symbol;
struct MappedRegion {
uintptr_t address;
size_t size;
};
struct RPathChain {
RPathChain(const RPathChain* n, std::vector<const char*>* p) : next(n), paths(p) {};
const RPathChain* next;
std::vector<const char*>* paths;
};
struct DOFInfo {
void* dof;
const mach_header* imageHeader;
const char* imageShortName;
};
struct DynamicReference {
ImageLoader* from;
ImageLoader* to;
};
struct LinkContext {
ImageLoader* (*loadLibrary)(const char* libraryName, bool search, const char* origin, const RPathChain* rpaths);
void (*terminationRecorder)(ImageLoader* image);
bool (*flatExportFinder)(const char* name, const Symbol** sym, const ImageLoader** image);
bool (*coalescedExportFinder)(const char* name, const Symbol** sym, const ImageLoader** image);
unsigned int (*getCoalescedImages)(ImageLoader* images[]);
void (*undefinedHandler)(const char* name);
MappedRegion* (*getAllMappedRegions)(MappedRegion*);
void * (*bindingHandler)(const char *, const char *, void *);
void (*notifySingle)(dyld_image_states, const ImageLoader* image);
void (*notifyBatch)(dyld_image_states state);
void (*removeImage)(ImageLoader* image);
void (*registerDOFs)(const std::vector<DOFInfo>& dofs);
void (*clearAllDepths)();
void (*printAllDepths)();
unsigned int (*imageCount)();
void (*setNewProgramVars)(const ProgramVars&);
bool (*inSharedCache)(const char* path);
void (*setErrorStrings)(unsigned errorCode, const char* errorClientOfDylibPath,
const char* errorTargetDylibPath, const char* errorSymbol);
ImageLoader* (*findImageContainingAddress)(const void* addr);
void (*addDynamicReference)(ImageLoader* from, ImageLoader* to);
#if SUPPORT_OLD_CRT_INITIALIZATION
void (*setRunInitialzersOldWay)();
#endif
BindingOptions bindingOptions;
int argc;
const char** argv;
const char** envp;
const char** apple;
const char* progname;
ProgramVars programVars;
ImageLoader* mainExecutable;
const char* imageSuffix;
const char** rootPaths;
const dyld_interpose_tuple* dynamicInterposeArray;
size_t dynamicInterposeCount;
PrebindMode prebindUsage;
SharedRegionMode sharedRegionMode;
bool dyldLoadedAtSameAddressNeededBySharedCache;
bool codeSigningEnforced;
bool mainExecutableCodeSigned;
bool preFetchDisabled;
bool prebinding;
bool bindFlat;
bool linkingMainExecutable;
bool startedInitializingMainExecutable;
bool processIsRestricted;
bool processRequiresLibraryValidation;
bool verboseOpts;
bool verboseEnv;
bool verboseMapping;
bool verboseRebase;
bool verboseBind;
bool verboseWeakBind;
bool verboseInit;
bool verboseDOF;
bool verbosePrebinding;
bool verboseCoreSymbolication;
bool verboseWarnings;
bool verboseRPaths;
bool verboseInterposing;
bool verboseCodeSignatures;
};
struct CoalIterator
{
ImageLoader* image;
const char* symbolName;
unsigned int loadOrder;
bool weakSymbol;
bool symbolMatches;
bool done;
uintptr_t curIndex;
uintptr_t endIndex;
uintptr_t address;
uintptr_t type;
uintptr_t addend;
};
virtual void initializeCoalIterator(CoalIterator&, unsigned int loadOrder) = 0;
virtual bool incrementCoalIterator(CoalIterator&) = 0;
virtual uintptr_t getAddressCoalIterator(CoalIterator&, const LinkContext& context) = 0;
virtual void updateUsesCoalIterator(CoalIterator&, uintptr_t newAddr, ImageLoader* target, const LinkContext& context) = 0;
struct InitializerTimingList
{
uintptr_t count;
struct {
ImageLoader* image;
uint64_t initTime;
} images[1];
};
struct UninitedUpwards
{
uintptr_t count;
ImageLoader* images[1];
};
virtual ~ImageLoader();
void link(const LinkContext& context, bool forceLazysBound, bool preflight, bool neverUnload, const RPathChain& loaderRPaths);
void runInitializers(const LinkContext& context, InitializerTimingList& timingInfo);
void bindAllLazyPointers(const LinkContext& context, bool recursive);
bool statMatch(const struct stat& stat_buf) const;
const char* getShortName() const;
const char* getPath() const { return fPath; }
uint32_t getPathHash() const { return fPathHash; }
const char* getRealPath() const;
virtual const char* getInstallPath() const = 0;
bool matchInstallPath() const;
void setMatchInstallPath(bool);
void setHideExports(bool hide = true);
bool hasHiddenExports() const;
bool isLinked() const;
void setLeaveMapped();
bool leaveMapped() { return fLeaveMapped; }
virtual bool inSharedCache() const = 0;
virtual bool containsAddress(const void* addr) const;
virtual bool containsSymbol(const void* addr) const = 0;
virtual bool overlapsWithAddressRange(const void* start, const void* end) const;
void getMappedRegions(MappedRegion*& region) const;
time_t lastModified() const;
virtual void* getThreadPC() const = 0;
virtual void* getMain() const = 0;
virtual const struct mach_header* machHeader() const = 0;
virtual uintptr_t getSlide() const = 0;
virtual const void* getEnd() const = 0;
virtual bool hasCoalescedExports() const = 0;
virtual const Symbol* findExportedSymbol(const char* name, bool searchReExports, const ImageLoader** foundIn) const = 0;
virtual uintptr_t getExportedSymbolAddress(const Symbol* sym, const LinkContext& context,
const ImageLoader* requestor=NULL, bool runResolver=false) const = 0;
virtual DefinitionFlags getExportedSymbolInfo(const Symbol* sym) const = 0;
virtual const char* getExportedSymbolName(const Symbol* sym) const = 0;
virtual uint32_t getExportedSymbolCount() const = 0;
virtual const Symbol* getIndexedExportedSymbol(uint32_t index) const = 0;
virtual const Symbol* findExportedSymbolInDependentImages(const char* name, const LinkContext& context, const ImageLoader** foundIn) const;
virtual const Symbol* findExportedSymbolInImageOrDependentImages(const char* name, const LinkContext& context, const ImageLoader** foundIn) const;
virtual uint32_t getImportedSymbolCount() const = 0;
virtual const Symbol* getIndexedImportedSymbol(uint32_t index) const = 0;
virtual ReferenceFlags getImportedSymbolInfo(const Symbol* sym) const = 0;
virtual const char* getImportedSymbolName(const Symbol* sym) const = 0;
virtual const char* findClosestSymbol(const void* addr, const void** closestAddr) const = 0;
virtual bool isBundle() const = 0;
virtual bool isDylib() const = 0;
virtual bool isExecutable() const = 0;
virtual bool isPositionIndependentExecutable() const = 0;
virtual bool forceFlat() const = 0;
virtual uintptr_t doBindLazySymbol(uintptr_t* lazyPointer, const LinkContext& context) = 0;
virtual uintptr_t doBindFastLazySymbol(uint32_t lazyBindingInfoOffset, const LinkContext& context,
void (*lock)(), void (*unlock)()) = 0;
virtual void doTermination(const LinkContext& context) = 0;
virtual bool needsInitialization() = 0;
virtual bool getSectionContent(const char* segmentName, const char* sectionName, void** start, size_t* length) = 0;
virtual void getUnwindInfo(dyld_unwind_sections* info) = 0;
virtual bool findSection(const void* imageInterior, const char** segmentName, const char** sectionName, size_t* sectionOffset) = 0;
virtual bool isPrebindable() const = 0;
virtual bool usablePrebinding(const LinkContext& context) const = 0;
virtual void getRPaths(const LinkContext& context, std::vector<const char*>&) const = 0;
virtual bool participatesInCoalescing() const = 0;
virtual bool getUUID(uuid_t) const = 0;
virtual void dynamicInterpose(const LinkContext& context) = 0;
void addDynamicInterposingTuples(const struct dyld_interpose_tuple array[], size_t count);
virtual unsigned int segmentCount() const = 0;
virtual const char* segName(unsigned int) const = 0;
virtual uintptr_t segSize(unsigned int) const = 0;
virtual uintptr_t segFileSize(unsigned int) const = 0;
virtual bool segHasTrailingZeroFill(unsigned int) = 0;
virtual uintptr_t segFileOffset(unsigned int) const = 0;
virtual bool segReadable(unsigned int) const = 0;
virtual bool segWriteable(unsigned int) const = 0;
virtual bool segExecutable(unsigned int) const = 0;
virtual bool segUnaccessible(unsigned int) const = 0;
virtual bool segHasPreferredLoadAddress(unsigned int) const = 0;
virtual uintptr_t segPreferredLoadAddress(unsigned int) const = 0;
virtual uintptr_t segActualLoadAddress(unsigned int) const = 0;
virtual uintptr_t segActualEndAddress(unsigned int) const = 0;
virtual uint32_t sdkVersion() const = 0;
virtual uint32_t minOSVersion() const = 0;
virtual void registerInterposing() = 0;
void reExport(ImageLoader* subImage);
void weakBind(const LinkContext& context);
void applyInterposing(const LinkContext& context);
dyld_image_states getState() { return (dyld_image_states)fState; }
int compare(const ImageLoader* right) const;
void incrementDlopenReferenceCount() { ++fDlopenReferenceCount; }
bool decrementDlopenReferenceCount();
void printReferenceCounts();
uint32_t dlopenCount() const { return fDlopenReferenceCount; }
void setCanUnload() { fNeverUnload = false; fLeaveMapped = false; }
bool neverUnload() const { return fNeverUnload; }
void setNeverUnload() { fNeverUnload = true; fLeaveMapped = true; }
void setNeverUnloadRecursive();
bool isReferencedDownward() { return fIsReferencedDownward; }
static void printStatistics(unsigned int imageCount, const InitializerTimingList& timingInfo);
static void addSuffix(const char* path, const char* suffix, char* result);
static uint32_t hash(const char*);
static void deleteImage(ImageLoader*);
bool dependsOn(ImageLoader* image);
void setPath(const char* path);
void setPaths(const char* path, const char* realPath);
void setPathUnowned(const char* path);
void clearDepth() { fDepth = 0; }
int getDepth() { return fDepth; }
void setBeingRemoved() { fBeingRemoved = true; }
bool isBeingRemoved() const { return fBeingRemoved; }
void markNotUsed() { fMarkedInUse = false; }
void markedUsedRecursive(const std::vector<DynamicReference>&);
bool isMarkedInUse() const { return fMarkedInUse; }
void setAddFuncNotified() { fAddFuncNotified = true; }
bool addFuncNotified() const { return fAddFuncNotified; }
struct InterposeTuple {
uintptr_t replacement;
ImageLoader* neverImage; ImageLoader* onlyImage; uintptr_t replacee;
};
protected:
ImageLoader(const char* path, unsigned int libCount);
ImageLoader(const ImageLoader&);
void operator=(const ImageLoader&);
void operator delete(void* image) throw() { ::free(image); }
struct LibraryInfo {
uint32_t checksum;
uint32_t minVersion;
uint32_t maxVersion;
};
struct DependentLibrary {
ImageLoader* image;
uint32_t required : 1,
checksumMatches : 1,
isReExported : 1,
isSubFramework : 1;
};
struct DependentLibraryInfo {
const char* name;
LibraryInfo info;
bool required;
bool reExported;
bool upward;
};
typedef void (*Initializer)(int argc, const char* argv[], const char* envp[], const char* apple[], const ProgramVars* vars);
typedef void (*Terminator)(void);
unsigned int libraryCount() const { return fLibraryCount; }
virtual ImageLoader* libImage(unsigned int) const = 0;
virtual bool libReExported(unsigned int) const = 0;
virtual bool libIsUpward(unsigned int) const = 0;
virtual void setLibImage(unsigned int, ImageLoader*, bool, bool) = 0;
void recursiveLoadLibraries(const LinkContext& context, bool preflightOnly, const RPathChain& loaderRPaths);
void recursiveUnLoadMappedLibraries(const LinkContext& context);
unsigned int recursiveUpdateDepth(unsigned int maxDepth);
void recursiveValidate(const LinkContext& context);
void recursiveRebase(const LinkContext& context);
void recursiveBind(const LinkContext& context, bool forceLazysBound, bool neverUnload);
void recursiveApplyInterposing(const LinkContext& context);
void recursiveGetDOFSections(const LinkContext& context, std::vector<DOFInfo>& dofs);
void recursiveInitialization(const LinkContext& context, mach_port_t this_thread,
ImageLoader::InitializerTimingList&, ImageLoader::UninitedUpwards&);
virtual void doGetDependentLibraries(DependentLibraryInfo libs[]) = 0;
virtual LibraryInfo doGetLibraryInfo() = 0;
virtual void doRebase(const LinkContext& context) = 0;
virtual void doBind(const LinkContext& context, bool forceLazysBound) = 0;
virtual void doBindJustLazies(const LinkContext& context) = 0;
virtual void doGetDOFSections(const LinkContext& context, std::vector<DOFInfo>& dofs) = 0;
virtual void doInterpose(const LinkContext& context) = 0;
virtual bool doInitialization(const LinkContext& context) = 0;
virtual bool needsTermination() = 0;
virtual bool segmentsMustSlideTogether() const = 0;
virtual bool segmentsCanSlide() const = 0;
virtual void setSlide(intptr_t slide) = 0;
bool allDependentLibrariesAsWhenPreBound() const;
virtual bool isSubframeworkOf(const LinkContext& context, const ImageLoader* image) const = 0;
virtual bool hasSubLibrary(const LinkContext& context, const ImageLoader* child) const = 0;
void setMapped(const LinkContext& context);
void setFileInfo(dev_t device, ino_t inode, time_t modDate);
static uintptr_t interposedAddress(const LinkContext& context, uintptr_t address, const ImageLoader* notInImage, const ImageLoader* onlyInImage=NULL);
static uintptr_t fgNextPIEDylibAddress;
static uint32_t fgImagesWithUsedPrebinding;
static uint32_t fgImagesUsedFromSharedCache;
static uint32_t fgImagesHasWeakDefinitions;
static uint32_t fgImagesRequiringCoalescing;
static uint32_t fgTotalRebaseFixups;
static uint32_t fgTotalBindFixups;
static uint32_t fgTotalBindSymbolsResolved;
static uint32_t fgTotalBindImageSearches;
static uint32_t fgTotalLazyBindFixups;
static uint32_t fgTotalPossibleLazyBindFixups;
static uint32_t fgTotalSegmentsMapped;
static uint64_t fgTotalBytesMapped;
static uint64_t fgTotalBytesPreFetched;
static uint64_t fgTotalLoadLibrariesTime;
static uint64_t fgTotalRebaseTime;
static uint64_t fgTotalBindTime;
static uint64_t fgTotalWeakBindTime;
static uint64_t fgTotalDOF;
static uint64_t fgTotalInitTime;
static std::vector<InterposeTuple> fgInterposingTuples;
const char* fPath;
const char* fRealPath;
dev_t fDevice;
ino_t fInode;
time_t fLastModified;
uint32_t fPathHash;
uint32_t fDlopenReferenceCount;
private:
struct recursive_lock {
recursive_lock(mach_port_t t) : thread(t), count(0) {}
mach_port_t thread;
int count;
};
void recursiveSpinLock(recursive_lock&);
void recursiveSpinUnLock();
const ImageLoader::Symbol* findExportedSymbolInDependentImagesExcept(const char* name, const ImageLoader** dsiStart,
const ImageLoader**& dsiCur, const ImageLoader** dsiEnd, const ImageLoader** foundIn) const;
void processInitializers(const LinkContext& context, mach_port_t this_thread,
InitializerTimingList& timingInfo, ImageLoader::UninitedUpwards& ups);
recursive_lock* fInitializerRecursiveLock;
uint16_t fDepth;
uint16_t fLoadOrder;
uint32_t fState : 8,
fLibraryCount : 10,
fAllLibraryChecksumsAndLoadAddressesMatch : 1,
fLeaveMapped : 1, fNeverUnload : 1, fHideSymbols : 1, fMatchByInstallName : 1, fInterposed : 1,
fRegisteredDOF : 1,
fAllLazyPointersBound : 1,
fMarkedInUse : 1,
fBeingRemoved : 1,
fAddFuncNotified : 1,
fPathOwnedByImage : 1,
fIsReferencedDownward : 1,
fWeakSymbolsBound : 1;
static uint16_t fgLoadOrdinal;
};
VECTOR_NEVER_DESTRUCTED_EXTERN(ImageLoader::InterposeTuple);
#endif