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>
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>
51 #include <CoreFoundation/CoreFoundation.h>
55 #include <unordered_set>
56 #include <unordered_set>
60 #include "MachOParser.h"
61 #include "FileUtils.h"
62 #include "StringUtils.h"
63 #include "DyldSharedCache.h"
65 struct MappedMachOsByCategory
68 std::vector
<DyldSharedCache::MappedMachO
> dylibsForCache
;
69 std::vector
<DyldSharedCache::MappedMachO
> otherDylibsAndBundles
;
70 std::vector
<DyldSharedCache::MappedMachO
> mainExecutables
;
73 static const char* sAllowedPrefixes
[] = {
78 "/Applications/App Store.app/",
79 "/Applications/Automator.app/",
80 "/Applications/Calculator.app/",
81 "/Applications/Calendar.app/",
82 "/Applications/Chess.app/",
83 "/Applications/Contacts.app/",
84 // "/Applications/DVD Player.app/",
85 "/Applications/Dashboard.app/",
86 "/Applications/Dictionary.app/",
87 "/Applications/FaceTime.app/",
88 "/Applications/Font Book.app/",
89 "/Applications/Image Capture.app/",
90 "/Applications/Launchpad.app/",
91 "/Applications/Mail.app/",
92 "/Applications/Maps.app/",
93 "/Applications/Messages.app/",
94 "/Applications/Mission Control.app/",
95 "/Applications/Notes.app/",
96 "/Applications/Photo Booth.app/",
97 // "/Applications/Photos.app/",
98 "/Applications/Preview.app/",
99 "/Applications/QuickTime Player.app/",
100 "/Applications/Reminders.app/",
101 "/Applications/Safari.app/",
102 "/Applications/Siri.app/",
103 "/Applications/Stickies.app/",
104 "/Applications/System Preferences.app/",
105 "/Applications/TextEdit.app/",
106 "/Applications/Time Machine.app/",
107 "/Applications/iBooks.app/",
108 "/Applications/iTunes.app/",
109 "/Applications/Utilities/Activity Monitor.app",
110 "/Applications/Utilities/AirPort Utility.app",
111 "/Applications/Utilities/Audio MIDI Setup.app",
112 "/Applications/Utilities/Bluetooth File Exchange.app",
113 "/Applications/Utilities/Boot Camp Assistant.app",
114 "/Applications/Utilities/ColorSync Utility.app",
115 "/Applications/Utilities/Console.app",
116 "/Applications/Utilities/Digital Color Meter.app",
117 "/Applications/Utilities/Disk Utility.app",
118 "/Applications/Utilities/Grab.app",
119 "/Applications/Utilities/Grapher.app",
120 "/Applications/Utilities/Keychain Access.app",
121 "/Applications/Utilities/Migration Assistant.app",
122 "/Applications/Utilities/Script Editor.app",
123 "/Applications/Utilities/System Information.app",
124 "/Applications/Utilities/Terminal.app",
125 "/Applications/Utilities/VoiceOver Utility.app",
126 "/Library/CoreMediaIO/Plug-Ins/DAL/" // temp until plugins moved or closured working
129 static const char* sDontUsePrefixes
[] = {
132 "/System/Library/Assets",
133 "/System/Library/StagedFrameworks",
134 "/System/Library/Kernels/",
135 "/bin/zsh", // until <rdar://31026756> is fixed
136 "/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/Metadata.framework/Versions/A/Support/mdworker", // these load third party plugins
137 "/usr/bin/mdimport", // these load third party plugins
141 static bool verbose
= false;
145 static bool addIfMachO(const std::string
& pathPrefix
, const std::string
& runtimePath
, const struct stat
& statBuf
, bool requireSIP
, std::vector
<MappedMachOsByCategory
>& files
)
147 // don't precompute closure info for any debug or profile dylibs
148 if ( endsWith(runtimePath
, "_profile.dylib") || endsWith(runtimePath
, "_debug.dylib") || endsWith(runtimePath
, "_profile") || endsWith(runtimePath
, "_debug") )
151 // read start of file to determine if it is mach-o or a fat file
152 std::string fullPath
= pathPrefix
+ runtimePath
;
153 int fd
= ::open(fullPath
.c_str(), O_RDONLY
);
157 const void* wholeFile
= ::mmap(NULL
, statBuf
.st_size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
158 if ( wholeFile
!= MAP_FAILED
) {
160 bool usedWholeFile
= false;
161 for (MappedMachOsByCategory
& file
: files
) {
164 bool fatButMissingSlice
;
165 const void* slice
= MAP_FAILED
;
166 if ( dyld3::FatUtil::isFatFileWithSlice(diag
, wholeFile
, statBuf
.st_size
, file
.archName
, sliceOffset
, sliceLength
, fatButMissingSlice
) ) {
167 slice
= ::mmap(NULL
, sliceLength
, PROT_READ
, MAP_PRIVATE
| MAP_RESILIENT_CODESIGN
, fd
, sliceOffset
);
168 if ( slice
!= MAP_FAILED
) {
169 //fprintf(stderr, "mapped slice at %p size=0x%0lX, offset=0x%0lX for %s\n", p, len, offset, fullPath.c_str());
170 if ( !dyld3::MachOParser::isValidMachO(diag
, file
.archName
, dyld3::Platform::macOS
, slice
, sliceLength
, fullPath
.c_str(), false) ) {
171 ::munmap((void*)slice
, sliceLength
);
176 else if ( !fatButMissingSlice
&& dyld3::MachOParser::isValidMachO(diag
, file
.archName
, dyld3::Platform::macOS
, wholeFile
, statBuf
.st_size
, fullPath
.c_str(), false) ) {
178 sliceLength
= statBuf
.st_size
;
180 usedWholeFile
= true;
181 //fprintf(stderr, "mapped whole file at %p size=0x%0lX for %s\n", p, len, inputPath.c_str());
183 std::vector
<std::string
> nonArchWarnings
;
184 for (const std::string
& warning
: diag
.warnings()) {
185 if ( !contains(warning
, "required architecture") && !contains(warning
, "not a dylib") )
186 nonArchWarnings
.push_back(warning
);
188 diag
.clearWarnings();
189 if ( !nonArchWarnings
.empty() ) {
190 fprintf(stderr
, "update_dyld_shared_cache: warning: %s for %s: ", file
.archName
.c_str(), runtimePath
.c_str());
191 for (const std::string
& warning
: nonArchWarnings
) {
192 fprintf(stderr
, "%s ", warning
.c_str());
194 fprintf(stderr
, "\n");
196 if ( slice
!= MAP_FAILED
) {
197 const mach_header
* mh
= (mach_header
*)slice
;
198 dyld3::MachOParser
parser((mach_header
*)slice
);
199 bool sipProtected
= isProtectedBySIP(fd
);
200 bool issetuid
= false;
201 if ( parser
.isDynamicExecutable() ) {
202 // When SIP enabled, only build closures for SIP protected programs
203 if ( !requireSIP
|| sipProtected
) {
204 //fprintf(stderr, "requireSIP=%d, sipProtected=%d, path=%s\n", requireSIP, sipProtected, fullPath.c_str());
205 issetuid
= (statBuf
.st_mode
& (S_ISUID
|S_ISGID
));
206 file
.mainExecutables
.emplace_back(runtimePath
, mh
, sliceLength
, issetuid
, sipProtected
, sliceOffset
, statBuf
.st_mtime
, statBuf
.st_ino
);
209 else if ( parser
.canBePlacedInDyldCache(runtimePath
) ) {
210 // when SIP is enabled, only dylib protected by SIP can go in cache
211 if ( !requireSIP
|| sipProtected
)
212 file
.dylibsForCache
.emplace_back(runtimePath
, mh
, sliceLength
, issetuid
, sipProtected
, sliceOffset
, statBuf
.st_mtime
, statBuf
.st_ino
);
214 file
.otherDylibsAndBundles
.emplace_back(runtimePath
, mh
, sliceLength
, issetuid
, sipProtected
, sliceOffset
, statBuf
.st_mtime
, statBuf
.st_ino
);
217 if ( parser
.fileType() == MH_DYLIB
) {
218 std::string installName
= parser
.installName();
219 if ( startsWith(installName
, "@") && !contains(runtimePath
, ".app/") ) {
220 if ( startsWith(runtimePath
, "/usr/lib/") || startsWith(runtimePath
, "/System/Library/") )
221 fprintf(stderr
, "update_dyld_shared_cache: warning @rpath install name for system framework: %s\n", runtimePath
.c_str());
224 file
.otherDylibsAndBundles
.emplace_back(runtimePath
, mh
, sliceLength
, issetuid
, sipProtected
, sliceOffset
, statBuf
.st_mtime
, statBuf
.st_ino
);
229 if ( !usedWholeFile
)
230 ::munmap((void*)wholeFile
, statBuf
.st_size
);
236 static void findAllFiles(const std::vector
<std::string
>& pathPrefixes
, bool requireSIP
, std::vector
<MappedMachOsByCategory
>& files
)
238 std::unordered_set
<std::string
> skipDirs
;
239 for (const char* s
: sDontUsePrefixes
)
242 __block
std::unordered_set
<std::string
> alreadyUsed
;
243 bool multiplePrefixes
= (pathPrefixes
.size() > 1);
244 for (const std::string
& prefix
: pathPrefixes
) {
245 // get all files from overlay for this search dir
246 for (const char* searchDir
: sAllowedPrefixes
) {
247 iterateDirectoryTree(prefix
, searchDir
, ^(const std::string
& dirPath
) { return (skipDirs
.count(dirPath
) != 0); }, ^(const std::string
& path
, const struct stat
& statBuf
) {
248 // ignore files that don't have 'x' bit set (all runnable mach-o files do)
249 const bool hasXBit
= ((statBuf
.st_mode
& S_IXOTH
) == S_IXOTH
);
250 if ( !hasXBit
&& !endsWith(path
, ".dylib") )
253 // ignore files too small
254 if ( statBuf
.st_size
< 0x3000 )
257 // don't add paths already found using previous prefix
258 if ( multiplePrefixes
&& (alreadyUsed
.count(path
) != 0) )
261 // if the file is mach-o, add to list
262 if ( addIfMachO(prefix
, path
, statBuf
, requireSIP
, files
) ) {
263 if ( multiplePrefixes
)
264 alreadyUsed
.insert(path
);
272 static void findOSFilesViaBOMS(const std::vector
<std::string
>& pathPrefixes
, bool requireSIP
, std::vector
<MappedMachOsByCategory
>& files
)
274 __block
std::unordered_set
<std::string
> runtimePathsFound
;
275 for (const std::string
& prefix
: pathPrefixes
) {
276 iterateDirectoryTree(prefix
, "/System/Library/Receipts", ^(const std::string
&) { return false; }, ^(const std::string
& path
, const struct stat
& statBuf
) {
277 if ( !contains(path
, "com.apple.pkg.") )
279 if ( !endsWith(path
, ".bom") )
281 std::string fullPath
= prefix
+ path
;
282 BOMBom bom
= BOMBomOpenWithSys(fullPath
.c_str(), false, NULL
);
283 if ( bom
== nullptr )
285 BOMFSObject rootFso
= BOMBomGetRootFSObject(bom
);
286 if ( rootFso
== nullptr ) {
290 BOMBomEnumerator e
= BOMBomEnumeratorNew(bom
, rootFso
);
291 if ( e
== nullptr ) {
292 fprintf(stderr
, "Can't get enumerator for BOM root FSObject\n");
295 BOMFSObjectFree(rootFso
);
296 //fprintf(stderr, "using BOM %s\n", path.c_str());
297 while (BOMFSObject fso
= BOMBomEnumeratorNext(e
)) {
298 if ( BOMFSObjectIsBinaryObject(fso
) ) {
299 const char* runPath
= BOMFSObjectPathName(fso
);
300 if ( (runPath
[0] == '.') && (runPath
[1] == '/') )
302 if ( runtimePathsFound
.count(runPath
) == 0 ) {
303 // only add files from sAllowedPrefixes and not in sDontUsePrefixes
304 bool inSearchDir
= false;
305 for (const char* searchDir
: sAllowedPrefixes
) {
306 if ( strncmp(searchDir
, runPath
, strlen(searchDir
)) == 0 ) {
312 bool inSkipDir
= false;
313 for (const char* skipDir
: sDontUsePrefixes
) {
314 if ( strncmp(skipDir
, runPath
, strlen(skipDir
)) == 0 ) {
320 for (const std::string
& prefix2
: pathPrefixes
) {
321 struct stat statBuf2
;
322 std::string fullPath2
= prefix2
+ runPath
;
323 if ( stat(fullPath2
.c_str(), &statBuf2
) == 0 ) {
324 addIfMachO(prefix2
, runPath
, statBuf2
, requireSIP
, files
);
325 runtimePathsFound
.insert(runPath
);
333 BOMFSObjectFree(fso
);
336 BOMBomEnumeratorFree(e
);
343 static bool dontCache(const std::string
& volumePrefix
, const std::string
& archName
,
344 const std::unordered_set
<std::string
>& pathsWithDuplicateInstallName
,
345 const DyldSharedCache::MappedMachO
& aFile
, bool warn
,
346 const std::unordered_set
<std::string
>& skipDylibs
)
348 if ( skipDylibs
.count(aFile
.runtimePath
) )
350 if ( startsWith(aFile
.runtimePath
, "/usr/lib/system/introspection/") )
352 if ( startsWith(aFile
.runtimePath
, "/System/Library/QuickTime/") )
354 if ( startsWith(aFile
.runtimePath
, "/System/Library/Tcl/") )
356 if ( startsWith(aFile
.runtimePath
, "/System/Library/Perl/") )
358 if ( startsWith(aFile
.runtimePath
, "/System/Library/MonitorPanels/") )
360 if ( startsWith(aFile
.runtimePath
, "/System/Library/Accessibility/") )
362 if ( startsWith(aFile
.runtimePath
, "/usr/local/") )
365 // anything inside a .app bundle is specific to app, so should not be in shared cache
366 if ( aFile
.runtimePath
.find(".app/") != std::string::npos
)
369 if ( archName
== "i386" ) {
370 if ( startsWith(aFile
.runtimePath
, "/System/Library/CoreServices/") )
372 if ( startsWith(aFile
.runtimePath
, "/System/Library/Extensions/") )
376 if ( aFile
.runtimePath
.find("//") != std::string::npos
) {
377 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());
381 dyld3::MachOParser
parser(aFile
.mh
);
382 const char* installName
= parser
.installName();
383 if ( (pathsWithDuplicateInstallName
.count(aFile
.runtimePath
) != 0) && (aFile
.runtimePath
!= installName
) ) {
384 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());
388 if ( aFile
.runtimePath
!= installName
) {
389 // see if install name is a symlink to actual path
390 std::string fullInstall
= volumePrefix
+ installName
;
391 char resolvedPath
[PATH_MAX
];
392 if ( realpath(fullInstall
.c_str(), resolvedPath
) != NULL
) {
393 std::string resolvedSymlink
= resolvedPath
;
394 if ( !volumePrefix
.empty() ) {
395 resolvedSymlink
= resolvedSymlink
.substr(volumePrefix
.size());
397 if ( aFile
.runtimePath
== resolvedSymlink
) {
401 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());
407 static void pruneCachedDylibs(const std::string
& volumePrefix
, const std::unordered_set
<std::string
>& skipDylibs
, MappedMachOsByCategory
& fileSet
)
409 std::unordered_set
<std::string
> pathsWithDuplicateInstallName
;
411 std::unordered_map
<std::string
, std::string
> installNameToFirstPath
;
412 for (DyldSharedCache::MappedMachO
& aFile
: fileSet
.dylibsForCache
) {
413 dyld3::MachOParser
parser(aFile
.mh
);
414 const char* installName
= parser
.installName();
415 auto pos
= installNameToFirstPath
.find(installName
);
416 if ( pos
== installNameToFirstPath
.end() ) {
417 installNameToFirstPath
[installName
] = aFile
.runtimePath
;
420 pathsWithDuplicateInstallName
.insert(aFile
.runtimePath
);
421 pathsWithDuplicateInstallName
.insert(installNameToFirstPath
[installName
]);
425 for (DyldSharedCache::MappedMachO
& aFile
: fileSet
.dylibsForCache
) {
426 if ( dontCache(volumePrefix
, fileSet
.archName
, pathsWithDuplicateInstallName
, aFile
, true, skipDylibs
) )
427 fileSet
.otherDylibsAndBundles
.push_back(aFile
);
429 fileSet
.dylibsForCache
.erase(std::remove_if(fileSet
.dylibsForCache
.begin(), fileSet
.dylibsForCache
.end(),
430 [&](const DyldSharedCache::MappedMachO
& aFile
) { return dontCache(volumePrefix
, fileSet
.archName
, pathsWithDuplicateInstallName
, aFile
, false, skipDylibs
); }),
431 fileSet
.dylibsForCache
.end());
434 static void pruneOtherDylibs(const std::string
& volumePrefix
, MappedMachOsByCategory
& fileSet
)
436 // other OS dylibs should not contain dylibs that are embedded in some .app bundle
437 fileSet
.otherDylibsAndBundles
.erase(std::remove_if(fileSet
.otherDylibsAndBundles
.begin(), fileSet
.otherDylibsAndBundles
.end(),
438 [&](const DyldSharedCache::MappedMachO
& aFile
) { return (aFile
.runtimePath
.find(".app/") != std::string::npos
); }),
439 fileSet
.otherDylibsAndBundles
.end());
443 static void pruneExecutables(const std::string
& volumePrefix
, MappedMachOsByCategory
& fileSet
)
445 // 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
446 fileSet
.mainExecutables
.erase(std::remove_if(fileSet
.mainExecutables
.begin(), fileSet
.mainExecutables
.end(),
447 [&](const DyldSharedCache::MappedMachO
& aFile
) {
448 if ( !startsWith(aFile
.runtimePath
, "/usr/bin/") )
450 dyld3::MachOParser
parser(aFile
.mh
);
451 __block
bool isXcodeShim
= false;
452 parser
.forEachDependentDylib(^(const char* loadPath
, bool, bool, bool, uint32_t, uint32_t, bool &stop
) {
453 if ( strcmp(loadPath
, "/usr/lib/libxcselect.dylib") == 0 )
457 }), fileSet
.mainExecutables
.end());
460 static bool existingCacheUpToDate(const std::string
& existingCache
, const std::vector
<DyldSharedCache::MappedMachO
>& currentDylibs
)
462 // if no existing cache, it is not up-to-date
463 int fd
= ::open(existingCache
.c_str(), O_RDONLY
);
467 // build map of found dylibs
468 std::unordered_map
<std::string
, const DyldSharedCache::MappedMachO
*> currentDylibMap
;
469 for (const DyldSharedCache::MappedMachO
& aFile
: currentDylibs
) {
470 //fprintf(stderr, "0x%0llX 0x%0llX %s\n", aFile.inode, aFile.modTime, aFile.runtimePath.c_str());
471 currentDylibMap
[aFile
.runtimePath
] = &aFile
;
474 // make sure all dylibs in existing cache have same mtime and inode as found dylib
475 __block
bool foundMismatch
= false;
476 const uint64_t cacheMapLen
= 0x40000000;
477 void *p
= ::mmap(NULL
, cacheMapLen
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
478 if ( p
!= MAP_FAILED
) {
479 const DyldSharedCache
* cache
= (DyldSharedCache
*)p
;
480 cache
->forEachImageEntry(^(const char* installName
, uint64_t mTime
, uint64_t inode
) {
481 bool foundMatch
= false;
482 auto pos
= currentDylibMap
.find(installName
);
483 if ( pos
!= currentDylibMap
.end() ) {
484 const DyldSharedCache::MappedMachO
* foundDylib
= pos
->second
;
485 if ( (foundDylib
->inode
== inode
) && (foundDylib
->modTime
== mTime
) ) {
490 // use slow path and look for any dylib with a matching inode and mtime
491 bool foundSlow
= false;
492 for (const DyldSharedCache::MappedMachO
& aFile
: currentDylibs
) {
493 if ( (aFile
.inode
== inode
) && (aFile
.modTime
== mTime
) ) {
499 foundMismatch
= true;
501 fprintf(stderr
, "rebuilding dyld cache because dylib changed: %s\n", installName
);
505 ::munmap(p
, cacheMapLen
);
510 return !foundMismatch
;
514 inline uint32_t absolutetime_to_milliseconds(uint64_t abstime
)
516 return (uint32_t)(abstime
/1000/1000);
519 static bool runningOnHaswell()
521 // check system is capable of running x86_64h code
522 struct host_basic_info info
;
523 mach_msg_type_number_t count
= HOST_BASIC_INFO_COUNT
;
524 mach_port_t hostPort
= mach_host_self();
525 kern_return_t result
= host_info(hostPort
, HOST_BASIC_INFO
, (host_info_t
)&info
, &count
);
526 mach_port_deallocate(mach_task_self(), hostPort
);
528 return ( (result
== KERN_SUCCESS
) && (info
.cpu_subtype
== CPU_SUBTYPE_X86_64_H
) );
533 #define TERMINATE_IF_LAST_ARG( s ) \
535 if ( i == argc - 1 ) { \
536 fprintf(stderr, s ); \
541 int main(int argc
, const char* argv
[])
543 std::string rootPath
;
544 std::string overlayPath
;
545 std::string dylibListFile
;
546 bool universal
= false;
548 bool searchDisk
= false;
549 bool dylibsRemoved
= false;
550 std::string cacheDir
;
551 std::unordered_set
<std::string
> archStrs
;
552 std::unordered_set
<std::string
> skipDylibs
;
554 // parse command line options
555 for (int i
= 1; i
< argc
; ++i
) {
556 const char* arg
= argv
[i
];
557 if (strcmp(arg
, "-debug") == 0) {
560 else if (strcmp(arg
, "-verbose") == 0) {
563 else if (strcmp(arg
, "-dont_map_local_symbols") == 0) {
564 //We are going to ignore this
566 else if (strcmp(arg
, "-dylib_list") == 0) {
567 TERMINATE_IF_LAST_ARG("-dylib_list missing argument");
568 dylibListFile
= argv
[++i
];
570 else if ((strcmp(arg
, "-root") == 0) || (strcmp(arg
, "--root") == 0)) {
571 TERMINATE_IF_LAST_ARG("-root missing path argument\n");
572 rootPath
= argv
[++i
];
574 else if (strcmp(arg
, "-overlay") == 0) {
575 TERMINATE_IF_LAST_ARG("-overlay missing path argument\n");
576 overlayPath
= argv
[++i
];
578 else if (strcmp(arg
, "-cache_dir") == 0) {
579 TERMINATE_IF_LAST_ARG("-cache_dir missing path argument\n");
580 cacheDir
= argv
[++i
];
582 else if (strcmp(arg
, "-arch") == 0) {
583 TERMINATE_IF_LAST_ARG("-arch missing argument\n");
584 archStrs
.insert(argv
[++i
]);
586 else if (strcmp(arg
, "-search_disk") == 0) {
589 else if (strcmp(arg
, "-dylibs_removed_in_mastering") == 0) {
590 dylibsRemoved
= true;
592 else if (strcmp(arg
, "-force") == 0) {
595 else if (strcmp(arg
, "-sort_by_name") == 0) {
596 //No-op, we always do this now
598 else if (strcmp(arg
, "-universal_boot") == 0) {
601 else if (strcmp(arg
, "-skip") == 0) {
602 TERMINATE_IF_LAST_ARG("-skip missing argument\n");
603 skipDylibs
.insert(argv
[++i
]);
607 fprintf(stderr
, "update_dyld_shared_cache: unknown option: %s\n", arg
);
612 if ( !rootPath
.empty() & !overlayPath
.empty() ) {
613 fprintf(stderr
, "-root and -overlay cannot be used together\n");
616 // canonicalize rootPath
617 if ( !rootPath
.empty() ) {
618 char resolvedPath
[PATH_MAX
];
619 if ( realpath(rootPath
.c_str(), resolvedPath
) != NULL
) {
620 rootPath
= resolvedPath
;
622 // <rdar://problem/33223984> when building closures for boot volume, pathPrefixes should be empty
623 if ( rootPath
== "/" ) {
627 // canonicalize overlayPath
628 if ( !overlayPath
.empty() ) {
629 char resolvedPath
[PATH_MAX
];
630 if ( realpath(overlayPath
.c_str(), resolvedPath
) != NULL
) {
631 overlayPath
= resolvedPath
;
635 // pathPrefixes for three modes:
636 // 1) no options: { "" } // search only boot volume
637 // 2) -overlay: { overlay, "" } // search overlay, then boot volume
638 // 3) -root: { root } // search only -root volume
640 std::vector
<std::string
> pathPrefixes
;
641 if ( !overlayPath
.empty() )
642 pathPrefixes
.push_back(overlayPath
);
643 pathPrefixes
.push_back(rootPath
);
646 if ( cacheDir
.empty() ) {
647 // write cache file into -root or -overlay directory, if used
648 if ( rootPath
!= "/" )
649 cacheDir
= rootPath
+ MACOSX_DYLD_SHARED_CACHE_DIR
;
650 else if ( !overlayPath
.empty() )
651 cacheDir
= overlayPath
+ MACOSX_DYLD_SHARED_CACHE_DIR
;
653 cacheDir
= MACOSX_DYLD_SHARED_CACHE_DIR
;
656 int err
= mkpath_np(cacheDir
.c_str(), S_IRWXU
| S_IRGRP
|S_IXGRP
| S_IROTH
|S_IXOTH
);
657 if ( (err
!= 0) && (err
!= EEXIST
) ) {
658 fprintf(stderr
, "mkpath_np fail: %d", err
);
662 if ( archStrs
.empty() ) {
664 // <rdar://problem/26182089> -universal_boot should make all possible dyld caches
665 archStrs
.insert("i386");
666 archStrs
.insert("x86_64");
667 archStrs
.insert("x86_64h");
670 // just make caches for this machine
671 archStrs
.insert("i386");
672 archStrs
.insert(runningOnHaswell() ? "x86_64h" : "x86_64");
676 uint64_t t1
= mach_absolute_time();
678 // find all mach-o files for requested architectures
679 bool requireDylibsBeRootlessProtected
= isProtectedBySIP(cacheDir
);
680 __block
std::vector
<MappedMachOsByCategory
> allFileSets
;
681 if ( archStrs
.count("x86_64") )
682 allFileSets
.push_back({"x86_64"});
683 if ( archStrs
.count("x86_64h") )
684 allFileSets
.push_back({"x86_64h"});
685 if ( archStrs
.count("i386") )
686 allFileSets
.push_back({"i386"});
688 findAllFiles(pathPrefixes
, requireDylibsBeRootlessProtected
, allFileSets
);
690 std::unordered_set
<std::string
> runtimePathsFound
;
691 findOSFilesViaBOMS(pathPrefixes
, requireDylibsBeRootlessProtected
, allFileSets
);
694 // nothing in OS uses i386 dylibs, so only dylibs used by third party apps need to be in cache
695 for (MappedMachOsByCategory
& fileSet
: allFileSets
) {
696 pruneCachedDylibs(rootPath
, skipDylibs
, fileSet
);
697 pruneOtherDylibs(rootPath
, fileSet
);
698 pruneExecutables(rootPath
, fileSet
);
701 uint64_t t2
= mach_absolute_time();
704 fprintf(stderr
, "time to scan file system and construct lists of mach-o files: %ums\n", absolutetime_to_milliseconds(t2
-t1
));
706 fprintf(stderr
, "time to read BOM and construct lists of mach-o files: %ums\n", absolutetime_to_milliseconds(t2
-t1
));
709 // build caches in parallel on machines with at leat 4GB of RAM
710 uint64_t memSize
= 0;
711 size_t sz
= sizeof(memSize
);;
712 bool buildInParallel
= false;
713 if ( sysctlbyname("hw.memsize", &memSize
, &sz
, NULL
, 0) == 0 ) {
714 if ( memSize
>= 0x100000000ULL
)
715 buildInParallel
= true;
717 dispatch_queue_t dqueue
= buildInParallel
? dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT
, 0)
718 : dispatch_queue_create("serial-queue", DISPATCH_QUEUE_SERIAL
);
721 __block
bool cacheBuildFailure
= false;
722 __block
bool wroteSomeCacheFile
= false;
723 dispatch_apply(allFileSets
.size(), dqueue
, ^(size_t index
) {
724 MappedMachOsByCategory
& fileSet
= allFileSets
[index
];
725 const std::string outFile
= cacheDir
+ "/dyld_shared_cache_" + fileSet
.archName
;
727 DyldSharedCache::MappedMachO (^loader
)(const std::string
&) = ^DyldSharedCache::MappedMachO(const std::string
& runtimePath
) {
728 if ( skipDylibs
.count(runtimePath
) )
729 return DyldSharedCache::MappedMachO();
730 for (const std::string
& prefix
: pathPrefixes
) {
731 std::string fullPath
= prefix
+ runtimePath
;
733 if ( stat(fullPath
.c_str(), &statBuf
) == 0 ) {
734 std::vector
<MappedMachOsByCategory
> mappedFiles
;
735 mappedFiles
.push_back({fileSet
.archName
});
736 if ( addIfMachO(prefix
, runtimePath
, statBuf
, requireDylibsBeRootlessProtected
, mappedFiles
) ) {
737 if ( !mappedFiles
.back().dylibsForCache
.empty() )
738 return mappedFiles
.back().dylibsForCache
.back();
742 return DyldSharedCache::MappedMachO();
744 size_t startCount
= fileSet
.dylibsForCache
.size();
745 std::vector
<std::pair
<DyldSharedCache::MappedMachO
, std::set
<std::string
>>> excludes
;
746 DyldSharedCache::verifySelfContained(fileSet
.dylibsForCache
, loader
, excludes
);
747 for (size_t i
=startCount
; i
< fileSet
.dylibsForCache
.size(); ++i
) {
748 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());
750 for (auto& exclude
: excludes
) {
751 std::string reasons
= "(\"";
752 for (auto i
= exclude
.second
.begin(); i
!= exclude
.second
.end(); ++i
) {
754 if (i
!= --exclude
.second
.end()) {
759 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());
760 fileSet
.otherDylibsAndBundles
.push_back(exclude
.first
);
763 // check if cache is already up to date
765 if ( existingCacheUpToDate(outFile
, fileSet
.dylibsForCache
) )
769 // add any extra dylibs needed which were not in .bom
770 fprintf(stderr
, "update_dyld_shared_cache: %s incorporating %lu OS dylibs, tracking %lu others, building closures for %lu executables\n", fileSet
.archName
.c_str(), fileSet
.dylibsForCache
.size(), fileSet
.otherDylibsAndBundles
.size(), fileSet
.mainExecutables
.size());
771 //for (const DyldSharedCache::MappedMachO& aFile : fileSet.dylibsForCache) {
772 // fprintf(stderr, " %s\n", aFile.runtimePath.c_str());
776 // build cache new cache file
777 DyldSharedCache::CreateOptions options
;
778 options
.archName
= fileSet
.archName
;
779 options
.platform
= dyld3::Platform::macOS
;
780 options
.excludeLocalSymbols
= false;
781 options
.optimizeStubs
= false;
782 options
.optimizeObjC
= true;
783 options
.codeSigningDigestMode
= DyldSharedCache::SHA256only
;
784 options
.dylibsRemovedDuringMastering
= dylibsRemoved
;
785 options
.inodesAreSameAsRuntime
= true;
786 options
.cacheSupportsASLR
= (fileSet
.archName
!= "i386");
787 options
.forSimulator
= false;
788 options
.verbose
= verbose
;
789 options
.evictLeafDylibsOnOverflow
= true;
790 options
.pathPrefixes
= pathPrefixes
;
791 DyldSharedCache::CreateResults results
= DyldSharedCache::create(options
, fileSet
.dylibsForCache
, fileSet
.otherDylibsAndBundles
, fileSet
.mainExecutables
);
793 // print any warnings
794 for (const std::string
& warn
: results
.warnings
) {
795 fprintf(stderr
, "update_dyld_shared_cache: warning: %s %s\n", fileSet
.archName
.c_str(), warn
.c_str());
797 if ( !results
.errorMessage
.empty() ) {
798 // print error (if one)
799 fprintf(stderr
, "update_dyld_shared_cache: %s\n", results
.errorMessage
.c_str());
800 cacheBuildFailure
= true;
803 // save new cache file to disk and write new .map file
804 assert(results
.cacheContent
!= nullptr);
805 if ( !safeSave(results
.cacheContent
, results
.cacheLength
, outFile
) )
806 cacheBuildFailure
= true;
807 if ( !cacheBuildFailure
) {
808 std::string mapStr
= results
.cacheContent
->mapFile();
809 std::string outFileMap
= cacheDir
+ "/dyld_shared_cache_" + fileSet
.archName
+ ".map";
810 safeSave(mapStr
.c_str(), mapStr
.size(), outFileMap
);
811 wroteSomeCacheFile
= true;
813 // free created cache buffer
814 vm_deallocate(mach_task_self(), (vm_address_t
)results
.cacheContent
, results
.cacheLength
);
819 // Save off spintrace data
820 if ( wroteSomeCacheFile
) {
821 void* h
= dlopen("/usr/lib/libdscsym.dylib", 0);
822 if ( h
!= nullptr ) {
823 typedef int (*dscym_func
)(const char*);
824 dscym_func func
= (dscym_func
)dlsym(h
, "dscsym_save_dscsyms_for_current_caches");
825 std::string nuggetRoot
= rootPath
;
826 if ( nuggetRoot
.empty() )
827 nuggetRoot
= overlayPath
;
828 if ( nuggetRoot
.empty() )
830 (*func
)(nuggetRoot
.c_str());
835 // we could unmap all input files, but tool is about to quit
837 return (cacheBuildFailure
? 1 : 0);