1 /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
3 * Copyright (c) 2016 Apple Inc. All rights reserved.
5 * @APPLE_LICENSE_HEADER_START@
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
22 * @APPLE_LICENSE_HEADER_END@
25 #include <sys/types.h>
28 #include <mach/mach.h>
29 #include <mach/mach_time.h>
42 #include <sys/param.h>
43 #include <sys/sysctl.h>
44 #include <sys/resource.h>
48 #include <dispatch/dispatch.h>
49 #include <pthread/pthread.h>
53 #include <unordered_set>
54 #include <unordered_set>
58 #include "MachOParser.h"
59 #include "FileUtils.h"
60 #include "StringUtils.h"
61 #include "DyldSharedCache.h"
65 struct MappedMachOsByCategory
68 std::vector
<DyldSharedCache::MappedMachO
> dylibsForCache
;
69 std::vector
<DyldSharedCache::MappedMachO
> otherDylibsAndBundles
;
70 std::vector
<DyldSharedCache::MappedMachO
> mainExecutables
;
73 static bool verbose
= false;
76 static bool addIfMachO(const std::string
& buildRootPath
, const std::string
& runtimePath
, const struct stat
& statBuf
, dyld3::Platform platform
, std::vector
<MappedMachOsByCategory
>& files
)
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
);
84 const void* wholeFile
= ::mmap(NULL
, (size_t)statBuf
.st_size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
85 if ( wholeFile
!= MAP_FAILED
) {
87 bool usedWholeFile
= false;
88 for (MappedMachOsByCategory
& file
: files
) {
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
);
103 else if ( !fatButMissingSlice
&& dyld3::MachOParser::isValidMachO(diag
, file
.archName
, platform
, wholeFile
, statBuf
.st_size
, fullPath
.c_str(), false) ) {
105 sliceLength
= statBuf
.st_size
;
107 usedWholeFile
= true;
108 //fprintf(stderr, "mapped whole file at %p size=0x%0lX for %s\n", p, len, inputPath.c_str());
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());
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
);
124 if ( parser
.canBePlacedInDyldCache(runtimePath
) ) {
125 file
.dylibsForCache
.emplace_back(runtimePath
, mh
, sliceLength
, false, sip
, sliceOffset
, statBuf
.st_mtime
, statBuf
.st_ino
);
128 file
.otherDylibsAndBundles
.emplace_back(runtimePath
, mh
, sliceLength
, false, sip
, sliceOffset
, statBuf
.st_mtime
, statBuf
.st_ino
);
135 if ( !usedWholeFile
)
136 ::munmap((void*)wholeFile
, statBuf
.st_size
);
143 static bool parsePathsFile(const std::string
& filePath
, std::vector
<std::string
>& paths
) {
144 std::ifstream
myfile( filePath
);
145 if ( myfile
.is_open() ) {
147 while ( std::getline(myfile
, line
) ) {
148 size_t pos
= line
.find('#');
149 if ( pos
!= std::string::npos
)
151 while ( line
.size() != 0 && isspace(line
.back()) ) {
155 paths
.push_back(line
);
164 static void mapAllFiles(const std::string
& dylibsRootDir
, const std::vector
<std::string
>& paths
, dyld3::Platform platform
, std::vector
<MappedMachOsByCategory
>& files
)
166 for (const std::string
& runtimePath
: paths
) {
167 std::string fullPath
= dylibsRootDir
+ runtimePath
;
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());
176 inline uint32_t absolutetime_to_milliseconds(uint64_t abstime
)
178 return (uint32_t)(abstime
/1000/1000);
182 #define TERMINATE_IF_LAST_ARG( s ) \
184 if ( i == argc - 1 ) { \
185 fprintf(stderr, s ); \
190 int main(int argc
, const char* argv
[])
192 std::string rootPath
;
193 std::string dylibListFile
;
195 std::string cacheDir
;
196 std::string dylibsList
;
197 std::unordered_set
<std::string
> archStrs
;
199 dyld3::Platform platform
= dyld3::Platform::iOS
;
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) {
207 else if (strcmp(arg
, "-verbose") == 0) {
210 else if (strcmp(arg
, "-tvOS") == 0) {
211 platform
= dyld3::Platform::tvOS
;
213 else if (strcmp(arg
, "-iOS") == 0) {
214 platform
= dyld3::Platform::iOS
;
216 else if (strcmp(arg
, "-watchOS") == 0) {
217 platform
= dyld3::Platform::watchOS
;
219 else if ( strcmp(arg
, "-root") == 0 ) {
220 TERMINATE_IF_LAST_ARG("-root missing path argument\n");
221 rootPath
= argv
[++i
];
223 else if ( strcmp(arg
, "-dylibs_list") == 0 ) {
224 TERMINATE_IF_LAST_ARG("-dylibs_list missing path argument\n");
225 dylibsList
= argv
[++i
];
227 else if (strcmp(arg
, "-cache_dir") == 0) {
228 TERMINATE_IF_LAST_ARG("-cache_dir missing path argument\n");
229 cacheDir
= argv
[++i
];
231 else if (strcmp(arg
, "-arch") == 0) {
232 TERMINATE_IF_LAST_ARG("-arch missing argument\n");
233 archStrs
.insert(argv
[++i
]);
235 else if (strcmp(arg
, "-force") == 0) {
240 fprintf(stderr
, "update_dyld_sim_shared_cache: unknown option: %s\n", arg
);
245 if ( cacheDir
.empty() ) {
246 fprintf(stderr
, "missing -cache_dir <path> option to specify directory in which to write cache file(s)\n");
250 if ( rootPath
.empty() ) {
251 fprintf(stderr
, "missing -runtime_dir <path> option to specify directory which is root of simulator runtime)\n");
255 // canonicalize rootPath
256 char resolvedPath
[PATH_MAX
];
257 if ( realpath(rootPath
.c_str(), resolvedPath
) != NULL
) {
258 rootPath
= resolvedPath
;
260 if ( rootPath
.back() != '/' )
261 rootPath
= rootPath
+ "/";
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
);
270 if ( archStrs
.empty() ) {
271 switch ( platform
) {
272 case dyld3::Platform::iOS
:
273 case dyld3::Platform::tvOS
:
274 archStrs
.insert("arm64");
276 case dyld3::Platform::watchOS
:
277 archStrs
.insert("armv7k");
279 case dyld3::Platform::unknown
:
280 case dyld3::Platform::macOS
:
281 assert(0 && "macOS not support with this tool");
286 uint64_t t1
= mach_absolute_time();
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
);
298 uint64_t t2
= mach_absolute_time();
300 fprintf(stderr
, "time to scan file system and construct lists of mach-o files: %ums\n", absolutetime_to_milliseconds(t2
-t1
));
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
;
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());
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
);
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());
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;
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
);
347 // free created cache buffer
348 vm_deallocate(mach_task_self(), (vm_address_t
)results
.cacheContent
, results
.cacheLength
);
352 // we could unmap all input files, but tool is about to quit
354 return (cacheBuildFailure
? 1 : 0);