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