1 /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
3 * Copyright (c) 2014 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>
30 #include <mach-o/dyld.h>
43 #include <sys/param.h>
44 #include <sys/sysctl.h>
45 #include <sys/resource.h>
49 #include <dispatch/dispatch.h>
50 #include <pthread/pthread.h>
52 #include <CoreFoundation/CoreFoundation.h>
56 #include <unordered_set>
57 #include <unordered_set>
61 #include "FileUtils.h"
62 #include "StringUtils.h"
63 #include "DyldSharedCache.h"
64 #include "MachOFile.h"
65 #include "MachOAnalyzer.h"
66 #include "ClosureFileSystemPhysical.h"
68 struct MappedMachOsByCategory
71 std::vector
<DyldSharedCache::MappedMachO
> dylibsForCache
;
72 std::vector
<DyldSharedCache::MappedMachO
> otherDylibsAndBundles
;
73 std::vector
<DyldSharedCache::MappedMachO
> mainExecutables
;
76 static const char* sAllowedPrefixes
[] = {
81 "/Applications/App Store.app/",
82 "/Applications/Automator.app/",
83 "/Applications/Calculator.app/",
84 "/Applications/Calendar.app/",
85 "/Applications/Chess.app/",
86 "/Applications/Contacts.app/",
87 // "/Applications/DVD Player.app/",
88 "/Applications/Dashboard.app/",
89 "/Applications/Dictionary.app/",
90 "/Applications/FaceTime.app/",
91 "/Applications/Font Book.app/",
92 "/Applications/Image Capture.app/",
93 "/Applications/Launchpad.app/",
94 "/Applications/Mail.app/",
95 "/Applications/Maps.app/",
96 "/Applications/Messages.app/",
97 "/Applications/Mission Control.app/",
98 "/Applications/Notes.app/",
99 "/Applications/Photo Booth.app/",
100 // "/Applications/Photos.app/",
101 "/Applications/Preview.app/",
102 "/Applications/QuickTime Player.app/",
103 "/Applications/Reminders.app/",
104 "/Applications/Safari.app/",
105 "/Applications/Siri.app/",
106 "/Applications/Stickies.app/",
107 "/Applications/System Preferences.app/",
108 "/Applications/TextEdit.app/",
109 "/Applications/Time Machine.app/",
110 "/Applications/iBooks.app/",
111 "/Applications/iTunes.app/",
112 "/Applications/Utilities/Activity Monitor.app",
113 "/Applications/Utilities/AirPort Utility.app",
114 "/Applications/Utilities/Audio MIDI Setup.app",
115 "/Applications/Utilities/Bluetooth File Exchange.app",
116 "/Applications/Utilities/Boot Camp Assistant.app",
117 "/Applications/Utilities/ColorSync Utility.app",
118 "/Applications/Utilities/Console.app",
119 "/Applications/Utilities/Digital Color Meter.app",
120 "/Applications/Utilities/Disk Utility.app",
121 "/Applications/Utilities/Grab.app",
122 "/Applications/Utilities/Grapher.app",
123 "/Applications/Utilities/Keychain Access.app",
124 "/Applications/Utilities/Migration Assistant.app",
125 "/Applications/Utilities/Script Editor.app",
126 "/Applications/Utilities/System Information.app",
127 "/Applications/Utilities/Terminal.app",
128 "/Applications/Utilities/VoiceOver Utility.app",
129 "/Library/CoreMediaIO/Plug-Ins/DAL/" // temp until plugins moved or closured working
132 static const char* sDontUsePrefixes
[] = {
135 "/System/Library/Assets",
136 "/System/Library/StagedFrameworks",
137 "/System/Library/Kernels/",
138 "/bin/zsh", // until <rdar://31026756> is fixed
139 "/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/Metadata.framework/Versions/A/Support/mdworker", // these load third party plugins
140 "/usr/bin/mdimport", // these load third party plugins
141 "/System/Library/Developer/CoreSimulator/", // ignore Marzipan
145 static bool verbose
= false;
149 static bool addIfMachO(const dyld3::closure::FileSystem
& fileSystem
, const std::string
& runtimePath
, const struct stat
& statBuf
, bool requireSIP
, std::vector
<MappedMachOsByCategory
>& files
)
151 // don't precompute closure info for any debug or profile dylibs
152 if ( endsWith(runtimePath
, "_profile.dylib") || endsWith(runtimePath
, "_debug.dylib") || endsWith(runtimePath
, "_profile") || endsWith(runtimePath
, "_debug") )
154 if ( startsWith(runtimePath
, "/usr/lib/system/introspection/") )
157 auto warningHandler
= ^(const char* msg
) {
159 fprintf(stderr
, "update_dyld_shared_cache: warning: cannot build dlopen closure for '%s' because %s\n", runtimePath
.c_str(), msg
);
163 for (MappedMachOsByCategory
& file
: files
) {
165 dyld3::closure::LoadedFileInfo loadedFileInfo
= dyld3::MachOAnalyzer::load(diag
, fileSystem
, runtimePath
.c_str(), file
.archName
.c_str(), dyld3::Platform::macOS
);
166 const dyld3::MachOAnalyzer
* ma
= (const dyld3::MachOAnalyzer
*)loadedFileInfo
.fileContent
;
167 if ( ma
!= nullptr ) {
168 bool sipProtected
= false; // isProtectedBySIP(fd);
169 bool issetuid
= false;
170 if ( ma
->isDynamicExecutable() ) {
171 // When SIP enabled, only build closures for SIP protected programs
172 if ( !requireSIP
|| sipProtected
) {
173 //fprintf(stderr, "requireSIP=%d, sipProtected=%d, path=%s\n", requireSIP, sipProtected, fullPath.c_str());
174 issetuid
= (statBuf
.st_mode
& (S_ISUID
|S_ISGID
));
175 file
.mainExecutables
.emplace_back(runtimePath
, ma
, loadedFileInfo
.sliceLen
, issetuid
, sipProtected
, loadedFileInfo
.sliceOffset
, statBuf
.st_mtime
, statBuf
.st_ino
);
178 else if ( ma
->canBePlacedInDyldCache(runtimePath
.c_str(), ^(const char* msg
) {}) ) {
179 // when SIP is enabled, only dylib protected by SIP can go in cache
180 if ( !requireSIP
|| sipProtected
)
181 file
.dylibsForCache
.emplace_back(runtimePath
, ma
, loadedFileInfo
.sliceLen
, issetuid
, sipProtected
, loadedFileInfo
.sliceOffset
, statBuf
.st_mtime
, statBuf
.st_ino
);
182 else if ( ma
->canHavePrecomputedDlopenClosure(runtimePath
.c_str(), warningHandler
) )
183 file
.otherDylibsAndBundles
.emplace_back(runtimePath
, ma
, loadedFileInfo
.sliceLen
, issetuid
, sipProtected
, loadedFileInfo
.sliceOffset
, statBuf
.st_mtime
, statBuf
.st_ino
);
186 if ( ma
->isDylib() ) {
187 std::string installName
= ma
->installName();
188 if ( startsWith(installName
, "@") && !contains(runtimePath
, ".app/") && !contains(runtimePath
, ".xpc/") ) {
189 if ( startsWith(runtimePath
, "/usr/lib/") || startsWith(runtimePath
, "/System/Library/") )
190 fprintf(stderr
, "update_dyld_shared_cache: warning @rpath install name for system framework: %s\n", runtimePath
.c_str());
193 else if ( ma
->canHavePrecomputedDlopenClosure(runtimePath
.c_str(), warningHandler
) ) {
194 file
.otherDylibsAndBundles
.emplace_back(runtimePath
, ma
, loadedFileInfo
.sliceLen
, issetuid
, sipProtected
, loadedFileInfo
.sliceOffset
, statBuf
.st_mtime
, statBuf
.st_ino
);
204 static void findAllFiles(const std::vector
<std::string
>& pathPrefixes
, bool requireSIP
, std::vector
<MappedMachOsByCategory
>& files
)
206 std::unordered_set
<std::string
> skipDirs
;
207 for (const char* s
: sDontUsePrefixes
)
210 __block
std::unordered_set
<std::string
> alreadyUsed
;
211 bool multiplePrefixes
= (pathPrefixes
.size() > 1);
212 for (const std::string
& prefix
: pathPrefixes
) {
213 // get all files from overlay for this search dir
214 dyld3::closure::FileSystemPhysical
fileSystem(prefix
.c_str());
215 for (const char* searchDir
: sAllowedPrefixes
) {
216 iterateDirectoryTree(prefix
, searchDir
, ^(const std::string
& dirPath
) { return (skipDirs
.count(dirPath
) != 0); }, ^(const std::string
& path
, const struct stat
& statBuf
) {
217 // ignore files that don't have 'x' bit set (all runnable mach-o files do)
218 const bool hasXBit
= ((statBuf
.st_mode
& S_IXOTH
) == S_IXOTH
);
219 if ( !hasXBit
&& !endsWith(path
, ".dylib") )
222 // ignore files too small
223 if ( statBuf
.st_size
< 0x3000 )
226 // don't add paths already found using previous prefix
227 if ( multiplePrefixes
&& (alreadyUsed
.count(path
) != 0) )
230 // if the file is mach-o, add to list
231 if ( addIfMachO(fileSystem
, path
, statBuf
, requireSIP
, files
) ) {
232 if ( multiplePrefixes
)
233 alreadyUsed
.insert(path
);
241 static void findOSFilesViaBOMS(const std::vector
<std::string
>& pathPrefixes
, bool requireSIP
, std::vector
<MappedMachOsByCategory
>& files
)
243 __block
std::unordered_set
<std::string
> runtimePathsFound
;
244 for (const std::string
& prefix
: pathPrefixes
) {
245 iterateDirectoryTree(prefix
, "/System/Library/Receipts", ^(const std::string
&) { return false; }, ^(const std::string
& path
, const struct stat
& statBuf
) {
246 if ( !contains(path
, "com.apple.pkg.") )
248 if ( !endsWith(path
, ".bom") )
250 std::string fullPath
= prefix
+ path
;
251 BOMBom bom
= BOMBomOpenWithSys(fullPath
.c_str(), false, NULL
);
252 if ( bom
== nullptr )
254 BOMFSObject rootFso
= BOMBomGetRootFSObject(bom
);
255 if ( rootFso
== nullptr ) {
259 BOMBomEnumerator e
= BOMBomEnumeratorNew(bom
, rootFso
);
260 if ( e
== nullptr ) {
261 fprintf(stderr
, "Can't get enumerator for BOM root FSObject\n");
264 BOMFSObjectFree(rootFso
);
265 //fprintf(stderr, "using BOM %s\n", path.c_str());
266 while (BOMFSObject fso
= BOMBomEnumeratorNext(e
)) {
267 if ( BOMFSObjectIsBinaryObject(fso
) ) {
268 const char* runPath
= BOMFSObjectPathName(fso
);
269 if ( (runPath
[0] == '.') && (runPath
[1] == '/') )
271 if ( runtimePathsFound
.count(runPath
) == 0 ) {
272 // only add files from sAllowedPrefixes and not in sDontUsePrefixes
273 bool inSearchDir
= false;
274 for (const char* searchDir
: sAllowedPrefixes
) {
275 if ( strncmp(searchDir
, runPath
, strlen(searchDir
)) == 0 ) {
281 bool inSkipDir
= false;
282 for (const char* skipDir
: sDontUsePrefixes
) {
283 if ( strncmp(skipDir
, runPath
, strlen(skipDir
)) == 0 ) {
289 for (const std::string
& prefix2
: pathPrefixes
) {
290 struct stat statBuf2
;
291 std::string fullPath2
= prefix2
+ runPath
;
292 if ( stat(fullPath2
.c_str(), &statBuf2
) == 0 ) {
293 dyld3::closure::FileSystemPhysical
fileSystem(prefix2
.c_str());
294 addIfMachO(fileSystem
, runPath
, statBuf2
, requireSIP
, files
);
295 runtimePathsFound
.insert(runPath
);
303 BOMFSObjectFree(fso
);
306 BOMBomEnumeratorFree(e
);
313 static bool dontCache(const std::string
& volumePrefix
, const std::string
& archName
,
314 const std::unordered_set
<std::string
>& pathsWithDuplicateInstallName
,
315 const DyldSharedCache::MappedMachO
& aFile
, bool warn
,
316 const std::unordered_set
<std::string
>& skipDylibs
)
318 if ( skipDylibs
.count(aFile
.runtimePath
) )
320 if ( startsWith(aFile
.runtimePath
, "/usr/lib/system/introspection/") )
322 if ( startsWith(aFile
.runtimePath
, "/System/Library/QuickTime/") )
324 if ( startsWith(aFile
.runtimePath
, "/System/Library/Tcl/") )
326 if ( startsWith(aFile
.runtimePath
, "/System/Library/Perl/") )
328 if ( startsWith(aFile
.runtimePath
, "/System/Library/MonitorPanels/") )
330 if ( startsWith(aFile
.runtimePath
, "/System/Library/Accessibility/") )
332 if ( startsWith(aFile
.runtimePath
, "/usr/local/") )
335 // anything inside a .app bundle is specific to app, so should not be in shared cache
336 if ( aFile
.runtimePath
.find(".app/") != std::string::npos
)
339 if ( archName
== "i386" ) {
340 if ( startsWith(aFile
.runtimePath
, "/System/Library/CoreServices/") )
342 if ( startsWith(aFile
.runtimePath
, "/System/Library/Extensions/") )
346 if ( aFile
.runtimePath
.find("//") != std::string::npos
) {
347 if (warn
) fprintf(stderr
, "update_dyld_shared_cache: warning: %s skipping because of bad install name %s\n", archName
.c_str(), aFile
.runtimePath
.c_str());
351 const char* installName
= aFile
.mh
->installName();
352 if ( (pathsWithDuplicateInstallName
.count(aFile
.runtimePath
) != 0) && (aFile
.runtimePath
!= installName
) ) {
353 if (warn
) fprintf(stderr
, "update_dyld_shared_cache: warning: %s skipping because of duplicate install name %s\n", archName
.c_str(), aFile
.runtimePath
.c_str());
357 if ( aFile
.runtimePath
!= installName
) {
358 // see if install name is a symlink to actual path
359 std::string fullInstall
= volumePrefix
+ installName
;
360 char resolvedPath
[PATH_MAX
];
361 if ( realpath(fullInstall
.c_str(), resolvedPath
) != NULL
) {
362 std::string resolvedSymlink
= resolvedPath
;
363 if ( !volumePrefix
.empty() ) {
364 resolvedSymlink
= resolvedSymlink
.substr(volumePrefix
.size());
366 if ( aFile
.runtimePath
== resolvedSymlink
) {
370 // <rdar://problem/38000411> also if runtime path is a symlink to install name
371 std::string fullRuntime
= volumePrefix
+ aFile
.runtimePath
;
372 if ( realpath(fullRuntime
.c_str(), resolvedPath
) != NULL
) {
373 std::string resolvedSymlink
= resolvedPath
;
374 if ( !volumePrefix
.empty() ) {
375 resolvedSymlink
= resolvedSymlink
.substr(volumePrefix
.size());
377 if ( resolvedSymlink
== installName
) {
381 if (warn
) fprintf(stderr
, "update_dyld_shared_cache: warning: %s skipping because of bad install name %s\n", archName
.c_str(), aFile
.runtimePath
.c_str());
387 static void pruneCachedDylibs(const std::string
& volumePrefix
, const std::unordered_set
<std::string
>& skipDylibs
, MappedMachOsByCategory
& fileSet
)
389 std::unordered_set
<std::string
> pathsWithDuplicateInstallName
;
391 std::unordered_map
<std::string
, std::string
> installNameToFirstPath
;
392 for (DyldSharedCache::MappedMachO
& aFile
: fileSet
.dylibsForCache
) {
393 const char* installName
= aFile
.mh
->installName();
394 auto pos
= installNameToFirstPath
.find(installName
);
395 if ( pos
== installNameToFirstPath
.end() ) {
396 installNameToFirstPath
[installName
] = aFile
.runtimePath
;
399 pathsWithDuplicateInstallName
.insert(aFile
.runtimePath
);
400 pathsWithDuplicateInstallName
.insert(installNameToFirstPath
[installName
]);
404 for (DyldSharedCache::MappedMachO
& aFile
: fileSet
.dylibsForCache
) {
405 if ( dontCache(volumePrefix
, fileSet
.archName
, pathsWithDuplicateInstallName
, aFile
, true, skipDylibs
) )
406 fileSet
.otherDylibsAndBundles
.push_back(aFile
);
408 fileSet
.dylibsForCache
.erase(std::remove_if(fileSet
.dylibsForCache
.begin(), fileSet
.dylibsForCache
.end(),
409 [&](const DyldSharedCache::MappedMachO
& aFile
) { return dontCache(volumePrefix
, fileSet
.archName
, pathsWithDuplicateInstallName
, aFile
, false, skipDylibs
); }),
410 fileSet
.dylibsForCache
.end());
413 static void pruneOtherDylibs(const std::string
& volumePrefix
, MappedMachOsByCategory
& fileSet
)
415 // other OS dylibs should not contain dylibs that are embedded in some .app bundle
416 fileSet
.otherDylibsAndBundles
.erase(std::remove_if(fileSet
.otherDylibsAndBundles
.begin(), fileSet
.otherDylibsAndBundles
.end(),
417 [&](const DyldSharedCache::MappedMachO
& aFile
) { return (aFile
.runtimePath
.find(".app/") != std::string::npos
); }),
418 fileSet
.otherDylibsAndBundles
.end());
420 static void pruneExecutables(const std::string
& volumePrefix
, MappedMachOsByCategory
& fileSet
)
422 // don't build closures for xcode shims in /usr/bin (e.g. /usr/bin/clang) which re-exec themselves to a tool inside Xcode.app
423 fileSet
.mainExecutables
.erase(std::remove_if(fileSet
.mainExecutables
.begin(), fileSet
.mainExecutables
.end(),
424 [&](const DyldSharedCache::MappedMachO
& aFile
) {
425 if ( !startsWith(aFile
.runtimePath
, "/usr/bin/") )
427 __block
bool isXcodeShim
= false;
428 aFile
.mh
->forEachDependentDylib(^(const char* loadPath
, bool, bool, bool, uint32_t, uint32_t, bool &stop
) {
429 if ( strcmp(loadPath
, "/usr/lib/libxcselect.dylib") == 0 )
433 }), fileSet
.mainExecutables
.end());
436 static bool existingCacheUpToDate(const std::string
& existingCache
, const std::vector
<DyldSharedCache::MappedMachO
>& currentDylibs
)
438 // if no existing cache, it is not up-to-date
439 int fd
= ::open(existingCache
.c_str(), O_RDONLY
);
443 // build map of found dylibs
444 std::unordered_map
<std::string
, const DyldSharedCache::MappedMachO
*> currentDylibMap
;
445 for (const DyldSharedCache::MappedMachO
& aFile
: currentDylibs
) {
446 //fprintf(stderr, "0x%0llX 0x%0llX %s\n", aFile.inode, aFile.modTime, aFile.runtimePath.c_str());
447 currentDylibMap
[aFile
.runtimePath
] = &aFile
;
450 // make sure all dylibs in existing cache have same mtime and inode as found dylib
451 __block
bool foundMismatch
= false;
452 const uint64_t cacheMapLen
= 0x40000000;
453 void *p
= ::mmap(NULL
, cacheMapLen
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
454 if ( p
!= MAP_FAILED
) {
455 const DyldSharedCache
* cache
= (DyldSharedCache
*)p
;
456 cache
->forEachImageEntry(^(const char* installName
, uint64_t mTime
, uint64_t inode
) {
457 bool foundMatch
= false;
458 auto pos
= currentDylibMap
.find(installName
);
459 if ( pos
!= currentDylibMap
.end() ) {
460 const DyldSharedCache::MappedMachO
* foundDylib
= pos
->second
;
461 if ( (foundDylib
->inode
== inode
) && (foundDylib
->modTime
== mTime
) ) {
466 // use slow path and look for any dylib with a matching inode and mtime
467 bool foundSlow
= false;
468 for (const DyldSharedCache::MappedMachO
& aFile
: currentDylibs
) {
469 if ( (aFile
.inode
== inode
) && (aFile
.modTime
== mTime
) ) {
475 foundMismatch
= true;
477 fprintf(stderr
, "rebuilding dyld cache because dylib changed: %s\n", installName
);
481 ::munmap(p
, cacheMapLen
);
486 return !foundMismatch
;
490 inline uint32_t absolutetime_to_milliseconds(uint64_t abstime
)
492 return (uint32_t)(abstime
/1000/1000);
495 static bool runningOnHaswell()
497 // check system is capable of running x86_64h code
498 struct host_basic_info info
;
499 mach_msg_type_number_t count
= HOST_BASIC_INFO_COUNT
;
500 mach_port_t hostPort
= mach_host_self();
501 kern_return_t result
= host_info(hostPort
, HOST_BASIC_INFO
, (host_info_t
)&info
, &count
);
502 mach_port_deallocate(mach_task_self(), hostPort
);
504 return ( (result
== KERN_SUCCESS
) && (info
.cpu_subtype
== CPU_SUBTYPE_X86_64_H
) );
509 #define TERMINATE_IF_LAST_ARG( s ) \
511 if ( i == argc - 1 ) { \
512 fprintf(stderr, s ); \
517 int main(int argc
, const char* argv
[], const char* envp
[])
519 std::string rootPath
;
520 std::string overlayPath
;
521 std::string dylibListFile
;
522 bool universal
= false;
524 bool searchDisk
= false;
525 bool dylibsRemoved
= false;
526 std::string cacheDir
;
527 std::unordered_set
<std::string
> archStrs
;
528 std::unordered_set
<std::string
> skipDylibs
;
530 // parse command line options
531 for (int i
= 1; i
< argc
; ++i
) {
532 const char* arg
= argv
[i
];
533 if (strcmp(arg
, "-debug") == 0) {
536 else if (strcmp(arg
, "-verbose") == 0) {
539 else if (strcmp(arg
, "-dont_map_local_symbols") == 0) {
540 //We are going to ignore this
542 else if (strcmp(arg
, "-dylib_list") == 0) {
543 TERMINATE_IF_LAST_ARG("-dylib_list missing argument");
544 dylibListFile
= argv
[++i
];
546 else if ((strcmp(arg
, "-root") == 0) || (strcmp(arg
, "--root") == 0)) {
547 TERMINATE_IF_LAST_ARG("-root missing path argument\n");
548 rootPath
= argv
[++i
];
550 else if (strcmp(arg
, "-overlay") == 0) {
551 TERMINATE_IF_LAST_ARG("-overlay missing path argument\n");
552 overlayPath
= argv
[++i
];
554 else if (strcmp(arg
, "-cache_dir") == 0) {
555 TERMINATE_IF_LAST_ARG("-cache_dir missing path argument\n");
556 cacheDir
= argv
[++i
];
558 else if (strcmp(arg
, "-arch") == 0) {
559 TERMINATE_IF_LAST_ARG("-arch missing argument\n");
560 archStrs
.insert(argv
[++i
]);
562 else if (strcmp(arg
, "-search_disk") == 0) {
565 else if (strcmp(arg
, "-dylibs_removed_in_mastering") == 0) {
566 dylibsRemoved
= true;
568 else if (strcmp(arg
, "-force") == 0) {
571 else if (strcmp(arg
, "-sort_by_name") == 0) {
572 //No-op, we always do this now
574 else if (strcmp(arg
, "-universal_boot") == 0) {
577 else if (strcmp(arg
, "-skip") == 0) {
578 TERMINATE_IF_LAST_ARG("-skip missing argument\n");
579 skipDylibs
.insert(argv
[++i
]);
583 fprintf(stderr
, "update_dyld_shared_cache: unknown option: %s\n", arg
);
588 if ( !rootPath
.empty() & !overlayPath
.empty() ) {
589 fprintf(stderr
, "-root and -overlay cannot be used together\n");
592 // canonicalize rootPath
593 if ( !rootPath
.empty() ) {
594 char resolvedPath
[PATH_MAX
];
595 if ( realpath(rootPath
.c_str(), resolvedPath
) != NULL
) {
596 rootPath
= resolvedPath
;
598 // <rdar://problem/33223984> when building closures for boot volume, pathPrefixes should be empty
599 if ( rootPath
== "/" ) {
603 // canonicalize overlayPath
604 if ( !overlayPath
.empty() ) {
605 char resolvedPath
[PATH_MAX
];
606 if ( realpath(overlayPath
.c_str(), resolvedPath
) != NULL
) {
607 overlayPath
= resolvedPath
;
611 // <rdar://problem/36362221> update_dyld_shared_cache should re-exec() itself to a newer version
613 if ( !rootPath
.empty() )
614 newTool
= rootPath
+ "/usr/bin/update_dyld_shared_cache";
615 else if ( !overlayPath
.empty() )
616 newTool
= overlayPath
+ "/usr/bin/update_dyld_shared_cache";
617 if ( !newTool
.empty() ) {
618 struct stat newToolStatBuf
;
619 if ( stat(newTool
.c_str(), &newToolStatBuf
) == 0 ) {
620 char curToolPath
[PATH_MAX
];
621 uint32_t curToolPathsize
= PATH_MAX
;
622 int result
= _NSGetExecutablePath(curToolPath
, &curToolPathsize
);
624 char resolvedCurToolPath
[PATH_MAX
];
625 if ( realpath(curToolPath
, resolvedCurToolPath
) != NULL
) {
626 // don't re-exec if we are already running that tool
627 if ( newTool
!= resolvedCurToolPath
) {
628 execve(newTool
.c_str(), (char**)argv
, (char**)envp
);
636 // pathPrefixes for three modes:
637 // 1) no options: { "" } // search only boot volume
638 // 2) -overlay: { overlay, "" } // search overlay, then boot volume
639 // 3) -root: { root } // search only -root volume
641 std::vector
<std::string
> pathPrefixes
;
642 if ( !overlayPath
.empty() )
643 pathPrefixes
.push_back(overlayPath
);
644 pathPrefixes
.push_back(rootPath
);
647 if ( cacheDir
.empty() ) {
648 // if -cache_dir is not specified, then write() will eventually fail if we are not running as root
649 if ( geteuid() != 0 ) {
650 fprintf(stderr
, "update_dyld_shared_cache: must be run as root (sudo)\n");
654 // write cache file into -root or -overlay directory, if used
655 if ( rootPath
!= "/" )
656 cacheDir
= rootPath
+ MACOSX_DYLD_SHARED_CACHE_DIR
;
657 else if ( !overlayPath
.empty() )
658 cacheDir
= overlayPath
+ MACOSX_DYLD_SHARED_CACHE_DIR
;
660 cacheDir
= MACOSX_DYLD_SHARED_CACHE_DIR
;
663 int err
= mkpath_np(cacheDir
.c_str(), S_IRWXU
| S_IRGRP
|S_IXGRP
| S_IROTH
|S_IXOTH
);
664 if ( (err
!= 0) && (err
!= EEXIST
) ) {
665 fprintf(stderr
, "update_dyld_shared_cache: could not access cache dir: mkpath_np(%s) failed errno=%d\n", cacheDir
.c_str(), err
);
669 if ( archStrs
.empty() ) {
671 // <rdar://problem/26182089> -universal_boot should make all possible dyld caches
672 archStrs
.insert("i386");
673 archStrs
.insert("x86_64");
674 archStrs
.insert("x86_64h");
677 // just make caches for this machine
678 archStrs
.insert("i386");
679 archStrs
.insert(runningOnHaswell() ? "x86_64h" : "x86_64");
683 uint64_t t1
= mach_absolute_time();
685 // find all mach-o files for requested architectures
686 bool requireDylibsBeRootlessProtected
= isProtectedBySIP(cacheDir
);
687 __block
std::vector
<MappedMachOsByCategory
> allFileSets
;
688 if ( archStrs
.count("x86_64") )
689 allFileSets
.push_back({"x86_64"});
690 if ( archStrs
.count("x86_64h") )
691 allFileSets
.push_back({"x86_64h"});
692 if ( archStrs
.count("i386") )
693 allFileSets
.push_back({"i386"});
695 findAllFiles(pathPrefixes
, requireDylibsBeRootlessProtected
, allFileSets
);
697 std::unordered_set
<std::string
> runtimePathsFound
;
698 findOSFilesViaBOMS(pathPrefixes
, requireDylibsBeRootlessProtected
, allFileSets
);
701 // nothing in OS uses i386 dylibs, so only dylibs used by third party apps need to be in cache
702 for (MappedMachOsByCategory
& fileSet
: allFileSets
) {
703 pruneCachedDylibs(rootPath
, skipDylibs
, fileSet
);
704 pruneOtherDylibs(rootPath
, fileSet
);
705 pruneExecutables(rootPath
, fileSet
);
708 uint64_t t2
= mach_absolute_time();
711 fprintf(stderr
, "time to scan file system and construct lists of mach-o files: %ums\n", absolutetime_to_milliseconds(t2
-t1
));
713 fprintf(stderr
, "time to read BOM and construct lists of mach-o files: %ums\n", absolutetime_to_milliseconds(t2
-t1
));
716 // build caches in parallel on machines with at leat 4GB of RAM
717 uint64_t memSize
= 0;
718 size_t sz
= sizeof(memSize
);;
719 bool buildInParallel
= false;
720 if ( sysctlbyname("hw.memsize", &memSize
, &sz
, NULL
, 0) == 0 ) {
721 if ( memSize
>= 0x100000000ULL
)
722 buildInParallel
= true;
724 dispatch_queue_t dqueue
= buildInParallel
? dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT
, 0)
725 : dispatch_queue_create("serial-queue", DISPATCH_QUEUE_SERIAL
);
728 __block
bool cacheBuildFailure
= false;
729 __block
bool wroteSomeCacheFile
= false;
730 dispatch_apply(allFileSets
.size(), dqueue
, ^(size_t index
) {
731 MappedMachOsByCategory
& fileSet
= allFileSets
[index
];
732 const std::string outFile
= cacheDir
+ "/dyld_shared_cache_" + fileSet
.archName
;
734 DyldSharedCache::MappedMachO (^loader
)(const std::string
&) = ^DyldSharedCache::MappedMachO(const std::string
& runtimePath
) {
735 if ( skipDylibs
.count(runtimePath
) )
736 return DyldSharedCache::MappedMachO();
737 for (const std::string
& prefix
: pathPrefixes
) {
738 std::string fullPath
= prefix
+ runtimePath
;
740 if ( stat(fullPath
.c_str(), &statBuf
) == 0 ) {
741 dyld3::closure::FileSystemPhysical
fileSystem(prefix
.c_str());
742 char resolvedPath
[PATH_MAX
];
743 if ( realpath(fullPath
.c_str(), resolvedPath
) != NULL
) {
744 std::string resolvedSymlink
= resolvedPath
;
745 if ( !rootPath
.empty() ) {
746 resolvedSymlink
= resolvedSymlink
.substr(rootPath
.size());
748 if ( (runtimePath
!= resolvedSymlink
) && !contains(runtimePath
, "InputContext") ) { //HACK remove InputContext when fixed
749 // path requested is a symlink path, check if real path already loaded
750 for (const DyldSharedCache::MappedMachO
& aDylibMapping
: fileSet
.dylibsForCache
) {
751 if ( aDylibMapping
.runtimePath
== resolvedSymlink
) {
753 fprintf(stderr
, "verifySelfContained, redirect %s to %s\n", runtimePath
.c_str(), aDylibMapping
.runtimePath
.c_str());
754 return aDylibMapping
;
760 std::vector
<MappedMachOsByCategory
> mappedFiles
;
761 mappedFiles
.push_back({fileSet
.archName
});
762 if ( addIfMachO(fileSystem
, runtimePath
, statBuf
, requireDylibsBeRootlessProtected
, mappedFiles
) ) {
763 if ( !mappedFiles
.back().dylibsForCache
.empty() ) {
765 fprintf(stderr
, "verifySelfContained, add %s\n", mappedFiles
.back().dylibsForCache
.back().runtimePath
.c_str());
766 return mappedFiles
.back().dylibsForCache
.back();
771 return DyldSharedCache::MappedMachO();
773 size_t startCount
= fileSet
.dylibsForCache
.size();
774 std::vector
<std::pair
<DyldSharedCache::MappedMachO
, std::set
<std::string
>>> excludes
;
775 DyldSharedCache::verifySelfContained(fileSet
.dylibsForCache
, loader
, excludes
);
776 for (size_t i
=startCount
; i
< fileSet
.dylibsForCache
.size(); ++i
) {
777 fprintf(stderr
, "update_dyld_shared_cache: warning: %s not in .bom, but adding required dylib %s\n", fileSet
.archName
.c_str(), fileSet
.dylibsForCache
[i
].runtimePath
.c_str());
779 for (auto& exclude
: excludes
) {
780 std::string reasons
= "(\"";
781 for (auto i
= exclude
.second
.begin(); i
!= exclude
.second
.end(); ++i
) {
783 if (i
!= --exclude
.second
.end()) {
788 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());
789 fileSet
.otherDylibsAndBundles
.push_back(exclude
.first
);
792 // check if cache is already up to date
794 if ( existingCacheUpToDate(outFile
, fileSet
.dylibsForCache
) )
798 // add any extra dylibs needed which were not in .bom
799 fprintf(stderr
, "update_dyld_shared_cache: %s incorporating %lu OS dylibs, tracking %lu others, building closures for %lu executables\n",
800 fileSet
.archName
.c_str(), fileSet
.dylibsForCache
.size(), fileSet
.otherDylibsAndBundles
.size(), fileSet
.mainExecutables
.size());
801 //for (const DyldSharedCache::MappedMachO& aFile : fileSet.otherDylibsAndBundles) {
802 // fprintf(stderr, " %s\n", aFile.runtimePath.c_str());
806 // build cache new cache file
807 DyldSharedCache::CreateOptions options
;
808 options
.outputFilePath
= outFile
;
809 options
.outputMapFilePath
= cacheDir
+ "/dyld_shared_cache_" + fileSet
.archName
+ ".map";
810 options
.archName
= fileSet
.archName
;
811 options
.platform
= dyld3::Platform::macOS
;
812 options
.excludeLocalSymbols
= false;
813 options
.optimizeStubs
= false;
814 options
.optimizeObjC
= true;
815 options
.codeSigningDigestMode
= DyldSharedCache::SHA256only
;
816 options
.dylibsRemovedDuringMastering
= dylibsRemoved
;
817 options
.inodesAreSameAsRuntime
= true;
818 options
.cacheSupportsASLR
= (fileSet
.archName
!= "i386");
819 options
.forSimulator
= false;
820 options
.isLocallyBuiltCache
= true;
821 options
.verbose
= verbose
;
822 options
.evictLeafDylibsOnOverflow
= true;
823 options
.pathPrefixes
= pathPrefixes
;
824 DyldSharedCache::CreateResults results
= DyldSharedCache::create(options
, fileSet
.dylibsForCache
, fileSet
.otherDylibsAndBundles
, fileSet
.mainExecutables
);
826 // print any warnings
827 for (const std::string
& warn
: results
.warnings
) {
828 fprintf(stderr
, "update_dyld_shared_cache: warning: %s %s\n", fileSet
.archName
.c_str(), warn
.c_str());
830 if ( results
.errorMessage
.empty() ) {
831 wroteSomeCacheFile
= true;
834 fprintf(stderr
, "update_dyld_shared_cache: %s\n", results
.errorMessage
.c_str());
835 cacheBuildFailure
= true;
840 // Save off spintrace data
841 if ( wroteSomeCacheFile
) {
842 void* h
= dlopen("/usr/lib/libdscsym.dylib", 0);
843 if ( h
!= nullptr ) {
844 typedef int (*dscym_func
)(const char*);
845 dscym_func func
= (dscym_func
)dlsym(h
, "dscsym_save_dscsyms_for_current_caches");
846 std::string nuggetRoot
= rootPath
;
847 if ( nuggetRoot
.empty() )
848 nuggetRoot
= overlayPath
;
849 if ( nuggetRoot
.empty() )
851 (*func
)(nuggetRoot
.c_str());
856 // we could unmap all input files, but tool is about to quit
858 return (cacheBuildFailure
? 1 : 0);