1 /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
3 * Copyright (c) 2016 Apple Inc. All rights reserved.
5 * @APPLE_LICENSE_HEADER_START@
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
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.
22 * @APPLE_LICENSE_HEADER_END@
25 #include <sys/types.h>
28 #include <mach/mach.h>
29 #include <mach/mach_time.h>
42 #include <sys/param.h>
43 #include <sys/sysctl.h>
44 #include <sys/resource.h>
48 #include <dispatch/dispatch.h>
49 #include <pthread/pthread.h>
53 #include <unordered_set>
54 #include <unordered_set>
58 #include "MachOFile.h"
59 #include "FileUtils.h"
60 #include "StringUtils.h"
61 #include "DyldSharedCache.h"
62 #include "MachOAnalyzer.h"
63 #include "ClosureFileSystemPhysical.h"
67 struct MappedMachOsByCategory
70 std::vector
<DyldSharedCache::MappedMachO
> dylibsForCache
;
71 std::vector
<DyldSharedCache::MappedMachO
> otherDylibsAndBundles
;
72 std::vector
<DyldSharedCache::MappedMachO
> mainExecutables
;
75 static const char* sSearchDirs
[] = {
82 static const char* sSkipDirs
[] = {
88 static const char* sMacOsAdditions
[] = {
89 "/usr/lib/system/libsystem_kernel.dylib",
90 "/usr/lib/system/libsystem_platform.dylib",
91 "/usr/lib/system/libsystem_pthread.dylib",
95 static bool verbose
= false;
97 static bool addIfMachO(const dyld3::closure::FileSystem
& fileSystem
, const std::string
& runtimePath
, const struct stat
& statBuf
, dyld3::Platform platform
, std::vector
<MappedMachOsByCategory
>& files
)
100 for (MappedMachOsByCategory
& file
: files
) {
102 dyld3::closure::LoadedFileInfo loadedFileInfo
= dyld3::MachOAnalyzer::load(diag
, fileSystem
, runtimePath
.c_str(), file
.archName
.c_str(), dyld3::Platform::macOS
);
103 const dyld3::MachOAnalyzer
* ma
= (const dyld3::MachOAnalyzer
*)loadedFileInfo
.fileContent
;
104 if ( ma
!= nullptr ) {
105 bool sipProtected
= false; // isProtectedBySIP(fd);
106 bool issetuid
= false;
107 if ( ma
->isDynamicExecutable() ) {
108 //fprintf(stderr, "requireSIP=%d, sipProtected=%d, path=%s\n", requireSIP, sipProtected, fullPath.c_str());
109 issetuid
= (statBuf
.st_mode
& (S_ISUID
|S_ISGID
));
110 file
.mainExecutables
.emplace_back(runtimePath
, ma
, loadedFileInfo
.sliceLen
, issetuid
, sipProtected
, loadedFileInfo
.sliceOffset
, statBuf
.st_mtime
, statBuf
.st_ino
);
113 else if ( ma
->canBePlacedInDyldCache(runtimePath
.c_str(), ^(const char* msg
) {}) ) {
114 file
.dylibsForCache
.emplace_back(runtimePath
, ma
, loadedFileInfo
.sliceLen
, issetuid
, sipProtected
, loadedFileInfo
.sliceOffset
, statBuf
.st_mtime
, statBuf
.st_ino
);
122 static void findAllFiles(const std::string
& simRuntimeRootPath
, dyld3::Platform platform
, std::vector
<MappedMachOsByCategory
>& files
)
124 std::unordered_set
<std::string
> skipDirs
;
125 for (const char* s
: sSkipDirs
)
128 for (const char* searchDir
: sSearchDirs
) {
129 dyld3::closure::FileSystemPhysical
fileSystem(simRuntimeRootPath
.c_str());
130 iterateDirectoryTree(simRuntimeRootPath
, searchDir
, ^(const std::string
& dirPath
) { return (skipDirs
.count(dirPath
) != 0); }, ^(const std::string
& path
, const struct stat
& statBuf
) {
131 // ignore files that don't have 'x' bit set (all runnable mach-o files do)
132 const bool hasXBit
= ((statBuf
.st_mode
& S_IXOTH
) == S_IXOTH
);
133 if ( !hasXBit
&& !endsWith(path
, ".dylib") )
136 // ignore files too small
137 if ( statBuf
.st_size
< 0x3000 )
140 // if the file is mach-o add to list
141 addIfMachO(fileSystem
, path
, statBuf
, platform
, files
);
146 static void addMacOSAdditions(std::vector
<MappedMachOsByCategory
>& allFileSets
)
148 dyld3::closure::FileSystemPhysical fileSystem
;
149 for (const char* addPath
: sMacOsAdditions
) {
151 if ( stat(addPath
, &statBuf
) == 0 ) {
152 addIfMachO(fileSystem
, addPath
, statBuf
, dyld3::Platform::macOS
, allFileSets
);
158 static bool dontCache(const std::string
& simRuntimeRootPath
, const std::string
& archName
,
159 const std::unordered_set
<std::string
>& pathsWithDuplicateInstallName
,
160 const DyldSharedCache::MappedMachO
& aFile
, bool warn
)
162 if ( startsWith(aFile
.runtimePath
, "/usr/lib/system/introspection/") )
164 if ( startsWith(aFile
.runtimePath
, "/usr/local/") )
167 // anything inside a .app bundle is specific to app, so should be in shared cache
168 if ( aFile
.runtimePath
.find(".app/") != std::string::npos
)
171 if ( aFile
.runtimePath
.find("//") != std::string::npos
) {
172 if (warn
) fprintf(stderr
, "update_dyld_sim_shared_cache: warning: %s double-slash in install name %s\n", archName
.c_str(), aFile
.runtimePath
.c_str());
175 const char* installName
= aFile
.mh
->installName();
176 if ( (pathsWithDuplicateInstallName
.count(aFile
.runtimePath
) != 0) && (aFile
.runtimePath
!= installName
) ) {
177 if (warn
) fprintf(stderr
, "update_dyld_sim_shared_cache: warning: %s skipping because of duplicate install name %s\n", archName
.c_str(), aFile
.runtimePath
.c_str());
181 if ( aFile
.runtimePath
!= installName
) {
182 // see if install name is a symlink to actual path
183 std::string fullInstall
= simRuntimeRootPath
+ installName
;
184 char resolvedPath
[PATH_MAX
];
185 if ( realpath(fullInstall
.c_str(), resolvedPath
) != NULL
) {
186 std::string resolvedSymlink
= resolvedPath
;
187 if ( !simRuntimeRootPath
.empty() ) {
188 resolvedSymlink
= resolvedSymlink
.substr(simRuntimeRootPath
.size());
190 if ( aFile
.runtimePath
== resolvedSymlink
) {
194 if (warn
) fprintf(stderr
, "update_dyld_sim_shared_cache: warning: %s skipping because of bad install name %s\n", archName
.c_str(), aFile
.runtimePath
.c_str());
201 static void pruneCachedDylibs(const std::string
& simRuntimeRootPath
, MappedMachOsByCategory
& fileSet
)
203 std::unordered_set
<std::string
> pathsWithDuplicateInstallName
;
205 std::unordered_map
<std::string
, std::string
> installNameToFirstPath
;
206 for (DyldSharedCache::MappedMachO
& aFile
: fileSet
.dylibsForCache
) {
207 //fprintf(stderr, "dylib: %s\n", aFile.runtimePath.c_str());
208 const char* installName
= aFile
.mh
->installName();
209 auto pos
= installNameToFirstPath
.find(installName
);
210 if ( pos
== installNameToFirstPath
.end() ) {
211 installNameToFirstPath
[installName
] = aFile
.runtimePath
;
214 pathsWithDuplicateInstallName
.insert(aFile
.runtimePath
);
215 pathsWithDuplicateInstallName
.insert(installNameToFirstPath
[installName
]);
219 for (DyldSharedCache::MappedMachO
& aFile
: fileSet
.dylibsForCache
) {
220 if ( dontCache(simRuntimeRootPath
, fileSet
.archName
, pathsWithDuplicateInstallName
, aFile
, true) )
221 fileSet
.otherDylibsAndBundles
.push_back(aFile
);
223 fileSet
.dylibsForCache
.erase(std::remove_if(fileSet
.dylibsForCache
.begin(), fileSet
.dylibsForCache
.end(),
224 [&](const DyldSharedCache::MappedMachO
& aFile
) { return dontCache(simRuntimeRootPath
, fileSet
.archName
, pathsWithDuplicateInstallName
, aFile
, false); }),
225 fileSet
.dylibsForCache
.end());
228 static bool existingCacheUpToDate(const std::string
& existingCache
, const std::vector
<DyldSharedCache::MappedMachO
>& currentDylibs
)
230 // if no existing cache, it is not up-to-date
231 int fd
= ::open(existingCache
.c_str(), O_RDONLY
);
235 // build map of found dylibs
236 std::unordered_map
<std::string
, const DyldSharedCache::MappedMachO
*> currentDylibMap
;
237 for (const DyldSharedCache::MappedMachO
& aFile
: currentDylibs
) {
238 //fprintf(stderr, "0x%0llX 0x%0llX %s\n", aFile.inode, aFile.modTime, aFile.runtimePath.c_str());
239 currentDylibMap
[aFile
.runtimePath
] = &aFile
;
242 // make sure all dylibs in existing cache have same mtime and inode as found dylib
243 __block
bool foundMismatch
= false;
244 const uint64_t cacheMapLen
= 0x40000000;
245 void *p
= ::mmap(NULL
, cacheMapLen
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
246 if ( p
!= MAP_FAILED
) {
247 const DyldSharedCache
* cache
= (DyldSharedCache
*)p
;
248 cache
->forEachImageEntry(^(const char* installName
, uint64_t mTime
, uint64_t inode
) {
249 bool foundMatch
= false;
250 auto pos
= currentDylibMap
.find(installName
);
251 if ( pos
!= currentDylibMap
.end() ) {
252 const DyldSharedCache::MappedMachO
* foundDylib
= pos
->second
;
253 if ( (foundDylib
->inode
== inode
) && (foundDylib
->modTime
== mTime
) ) {
258 // use slow path and look for any dylib with a matching inode and mtime
259 bool foundSlow
= false;
260 for (const DyldSharedCache::MappedMachO
& aFile
: currentDylibs
) {
261 if ( (aFile
.inode
== inode
) && (aFile
.modTime
== mTime
) ) {
267 foundMismatch
= true;
269 fprintf(stderr
, "rebuilding dyld cache because dylib changed: %s\n", installName
);
273 ::munmap(p
, cacheMapLen
);
278 return !foundMismatch
;
282 inline uint32_t absolutetime_to_milliseconds(uint64_t abstime
)
284 return (uint32_t)(abstime
/1000/1000);
288 #define TERMINATE_IF_LAST_ARG( s ) \
290 if ( i == argc - 1 ) { \
291 fprintf(stderr, s ); \
296 int main(int argc
, const char* argv
[])
298 std::string rootPath
;
299 std::string dylibListFile
;
301 std::string cacheDir
;
302 std::unordered_set
<std::string
> archStrs
;
304 dyld3::Platform platform
= dyld3::Platform::iOS
;
306 // parse command line options
307 for (int i
= 1; i
< argc
; ++i
) {
308 const char* arg
= argv
[i
];
309 if (strcmp(arg
, "-debug") == 0) {
312 else if (strcmp(arg
, "-verbose") == 0) {
315 else if (strcmp(arg
, "-tvOS") == 0) {
316 platform
= dyld3::Platform::tvOS_simulator
;
318 else if (strcmp(arg
, "-iOS") == 0) {
319 platform
= dyld3::Platform::iOS_simulator
;
321 else if (strcmp(arg
, "-watchOS") == 0) {
322 platform
= dyld3::Platform::watchOS_simulator
;
324 else if ( strcmp(arg
, "-runtime_dir") == 0 ) {
325 TERMINATE_IF_LAST_ARG("-runtime_dir missing path argument\n");
326 rootPath
= argv
[++i
];
328 else if (strcmp(arg
, "-cache_dir") == 0) {
329 TERMINATE_IF_LAST_ARG("-cache_dir missing path argument\n");
330 cacheDir
= argv
[++i
];
332 else if (strcmp(arg
, "-arch") == 0) {
333 TERMINATE_IF_LAST_ARG("-arch missing argument\n");
334 archStrs
.insert(argv
[++i
]);
336 else if (strcmp(arg
, "-force") == 0) {
341 fprintf(stderr
, "update_dyld_sim_shared_cache: unknown option: %s\n", arg
);
346 if ( cacheDir
.empty() ) {
347 fprintf(stderr
, "missing -cache_dir <path> option to specify directory in which to write cache file(s)\n");
351 if ( rootPath
.empty() ) {
352 fprintf(stderr
, "missing -runtime_dir <path> option to specify directory which is root of simulator runtime)\n");
356 // canonicalize rootPath
357 char resolvedPath
[PATH_MAX
];
358 if ( realpath(rootPath
.c_str(), resolvedPath
) != NULL
) {
359 rootPath
= resolvedPath
;
363 int err
= mkpath_np(cacheDir
.c_str(), S_IRWXU
| S_IRGRP
|S_IXGRP
| S_IROTH
|S_IXOTH
);
364 if ( (err
!= 0) && (err
!= EEXIST
) ) {
365 fprintf(stderr
, "mkpath_np fail: %d", err
);
369 if ( archStrs
.empty() ) {
370 switch ( platform
) {
371 case dyld3::Platform::iOS_simulator
:
372 archStrs
.insert("x86_64");
374 case dyld3::Platform::tvOS_simulator
:
375 archStrs
.insert("x86_64");
377 case dyld3::Platform::watchOS_simulator
:
378 archStrs
.insert("i386");
380 case dyld3::Platform::macOS
:
381 assert(0 && "macOS does not have a simulator");
383 case dyld3::Platform::bridgeOS
:
384 assert(0 && "bridgeOS does not have a simulator");
386 case dyld3::Platform::iOS
:
387 case dyld3::Platform::tvOS
:
388 case dyld3::Platform::watchOS
:
389 case dyld3::Platform::iOSMac
:
390 case dyld3::Platform::unknown
:
391 assert(0 && "invalid platform");
396 uint64_t t1
= mach_absolute_time();
398 // find all mach-o files for requested architectures
399 __block
std::vector
<MappedMachOsByCategory
> allFileSets
;
400 if ( archStrs
.count("x86_64") )
401 allFileSets
.push_back({"x86_64"});
402 if ( archStrs
.count("i386") )
403 allFileSets
.push_back({"i386"});
404 findAllFiles(rootPath
, platform
, allFileSets
);
405 addMacOSAdditions(allFileSets
);
406 for (MappedMachOsByCategory
& fileSet
: allFileSets
) {
407 pruneCachedDylibs(rootPath
, fileSet
);
410 uint64_t t2
= mach_absolute_time();
412 fprintf(stderr
, "time to scan file system and construct lists of mach-o files: %ums\n", absolutetime_to_milliseconds(t2
-t1
));
414 // build all caches in parallel
415 __block
bool cacheBuildFailure
= false;
416 dispatch_apply(allFileSets
.size(), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT
, 0), ^(size_t index
) {
417 MappedMachOsByCategory
& fileSet
= allFileSets
[index
];
418 const std::string outFile
= cacheDir
+ "/dyld_shared_cache_" + fileSet
.archName
;
419 __block
std::unordered_set
<std::string
> knownMissingDylib
;
421 DyldSharedCache::MappedMachO (^loader
)(const std::string
&) = ^DyldSharedCache::MappedMachO(const std::string
& runtimePath
) {
422 std::string fullPath
= rootPath
+ runtimePath
;
424 if ( stat(fullPath
.c_str(), &statBuf
) == 0 ) {
425 std::vector
<MappedMachOsByCategory
> mappedFiles
;
426 mappedFiles
.push_back({fileSet
.archName
});
427 dyld3::closure::FileSystemPhysical
fileSystem(rootPath
.c_str());
428 if ( addIfMachO(fileSystem
, runtimePath
, statBuf
, platform
, mappedFiles
) ) {
429 if ( !mappedFiles
.back().dylibsForCache
.empty() )
430 return mappedFiles
.back().dylibsForCache
.back();
433 if ( knownMissingDylib
.count(runtimePath
) == 0 ) {
434 fprintf(stderr
, "update_dyld_sim_shared_cache: warning: %s could not use in dylid cache: %s\n", fileSet
.archName
.c_str(), runtimePath
.c_str());
435 knownMissingDylib
.insert(runtimePath
);
437 return DyldSharedCache::MappedMachO();
439 size_t startCount
= fileSet
.dylibsForCache
.size();
440 std::vector
<std::pair
<DyldSharedCache::MappedMachO
, std::set
<std::string
>>> excludes
;
441 DyldSharedCache::verifySelfContained(fileSet
.dylibsForCache
, loader
, excludes
);
442 for (size_t i
=startCount
; i
< fileSet
.dylibsForCache
.size(); ++i
) {
443 fprintf(stderr
, "update_dyld_sim_shared_cache: warning: %s not found in initial scan, but adding required dylib %s\n", fileSet
.archName
.c_str(), fileSet
.dylibsForCache
[i
].runtimePath
.c_str());
445 for (auto& exclude
: excludes
) {
446 std::string reasons
= "(\"";
447 for (auto i
= exclude
.second
.begin(); i
!= exclude
.second
.end(); ++i
) {
449 if (i
!= --exclude
.second
.end()) {
454 fprintf(stderr
, "update_dyld_shared_cache: warning: %s rejected from cached dylibs: %s (%s)\n", fileSet
.archName
.c_str(), exclude
.first
.runtimePath
.c_str(), reasons
.c_str());
455 fileSet
.otherDylibsAndBundles
.push_back(exclude
.first
);
458 // check if cache is already up to date
460 if ( existingCacheUpToDate(outFile
, fileSet
.dylibsForCache
) )
463 fprintf(stderr
, "make %s cache with %lu dylibs, %lu other dylibs, %lu programs\n", fileSet
.archName
.c_str(), fileSet
.dylibsForCache
.size(), fileSet
.otherDylibsAndBundles
.size(), fileSet
.mainExecutables
.size());
465 // build cache new cache file
466 DyldSharedCache::CreateOptions options
;
467 options
.outputFilePath
= outFile
;
468 options
.outputMapFilePath
= cacheDir
+ "/dyld_shared_cache_" + fileSet
.archName
+ ".map";
469 options
.archName
= fileSet
.archName
;
470 options
.platform
= platform
;
471 options
.excludeLocalSymbols
= false;
472 options
.optimizeStubs
= false;
473 options
.optimizeObjC
= true;
474 options
.codeSigningDigestMode
= DyldSharedCache::SHA256only
;
475 options
.dylibsRemovedDuringMastering
= false;
476 options
.inodesAreSameAsRuntime
= true;
477 options
.cacheSupportsASLR
= false;
478 options
.forSimulator
= true;
479 options
.isLocallyBuiltCache
= true;
480 options
.verbose
= verbose
;
481 options
.evictLeafDylibsOnOverflow
= true;
482 options
.pathPrefixes
= { rootPath
};
483 DyldSharedCache::CreateResults results
= DyldSharedCache::create(options
, fileSet
.dylibsForCache
, fileSet
.otherDylibsAndBundles
, fileSet
.mainExecutables
);
485 // print any warnings
486 for (const std::string
& warn
: results
.warnings
) {
487 fprintf(stderr
, "update_dyld_shared_cache: warning: %s %s\n", fileSet
.archName
.c_str(), warn
.c_str());
489 if ( !results
.errorMessage
.empty() ) {
490 fprintf(stderr
, "update_dyld_shared_cache: %s\n", results
.errorMessage
.c_str());
491 cacheBuildFailure
= true;
495 // we could unmap all input files, but tool is about to quit
497 return (cacheBuildFailure
? 1 : 0);