dyld-640.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 <mach-o/dyld.h>
31 #include <limits.h>
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <math.h>
36 #include <fcntl.h>
37 #include <dlfcn.h>
38 #include <signal.h>
39 #include <errno.h>
40 #include <assert.h>
41 #include <sys/uio.h>
42 #include <unistd.h>
43 #include <sys/param.h>
44 #include <sys/sysctl.h>
45 #include <sys/resource.h>
46 #include <dirent.h>
47 #include <rootless.h>
48 #include <dscsym.h>
49 #include <dispatch/dispatch.h>
50 #include <pthread/pthread.h>
51 #include <Bom/Bom.h>
52 #include <CoreFoundation/CoreFoundation.h>
53
54 #include <algorithm>
55 #include <vector>
56 #include <unordered_set>
57 #include <unordered_set>
58 #include <iostream>
59 #include <fstream>
60
61 #include "FileUtils.h"
62 #include "StringUtils.h"
63 #include "DyldSharedCache.h"
64 #include "MachOFile.h"
65 #include "MachOAnalyzer.h"
66 #include "ClosureFileSystemPhysical.h"
67
68 struct MappedMachOsByCategory
69 {
70 std::string archName;
71 std::vector<DyldSharedCache::MappedMachO> dylibsForCache;
72 std::vector<DyldSharedCache::MappedMachO> otherDylibsAndBundles;
73 std::vector<DyldSharedCache::MappedMachO> mainExecutables;
74 };
75
76 static const char* sAllowedPrefixes[] = {
77 "/bin/",
78 "/sbin/",
79 "/usr/",
80 "/System",
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
130 };
131
132 static const char* sDontUsePrefixes[] = {
133 "/usr/share",
134 "/usr/local/",
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
142 };
143
144
145 static bool verbose = false;
146
147
148
149 static bool addIfMachO(const dyld3::closure::FileSystem& fileSystem, const std::string& runtimePath, const struct stat& statBuf, bool requireSIP,
150 dev_t rootFS, std::vector<MappedMachOsByCategory>& files)
151 {
152 // don't precompute closure info for any debug or profile dylibs
153 if ( endsWith(runtimePath, "_profile.dylib") || endsWith(runtimePath, "_debug.dylib") || endsWith(runtimePath, "_profile") || endsWith(runtimePath, "_debug") )
154 return false;
155 if ( startsWith(runtimePath, "/usr/lib/system/introspection/") )
156 return false;
157
158 // Only use files on the same volume as the boot volume
159 if (statBuf.st_dev != rootFS) {
160 if ( verbose )
161 fprintf(stderr, "update_dyld_shared_cache: warning: skipping overlay file '%s' which is not on the root volume\n", runtimePath.c_str());
162 return false;
163 }
164
165 auto warningHandler = ^(const char* msg) {
166 if ( verbose )
167 fprintf(stderr, "update_dyld_shared_cache: warning: cannot build dlopen closure for '%s' because %s\n", runtimePath.c_str(), msg);
168 };
169
170 bool result = false;
171 for (MappedMachOsByCategory& file : files) {
172 Diagnostics diag;
173 dyld3::closure::LoadedFileInfo loadedFileInfo = dyld3::MachOAnalyzer::load(diag, fileSystem, runtimePath.c_str(), file.archName.c_str(), dyld3::Platform::macOS);
174 const dyld3::MachOAnalyzer* ma = (const dyld3::MachOAnalyzer*)loadedFileInfo.fileContent;
175 if ( ma != nullptr ) {
176 bool sipProtected = false; // isProtectedBySIP(fd);
177 bool issetuid = false;
178 if ( ma->isDynamicExecutable() ) {
179 // When SIP enabled, only build closures for SIP protected programs
180 if ( !requireSIP || sipProtected ) {
181 //fprintf(stderr, "requireSIP=%d, sipProtected=%d, path=%s\n", requireSIP, sipProtected, fullPath.c_str());
182 issetuid = (statBuf.st_mode & (S_ISUID|S_ISGID));
183 file.mainExecutables.emplace_back(runtimePath, ma, loadedFileInfo.sliceLen, issetuid, sipProtected, loadedFileInfo.sliceOffset, statBuf.st_mtime, statBuf.st_ino);
184 }
185 }
186 else if ( ma->canBePlacedInDyldCache(runtimePath.c_str(), ^(const char* msg) {}) ) {
187 // when SIP is enabled, only dylib protected by SIP can go in cache
188 if ( !requireSIP || sipProtected )
189 file.dylibsForCache.emplace_back(runtimePath, ma, loadedFileInfo.sliceLen, issetuid, sipProtected, loadedFileInfo.sliceOffset, statBuf.st_mtime, statBuf.st_ino);
190 else if ( ma->canHavePrecomputedDlopenClosure(runtimePath.c_str(), warningHandler) )
191 file.otherDylibsAndBundles.emplace_back(runtimePath, ma, loadedFileInfo.sliceLen, issetuid, sipProtected, loadedFileInfo.sliceOffset, statBuf.st_mtime, statBuf.st_ino);
192 }
193 else {
194 if ( ma->isDylib() ) {
195 std::string installName = ma->installName();
196 if ( startsWith(installName, "@") && !contains(runtimePath, ".app/") && !contains(runtimePath, ".xpc/") ) {
197 if ( startsWith(runtimePath, "/usr/lib/") || startsWith(runtimePath, "/System/Library/") )
198 fprintf(stderr, "update_dyld_shared_cache: warning @rpath install name for system framework: %s\n", runtimePath.c_str());
199 }
200 }
201 else if ( ma->canHavePrecomputedDlopenClosure(runtimePath.c_str(), warningHandler) ) {
202 file.otherDylibsAndBundles.emplace_back(runtimePath, ma, loadedFileInfo.sliceLen, issetuid, sipProtected, loadedFileInfo.sliceOffset, statBuf.st_mtime, statBuf.st_ino);
203 }
204 }
205 result = true;
206 }
207 }
208
209 return result;
210 }
211
212 static void findAllFiles(const std::vector<std::string>& pathPrefixes, bool requireSIP, dev_t rootFS, std::vector<MappedMachOsByCategory>& files)
213 {
214 std::unordered_set<std::string> skipDirs;
215 for (const char* s : sDontUsePrefixes)
216 skipDirs.insert(s);
217
218 __block std::unordered_set<std::string> alreadyUsed;
219 bool multiplePrefixes = (pathPrefixes.size() > 1);
220 for (const std::string& prefix : pathPrefixes) {
221 // get all files from overlay for this search dir
222 dyld3::closure::FileSystemPhysical fileSystem(prefix.c_str());
223 for (const char* searchDir : sAllowedPrefixes ) {
224 iterateDirectoryTree(prefix, searchDir, ^(const std::string& dirPath) { return (skipDirs.count(dirPath) != 0); }, ^(const std::string& path, const struct stat& statBuf) {
225 // ignore files that don't have 'x' bit set (all runnable mach-o files do)
226 const bool hasXBit = ((statBuf.st_mode & S_IXOTH) == S_IXOTH);
227 if ( !hasXBit && !endsWith(path, ".dylib") )
228 return;
229
230 // ignore files too small
231 if ( statBuf.st_size < 0x3000 )
232 return;
233
234 // don't add paths already found using previous prefix
235 if ( multiplePrefixes && (alreadyUsed.count(path) != 0) )
236 return;
237
238 // if the file is mach-o, add to list
239 if ( addIfMachO(fileSystem, path, statBuf, requireSIP, rootFS, files) ) {
240 if ( multiplePrefixes )
241 alreadyUsed.insert(path);
242 }
243 });
244 }
245 }
246 }
247
248
249 static void findOSFilesViaBOMS(const std::vector<std::string>& pathPrefixes, bool requireSIP, dev_t rootFS, std::vector<MappedMachOsByCategory>& files)
250 {
251 __block std::unordered_set<std::string> runtimePathsFound;
252 for (const std::string& prefix : pathPrefixes) {
253 iterateDirectoryTree(prefix, "/System/Library/Receipts", ^(const std::string&) { return false; }, ^(const std::string& path, const struct stat& statBuf) {
254 if ( !contains(path, "com.apple.pkg.") )
255 return;
256 if ( !endsWith(path, ".bom") )
257 return;
258 std::string fullPath = prefix + path;
259 BOMBom bom = BOMBomOpenWithSys(fullPath.c_str(), false, NULL);
260 if ( bom == nullptr )
261 return;
262 BOMFSObject rootFso = BOMBomGetRootFSObject(bom);
263 if ( rootFso == nullptr ) {
264 BOMBomFree(bom);
265 return;
266 }
267 BOMBomEnumerator e = BOMBomEnumeratorNew(bom, rootFso);
268 if ( e == nullptr ) {
269 fprintf(stderr, "Can't get enumerator for BOM root FSObject\n");
270 return;
271 }
272 BOMFSObjectFree(rootFso);
273 //fprintf(stderr, "using BOM %s\n", path.c_str());
274 while (BOMFSObject fso = BOMBomEnumeratorNext(e)) {
275 if ( BOMFSObjectIsBinaryObject(fso) ) {
276 const char* runPath = BOMFSObjectPathName(fso);
277 if ( (runPath[0] == '.') && (runPath[1] == '/') )
278 ++runPath;
279 if ( runtimePathsFound.count(runPath) == 0 ) {
280 // only add files from sAllowedPrefixes and not in sDontUsePrefixes
281 bool inSearchDir = false;
282 for (const char* searchDir : sAllowedPrefixes ) {
283 if ( strncmp(searchDir, runPath, strlen(searchDir)) == 0 ) {
284 inSearchDir = true;
285 break;
286 }
287 }
288 if ( inSearchDir ) {
289 bool inSkipDir = false;
290 for (const char* skipDir : sDontUsePrefixes) {
291 if ( strncmp(skipDir, runPath, strlen(skipDir)) == 0 ) {
292 inSkipDir = true;
293 break;
294 }
295 }
296 if ( !inSkipDir ) {
297 for (const std::string& prefix2 : pathPrefixes) {
298 struct stat statBuf2;
299 std::string fullPath2 = prefix2 + runPath;
300 if ( stat(fullPath2.c_str(), &statBuf2) == 0 ) {
301 dyld3::closure::FileSystemPhysical fileSystem(prefix2.c_str());
302 if ( addIfMachO(fileSystem, runPath, statBuf2, requireSIP, rootFS, files) ) {
303 runtimePathsFound.insert(runPath);
304 break;
305 }
306 }
307 }
308 }
309 }
310 }
311 }
312 BOMFSObjectFree(fso);
313 }
314
315 BOMBomEnumeratorFree(e);
316 BOMBomFree(bom);
317 });
318 }
319 }
320
321
322 static bool dontCache(const std::string& volumePrefix, const std::string& archName,
323 const std::unordered_set<std::string>& pathsWithDuplicateInstallName,
324 const DyldSharedCache::MappedMachO& aFile, bool warn,
325 const std::unordered_set<std::string>& skipDylibs)
326 {
327 if ( skipDylibs.count(aFile.runtimePath) )
328 return true;
329 if ( startsWith(aFile.runtimePath, "/usr/lib/system/introspection/") )
330 return true;
331 if ( startsWith(aFile.runtimePath, "/System/Library/QuickTime/") )
332 return true;
333 if ( startsWith(aFile.runtimePath, "/System/Library/Tcl/") )
334 return true;
335 if ( startsWith(aFile.runtimePath, "/System/Library/Perl/") )
336 return true;
337 if ( startsWith(aFile.runtimePath, "/System/Library/MonitorPanels/") )
338 return true;
339 if ( startsWith(aFile.runtimePath, "/System/Library/Accessibility/") )
340 return true;
341 if ( startsWith(aFile.runtimePath, "/usr/local/") )
342 return true;
343
344 // anything inside a .app bundle is specific to app, so should not be in shared cache
345 if ( aFile.runtimePath.find(".app/") != std::string::npos )
346 return true;
347
348 if ( archName == "i386" ) {
349 if ( startsWith(aFile.runtimePath, "/System/Library/CoreServices/") )
350 return true;
351 if ( startsWith(aFile.runtimePath, "/System/Library/Extensions/") )
352 return true;
353 }
354
355 if ( aFile.runtimePath.find("//") != std::string::npos ) {
356 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());
357 return true;
358 }
359
360 const char* installName = aFile.mh->installName();
361 if ( (pathsWithDuplicateInstallName.count(aFile.runtimePath) != 0) && (aFile.runtimePath != installName) ) {
362 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());
363 return true;
364 }
365
366 if ( aFile.runtimePath != installName ) {
367 // see if install name is a symlink to actual path
368 std::string fullInstall = volumePrefix + installName;
369 char resolvedPath[PATH_MAX];
370 if ( realpath(fullInstall.c_str(), resolvedPath) != NULL ) {
371 std::string resolvedSymlink = resolvedPath;
372 if ( !volumePrefix.empty() ) {
373 resolvedSymlink = resolvedSymlink.substr(volumePrefix.size());
374 }
375 if ( aFile.runtimePath == resolvedSymlink ) {
376 return false;
377 }
378 }
379 // <rdar://problem/38000411> also if runtime path is a symlink to install name
380 std::string fullRuntime = volumePrefix + aFile.runtimePath;
381 if ( realpath(fullRuntime.c_str(), resolvedPath) != NULL ) {
382 std::string resolvedSymlink = resolvedPath;
383 if ( !volumePrefix.empty() ) {
384 resolvedSymlink = resolvedSymlink.substr(volumePrefix.size());
385 }
386 if ( resolvedSymlink == installName ) {
387 return false;
388 }
389 }
390 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());
391 return true;
392 }
393 return false;
394 }
395
396 static void pruneCachedDylibs(const std::string& volumePrefix, const std::unordered_set<std::string>& skipDylibs, MappedMachOsByCategory& fileSet)
397 {
398 std::unordered_set<std::string> pathsWithDuplicateInstallName;
399
400 std::unordered_map<std::string, std::string> installNameToFirstPath;
401 for (DyldSharedCache::MappedMachO& aFile : fileSet.dylibsForCache) {
402 const char* installName = aFile.mh->installName();
403 auto pos = installNameToFirstPath.find(installName);
404 if ( pos == installNameToFirstPath.end() ) {
405 installNameToFirstPath[installName] = aFile.runtimePath;
406 }
407 else {
408 pathsWithDuplicateInstallName.insert(aFile.runtimePath);
409 pathsWithDuplicateInstallName.insert(installNameToFirstPath[installName]);
410 }
411 }
412
413 for (DyldSharedCache::MappedMachO& aFile : fileSet.dylibsForCache) {
414 if ( dontCache(volumePrefix, fileSet.archName, pathsWithDuplicateInstallName, aFile, true, skipDylibs) )
415 fileSet.otherDylibsAndBundles.push_back(aFile);
416 }
417 fileSet.dylibsForCache.erase(std::remove_if(fileSet.dylibsForCache.begin(), fileSet.dylibsForCache.end(),
418 [&](const DyldSharedCache::MappedMachO& aFile) { return dontCache(volumePrefix, fileSet.archName, pathsWithDuplicateInstallName, aFile, false, skipDylibs); }),
419 fileSet.dylibsForCache.end());
420 }
421
422 static void pruneOtherDylibs(const std::string& volumePrefix, MappedMachOsByCategory& fileSet)
423 {
424 // other OS dylibs should not contain dylibs that are embedded in some .app bundle
425 fileSet.otherDylibsAndBundles.erase(std::remove_if(fileSet.otherDylibsAndBundles.begin(), fileSet.otherDylibsAndBundles.end(),
426 [&](const DyldSharedCache::MappedMachO& aFile) { return (aFile.runtimePath.find(".app/") != std::string::npos); }),
427 fileSet.otherDylibsAndBundles.end());
428 }
429 static void pruneExecutables(const std::string& volumePrefix, MappedMachOsByCategory& fileSet)
430 {
431 // 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
432 fileSet.mainExecutables.erase(std::remove_if(fileSet.mainExecutables.begin(), fileSet.mainExecutables.end(),
433 [&](const DyldSharedCache::MappedMachO& aFile) {
434 if ( !startsWith(aFile.runtimePath, "/usr/bin/") )
435 return false;
436 __block bool isXcodeShim = false;
437 aFile.mh->forEachDependentDylib(^(const char* loadPath, bool, bool, bool, uint32_t, uint32_t, bool &stop) {
438 if ( strcmp(loadPath, "/usr/lib/libxcselect.dylib") == 0 )
439 isXcodeShim = true;
440 });
441 return isXcodeShim;
442 }), fileSet.mainExecutables.end());
443 }
444
445 static bool existingCacheUpToDate(const std::string& existingCache, const std::vector<DyldSharedCache::MappedMachO>& currentDylibs)
446 {
447 // if no existing cache, it is not up-to-date
448 int fd = ::open(existingCache.c_str(), O_RDONLY);
449 if ( fd < 0 )
450 return false;
451
452 // build map of found dylibs
453 std::unordered_map<std::string, const DyldSharedCache::MappedMachO*> currentDylibMap;
454 for (const DyldSharedCache::MappedMachO& aFile : currentDylibs) {
455 //fprintf(stderr, "0x%0llX 0x%0llX %s\n", aFile.inode, aFile.modTime, aFile.runtimePath.c_str());
456 currentDylibMap[aFile.runtimePath] = &aFile;
457 }
458
459 // make sure all dylibs in existing cache have same mtime and inode as found dylib
460 __block bool foundMismatch = false;
461 const uint64_t cacheMapLen = 0x40000000;
462 void *p = ::mmap(NULL, cacheMapLen, PROT_READ, MAP_PRIVATE, fd, 0);
463 if ( p != MAP_FAILED ) {
464 const DyldSharedCache* cache = (DyldSharedCache*)p;
465 cache->forEachImageEntry(^(const char* installName, uint64_t mTime, uint64_t inode) {
466 bool foundMatch = false;
467 auto pos = currentDylibMap.find(installName);
468 if ( pos != currentDylibMap.end() ) {
469 const DyldSharedCache::MappedMachO* foundDylib = pos->second;
470 if ( (foundDylib->inode == inode) && (foundDylib->modTime == mTime) ) {
471 foundMatch = true;
472 }
473 }
474 if ( !foundMatch ) {
475 // use slow path and look for any dylib with a matching inode and mtime
476 bool foundSlow = false;
477 for (const DyldSharedCache::MappedMachO& aFile : currentDylibs) {
478 if ( (aFile.inode == inode) && (aFile.modTime == mTime) ) {
479 foundSlow = true;
480 break;
481 }
482 }
483 if ( !foundSlow ) {
484 foundMismatch = true;
485 if ( verbose )
486 fprintf(stderr, "rebuilding dyld cache because dylib changed: %s\n", installName);
487 }
488 }
489 });
490 ::munmap(p, cacheMapLen);
491 }
492
493 ::close(fd);
494
495 return !foundMismatch;
496 }
497
498
499 inline uint32_t absolutetime_to_milliseconds(uint64_t abstime)
500 {
501 return (uint32_t)(abstime/1000/1000);
502 }
503
504 static bool runningOnHaswell()
505 {
506 // check system is capable of running x86_64h code
507 struct host_basic_info info;
508 mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
509 mach_port_t hostPort = mach_host_self();
510 kern_return_t result = host_info(hostPort, HOST_BASIC_INFO, (host_info_t)&info, &count);
511 mach_port_deallocate(mach_task_self(), hostPort);
512
513 return ( (result == KERN_SUCCESS) && (info.cpu_subtype == CPU_SUBTYPE_X86_64_H) );
514 }
515
516
517
518 #define TERMINATE_IF_LAST_ARG( s ) \
519 do { \
520 if ( i == argc - 1 ) { \
521 fprintf(stderr, s ); \
522 return 1; \
523 } \
524 } while ( 0 )
525
526 int main(int argc, const char* argv[], const char* envp[])
527 {
528 std::string rootPath;
529 std::string overlayPath;
530 std::string dylibListFile;
531 bool universal = false;
532 bool force = false;
533 bool searchDisk = false;
534 bool dylibsRemoved = false;
535 std::string cacheDir;
536 std::unordered_set<std::string> archStrs;
537 std::unordered_set<std::string> skipDylibs;
538
539 // parse command line options
540 for (int i = 1; i < argc; ++i) {
541 const char* arg = argv[i];
542 if (strcmp(arg, "-debug") == 0) {
543 verbose = true;
544 }
545 else if (strcmp(arg, "-verbose") == 0) {
546 verbose = true;
547 }
548 else if (strcmp(arg, "-dont_map_local_symbols") == 0) {
549 //We are going to ignore this
550 }
551 else if (strcmp(arg, "-dylib_list") == 0) {
552 TERMINATE_IF_LAST_ARG("-dylib_list missing argument");
553 dylibListFile = argv[++i];
554 }
555 else if ((strcmp(arg, "-root") == 0) || (strcmp(arg, "--root") == 0)) {
556 TERMINATE_IF_LAST_ARG("-root missing path argument\n");
557 rootPath = argv[++i];
558 }
559 else if (strcmp(arg, "-overlay") == 0) {
560 TERMINATE_IF_LAST_ARG("-overlay missing path argument\n");
561 overlayPath = argv[++i];
562 }
563 else if (strcmp(arg, "-cache_dir") == 0) {
564 TERMINATE_IF_LAST_ARG("-cache_dir missing path argument\n");
565 cacheDir = argv[++i];
566 }
567 else if (strcmp(arg, "-arch") == 0) {
568 TERMINATE_IF_LAST_ARG("-arch missing argument\n");
569 archStrs.insert(argv[++i]);
570 }
571 else if (strcmp(arg, "-search_disk") == 0) {
572 searchDisk = true;
573 }
574 else if (strcmp(arg, "-dylibs_removed_in_mastering") == 0) {
575 dylibsRemoved = true;
576 }
577 else if (strcmp(arg, "-force") == 0) {
578 force = true;
579 }
580 else if (strcmp(arg, "-sort_by_name") == 0) {
581 //No-op, we always do this now
582 }
583 else if (strcmp(arg, "-universal_boot") == 0) {
584 universal = true;
585 }
586 else if (strcmp(arg, "-skip") == 0) {
587 TERMINATE_IF_LAST_ARG("-skip missing argument\n");
588 skipDylibs.insert(argv[++i]);
589 }
590 else {
591 //usage();
592 fprintf(stderr, "update_dyld_shared_cache: unknown option: %s\n", arg);
593 return 1;
594 }
595 }
596
597 if ( !rootPath.empty() & !overlayPath.empty() ) {
598 fprintf(stderr, "-root and -overlay cannot be used together\n");
599 return 1;
600 }
601 // canonicalize rootPath
602 if ( !rootPath.empty() ) {
603 char resolvedPath[PATH_MAX];
604 if ( realpath(rootPath.c_str(), resolvedPath) != NULL ) {
605 rootPath = resolvedPath;
606 }
607 // <rdar://problem/33223984> when building closures for boot volume, pathPrefixes should be empty
608 if ( rootPath == "/" ) {
609 rootPath = "";
610 }
611 }
612 // canonicalize overlayPath
613 if ( !overlayPath.empty() ) {
614 char resolvedPath[PATH_MAX];
615 if ( realpath(overlayPath.c_str(), resolvedPath) != NULL ) {
616 overlayPath = resolvedPath;
617 }
618 }
619
620 // <rdar://problem/36362221> update_dyld_shared_cache should re-exec() itself to a newer version
621 std::string newTool;
622 if ( !rootPath.empty() )
623 newTool = rootPath + "/usr/bin/update_dyld_shared_cache";
624 else if ( !overlayPath.empty() )
625 newTool = overlayPath + "/usr/bin/update_dyld_shared_cache";
626 if ( !newTool.empty() ) {
627 struct stat newToolStatBuf;
628 if ( stat(newTool.c_str(), &newToolStatBuf) == 0 ) {
629 char curToolPath[PATH_MAX];
630 uint32_t curToolPathsize = PATH_MAX;
631 int result = _NSGetExecutablePath(curToolPath, &curToolPathsize);
632 if ( result == 0 ) {
633 char resolvedCurToolPath[PATH_MAX];
634 if ( realpath(curToolPath, resolvedCurToolPath) != NULL ) {
635 // don't re-exec if we are already running that tool
636 if ( newTool != resolvedCurToolPath ) {
637 execve(newTool.c_str(), (char**)argv, (char**)envp);
638 }
639 }
640 }
641 }
642 }
643
644 // Find the boot volume so that we can ensure all overlays are on the same volume
645 struct stat rootStatBuf;
646 if ( stat(rootPath == "" ? "/" : rootPath.c_str(), &rootStatBuf) != 0 ) {
647 fprintf(stderr, "update_dyld_shared_cache: error: could not stat root file system because '%s'\n", strerror(errno));
648 return 1;
649 }
650
651 dev_t rootFS = rootStatBuf.st_dev;
652
653 //
654 // pathPrefixes for three modes:
655 // 1) no options: { "" } // search only boot volume
656 // 2) -overlay: { overlay, "" } // search overlay, then boot volume
657 // 3) -root: { root } // search only -root volume
658 //
659 std::vector<std::string> pathPrefixes;
660 if ( !overlayPath.empty() ) {
661 // Only add the overlay path if it exists, and is the same volume as the root
662 struct stat overlayStatBuf;
663 if ( stat(overlayPath.c_str(), &overlayStatBuf) != 0 ) {
664 fprintf(stderr, "update_dyld_shared_cache: warning: ignoring overlay dir '%s' because '%s'\n", overlayPath.c_str(), strerror(errno));
665 overlayPath.clear();
666 } else if (overlayStatBuf.st_dev != rootFS) {
667 fprintf(stderr, "update_dyld_shared_cache: warning: ignoring overlay dir '%s' because it is not the boot volume\n", overlayPath.c_str());
668 overlayPath.clear();
669 } else {
670 pathPrefixes.push_back(overlayPath);
671 }
672 }
673 pathPrefixes.push_back(rootPath);
674
675 if ( cacheDir.empty() ) {
676 // if -cache_dir is not specified, then write() will eventually fail if we are not running as root
677 if ( geteuid() != 0 ) {
678 fprintf(stderr, "update_dyld_shared_cache: must be run as root (sudo)\n");
679 return 1;
680 }
681
682 // write cache file into -root or -overlay directory, if used
683 if ( rootPath != "/" )
684 cacheDir = rootPath + MACOSX_DYLD_SHARED_CACHE_DIR;
685 else if ( !overlayPath.empty() )
686 cacheDir = overlayPath + MACOSX_DYLD_SHARED_CACHE_DIR;
687 else
688 cacheDir = MACOSX_DYLD_SHARED_CACHE_DIR;
689 }
690
691 int err = mkpath_np(cacheDir.c_str(), S_IRWXU | S_IRGRP|S_IXGRP | S_IROTH|S_IXOTH);
692 if ( (err != 0) && (err != EEXIST) ) {
693 fprintf(stderr, "update_dyld_shared_cache: could not access cache dir: mkpath_np(%s) failed errno=%d\n", cacheDir.c_str(), err);
694 return 1;
695 }
696
697 if ( archStrs.empty() ) {
698 if ( universal ) {
699 // <rdar://problem/26182089> -universal_boot should make all possible dyld caches
700 archStrs.insert("i386");
701 archStrs.insert("x86_64");
702 archStrs.insert("x86_64h");
703 }
704 else {
705 // just make caches for this machine
706 archStrs.insert("i386");
707 archStrs.insert(runningOnHaswell() ? "x86_64h" : "x86_64");
708 }
709 }
710
711 uint64_t t1 = mach_absolute_time();
712
713 // find all mach-o files for requested architectures
714 bool requireDylibsBeRootlessProtected = isProtectedBySIP(cacheDir);
715 __block std::vector<MappedMachOsByCategory> allFileSets;
716 if ( archStrs.count("x86_64") )
717 allFileSets.push_back({"x86_64"});
718 if ( archStrs.count("x86_64h") )
719 allFileSets.push_back({"x86_64h"});
720 if ( archStrs.count("i386") )
721 allFileSets.push_back({"i386"});
722 if ( searchDisk )
723 findAllFiles(pathPrefixes, requireDylibsBeRootlessProtected, rootFS, allFileSets);
724 else {
725 std::unordered_set<std::string> runtimePathsFound;
726 findOSFilesViaBOMS(pathPrefixes, requireDylibsBeRootlessProtected, rootFS, allFileSets);
727 }
728
729 // nothing in OS uses i386 dylibs, so only dylibs used by third party apps need to be in cache
730 for (MappedMachOsByCategory& fileSet : allFileSets) {
731 pruneCachedDylibs(rootPath, skipDylibs, fileSet);
732 pruneOtherDylibs(rootPath, fileSet);
733 pruneExecutables(rootPath, fileSet);
734 }
735
736 uint64_t t2 = mach_absolute_time();
737 if ( verbose ) {
738 if ( searchDisk )
739 fprintf(stderr, "time to scan file system and construct lists of mach-o files: %ums\n", absolutetime_to_milliseconds(t2-t1));
740 else
741 fprintf(stderr, "time to read BOM and construct lists of mach-o files: %ums\n", absolutetime_to_milliseconds(t2-t1));
742 }
743
744 // build caches in parallel on machines with at leat 4GB of RAM
745 uint64_t memSize = 0;
746 size_t sz = sizeof(memSize);;
747 bool buildInParallel = false;
748 if ( sysctlbyname("hw.memsize", &memSize, &sz, NULL, 0) == 0 ) {
749 if ( memSize >= 0x100000000ULL )
750 buildInParallel = true;
751 }
752 dispatch_queue_t dqueue = buildInParallel ? dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
753 : dispatch_queue_create("serial-queue", DISPATCH_QUEUE_SERIAL);
754
755 // build all caches
756 __block bool cacheBuildFailure = false;
757 __block bool wroteSomeCacheFile = false;
758 dispatch_apply(allFileSets.size(), dqueue, ^(size_t index) {
759 MappedMachOsByCategory& fileSet = allFileSets[index];
760 const std::string outFile = cacheDir + "/dyld_shared_cache_" + fileSet.archName;
761
762 DyldSharedCache::MappedMachO (^loader)(const std::string&) = ^DyldSharedCache::MappedMachO(const std::string& runtimePath) {
763 if ( skipDylibs.count(runtimePath) )
764 return DyldSharedCache::MappedMachO();
765 for (const std::string& prefix : pathPrefixes) {
766 std::string fullPath = prefix + runtimePath;
767 struct stat statBuf;
768 if ( stat(fullPath.c_str(), &statBuf) == 0 ) {
769 dyld3::closure::FileSystemPhysical fileSystem(prefix.c_str());
770 char resolvedPath[PATH_MAX];
771 if ( realpath(fullPath.c_str(), resolvedPath) != NULL ) {
772 std::string resolvedSymlink = resolvedPath;
773 if ( !rootPath.empty() ) {
774 resolvedSymlink = resolvedSymlink.substr(rootPath.size());
775 }
776 if ( (runtimePath != resolvedSymlink) && !contains(runtimePath, "InputContext") ) { //HACK remove InputContext when fixed
777 // path requested is a symlink path, check if real path already loaded
778 for (const DyldSharedCache::MappedMachO& aDylibMapping : fileSet.dylibsForCache) {
779 if ( aDylibMapping.runtimePath == resolvedSymlink ) {
780 if ( verbose )
781 fprintf(stderr, "verifySelfContained, redirect %s to %s\n", runtimePath.c_str(), aDylibMapping.runtimePath.c_str());
782 return aDylibMapping;
783 }
784 }
785 }
786 }
787
788 std::vector<MappedMachOsByCategory> mappedFiles;
789 mappedFiles.push_back({fileSet.archName});
790 if ( addIfMachO(fileSystem, runtimePath, statBuf, requireDylibsBeRootlessProtected, rootFS, mappedFiles) ) {
791 if ( !mappedFiles.back().dylibsForCache.empty() ) {
792 if ( verbose )
793 fprintf(stderr, "verifySelfContained, add %s\n", mappedFiles.back().dylibsForCache.back().runtimePath.c_str());
794 return mappedFiles.back().dylibsForCache.back();
795 }
796 }
797 }
798 }
799 return DyldSharedCache::MappedMachO();
800 };
801 size_t startCount = fileSet.dylibsForCache.size();
802 std::vector<std::pair<DyldSharedCache::MappedMachO, std::set<std::string>>> excludes;
803 DyldSharedCache::verifySelfContained(fileSet.dylibsForCache, loader, excludes);
804 for (size_t i=startCount; i < fileSet.dylibsForCache.size(); ++i) {
805 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());
806 }
807 for (auto& exclude : excludes) {
808 std::string reasons = "(\"";
809 for (auto i = exclude.second.begin(); i != exclude.second.end(); ++i) {
810 reasons += *i;
811 if (i != --exclude.second.end()) {
812 reasons += "\", \"";
813 }
814 }
815 reasons += "\")";
816 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());
817 fileSet.otherDylibsAndBundles.push_back(exclude.first);
818 }
819
820 // check if cache is already up to date
821 if ( !force ) {
822 if ( existingCacheUpToDate(outFile, fileSet.dylibsForCache) )
823 return;
824 }
825
826 // add any extra dylibs needed which were not in .bom
827 fprintf(stderr, "update_dyld_shared_cache: %s incorporating %lu OS dylibs, tracking %lu others, building closures for %lu executables\n",
828 fileSet.archName.c_str(), fileSet.dylibsForCache.size(), fileSet.otherDylibsAndBundles.size(), fileSet.mainExecutables.size());
829 //for (const DyldSharedCache::MappedMachO& aFile : fileSet.otherDylibsAndBundles) {
830 // fprintf(stderr, " %s\n", aFile.runtimePath.c_str());
831 //}
832
833
834 // build cache new cache file
835 DyldSharedCache::CreateOptions options;
836 options.outputFilePath = outFile;
837 options.outputMapFilePath = cacheDir + "/dyld_shared_cache_" + fileSet.archName + ".map";
838 options.archName = fileSet.archName;
839 options.platform = dyld3::Platform::macOS;
840 options.excludeLocalSymbols = false;
841 options.optimizeStubs = false;
842 options.optimizeObjC = true;
843 options.codeSigningDigestMode = DyldSharedCache::SHA256only;
844 options.dylibsRemovedDuringMastering = dylibsRemoved;
845 options.inodesAreSameAsRuntime = true;
846 options.cacheSupportsASLR = (fileSet.archName != "i386");
847 options.forSimulator = false;
848 options.isLocallyBuiltCache = true;
849 options.verbose = verbose;
850 options.evictLeafDylibsOnOverflow = true;
851 options.pathPrefixes = pathPrefixes;
852 DyldSharedCache::CreateResults results = DyldSharedCache::create(options, fileSet.dylibsForCache, fileSet.otherDylibsAndBundles, fileSet.mainExecutables);
853
854 // print any warnings
855 for (const std::string& warn : results.warnings) {
856 fprintf(stderr, "update_dyld_shared_cache: warning: %s %s\n", fileSet.archName.c_str(), warn.c_str());
857 }
858 if ( results.errorMessage.empty() ) {
859 wroteSomeCacheFile = true;
860 }
861 else {
862 fprintf(stderr, "update_dyld_shared_cache: %s\n", results.errorMessage.c_str());
863 cacheBuildFailure = true;
864 }
865 });
866
867
868 // Save off spintrace data
869 if ( wroteSomeCacheFile ) {
870 void* h = dlopen("/usr/lib/libdscsym.dylib", 0);
871 if ( h != nullptr ) {
872 typedef int (*dscym_func)(const char*);
873 dscym_func func = (dscym_func)dlsym(h, "dscsym_save_dscsyms_for_current_caches");
874 std::string nuggetRoot = rootPath;
875 if ( nuggetRoot.empty() )
876 nuggetRoot = overlayPath;
877 if ( nuggetRoot.empty() )
878 nuggetRoot = "/";
879 (*func)(nuggetRoot.c_str());
880 }
881 }
882
883
884 // we could unmap all input files, but tool is about to quit
885
886 return (cacheBuildFailure ? 1 : 0);
887 }
888