]> git.saurik.com Git - apple/dyld.git/blob - dyld3/shared-cache/make_ios_dyld_cache.cpp
dyld-519.2.1.tar.gz
[apple/dyld.git] / dyld3 / shared-cache / make_ios_dyld_cache.cpp
1 /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
2 *
3 * Copyright (c) 2016 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
51 #include <algorithm>
52 #include <vector>
53 #include <unordered_set>
54 #include <unordered_set>
55 #include <iostream>
56 #include <fstream>
57
58 #include "MachOParser.h"
59 #include "FileUtils.h"
60 #include "StringUtils.h"
61 #include "DyldSharedCache.h"
62
63
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 bool verbose = false;
74
75
76 static bool addIfMachO(const std::string& buildRootPath, const std::string& runtimePath, const struct stat& statBuf, dyld3::Platform platform, std::vector<MappedMachOsByCategory>& files)
77 {
78 // read start of file to determine if it is mach-o or a fat file
79 std::string fullPath = buildRootPath + runtimePath;
80 int fd = ::open(fullPath.c_str(), O_RDONLY);
81 if ( fd < 0 )
82 return false;
83 bool result = false;
84 const void* wholeFile = ::mmap(NULL, (size_t)statBuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
85 if ( wholeFile != MAP_FAILED ) {
86 Diagnostics diag;
87 bool usedWholeFile = false;
88 for (MappedMachOsByCategory& file : files) {
89 size_t sliceOffset;
90 size_t sliceLength;
91 bool fatButMissingSlice;
92 const void* slice = MAP_FAILED;
93 if ( dyld3::FatUtil::isFatFileWithSlice(diag, wholeFile, statBuf.st_size, file.archName, sliceOffset, sliceLength, fatButMissingSlice) ) {
94 slice = ::mmap(NULL, sliceLength, PROT_READ, MAP_PRIVATE, fd, sliceOffset);
95 if ( slice != MAP_FAILED ) {
96 //fprintf(stderr, "mapped slice at %p size=0x%0lX, offset=0x%0lX for %s\n", p, len, offset, fullPath.c_str());
97 if ( !dyld3::MachOParser::isValidMachO(diag, file.archName, platform, slice, sliceLength, fullPath.c_str(), false) ) {
98 ::munmap((void*)slice, sliceLength);
99 slice = MAP_FAILED;
100 }
101 }
102 }
103 else if ( !fatButMissingSlice && dyld3::MachOParser::isValidMachO(diag, file.archName, platform, wholeFile, statBuf.st_size, fullPath.c_str(), false) ) {
104 slice = wholeFile;
105 sliceLength = statBuf.st_size;
106 sliceOffset = 0;
107 usedWholeFile = true;
108 //fprintf(stderr, "mapped whole file at %p size=0x%0lX for %s\n", p, len, inputPath.c_str());
109 }
110 if ( slice != MAP_FAILED ) {
111 const mach_header* mh = (mach_header*)slice;
112 dyld3::MachOParser parser(mh);
113 if ( parser.platform() != platform ) {
114 fprintf(stderr, "skipped wrong platform binary: %s\n", fullPath.c_str());
115 result = false;
116 }
117 else {
118 bool sip = true; // assume anything found in the simulator runtime is a platform binary
119 if ( parser.isDynamicExecutable() ) {
120 bool issetuid = (statBuf.st_mode & (S_ISUID|S_ISGID));
121 file.mainExecutables.emplace_back(runtimePath, mh, sliceLength, issetuid, sip, sliceOffset, statBuf.st_mtime, statBuf.st_ino);
122 }
123 else {
124 if ( parser.canBePlacedInDyldCache(runtimePath) ) {
125 file.dylibsForCache.emplace_back(runtimePath, mh, sliceLength, false, sip, sliceOffset, statBuf.st_mtime, statBuf.st_ino);
126 }
127 else {
128 file.otherDylibsAndBundles.emplace_back(runtimePath, mh, sliceLength, false, sip, sliceOffset, statBuf.st_mtime, statBuf.st_ino);
129 }
130 }
131 result = true;
132 }
133 }
134 }
135 if ( !usedWholeFile )
136 ::munmap((void*)wholeFile, statBuf.st_size);
137 }
138 ::close(fd);
139 return result;
140 }
141
142
143 static bool parsePathsFile(const std::string& filePath, std::vector<std::string>& paths) {
144 std::ifstream myfile( filePath );
145 if ( myfile.is_open() ) {
146 std::string line;
147 while ( std::getline(myfile, line) ) {
148 size_t pos = line.find('#');
149 if ( pos != std::string::npos )
150 line.resize(pos);
151 while ( line.size() != 0 && isspace(line.back()) ) {
152 line.pop_back();
153 }
154 if ( !line.empty() )
155 paths.push_back(line);
156 }
157 myfile.close();
158 return true;
159 }
160 return false;
161 }
162
163
164 static void mapAllFiles(const std::string& dylibsRootDir, const std::vector<std::string>& paths, dyld3::Platform platform, std::vector<MappedMachOsByCategory>& files)
165 {
166 for (const std::string& runtimePath : paths) {
167 std::string fullPath = dylibsRootDir + runtimePath;
168 struct stat statBuf;
169 if ( (stat(fullPath.c_str(), &statBuf) != 0) || !addIfMachO(dylibsRootDir, runtimePath, statBuf, platform, files) )
170 fprintf(stderr, "could not load: %s\n", fullPath.c_str());
171 }
172 }
173
174
175
176 inline uint32_t absolutetime_to_milliseconds(uint64_t abstime)
177 {
178 return (uint32_t)(abstime/1000/1000);
179 }
180
181
182 #define TERMINATE_IF_LAST_ARG( s ) \
183 do { \
184 if ( i == argc - 1 ) { \
185 fprintf(stderr, s ); \
186 return 1; \
187 } \
188 } while ( 0 )
189
190 int main(int argc, const char* argv[])
191 {
192 std::string rootPath;
193 std::string dylibListFile;
194 bool force = false;
195 std::string cacheDir;
196 std::string dylibsList;
197 std::unordered_set<std::string> archStrs;
198
199 dyld3::Platform platform = dyld3::Platform::iOS;
200
201 // parse command line options
202 for (int i = 1; i < argc; ++i) {
203 const char* arg = argv[i];
204 if (strcmp(arg, "-debug") == 0) {
205 verbose = true;
206 }
207 else if (strcmp(arg, "-verbose") == 0) {
208 verbose = true;
209 }
210 else if (strcmp(arg, "-tvOS") == 0) {
211 platform = dyld3::Platform::tvOS;
212 }
213 else if (strcmp(arg, "-iOS") == 0) {
214 platform = dyld3::Platform::iOS;
215 }
216 else if (strcmp(arg, "-watchOS") == 0) {
217 platform = dyld3::Platform::watchOS;
218 }
219 else if ( strcmp(arg, "-root") == 0 ) {
220 TERMINATE_IF_LAST_ARG("-root missing path argument\n");
221 rootPath = argv[++i];
222 }
223 else if ( strcmp(arg, "-dylibs_list") == 0 ) {
224 TERMINATE_IF_LAST_ARG("-dylibs_list missing path argument\n");
225 dylibsList = argv[++i];
226 }
227 else if (strcmp(arg, "-cache_dir") == 0) {
228 TERMINATE_IF_LAST_ARG("-cache_dir missing path argument\n");
229 cacheDir = argv[++i];
230 }
231 else if (strcmp(arg, "-arch") == 0) {
232 TERMINATE_IF_LAST_ARG("-arch missing argument\n");
233 archStrs.insert(argv[++i]);
234 }
235 else if (strcmp(arg, "-force") == 0) {
236 force = true;
237 }
238 else {
239 //usage();
240 fprintf(stderr, "update_dyld_sim_shared_cache: unknown option: %s\n", arg);
241 return 1;
242 }
243 }
244
245 if ( cacheDir.empty() ) {
246 fprintf(stderr, "missing -cache_dir <path> option to specify directory in which to write cache file(s)\n");
247 return 1;
248 }
249
250 if ( rootPath.empty() ) {
251 fprintf(stderr, "missing -runtime_dir <path> option to specify directory which is root of simulator runtime)\n");
252 return 1;
253 }
254 else {
255 // canonicalize rootPath
256 char resolvedPath[PATH_MAX];
257 if ( realpath(rootPath.c_str(), resolvedPath) != NULL ) {
258 rootPath = resolvedPath;
259 }
260 if ( rootPath.back() != '/' )
261 rootPath = rootPath + "/";
262 }
263
264 int err = mkpath_np(cacheDir.c_str(), S_IRWXU | S_IRGRP|S_IXGRP | S_IROTH|S_IXOTH);
265 if ( (err != 0) && (err != EEXIST) ) {
266 fprintf(stderr, "mkpath_np fail: %d", err);
267 return 1;
268 }
269
270 if ( archStrs.empty() ) {
271 switch ( platform ) {
272 case dyld3::Platform::iOS:
273 case dyld3::Platform::tvOS:
274 archStrs.insert("arm64");
275 break;
276 case dyld3::Platform::watchOS:
277 archStrs.insert("armv7k");
278 break;
279 case dyld3::Platform::unknown:
280 case dyld3::Platform::macOS:
281 assert(0 && "macOS not support with this tool");
282 break;
283 }
284 }
285
286 uint64_t t1 = mach_absolute_time();
287
288 // find all mach-o files for requested architectures
289 std::vector<MappedMachOsByCategory> allFileSets;
290 if ( archStrs.count("arm64") )
291 allFileSets.push_back({"arm64"});
292 if ( archStrs.count("armv7k") )
293 allFileSets.push_back({"armv7k"});
294 std::vector<std::string> paths;
295 parsePathsFile(dylibsList, paths);
296 mapAllFiles(rootPath, paths, platform, allFileSets);
297
298 uint64_t t2 = mach_absolute_time();
299
300 fprintf(stderr, "time to scan file system and construct lists of mach-o files: %ums\n", absolutetime_to_milliseconds(t2-t1));
301
302 // build all caches in parallel
303 __block bool cacheBuildFailure = false;
304 dispatch_apply(allFileSets.size(), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t index) {
305 const MappedMachOsByCategory& fileSet = allFileSets[index];
306 const std::string outFile = cacheDir + "/dyld_shared_cache_" + fileSet.archName;
307
308 fprintf(stderr, "make %s cache with %lu dylibs, %lu other dylibs, %lu programs\n", fileSet.archName.c_str(), fileSet.dylibsForCache.size(), fileSet.otherDylibsAndBundles.size(), fileSet.mainExecutables.size());
309
310 // build cache new cache file
311 DyldSharedCache::CreateOptions options;
312 options.archName = fileSet.archName;
313 options.platform = platform;
314 options.excludeLocalSymbols = true;
315 options.optimizeStubs = false;
316 options.optimizeObjC = true;
317 options.codeSigningDigestMode = (platform() == dyld3::Platform::watchOS) ?
318 DyldSharedCache::Agile : DyldSharedCache::SHA256only;
319 options.dylibsRemovedDuringMastering = true;
320 options.inodesAreSameAsRuntime = false;
321 options.cacheSupportsASLR = true;
322 options.forSimulator = false;
323 options.verbose = verbose;
324 options.evictLeafDylibsOnOverflow = false;
325 options.pathPrefixes = { rootPath };
326 DyldSharedCache::CreateResults results = DyldSharedCache::create(options, fileSet.dylibsForCache, fileSet.otherDylibsAndBundles, fileSet.mainExecutables);
327
328 // print any warnings
329 for (const std::string& warn : results.warnings) {
330 fprintf(stderr, "update_dyld_sim_shared_cache: warning: %s %s\n", fileSet.archName.c_str(), warn.c_str());
331 }
332 if ( !results.errorMessage.empty() ) {
333 // print error (if one)
334 fprintf(stderr, "update_dyld_sim_shared_cache: %s\n", results.errorMessage.c_str());
335 cacheBuildFailure = true;
336 }
337 else {
338 // save new cache file to disk and write new .map file
339 assert(results.cacheContent != nullptr);
340 if ( !safeSave(results.cacheContent, results.cacheLength, outFile) )
341 cacheBuildFailure = true;
342 if ( !cacheBuildFailure ) {
343 std::string mapStr = results.cacheContent->mapFile();
344 std::string outFileMap = cacheDir + "/dyld_shared_cache_" + fileSet.archName + ".map";
345 safeSave(mapStr.c_str(), mapStr.size(), outFileMap);
346 }
347 // free created cache buffer
348 vm_deallocate(mach_task_self(), (vm_address_t)results.cacheContent, results.cacheLength);
349 }
350 });
351
352 // we could unmap all input files, but tool is about to quit
353
354 return (cacheBuildFailure ? 1 : 0);
355 }
356