]> git.saurik.com Git - apple/dyld.git/blob - src/ImageLoader.h
dyld-733.8.tar.gz
[apple/dyld.git] / src / ImageLoader.h
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2004-2010 Apple Inc. All rights reserved.
4 *
5 * @APPLE_LICENSE_HEADER_START@
6 *
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
12 * file.
13 *
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24
25
26 #ifndef __IMAGELOADER__
27 #define __IMAGELOADER__
28
29 #include <sys/types.h>
30 #include <unistd.h>
31 #include <stdlib.h>
32 #include <mach/mach_time.h> // struct mach_timebase_info
33 #include <mach/mach_init.h> // struct mach_thread_self
34 #include <mach/shared_region.h>
35 #include <mach-o/loader.h>
36 #include <mach-o/nlist.h>
37 #include <mach-o/dyld_images.h>
38 #include <mach-o/dyld_priv.h>
39 #include <stdint.h>
40 #include <stdlib.h>
41 #include <TargetConditionals.h>
42 #include <vector>
43 #include <new>
44 #include <uuid/uuid.h>
45
46 #if !TARGET_OS_DRIVERKIT && (BUILDING_LIBDYLD || BUILDING_DYLD)
47 #include <CrashReporterClient.h>
48 #else
49 #define CRSetCrashLogMessage(x)
50 #define CRSetCrashLogMessage2(x)
51 #endif
52
53 #include "DyldSharedCache.h"
54
55 #include "Map.h"
56
57 #if __arm__
58 #include <mach/vm_page_size.h>
59 #endif
60
61
62 #ifndef SHARED_REGION_BASE_ARM64
63 #define SHARED_REGION_BASE_ARM64 0x7FFF80000000LL
64 #endif
65
66 #ifndef SHARED_REGION_SIZE_ARM64
67 #define SHARED_REGION_SIZE_ARM64 0x10000000LL
68 #endif
69
70
71 #define LOG_BINDINGS 0
72
73
74 #if __IPHONE_OS_VERSION_MIN_REQUIRED
75 #define SPLIT_SEG_SHARED_REGION_SUPPORT 0
76 #define SPLIT_SEG_DYLIB_SUPPORT 0
77 #define PREBOUND_IMAGE_SUPPORT __arm__
78 #define TEXT_RELOC_SUPPORT __i386__
79 #define SUPPORT_OLD_CRT_INITIALIZATION 0
80 #define SUPPORT_LC_DYLD_ENVIRONMENT 1
81 #define SUPPORT_VERSIONED_PATHS 0
82 #define SUPPORT_CLASSIC_MACHO __arm__
83 #define SUPPORT_ZERO_COST_EXCEPTIONS (!__USING_SJLJ_EXCEPTIONS__)
84 #define INITIAL_IMAGE_COUNT 150
85 #define SUPPORT_ACCELERATE_TABLES !TARGET_OS_SIMULATOR
86 #define SUPPORT_ROOT_PATH TARGET_OS_SIMULATOR
87 #else
88 #define SPLIT_SEG_SHARED_REGION_SUPPORT 0
89 #define SPLIT_SEG_DYLIB_SUPPORT __i386__
90 #define PREBOUND_IMAGE_SUPPORT __i386__
91 #define TEXT_RELOC_SUPPORT __i386__
92 #define SUPPORT_OLD_CRT_INITIALIZATION __i386__
93 #define SUPPORT_LC_DYLD_ENVIRONMENT (__i386__ || __x86_64__)
94 #define SUPPORT_VERSIONED_PATHS 1
95 #define SUPPORT_CLASSIC_MACHO 1
96 #define SUPPORT_ZERO_COST_EXCEPTIONS 1
97 #define INITIAL_IMAGE_COUNT 200
98 #define SUPPORT_ACCELERATE_TABLES 0
99 #define SUPPORT_ROOT_PATH 1
100 #endif
101
102 #define MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE (32*1024)
103
104
105 // <rdar://problem/13590567> optimize away dyld's initializers
106 #define VECTOR_NEVER_DESTRUCTED(type) \
107 namespace std { \
108 template <> \
109 __vector_base<type, std::allocator<type> >::~__vector_base() { } \
110 }
111 #define VECTOR_NEVER_DESTRUCTED_EXTERN(type) \
112 namespace std { \
113 template <> \
114 __vector_base<type, std::allocator<type> >::~__vector_base(); \
115 }
116 #define VECTOR_NEVER_DESTRUCTED_IMPL(type) \
117 namespace std { \
118 template <> \
119 __vector_base<type, std::allocator<type> >::~__vector_base() { } \
120 }
121
122 // utilities
123 namespace dyld {
124 extern __attribute__((noreturn)) void throwf(const char* format, ...) __attribute__((format(printf, 1, 2)));
125 extern void log(const char* format, ...) __attribute__((format(printf, 1, 2)));
126 extern void warn(const char* format, ...) __attribute__((format(printf, 1, 2)));
127 extern const char* mkstringf(const char* format, ...) __attribute__((format(printf, 1, 2)));
128 #if LOG_BINDINGS
129 extern void logBindings(const char* format, ...) __attribute__((format(printf, 1, 2)));
130 #endif
131 }
132 extern "C" int vm_alloc(vm_address_t* addr, vm_size_t size, uint32_t flags);
133 extern "C" void* xmmap(void* addr, size_t len, int prot, int flags, int fd, off_t offset);
134
135
136 #if __LP64__
137 struct macho_header : public mach_header_64 {};
138 struct macho_nlist : public nlist_64 {};
139 #else
140 struct macho_header : public mach_header {};
141 struct macho_nlist : public nlist {};
142 #endif
143
144
145 #if __arm64__
146 #define dyld_page_trunc(__addr) (__addr & (-16384))
147 #define dyld_page_round(__addr) ((__addr + 16383) & (-16384))
148 #define dyld_page_size 16384
149 #elif __arm__
150 #define dyld_page_trunc(__addr) trunc_page_kernel(__addr)
151 #define dyld_page_round(__addr) round_page_kernel(__addr)
152 #define dyld_page_size vm_kernel_page_size
153 #else
154 #define dyld_page_trunc(__addr) (__addr & (-4096))
155 #define dyld_page_round(__addr) ((__addr + 4095) & (-4096))
156 #define dyld_page_size 4096
157 #endif
158
159
160 #define DYLD_PACKED_VERSION(major, minor, tiny) ((((major) & 0xffff) << 16) | (((minor) & 0xff) << 8) | ((tiny) & 0xff))
161
162 struct ProgramVars
163 {
164 const void* mh;
165 int* NXArgcPtr;
166 const char*** NXArgvPtr;
167 const char*** environPtr;
168 const char** __prognamePtr;
169 };
170
171
172
173 enum dyld_image_states
174 {
175 dyld_image_state_mapped = 10, // No batch notification for this
176 dyld_image_state_dependents_mapped = 20, // Only batch notification for this
177 dyld_image_state_rebased = 30,
178 dyld_image_state_bound = 40,
179 dyld_image_state_dependents_initialized = 45, // Only single notification for this
180 dyld_image_state_initialized = 50,
181 dyld_image_state_terminated = 60 // Only single notification for this
182 };
183 typedef const char* (*dyld_image_state_change_handler)(enum dyld_image_states state, uint32_t infoCount, const struct dyld_image_info info[]);
184
185 //
186 // ImageLoader is an abstract base class. To support loading a particular executable
187 // file format, you make a concrete subclass of ImageLoader.
188 //
189 // For each executable file (dynamic shared object) in use, an ImageLoader is instantiated.
190 //
191 // The ImageLoader base class does the work of linking together images, but it knows nothing
192 // about any particular file format.
193 //
194 //
195 class ImageLoader {
196 public:
197
198 typedef uint32_t DefinitionFlags;
199 static const DefinitionFlags kNoDefinitionOptions = 0;
200 static const DefinitionFlags kWeakDefinition = 1;
201
202 typedef uint32_t ReferenceFlags;
203 static const ReferenceFlags kNoReferenceOptions = 0;
204 static const ReferenceFlags kWeakReference = 1;
205 static const ReferenceFlags kTentativeDefinition = 2;
206
207 enum PrebindMode { kUseAllPrebinding, kUseSplitSegPrebinding, kUseAllButAppPredbinding, kUseNoPrebinding };
208 enum BindingOptions { kBindingNone, kBindingLazyPointers, kBindingNeverSetLazyPointers };
209 enum SharedRegionMode { kUseSharedRegion, kUsePrivateSharedRegion, kDontUseSharedRegion, kSharedRegionIsSharedCache };
210
211 struct Symbol; // abstact symbol
212
213 struct MappedRegion {
214 uintptr_t address;
215 size_t size;
216 };
217
218 struct RPathChain {
219 RPathChain(const RPathChain* n, std::vector<const char*>* p) : next(n), paths(p) {};
220 const RPathChain* next;
221 std::vector<const char*>* paths;
222 };
223
224 struct DOFInfo {
225 void* dof;
226 const mach_header* imageHeader;
227 const char* imageShortName;
228 };
229
230 struct DynamicReference {
231 ImageLoader* from;
232 ImageLoader* to;
233 };
234
235 struct InitializerTimingList
236 {
237 uintptr_t count;
238 struct {
239 const char* shortName;
240 uint64_t initTime;
241 } images[1];
242
243 void addTime(const char* name, uint64_t time);
244 };
245
246 typedef void (^CoalesceNotifier)(const Symbol* implSym, const ImageLoader* implIn, const mach_header* implMh);
247
248 struct HashCString {
249 static size_t hash(const char* v);
250 };
251
252 struct EqualCString {
253 static bool equal(const char* s1, const char* s2);
254 };
255
256 struct LinkContext {
257 ImageLoader* (*loadLibrary)(const char* libraryName, bool search, const char* origin, const RPathChain* rpaths, unsigned& cacheIndex);
258 void (*terminationRecorder)(ImageLoader* image);
259 bool (*flatExportFinder)(const char* name, const Symbol** sym, const ImageLoader** image);
260 bool (*coalescedExportFinder)(const char* name, const Symbol** sym, const ImageLoader** image, CoalesceNotifier);
261 unsigned int (*getCoalescedImages)(ImageLoader* images[], unsigned imageIndex[]);
262 void (*undefinedHandler)(const char* name);
263 MappedRegion* (*getAllMappedRegions)(MappedRegion*);
264 void * (*bindingHandler)(const char *, const char *, void *);
265 void (*notifySingle)(dyld_image_states, const ImageLoader* image, InitializerTimingList*);
266 void (*notifyBatch)(dyld_image_states state, bool preflightOnly);
267 void (*removeImage)(ImageLoader* image);
268 void (*registerDOFs)(const std::vector<DOFInfo>& dofs);
269 void (*clearAllDepths)();
270 void (*printAllDepths)();
271 unsigned int (*imageCount)();
272 void (*setNewProgramVars)(const ProgramVars&);
273 bool (*inSharedCache)(const char* path);
274 void (*setErrorStrings)(unsigned errorCode, const char* errorClientOfDylibPath,
275 const char* errorTargetDylibPath, const char* errorSymbol);
276 ImageLoader* (*findImageContainingAddress)(const void* addr);
277 void (*addDynamicReference)(ImageLoader* from, ImageLoader* to);
278 #if SUPPORT_ACCELERATE_TABLES
279 void (*notifySingleFromCache)(dyld_image_states, const mach_header* mh, const char* path);
280 dyld_image_state_change_handler (*getPreInitNotifyHandler)(unsigned index);
281 dyld_image_state_change_handler (*getBoundBatchHandler)(unsigned index);
282 #endif
283
284 #if SUPPORT_OLD_CRT_INITIALIZATION
285 void (*setRunInitialzersOldWay)();
286 #endif
287 BindingOptions bindingOptions;
288 int argc;
289 const char** argv;
290 const char** envp;
291 const char** apple;
292 const char* progname;
293 ProgramVars programVars;
294 ImageLoader* mainExecutable;
295 const char* const * imageSuffix;
296 #if SUPPORT_ROOT_PATH
297 const char** rootPaths;
298 #endif
299 const DyldSharedCache* dyldCache;
300 const dyld_interpose_tuple* dynamicInterposeArray;
301 size_t dynamicInterposeCount;
302 PrebindMode prebindUsage;
303 SharedRegionMode sharedRegionMode;
304 mutable dyld3::Map<const char*, std::pair<const ImageLoader*, uintptr_t>, HashCString, EqualCString> weakDefMap;
305 mutable bool weakDefMapInitialized = false;
306 mutable bool weakDefMapProcessedLaunchDefs = false;
307 mutable bool useNewWeakBind = false;
308 bool dyldLoadedAtSameAddressNeededBySharedCache;
309 bool strictMachORequired;
310 bool allowAtPaths;
311 bool allowEnvVarsPrint;
312 bool allowEnvVarsPath;
313 bool allowEnvVarsSharedCache;
314 bool allowClassicFallbackPaths;
315 bool allowInsertFailures;
316 bool allowInterposing;
317 bool mainExecutableCodeSigned;
318 bool prebinding;
319 bool bindFlat;
320 bool linkingMainExecutable;
321 bool startedInitializingMainExecutable;
322 #if __MAC_OS_X_VERSION_MIN_REQUIRED
323 bool iOSonMac;
324 bool driverKit;
325 #endif
326 bool verboseOpts;
327 bool verboseEnv;
328 bool verboseLoading;
329 bool verboseMapping;
330 bool verboseRebase;
331 bool verboseBind;
332 bool verboseWeakBind;
333 bool verboseInit;
334 bool verboseDOF;
335 bool verbosePrebinding;
336 bool verboseCoreSymbolication;
337 bool verboseWarnings;
338 bool verboseRPaths;
339 bool verboseInterposing;
340 bool verboseCodeSignatures;
341 };
342
343 struct CoalIterator
344 {
345 ImageLoader* image;
346 const char* symbolName;
347 unsigned int loadOrder;
348 bool weakSymbol;
349 bool symbolMatches;
350 bool done;
351 // the following are private to the ImageLoader subclass
352 uintptr_t curIndex;
353 uintptr_t endIndex;
354 uintptr_t address;
355 uintptr_t type;
356 uintptr_t addend;
357 uintptr_t imageIndex;
358 };
359
360 virtual void initializeCoalIterator(CoalIterator&, unsigned int loadOrder, unsigned imageIndex) = 0;
361 virtual bool incrementCoalIterator(CoalIterator&) = 0;
362 virtual uintptr_t getAddressCoalIterator(CoalIterator&, const LinkContext& context) = 0;
363 virtual void updateUsesCoalIterator(CoalIterator&, uintptr_t newAddr, ImageLoader* target, unsigned targetIndex, const LinkContext& context) = 0;
364
365 struct UninitedUpwards
366 {
367 uintptr_t count;
368 std::pair<ImageLoader*, const char*> imagesAndPaths[1];
369 };
370
371
372 // constructor is protected, but anyone can delete an image
373 virtual ~ImageLoader();
374
375 // link() takes a newly instantiated ImageLoader and does all
376 // fixups needed to make it usable by the process
377 void link(const LinkContext& context, bool forceLazysBound, bool preflight, bool neverUnload, const RPathChain& loaderRPaths, const char* imagePath);
378
379 // runInitializers() is normally called in link() but the main executable must
380 // run crt code before initializers
381 void runInitializers(const LinkContext& context, InitializerTimingList& timingInfo);
382
383 // called after link() forces all lazy pointers to be bound
384 void bindAllLazyPointers(const LinkContext& context, bool recursive);
385
386 // used by dyld to see if a requested library is already loaded (might be symlink)
387 bool statMatch(const struct stat& stat_buf) const;
388
389 // get short name of this image
390 const char* getShortName() const;
391
392 // returns leaf name
393 static const char* shortName(const char* fullName);
394
395 // get path used to load this image, not necessarily the "real" path
396 const char* getPath() const { return fPath; }
397
398 uint32_t getPathHash() const { return fPathHash; }
399
400 // get the "real" path for this image (e.g. no @rpath)
401 const char* getRealPath() const;
402
403 // get path this image is intended to be placed on disk or NULL if no preferred install location
404 virtual const char* getInstallPath() const = 0;
405
406 // image was loaded with NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME and all clients are looking for install path
407 bool matchInstallPath() const;
408 void setMatchInstallPath(bool);
409
410 // mark that this image's exported symbols should be ignored when linking other images (e.g. RTLD_LOCAL)
411 void setHideExports(bool hide = true);
412
413 // check if this image's exported symbols should be ignored when linking other images
414 bool hasHiddenExports() const;
415
416 // checks if this image is already linked into the process
417 bool isLinked() const;
418
419 // even if image is deleted, leave segments mapped in
420 void setLeaveMapped();
421
422 // even if image is deleted, leave segments mapped in
423 bool leaveMapped() { return fLeaveMapped; }
424
425 // image resides in dyld shared cache
426 virtual bool inSharedCache() const { return false; };
427
428 // checks if the specifed address is within one of this image's segments
429 virtual bool containsAddress(const void* addr) const;
430
431 // checks if the specifed symbol is within this image's symbol table
432 virtual bool containsSymbol(const void* addr) const = 0;
433
434 // checks if the specifed address range overlaps any of this image's segments
435 virtual bool overlapsWithAddressRange(const void* start, const void* end) const;
436
437 // adds to list of ranges of memory mapped in
438 void getMappedRegions(MappedRegion*& region) const;
439
440 // st_mtime from stat() on file
441 time_t lastModified() const;
442
443 // only valid for main executables, returns a pointer its entry point from LC_MAIN
444 virtual void* getEntryFromLC_MAIN() const = 0;
445
446 // only valid for main executables, returns a pointer its main from LC_UNIXTHREAD
447 virtual void* getEntryFromLC_UNIXTHREAD() const = 0;
448
449 // dyld API's require each image to have an associated mach_header
450 virtual const struct mach_header* machHeader() const = 0;
451
452 // dyld API's require each image to have a slide (actual load address minus preferred load address)
453 virtual uintptr_t getSlide() const = 0;
454
455 // last address mapped by image
456 virtual const void* getEnd() const = 0;
457
458 // image has exports that participate in runtime coalescing
459 virtual bool hasCoalescedExports() const = 0;
460
461 // search symbol table of definitions in this image for requested name
462 virtual bool findExportedSymbolAddress(const LinkContext& context, const char* symbolName,
463 const ImageLoader* requestorImage, int requestorOrdinalOfDef,
464 bool runResolver, const ImageLoader** foundIn, uintptr_t* address) const;
465
466 // search symbol table of definitions in this image for requested name
467 virtual const Symbol* findExportedSymbol(const char* name, bool searchReExports, const char* thisPath, const ImageLoader** foundIn) const = 0;
468
469 // search symbol table of definitions in this image for requested name
470 virtual const Symbol* findExportedSymbol(const char* name, bool searchReExports, const ImageLoader** foundIn) const {
471 return findExportedSymbol(name, searchReExports, this->getPath(), foundIn);
472 }
473
474 // gets address of implementation (code) of the specified exported symbol
475 virtual uintptr_t getExportedSymbolAddress(const Symbol* sym, const LinkContext& context,
476 const ImageLoader* requestor=NULL, bool runResolver=false, const char* symbolName=NULL) const = 0;
477
478 // gets attributes of the specified exported symbol
479 virtual DefinitionFlags getExportedSymbolInfo(const Symbol* sym) const = 0;
480
481 // gets name of the specified exported symbol
482 virtual const char* getExportedSymbolName(const Symbol* sym) const = 0;
483
484 // gets how many symbols are exported by this image
485 virtual uint32_t getExportedSymbolCount() const = 0;
486
487 // gets the i'th exported symbol
488 virtual const Symbol* getIndexedExportedSymbol(uint32_t index) const = 0;
489
490 // find exported symbol as if imported by this image
491 // used by RTLD_NEXT
492 virtual const Symbol* findExportedSymbolInDependentImages(const char* name, const LinkContext& context, const ImageLoader** foundIn) const;
493
494 // find exported symbol as if imported by this image
495 // used by RTLD_SELF
496 virtual const Symbol* findExportedSymbolInImageOrDependentImages(const char* name, const LinkContext& context, const ImageLoader** foundIn) const;
497
498 // gets how many symbols are imported by this image
499 virtual uint32_t getImportedSymbolCount() const = 0;
500
501 // gets the i'th imported symbol
502 virtual const Symbol* getIndexedImportedSymbol(uint32_t index) const = 0;
503
504 // gets attributes of the specified imported symbol
505 virtual ReferenceFlags getImportedSymbolInfo(const Symbol* sym) const = 0;
506
507 // gets name of the specified imported symbol
508 virtual const char* getImportedSymbolName(const Symbol* sym) const = 0;
509
510 // find the closest symbol before addr
511 virtual const char* findClosestSymbol(const void* addr, const void** closestAddr) const = 0;
512
513 // for use with accelerator tables
514 virtual const char* getIndexedPath(unsigned) const { return getPath(); }
515 virtual const char* getIndexedShortName(unsigned) const { return getShortName(); }
516
517 // checks if this image is a bundle and can be loaded but not linked
518 virtual bool isBundle() const = 0;
519
520 // checks if this image is a dylib
521 virtual bool isDylib() const = 0;
522
523 // checks if this image is a main executable
524 virtual bool isExecutable() const = 0;
525
526 // checks if this image is a main executable
527 virtual bool isPositionIndependentExecutable() const = 0;
528
529 // only for main executable
530 virtual bool forceFlat() const = 0;
531
532 // called at runtime when a lazily bound function is first called
533 virtual uintptr_t doBindLazySymbol(uintptr_t* lazyPointer, const LinkContext& context) = 0;
534
535 // called at runtime when a fast lazily bound function is first called
536 virtual uintptr_t doBindFastLazySymbol(uint32_t lazyBindingInfoOffset, const LinkContext& context,
537 void (*lock)(), void (*unlock)()) = 0;
538
539 // calls termination routines (e.g. C++ static destructors for image)
540 virtual void doTermination(const LinkContext& context) = 0;
541
542 // return if this image has initialization routines
543 virtual bool needsInitialization() = 0;
544
545 // return if this image has specified section and set start and length
546 virtual bool getSectionContent(const char* segmentName, const char* sectionName, void** start, size_t* length) = 0;
547
548 // fills in info about __eh_frame and __unwind_info sections
549 virtual void getUnwindInfo(dyld_unwind_sections* info) = 0;
550
551 // given a pointer into an image, find which segment and section it is in
552 virtual const struct macho_section* findSection(const void* imageInterior) const = 0;
553
554 // given a pointer into an image, find which segment and section it is in
555 virtual bool findSection(const void* imageInterior, const char** segmentName, const char** sectionName, size_t* sectionOffset) = 0;
556
557 // the image supports being prebound
558 virtual bool isPrebindable() const = 0;
559
560 // the image is prebindable and its prebinding is valid
561 virtual bool usablePrebinding(const LinkContext& context) const = 0;
562
563 // add all RPATH paths this image contains
564 virtual void getRPaths(const LinkContext& context, std::vector<const char*>&) const = 0;
565
566 // image has or uses weak definitions that need runtime coalescing
567 virtual bool participatesInCoalescing() const = 0;
568
569 // if image has a UUID, copy into parameter and return true
570 virtual bool getUUID(uuid_t) const = 0;
571
572 // dynamic interpose values onto this image
573 virtual void dynamicInterpose(const LinkContext& context) = 0;
574
575 // record interposing for any late binding
576 void addDynamicInterposingTuples(const struct dyld_interpose_tuple array[], size_t count);
577
578 virtual const char* libPath(unsigned int) const = 0;
579
580 // Image has objc sections, so information objc about when it comes and goes
581 virtual bool notifyObjC() const { return false; }
582
583 virtual bool overridesCachedDylib(uint32_t& num) const { return false; }
584 virtual void setOverridesCachedDylib(uint32_t num) { }
585
586
587 //
588 // A segment is a chunk of an executable file that is mapped into memory.
589 //
590 virtual unsigned int segmentCount() const = 0;
591 virtual const char* segName(unsigned int) const = 0;
592 virtual uintptr_t segSize(unsigned int) const = 0;
593 virtual uintptr_t segFileSize(unsigned int) const = 0;
594 virtual bool segHasTrailingZeroFill(unsigned int) = 0;
595 virtual uintptr_t segFileOffset(unsigned int) const = 0;
596 virtual bool segReadable(unsigned int) const = 0;
597 virtual bool segWriteable(unsigned int) const = 0;
598 virtual bool segExecutable(unsigned int) const = 0;
599 virtual bool segUnaccessible(unsigned int) const = 0;
600 virtual bool segHasPreferredLoadAddress(unsigned int) const = 0;
601 virtual uintptr_t segPreferredLoadAddress(unsigned int) const = 0;
602 virtual uintptr_t segActualLoadAddress(unsigned int) const = 0;
603 virtual uintptr_t segActualEndAddress(unsigned int) const = 0;
604
605
606 // info from LC_VERSION_MIN_MACOSX or LC_VERSION_MIN_IPHONEOS
607 virtual uint32_t sdkVersion() const = 0;
608 virtual uint32_t minOSVersion() const = 0;
609
610 // if the image contains interposing functions, register them
611 virtual void registerInterposing(const LinkContext& context) = 0;
612
613 virtual bool usesChainedFixups() const { return false; }
614
615 virtual void makeDataReadOnly() const {}
616
617 // when resolving symbols look in subImage if symbol can't be found
618 void reExport(ImageLoader* subImage);
619
620 virtual void recursiveBind(const LinkContext& context, bool forceLazysBound, bool neverUnload);
621 void recursiveBindWithAccounting(const LinkContext& context, bool forceLazysBound, bool neverUnload);
622 void recursiveRebaseWithAccounting(const LinkContext& context);
623 void weakBind(const LinkContext& context);
624
625 void applyInterposing(const LinkContext& context);
626
627 dyld_image_states getState() { return (dyld_image_states)fState; }
628
629 ino_t getInode() const { return fInode; }
630 dev_t getDevice() const { return fDevice; }
631
632 // used to sort images bottom-up
633 int compare(const ImageLoader* right) const;
634
635 void incrementDlopenReferenceCount() { ++fDlopenReferenceCount; }
636
637 bool decrementDlopenReferenceCount();
638
639 void printReferenceCounts();
640
641 uint32_t dlopenCount() const { return fDlopenReferenceCount; }
642
643 void setCanUnload() { fNeverUnload = false; fLeaveMapped = false; }
644
645 bool neverUnload() const { return fNeverUnload; }
646
647 void setNeverUnload() { fNeverUnload = true; fLeaveMapped = true; }
648 void setNeverUnloadRecursive();
649
650 bool isReferencedDownward() { return fIsReferencedDownward; }
651
652 virtual void recursiveMakeDataReadOnly(const LinkContext& context);
653
654 virtual uintptr_t resolveWeak(const LinkContext& context, const char* symbolName, bool weak_import, bool runResolver,
655 const ImageLoader** foundIn) { return 0; }
656
657 // triggered by DYLD_PRINT_STATISTICS to write info on work done and how fast
658 static void printStatistics(unsigned int imageCount, const InitializerTimingList& timingInfo);
659 static void printStatisticsDetails(unsigned int imageCount, const InitializerTimingList& timingInfo);
660
661 // used with DYLD_IMAGE_SUFFIX
662 static void addSuffix(const char* path, const char* suffix, char* result);
663
664 static uint32_t hash(const char*);
665
666 static const uint8_t* trieWalk(const uint8_t* start, const uint8_t* end, const char* stringToFind);
667
668 // used instead of directly deleting image
669 static void deleteImage(ImageLoader*);
670
671 static bool haveInterposingTuples() { return !fgInterposingTuples.empty(); }
672 static void clearInterposingTuples() { fgInterposingTuples.clear(); }
673
674 static void applyInterposingToDyldCache(const LinkContext& context);
675
676 bool dependsOn(ImageLoader* image);
677
678 void setPath(const char* path);
679 void setPaths(const char* path, const char* realPath);
680 void setPathUnowned(const char* path);
681
682 void clearDepth() { fDepth = 0; }
683 int getDepth() { return fDepth; }
684
685 void setBeingRemoved() { fBeingRemoved = true; }
686 bool isBeingRemoved() const { return fBeingRemoved; }
687
688 void markNotUsed() { fMarkedInUse = false; }
689 void markedUsedRecursive(const std::vector<DynamicReference>&);
690 bool isMarkedInUse() const { return fMarkedInUse; }
691
692 void setAddFuncNotified() { fAddFuncNotified = true; }
693 bool addFuncNotified() const { return fAddFuncNotified; }
694
695 void setObjCMappedNotified() { fObjCMappedNotified = true; }
696 bool objCMappedNotified() const { return fObjCMappedNotified; }
697
698 struct InterposeTuple {
699 uintptr_t replacement;
700 ImageLoader* neverImage; // don't apply replacement to this image
701 ImageLoader* onlyImage; // only apply replacement to this image
702 uintptr_t replacee;
703 };
704
705 static uintptr_t read_uleb128(const uint8_t*& p, const uint8_t* end);
706 static intptr_t read_sleb128(const uint8_t*& p, const uint8_t* end);
707
708 void vmAccountingSetSuspended(const LinkContext& context, bool suspend);
709
710 protected:
711 // abstract base class so all constructors protected
712 ImageLoader(const char* path, unsigned int libCount);
713 ImageLoader(const ImageLoader&);
714 void operator=(const ImageLoader&);
715 void operator delete(void* image) throw() { ::free(image); }
716
717
718 struct LibraryInfo {
719 uint32_t checksum;
720 uint32_t minVersion;
721 uint32_t maxVersion;
722 };
723
724 struct DependentLibrary {
725 ImageLoader* image;
726 uint32_t required : 1,
727 checksumMatches : 1,
728 isReExported : 1,
729 isSubFramework : 1;
730 };
731
732 struct DependentLibraryInfo {
733 const char* name;
734 LibraryInfo info;
735 bool required;
736 bool reExported;
737 bool upward;
738 };
739
740
741 typedef void (*Initializer)(int argc, const char* argv[], const char* envp[], const char* apple[], const ProgramVars* vars);
742 typedef void (*Terminator)(void);
743
744
745
746 unsigned int libraryCount() const { return fLibraryCount; }
747 virtual ImageLoader* libImage(unsigned int) const = 0;
748 virtual bool libReExported(unsigned int) const = 0;
749 virtual bool libIsUpward(unsigned int) const = 0;
750 virtual void setLibImage(unsigned int, ImageLoader*, bool, bool) = 0;
751
752 // To link() an image, its dependent libraries are loaded, it is rebased, bound, and initialized.
753 // These methods do the above, exactly once, and it the right order
754 virtual void recursiveLoadLibraries(const LinkContext& context, bool preflightOnly, const RPathChain& loaderRPaths, const char* loadPath);
755 virtual unsigned recursiveUpdateDepth(unsigned int maxDepth);
756 virtual void recursiveRebase(const LinkContext& context);
757 virtual void recursiveApplyInterposing(const LinkContext& context);
758 virtual void recursiveGetDOFSections(const LinkContext& context, std::vector<DOFInfo>& dofs);
759 virtual void recursiveInitialization(const LinkContext& context, mach_port_t this_thread, const char* pathToInitialize,
760 ImageLoader::InitializerTimingList&, ImageLoader::UninitedUpwards&);
761
762 // fill in information about dependent libraries (array length is fLibraryCount)
763 virtual void doGetDependentLibraries(DependentLibraryInfo libs[]) = 0;
764
765 // called on images that are libraries, returns info about itself
766 virtual LibraryInfo doGetLibraryInfo(const LibraryInfo& requestorInfo) = 0;
767
768 // do any fix ups in this image that depend only on the load address of the image
769 virtual void doRebase(const LinkContext& context) = 0;
770
771 // do any symbolic fix ups in this image
772 virtual void doBind(const LinkContext& context, bool forceLazysBound) = 0;
773
774 // called later via API to force all lazy pointer to be bound
775 virtual void doBindJustLazies(const LinkContext& context) = 0;
776
777 // if image has any dtrace DOF sections, append them to list to be registered
778 virtual void doGetDOFSections(const LinkContext& context, std::vector<DOFInfo>& dofs) = 0;
779
780 // do interpose
781 virtual void doInterpose(const LinkContext& context) = 0;
782
783 // run any initialization routines in this image
784 virtual bool doInitialization(const LinkContext& context) = 0;
785
786 // return if this image has termination routines
787 virtual bool needsTermination() = 0;
788
789 // support for runtimes in which segments don't have to maintain their relative positions
790 virtual bool segmentsMustSlideTogether() const = 0;
791
792 // built with PIC code and can load at any address
793 virtual bool segmentsCanSlide() const = 0;
794
795 // set how much all segments slide
796 virtual void setSlide(intptr_t slide) = 0;
797
798 // returns if all dependent libraries checksum's were as expected and none slide
799 bool allDependentLibrariesAsWhenPreBound() const;
800
801 // in mach-o a child tells it parent to re-export, instead of the other way around...
802 virtual bool isSubframeworkOf(const LinkContext& context, const ImageLoader* image) const = 0;
803
804 // in mach-o a parent library knows name of sub libraries it re-exports..
805 virtual bool hasSubLibrary(const LinkContext& context, const ImageLoader* child) const = 0;
806
807 virtual bool weakSymbolsBound(unsigned index) const { return fWeakSymbolsBound; }
808 virtual void setWeakSymbolsBound(unsigned index) { fWeakSymbolsBound = true; }
809
810 // set fState to dyld_image_state_memory_mapped
811 void setMapped(const LinkContext& context);
812
813 void setFileInfo(dev_t device, ino_t inode, time_t modDate);
814
815 void setDepth(uint16_t depth) { fDepth = depth; }
816
817 static uintptr_t interposedAddress(const LinkContext& context, uintptr_t address, const ImageLoader* notInImage, const ImageLoader* onlyInImage=NULL);
818
819 static uintptr_t fgNextPIEDylibAddress;
820 static uint32_t fgImagesWithUsedPrebinding;
821 static uint32_t fgImagesUsedFromSharedCache;
822 static uint32_t fgImagesHasWeakDefinitions;
823 static uint32_t fgImagesRequiringCoalescing;
824 static uint32_t fgTotalRebaseFixups;
825 static uint32_t fgTotalBindFixups;
826 static uint32_t fgTotalBindSymbolsResolved;
827 static uint32_t fgTotalBindImageSearches;
828 static uint32_t fgTotalLazyBindFixups;
829 static uint32_t fgTotalPossibleLazyBindFixups;
830 static uint32_t fgTotalSegmentsMapped;
831 static uint32_t fgSymbolTrieSearchs;
832 static uint64_t fgTotalBytesMapped;
833 static uint64_t fgTotalLoadLibrariesTime;
834 public:
835 static uint64_t fgTotalObjCSetupTime;
836 static uint64_t fgTotalDebuggerPausedTime;
837 static uint64_t fgTotalRebindCacheTime;
838 static uint64_t fgTotalRebaseTime;
839 static uint64_t fgTotalBindTime;
840 static uint64_t fgTotalWeakBindTime;
841 static uint64_t fgTotalDOF;
842 static uint64_t fgTotalInitTime;
843
844 protected:
845 static std::vector<InterposeTuple> fgInterposingTuples;
846
847 const char* fPath;
848 const char* fRealPath;
849 dev_t fDevice;
850 ino_t fInode;
851 time_t fLastModified;
852 uint32_t fPathHash;
853 uint32_t fDlopenReferenceCount; // count of how many dlopens have been done on this image
854
855 struct recursive_lock {
856 recursive_lock(mach_port_t t) : thread(t), count(0) {}
857 mach_port_t thread;
858 int count;
859 };
860 void recursiveSpinLock(recursive_lock&);
861 void recursiveSpinUnLock();
862
863 private:
864 const ImageLoader::Symbol* findExportedSymbolInDependentImagesExcept(const char* name, const ImageLoader** dsiStart,
865 const ImageLoader**& dsiCur, const ImageLoader** dsiEnd, const ImageLoader** foundIn) const;
866
867 void processInitializers(const LinkContext& context, mach_port_t this_thread,
868 InitializerTimingList& timingInfo, ImageLoader::UninitedUpwards& ups);
869
870 void weakBindOld(const LinkContext& context);
871
872
873 recursive_lock* fInitializerRecursiveLock;
874 union {
875 struct {
876 uint16_t fLoadOrder;
877 uint16_t fDepth : 15,
878 fObjCMappedNotified : 1;
879 uint32_t fState : 8,
880 fLibraryCount : 9,
881 fMadeReadOnly : 1,
882 fAllLibraryChecksumsAndLoadAddressesMatch : 1,
883 fLeaveMapped : 1, // when unloaded, leave image mapped in cause some other code may have pointers into it
884 fNeverUnload : 1, // image was statically loaded by main executable
885 fHideSymbols : 1, // ignore this image's exported symbols when linking other images
886 fMatchByInstallName : 1,// look at image's install-path not its load path
887 fInterposed : 1,
888 fRegisteredDOF : 1,
889 fAllLazyPointersBound : 1,
890 fMarkedInUse : 1,
891 fBeingRemoved : 1,
892 fAddFuncNotified : 1,
893 fPathOwnedByImage : 1,
894 fIsReferencedDownward : 1,
895 fWeakSymbolsBound : 1;
896 };
897 uint64_t sizeOfData;
898 };
899 static_assert(sizeof(sizeOfData) == 8, "Bad data size");
900
901 static uint16_t fgLoadOrdinal;
902 };
903
904
905 VECTOR_NEVER_DESTRUCTED_EXTERN(ImageLoader::InterposeTuple);
906
907
908 #endif
909