]> git.saurik.com Git - apple/dyld.git/blob - dyld3/shared-cache/update_dyld_shared_cache.cpp
dyld-519.2.2.tar.gz
[apple/dyld.git] / dyld3 / shared-cache / update_dyld_shared_cache.cpp
1 /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
2 *
3 * Copyright (c) 2014 Apple Inc. All rights reserved.
4 *
5 * @APPLE_LICENSE_HEADER_START@
6 *
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
12 * file.
13 *
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <sys/mman.h>
28 #include <mach/mach.h>
29 #include <mach/mach_time.h>
30 #include <limits.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <math.h>
35 #include <fcntl.h>
36 #include <dlfcn.h>
37 #include <signal.h>
38 #include <errno.h>
39 #include <assert.h>
40 #include <sys/uio.h>
41 #include <unistd.h>
42 #include <sys/param.h>
43 #include <sys/sysctl.h>
44 #include <sys/resource.h>
45 #include <dirent.h>
46 #include <rootless.h>
47 #include <dscsym.h>
48 #include <dispatch/dispatch.h>
49 #include <pthread/pthread.h>
50 #include <Bom/Bom.h>
51 #include <CoreFoundation/CoreFoundation.h>
52
53 #include <algorithm>
54 #include <vector>
55 #include <unordered_set>
56 #include <unordered_set>
57 #include <iostream>
58 #include <fstream>
59
60 #include "MachOParser.h"
61 #include "FileUtils.h"
62 #include "StringUtils.h"
63 #include "DyldSharedCache.h"
64
65 struct MappedMachOsByCategory
66 {
67 std::string archName;
68 std::vector<DyldSharedCache::MappedMachO> dylibsForCache;
69 std::vector<DyldSharedCache::MappedMachO> otherDylibsAndBundles;
70 std::vector<DyldSharedCache::MappedMachO> mainExecutables;
71 };
72
73 static const char* sAllowedPrefixes[] = {
74 "/bin/",
75 "/sbin/",
76 "/usr/",
77 "/System",
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
127 };
128
129 static const char* sDontUsePrefixes[] = {
130 "/usr/share",
131 "/usr/local/",
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
138 };
139
140
141 static bool verbose = false;
142
143
144
145 static bool addIfMachO(const std::string& pathPrefix, const std::string& runtimePath, const struct stat& statBuf, bool requireSIP, std::vector<MappedMachOsByCategory>& files)
146 {
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") )
149 return false;
150
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);
154 if ( fd < 0 )
155 return false;
156 bool result = false;
157 const void* wholeFile = ::mmap(NULL, statBuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
158 if ( wholeFile != MAP_FAILED ) {
159 Diagnostics diag;
160 bool usedWholeFile = false;
161 for (MappedMachOsByCategory& file : files) {
162 size_t sliceOffset;
163 size_t sliceLength;
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);
172 slice = MAP_FAILED;
173 }
174 }
175 }
176 else if ( !fatButMissingSlice && dyld3::MachOParser::isValidMachO(diag, file.archName, dyld3::Platform::macOS, wholeFile, statBuf.st_size, fullPath.c_str(), false) ) {
177 slice = wholeFile;
178 sliceLength = statBuf.st_size;
179 sliceOffset = 0;
180 usedWholeFile = true;
181 //fprintf(stderr, "mapped whole file at %p size=0x%0lX for %s\n", p, len, inputPath.c_str());
182 }
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);
187 }
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());
193 }
194 fprintf(stderr, "\n");
195 }
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);
207 }
208 }
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);
213 else
214 file.otherDylibsAndBundles.emplace_back(runtimePath, mh, sliceLength, issetuid, sipProtected, sliceOffset, statBuf.st_mtime, statBuf.st_ino);
215 }
216 else {
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());
222 }
223 }
224 file.otherDylibsAndBundles.emplace_back(runtimePath, mh, sliceLength, issetuid, sipProtected, sliceOffset, statBuf.st_mtime, statBuf.st_ino);
225 }
226 result = true;
227 }
228 }
229 if ( !usedWholeFile )
230 ::munmap((void*)wholeFile, statBuf.st_size);
231 }
232 ::close(fd);
233 return result;
234 }
235
236 static void findAllFiles(const std::vector<std::string>& pathPrefixes, bool requireSIP, std::vector<MappedMachOsByCategory>& files)
237 {
238 std::unordered_set<std::string> skipDirs;
239 for (const char* s : sDontUsePrefixes)
240 skipDirs.insert(s);
241
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") )
251 return;
252
253 // ignore files too small
254 if ( statBuf.st_size < 0x3000 )
255 return;
256
257 // don't add paths already found using previous prefix
258 if ( multiplePrefixes && (alreadyUsed.count(path) != 0) )
259 return;
260
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);
265 }
266 });
267 }
268 }
269 }
270
271
272 static void findOSFilesViaBOMS(const std::vector<std::string>& pathPrefixes, bool requireSIP, std::vector<MappedMachOsByCategory>& files)
273 {
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.") )
278 return;
279 if ( !endsWith(path, ".bom") )
280 return;
281 std::string fullPath = prefix + path;
282 BOMBom bom = BOMBomOpenWithSys(fullPath.c_str(), false, NULL);
283 if ( bom == nullptr )
284 return;
285 BOMFSObject rootFso = BOMBomGetRootFSObject(bom);
286 if ( rootFso == nullptr ) {
287 BOMBomFree(bom);
288 return;
289 }
290 BOMBomEnumerator e = BOMBomEnumeratorNew(bom, rootFso);
291 if ( e == nullptr ) {
292 fprintf(stderr, "Can't get enumerator for BOM root FSObject\n");
293 return;
294 }
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] == '/') )
301 ++runPath;
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 ) {
307 inSearchDir = true;
308 break;
309 }
310 }
311 if ( inSearchDir ) {
312 bool inSkipDir = false;
313 for (const char* skipDir : sDontUsePrefixes) {
314 if ( strncmp(skipDir, runPath, strlen(skipDir)) == 0 ) {
315 inSkipDir = true;
316 break;
317 }
318 }
319 if ( !inSkipDir ) {
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);
326 break;
327 }
328 }
329 }
330 }
331 }
332 }
333 BOMFSObjectFree(fso);
334 }
335
336 BOMBomEnumeratorFree(e);
337 BOMBomFree(bom);
338 });
339 }
340 }
341
342
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)
347 {
348 if ( skipDylibs.count(aFile.runtimePath) )
349 return true;
350 if ( startsWith(aFile.runtimePath, "/usr/lib/system/introspection/") )
351 return true;
352 if ( startsWith(aFile.runtimePath, "/System/Library/QuickTime/") )
353 return true;
354 if ( startsWith(aFile.runtimePath, "/System/Library/Tcl/") )
355 return true;
356 if ( startsWith(aFile.runtimePath, "/System/Library/Perl/") )
357 return true;
358 if ( startsWith(aFile.runtimePath, "/System/Library/MonitorPanels/") )
359 return true;
360 if ( startsWith(aFile.runtimePath, "/System/Library/Accessibility/") )
361 return true;
362 if ( startsWith(aFile.runtimePath, "/usr/local/") )
363 return true;
364
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 )
367 return true;
368
369 if ( archName == "i386" ) {
370 if ( startsWith(aFile.runtimePath, "/System/Library/CoreServices/") )
371 return true;
372 if ( startsWith(aFile.runtimePath, "/System/Library/Extensions/") )
373 return true;
374 }
375
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());
378 return true;
379 }
380
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());
385 return true;
386 }
387
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());
396 }
397 if ( aFile.runtimePath == resolvedSymlink ) {
398 return false;
399 }
400 }
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());
402 return true;
403 }
404 return false;
405 }
406
407 static void pruneCachedDylibs(const std::string& volumePrefix, const std::unordered_set<std::string>& skipDylibs, MappedMachOsByCategory& fileSet)
408 {
409 std::unordered_set<std::string> pathsWithDuplicateInstallName;
410
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;
418 }
419 else {
420 pathsWithDuplicateInstallName.insert(aFile.runtimePath);
421 pathsWithDuplicateInstallName.insert(installNameToFirstPath[installName]);
422 }
423 }
424
425 for (DyldSharedCache::MappedMachO& aFile : fileSet.dylibsForCache) {
426 if ( dontCache(volumePrefix, fileSet.archName, pathsWithDuplicateInstallName, aFile, true, skipDylibs) )
427 fileSet.otherDylibsAndBundles.push_back(aFile);
428 }
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());
432 }
433
434 static void pruneOtherDylibs(const std::string& volumePrefix, MappedMachOsByCategory& fileSet)
435 {
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());
440 }
441
442
443 static void pruneExecutables(const std::string& volumePrefix, MappedMachOsByCategory& fileSet)
444 {
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/") )
449 return false;
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 )
454 isXcodeShim = true;
455 });
456 return isXcodeShim;
457 }), fileSet.mainExecutables.end());
458 }
459
460 static bool existingCacheUpToDate(const std::string& existingCache, const std::vector<DyldSharedCache::MappedMachO>& currentDylibs)
461 {
462 // if no existing cache, it is not up-to-date
463 int fd = ::open(existingCache.c_str(), O_RDONLY);
464 if ( fd < 0 )
465 return false;
466
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;
472 }
473
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) ) {
486 foundMatch = true;
487 }
488 }
489 if ( !foundMatch ) {
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) ) {
494 foundSlow = true;
495 break;
496 }
497 }
498 if ( !foundSlow ) {
499 foundMismatch = true;
500 if ( verbose )
501 fprintf(stderr, "rebuilding dyld cache because dylib changed: %s\n", installName);
502 }
503 }
504 });
505 ::munmap(p, cacheMapLen);
506 }
507
508 ::close(fd);
509
510 return !foundMismatch;
511 }
512
513
514 inline uint32_t absolutetime_to_milliseconds(uint64_t abstime)
515 {
516 return (uint32_t)(abstime/1000/1000);
517 }
518
519 static bool runningOnHaswell()
520 {
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);
527
528 return ( (result == KERN_SUCCESS) && (info.cpu_subtype == CPU_SUBTYPE_X86_64_H) );
529 }
530
531
532
533 #define TERMINATE_IF_LAST_ARG( s ) \
534 do { \
535 if ( i == argc - 1 ) { \
536 fprintf(stderr, s ); \
537 return 1; \
538 } \
539 } while ( 0 )
540
541 int main(int argc, const char* argv[])
542 {
543 std::string rootPath;
544 std::string overlayPath;
545 std::string dylibListFile;
546 bool universal = false;
547 bool force = 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;
553
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) {
558 verbose = true;
559 }
560 else if (strcmp(arg, "-verbose") == 0) {
561 verbose = true;
562 }
563 else if (strcmp(arg, "-dont_map_local_symbols") == 0) {
564 //We are going to ignore this
565 }
566 else if (strcmp(arg, "-dylib_list") == 0) {
567 TERMINATE_IF_LAST_ARG("-dylib_list missing argument");
568 dylibListFile = argv[++i];
569 }
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];
573 }
574 else if (strcmp(arg, "-overlay") == 0) {
575 TERMINATE_IF_LAST_ARG("-overlay missing path argument\n");
576 overlayPath = argv[++i];
577 }
578 else if (strcmp(arg, "-cache_dir") == 0) {
579 TERMINATE_IF_LAST_ARG("-cache_dir missing path argument\n");
580 cacheDir = argv[++i];
581 }
582 else if (strcmp(arg, "-arch") == 0) {
583 TERMINATE_IF_LAST_ARG("-arch missing argument\n");
584 archStrs.insert(argv[++i]);
585 }
586 else if (strcmp(arg, "-search_disk") == 0) {
587 searchDisk = true;
588 }
589 else if (strcmp(arg, "-dylibs_removed_in_mastering") == 0) {
590 dylibsRemoved = true;
591 }
592 else if (strcmp(arg, "-force") == 0) {
593 force = true;
594 }
595 else if (strcmp(arg, "-sort_by_name") == 0) {
596 //No-op, we always do this now
597 }
598 else if (strcmp(arg, "-universal_boot") == 0) {
599 universal = true;
600 }
601 else if (strcmp(arg, "-skip") == 0) {
602 TERMINATE_IF_LAST_ARG("-skip missing argument\n");
603 skipDylibs.insert(argv[++i]);
604 }
605 else {
606 //usage();
607 fprintf(stderr, "update_dyld_shared_cache: unknown option: %s\n", arg);
608 return 1;
609 }
610 }
611
612 if ( !rootPath.empty() & !overlayPath.empty() ) {
613 fprintf(stderr, "-root and -overlay cannot be used together\n");
614 return 1;
615 }
616 // canonicalize rootPath
617 if ( !rootPath.empty() ) {
618 char resolvedPath[PATH_MAX];
619 if ( realpath(rootPath.c_str(), resolvedPath) != NULL ) {
620 rootPath = resolvedPath;
621 }
622 // <rdar://problem/33223984> when building closures for boot volume, pathPrefixes should be empty
623 if ( rootPath == "/" ) {
624 rootPath = "";
625 }
626 }
627 // canonicalize overlayPath
628 if ( !overlayPath.empty() ) {
629 char resolvedPath[PATH_MAX];
630 if ( realpath(overlayPath.c_str(), resolvedPath) != NULL ) {
631 overlayPath = resolvedPath;
632 }
633 }
634 //
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
639 //
640 std::vector<std::string> pathPrefixes;
641 if ( !overlayPath.empty() )
642 pathPrefixes.push_back(overlayPath);
643 pathPrefixes.push_back(rootPath);
644
645
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;
652 else
653 cacheDir = MACOSX_DYLD_SHARED_CACHE_DIR;
654 }
655
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);
659 return 1;
660 }
661
662 if ( archStrs.empty() ) {
663 if ( universal ) {
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");
668 }
669 else {
670 // just make caches for this machine
671 archStrs.insert("i386");
672 archStrs.insert(runningOnHaswell() ? "x86_64h" : "x86_64");
673 }
674 }
675
676 uint64_t t1 = mach_absolute_time();
677
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"});
687 if ( searchDisk )
688 findAllFiles(pathPrefixes, requireDylibsBeRootlessProtected, allFileSets);
689 else {
690 std::unordered_set<std::string> runtimePathsFound;
691 findOSFilesViaBOMS(pathPrefixes, requireDylibsBeRootlessProtected, allFileSets);
692 }
693
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);
699 }
700
701 uint64_t t2 = mach_absolute_time();
702 if ( verbose ) {
703 if ( searchDisk )
704 fprintf(stderr, "time to scan file system and construct lists of mach-o files: %ums\n", absolutetime_to_milliseconds(t2-t1));
705 else
706 fprintf(stderr, "time to read BOM and construct lists of mach-o files: %ums\n", absolutetime_to_milliseconds(t2-t1));
707 }
708
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;
716 }
717 dispatch_queue_t dqueue = buildInParallel ? dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
718 : dispatch_queue_create("serial-queue", DISPATCH_QUEUE_SERIAL);
719
720 // build all caches
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;
726
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;
732 struct stat statBuf;
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();
739 }
740 }
741 }
742 return DyldSharedCache::MappedMachO();
743 };
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());
749 }
750 for (auto& exclude : excludes) {
751 std::string reasons = "(\"";
752 for (auto i = exclude.second.begin(); i != exclude.second.end(); ++i) {
753 reasons += *i;
754 if (i != --exclude.second.end()) {
755 reasons += "\", \"";
756 }
757 }
758 reasons += "\")";
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);
761 }
762
763 // check if cache is already up to date
764 if ( !force ) {
765 if ( existingCacheUpToDate(outFile, fileSet.dylibsForCache) )
766 return;
767 }
768
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());
773 //}
774
775
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);
792
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());
796 }
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;
801 }
802 else {
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;
812 }
813 // free created cache buffer
814 vm_deallocate(mach_task_self(), (vm_address_t)results.cacheContent, results.cacheLength);
815 }
816 });
817
818
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() )
829 nuggetRoot = "/";
830 (*func)(nuggetRoot.c_str());
831 }
832 }
833
834
835 // we could unmap all input files, but tool is about to quit
836
837 return (cacheBuildFailure ? 1 : 0);
838 }
839