2 * Copyright (c) 2017 Apple Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
29 #include <sys/errno.h>
34 #include <TargetConditionals.h>
35 #include <malloc/malloc.h>
36 #include <mach-o/dyld_priv.h>
37 #include <mach-o/dyld_images.h>
43 #include "AllImages.h"
46 #include "Diagnostics.h"
47 #include "DyldSharedCache.h"
54 void parseDlHandle(void* h
, const MachOLoaded
** mh
, bool* dontContinue
);
57 // only in macOS and deprecated
58 #if __MAC_OS_X_VERSION_MIN_REQUIRED
60 // macOS needs to support an old API that only works with fileype==MH_BUNDLE.
61 // In this deprecated API (unlike dlopen), loading and linking are separate steps.
62 // NSCreateObjectFileImageFrom*() just maps in the bundle mach-o file.
63 // NSLinkModule() does the load of dependent modules and rebasing/binding.
64 // To unload one of these, you must call NSUnLinkModule() and NSDestroyObjectFileImage() in any order!
67 NSObjectFileImageReturnCode
NSCreateObjectFileImageFromFile(const char* path
, NSObjectFileImage
* ofi
)
69 log_apis("NSCreateObjectFileImageFromFile(\"%s\", %p)\n", path
, ofi
);
73 if ( ::stat(path
, &statbuf
) == -1 )
74 return NSObjectFileImageFailure
;
76 // create ofi that just contains path. NSLinkModule does all the work
78 result
.path
= strdup(path
);
79 result
.memSource
= nullptr;
81 result
.loadAddress
= nullptr;
83 *ofi
= gAllImages
.addNSObjectFileImage(result
);
85 log_apis("NSCreateObjectFileImageFromFile() => %p\n", *ofi
);
87 return NSObjectFileImageSuccess
;
90 NSObjectFileImageReturnCode
NSCreateObjectFileImageFromMemory(const void* memImage
, size_t memImageSize
, NSObjectFileImage
*ofi
)
92 log_apis("NSCreateObjectFileImageFromMemory(%p, 0x%0lX, %p)\n", memImage
, memImageSize
, ofi
);
94 // sanity check the buffer is a mach-o file
95 __block Diagnostics diag
;
97 // check if it is current arch mach-o or fat with slice for current arch
99 const MachOFile
* mf
= (MachOFile
*)memImage
;
100 if ( mf
->hasMachOMagic() && mf
->isMachO(diag
, memImageSize
) ) {
101 usable
= (gAllImages
.archs().grade(mf
->cputype
, mf
->cpusubtype
) != 0);
103 else if ( const FatFile
* ff
= FatFile::isFatFile(memImage
) ) {
104 uint64_t sliceOffset
;
107 if ( ff
->isFatFileWithSlice(diag
, memImageSize
, gAllImages
.archs(), sliceOffset
, sliceLen
, missingSlice
) ) {
108 mf
= (MachOFile
*)((long)memImage
+sliceOffset
);
109 if ( mf
->isMachO(diag
, sliceLen
) ) {
115 if ( !mf
->supportsPlatform(Platform::macOS
) )
119 log_apis("NSCreateObjectFileImageFromMemory() not mach-o\n");
120 return NSObjectFileImageFailure
;
123 // this API can only be used with bundles
124 if ( !mf
->isBundle() ) {
125 log_apis("NSCreateObjectFileImageFromMemory() not a bundle\n");
126 return NSObjectFileImageInappropriateFile
;
129 // allocate ofi that just lists the memory range
131 result
.path
= nullptr;
132 result
.memSource
= memImage
;
133 result
.memLength
= memImageSize
;
134 result
.loadAddress
= nullptr;
136 *ofi
= gAllImages
.addNSObjectFileImage(result
);
138 log_apis("NSCreateObjectFileImageFromMemory() => %p\n", *ofi
);
140 return NSObjectFileImageSuccess
;
143 NSModule
NSLinkModule(NSObjectFileImage ofi
, const char* moduleName
, uint32_t options
)
145 DYLD_LOAD_LOCK_THIS_BLOCK
146 log_apis("NSLinkModule(%p, \"%s\", 0x%08X)\n", ofi
, moduleName
, options
);
148 __block
const char* path
= nullptr;
149 bool foundImage
= gAllImages
.forNSObjectFileImage(ofi
, ^(OFIInfo
&image
) {
150 // if this is memory based image, write to temp file, then use file based loading
151 if ( image
.memSource
!= nullptr ) {
152 // make temp file with content of memory buffer
153 image
.path
= nullptr;
154 char tempFileName
[PATH_MAX
];
155 const char* tmpDir
= getenv("TMPDIR");
156 if ( (tmpDir
!= nullptr) && (strlen(tmpDir
) > 2) ) {
157 strlcpy(tempFileName
, tmpDir
, PATH_MAX
);
158 if ( tmpDir
[strlen(tmpDir
)-1] != '/' )
159 strlcat(tempFileName
, "/", PATH_MAX
);
162 strlcpy(tempFileName
,"/tmp/", PATH_MAX
);
163 strlcat(tempFileName
, "NSCreateObjectFileImageFromMemory-XXXXXXXX", PATH_MAX
);
164 int fd
= ::mkstemp(tempFileName
);
166 ssize_t writtenSize
= ::pwrite(fd
, image
.memSource
, image
.memLength
, 0);
167 if ( writtenSize
== image
.memLength
) {
168 image
.path
= strdup(tempFileName
);
171 log_apis("NSLinkModule() => NULL (could not save memory image to temp file)\n");
180 // ofi is invalid if not in list
181 log_apis("NSLinkModule() => NULL (invalid NSObjectFileImage)\n");
188 // dlopen the binary outside of the read lock as we don't want to risk deadlock
190 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
191 const MachOLoaded
* loadAddress
= gAllImages
.dlopen(diag
, path
, false, false, false, false, true, callerAddress
);
192 if ( diag
.hasError() ) {
193 log_apis(" NSLinkModule: failed: %s\n", diag
.errorMessage());
197 // Now update the load address of this object
198 gAllImages
.forNSObjectFileImage(ofi
, ^(OFIInfo
&image
) {
199 image
.loadAddress
= loadAddress
;
201 // if memory based load, delete temp file
202 if ( image
.memSource
!= nullptr ) {
203 log_apis(" NSLinkModule: delete temp file: %s\n", image
.path
);
204 ::unlink(image
.path
);
208 log_apis("NSLinkModule() => %p\n", loadAddress
);
209 return (NSModule
)loadAddress
;
212 // NSUnLinkModule unmaps the image, but does not release the NSObjectFileImage
213 bool NSUnLinkModule(NSModule
module, uint32_t options
)
215 DYLD_LOAD_LOCK_THIS_BLOCK
216 log_apis("NSUnLinkModule(%p, 0x%08X)\n", module, options
);
218 __block
const mach_header
* mh
= nullptr;
219 gAllImages
.infoForImageMappedAt(module, ^(const LoadedImage
& foundImage
, uint8_t permissions
) {
220 mh
= foundImage
.loadedAddress();
224 gAllImages
.decRefCount(mh
); // removes image if reference count went to zero
226 log_apis("NSUnLinkModule() => %d\n", mh
!= nullptr);
228 return mh
!= nullptr;
231 // NSDestroyObjectFileImage releases the NSObjectFileImage, but the mapped image may remain in use
232 bool NSDestroyObjectFileImage(NSObjectFileImage imageHandle
)
234 log_apis("NSDestroyObjectFileImage(%p)\n", imageHandle
);
236 __block
const void* memSource
= nullptr;
237 __block
size_t memLength
= 0;
238 __block
const char* path
= nullptr;
239 bool foundImage
= gAllImages
.forNSObjectFileImage(imageHandle
, ^(OFIInfo
&image
) {
241 memSource
= image
.memSource
;
242 memLength
= image
.memLength
;
250 gAllImages
.removeNSObjectFileImage(imageHandle
);
252 // if object was created from a memory, release that memory
253 // NOTE: this is the way dyld has always done this. NSCreateObjectFileImageFromMemory() hands ownership of the memory to dyld
254 if ( memSource
!= nullptr ) {
255 // we don't know if memory came from malloc or vm_allocate, so ask malloc
256 if ( malloc_size(memSource
) != 0 )
257 free((void*)(memSource
));
259 vm_deallocate(mach_task_self(), (vm_address_t
)memSource
, memLength
);
266 uint32_t NSSymbolDefinitionCountInObjectFileImage(NSObjectFileImage objectFileImage
)
268 halt("NSSymbolDefinitionCountInObjectFileImage() is obsolete");
271 const char* NSSymbolDefinitionNameInObjectFileImage(NSObjectFileImage objectFileImage
, uint32_t ordinal
)
273 halt("NSSymbolDefinitionNameInObjectFileImage() is obsolete");
276 uint32_t NSSymbolReferenceCountInObjectFileImage(NSObjectFileImage objectFileImage
)
278 halt("NSSymbolReferenceCountInObjectFileImage() is obsolete");
281 const char* NSSymbolReferenceNameInObjectFileImage(NSObjectFileImage objectFileImage
, uint32_t ordinal
, bool *tentative_definition
)
283 halt("NSSymbolReferenceNameInObjectFileImage() is obsolete");
286 bool NSIsSymbolDefinedInObjectFileImage(NSObjectFileImage imageHandle
, const char* symbolName
)
288 log_apis("NSIsSymbolDefinedInObjectFileImage(%p, %s)\n", imageHandle
, symbolName
);
290 __block
bool hasSymbol
= false;
291 bool foundImage
= gAllImages
.forNSObjectFileImage(imageHandle
, ^(OFIInfo
&image
) {
293 bool resultPointsToInstructions
= false;
294 hasSymbol
= image
.loadAddress
->hasExportedSymbol(symbolName
, nullptr, &addr
, &resultPointsToInstructions
);
297 // ofi is invalid if not in list
304 void* NSGetSectionDataInObjectFileImage(NSObjectFileImage imageHandle
, const char* segmentName
, const char* sectionName
, size_t* size
)
306 __block
const void* result
= nullptr;
307 bool foundImage
= gAllImages
.forNSObjectFileImage(imageHandle
, ^(OFIInfo
&image
) {
309 result
= image
.loadAddress
->findSectionContent(segmentName
, sectionName
, sz
);
313 // ofi is invalid if not in list
317 return (void*)result
;
320 const char* NSNameOfModule(NSModule m
)
322 log_apis("NSNameOfModule(%p)\n", m
);
324 __block
const char* result
= nullptr;
325 gAllImages
.infoForImageMappedAt(m
, ^(const LoadedImage
& foundImage
, uint8_t permissions
) {
326 result
= gAllImages
.imagePath(foundImage
.image());
332 const char* NSLibraryNameForModule(NSModule m
)
334 log_apis("NSLibraryNameForModule(%p)\n", m
);
336 __block
const char* result
= nullptr;
337 gAllImages
.infoForImageMappedAt(m
, ^(const LoadedImage
& foundImage
, uint8_t permissions
) {
338 result
= gAllImages
.imagePath(foundImage
.image());
344 static bool flatFindSymbol(const char* symbolName
, void** symbolAddress
, const mach_header
** foundInImageAtLoadAddress
)
346 __block
bool result
= false;
347 gAllImages
.forEachImage(^(const LoadedImage
& loadedImage
, bool& stop
) {
348 bool resultPointsToInstructions
= false;
349 if ( loadedImage
.loadedAddress()->hasExportedSymbol(symbolName
, nullptr, symbolAddress
, &resultPointsToInstructions
) ) {
350 *foundInImageAtLoadAddress
= loadedImage
.loadedAddress();
358 bool NSIsSymbolNameDefined(const char* symbolName
)
360 log_apis("NSIsSymbolNameDefined(%s)\n", symbolName
);
362 const mach_header
* foundInImageAtLoadAddress
;
364 return flatFindSymbol(symbolName
, &address
, &foundInImageAtLoadAddress
);
367 bool NSIsSymbolNameDefinedWithHint(const char* symbolName
, const char* libraryNameHint
)
369 log_apis("NSIsSymbolNameDefinedWithHint(%s, %s)\n", symbolName
, libraryNameHint
);
371 const mach_header
* foundInImageAtLoadAddress
;
373 return flatFindSymbol(symbolName
, &address
, &foundInImageAtLoadAddress
);
376 bool NSIsSymbolNameDefinedInImage(const struct mach_header
* mh
, const char* symbolName
)
378 log_apis("NSIsSymbolNameDefinedInImage(%p, %s)\n", mh
, symbolName
);
381 bool resultPointsToInstructions
= false;
382 return ((MachOLoaded
*)mh
)->hasExportedSymbol(symbolName
, nullptr, &addr
, &resultPointsToInstructions
);
385 NSSymbol
NSLookupAndBindSymbol(const char* symbolName
)
387 log_apis("NSLookupAndBindSymbol(%s)\n", symbolName
);
389 const mach_header
* foundInImageAtLoadAddress
;
391 if ( flatFindSymbol(symbolName
, &symbolAddress
, &foundInImageAtLoadAddress
) ) {
392 return (NSSymbol
)symbolAddress
;
397 NSSymbol
NSLookupAndBindSymbolWithHint(const char* symbolName
, const char* libraryNameHint
)
399 log_apis("NSLookupAndBindSymbolWithHint(%s, %s)\n", symbolName
, libraryNameHint
);
401 const mach_header
* foundInImageAtLoadAddress
;
403 if ( flatFindSymbol(symbolName
, &symbolAddress
, &foundInImageAtLoadAddress
) ) {
404 return (NSSymbol
)symbolAddress
;
409 NSSymbol
NSLookupSymbolInModule(NSModule
module, const char* symbolName
)
411 log_apis("NSLookupSymbolInModule(%p. %s)\n", module, symbolName
);
413 const MachOLoaded
* mh
= (const MachOLoaded
*)module;
415 bool resultPointsToInstructions
= false;
416 if ( mh
->hasExportedSymbol(symbolName
, nullptr, &addr
, &resultPointsToInstructions
) ) {
417 return (NSSymbol
)addr
;
422 NSSymbol
NSLookupSymbolInImage(const mach_header
* mh
, const char* symbolName
, uint32_t options
)
424 log_apis("NSLookupSymbolInImage(%p, \"%s\", 0x%08X)\n", mh
, symbolName
, options
);
427 bool resultPointsToInstructions
= false;
428 if ( ((MachOLoaded
*)mh
)->hasExportedSymbol(symbolName
, nullptr, &addr
, &resultPointsToInstructions
) ) {
429 log_apis(" NSLookupSymbolInImage() => %p\n", addr
);
430 return (NSSymbol
)addr
;
432 if ( options
& NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR
) {
433 log_apis(" NSLookupSymbolInImage() => NULL\n");
440 const char* NSNameOfSymbol(NSSymbol symbol
)
442 halt("NSNameOfSymbol() is obsolete");
445 void* NSAddressOfSymbol(NSSymbol symbol
)
447 log_apis("NSAddressOfSymbol(%p)\n", symbol
);
449 // in dyld 1.0, NSSymbol was a pointer to the nlist entry in the symbol table
450 return (void*)symbol
;
453 NSModule
NSModuleForSymbol(NSSymbol symbol
)
455 log_apis("NSModuleForSymbol(%p)\n", symbol
);
457 __block NSModule result
= nullptr;
458 gAllImages
.infoForImageMappedAt(symbol
, ^(const LoadedImage
& foundImage
, uint8_t permissions
) {
459 result
= (NSModule
)foundImage
.loadedAddress();
465 void NSLinkEditError(NSLinkEditErrors
*c
, int *errorNumber
, const char** fileName
, const char** errorString
)
467 log_apis("NSLinkEditError(%p, %p, %p, %p)\n", c
, errorNumber
, fileName
, errorString
);
468 *c
= NSLinkEditOtherError
;
474 bool NSAddLibrary(const char* pathName
)
476 log_apis("NSAddLibrary(%s)\n", pathName
);
478 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
479 return ( dlopen_internal(pathName
, 0, callerAddress
) != nullptr);
482 bool NSAddLibraryWithSearching(const char* pathName
)
484 log_apis("NSAddLibraryWithSearching(%s)\n", pathName
);
486 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
487 return ( dlopen_internal(pathName
, 0, callerAddress
) != nullptr);
490 const mach_header
* NSAddImage(const char* imageName
, uint32_t options
)
492 log_apis("NSAddImage(\"%s\", 0x%08X)\n", imageName
, options
);
494 // Note: this is a quick and dirty implementation that just uses dlopen() and ignores some option flags
495 uint32_t dloptions
= 0;
496 if ( (options
& NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
) != 0 )
497 dloptions
|= RTLD_NOLOAD
;
499 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
500 void* h
= dlopen_internal(imageName
, dloptions
, callerAddress
);
501 if ( h
!= nullptr ) {
502 const MachOLoaded
* mh
;
504 parseDlHandle(h
, &mh
, &dontContinue
);
508 if ( (options
& (NSADDIMAGE_OPTION_RETURN_ON_ERROR
|NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
)) == 0 ) {
509 halt("NSAddImage() image not found");
514 void NSInstallLinkEditErrorHandlers(const NSLinkEditErrorHandlers
*handlers
)
516 halt("NSInstallLinkEditErrorHandlers() is obsolete");
519 bool _dyld_present(void)
521 log_apis("_dyld_present()\n");
526 bool _dyld_launched_prebound(void)
528 halt("_dyld_launched_prebound() is obsolete");
531 bool _dyld_all_twolevel_modules_prebound(void)
533 halt("_dyld_all_twolevel_modules_prebound() is obsolete");
536 bool _dyld_bind_fully_image_containing_address(const void* address
)
538 log_apis("_dyld_bind_fully_image_containing_address(%p)\n", address
);
540 // in dyld3, everything is always fully bound
544 bool _dyld_image_containing_address(const void* address
)
546 log_apis("_dyld_image_containing_address(%p)\n", address
);
548 return (dyld_image_header_containing_address(address
) != nullptr);
551 void _dyld_lookup_and_bind(const char* symbolName
, void **address
, NSModule
* module)
553 log_apis("_dyld_lookup_and_bind(%s, %p, %p)\n", symbolName
, address
, module);
555 const mach_header
* foundInImageAtLoadAddress
;
556 if ( flatFindSymbol(symbolName
, address
, &foundInImageAtLoadAddress
) ) {
557 *module = (NSModule
)foundInImageAtLoadAddress
;
565 void _dyld_lookup_and_bind_with_hint(const char* symbolName
, const char* libraryNameHint
, void** address
, NSModule
* module)
567 log_apis("_dyld_lookup_and_bind_with_hint(%s, %s, %p, %p)\n", symbolName
, libraryNameHint
, address
, module);
569 const mach_header
* foundInImageAtLoadAddress
;
570 if ( flatFindSymbol(symbolName
, address
, &foundInImageAtLoadAddress
) ) {
571 *module = (NSModule
)foundInImageAtLoadAddress
;
580 void _dyld_lookup_and_bind_fully(const char* symbolName
, void** address
, NSModule
* module)
582 log_apis("_dyld_lookup_and_bind_fully(%s, %p, %p)\n", symbolName
, address
, module);
584 const mach_header
* foundInImageAtLoadAddress
;
585 if ( flatFindSymbol(symbolName
, address
, &foundInImageAtLoadAddress
) ) {
586 *module = (NSModule
)foundInImageAtLoadAddress
;
594 const struct mach_header
* _dyld_get_image_header_containing_address(const void* address
)
596 log_apis("_dyld_get_image_header_containing_address(%p)\n", address
);
598 return dyld_image_header_containing_address(address
);