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 <sys/resource.h>
29 #include <mach/mach.h>
30 #include <mach/mach_time.h>
42 #include <sys/param.h>
43 #include <sys/sysctl.h>
44 #include <sys/resource.h>
54 #include <unordered_set>
62 #include "Diagnostics.h"
63 #include "DyldSharedCache.h"
64 #include "BuilderUtils.h"
65 #include "FileUtils.h"
66 #include "StringUtils.h"
67 #include "MachOParser.h"
69 #if !__has_feature(objc_arc)
70 #error The use of libdispatch in this files requires it to be compiled with ARC in order to avoid leaks
73 extern char** environ;
75 static dispatch_queue_t build_queue;
77 static const char* tempRootDirTemplate = "/tmp/dyld_shared_cache_builder.XXXXXX";
78 static char* tempRootDir = nullptr;
80 int runCommandAndWait(Diagnostics& diags, const char* args[])
84 int res = posix_spawn(&pid, args[0], nullptr, nullptr, (char**)args, environ);
86 diags.error("Failed to spawn %s: %s (%d)", args[0], strerror(res), res);
89 res = waitpid(pid, &status, 0);
90 } while (res == -1 && errno == EINTR);
92 if (WIFEXITED(status)) {
93 res = WEXITSTATUS(status);
102 void processRoots(Diagnostics& diags, std::set<std::string>& roots)
104 std::set<std::string> processedRoots;
109 for (const auto& root : roots) {
110 res = stat(root.c_str(), &sb);
112 if (res == 0 && S_ISDIR(sb.st_mode)) {
115 } else if (endsWith(root, ".cpio") || endsWith(root, ".cpio.gz") || endsWith(root, ".cpgz") || endsWith(root, ".cpio.bz2") || endsWith(root, ".cpbz2") || endsWith(root, ".pax") || endsWith(root, ".pax.gz") || endsWith(root, ".pgz") || endsWith(root, ".pax.bz2") || endsWith(root, ".pbz2")) {
116 args[0] = (char*)"/usr/bin/ditto";
117 args[1] = (char*)"-x";
118 args[2] = (char*)root.c_str();
119 args[3] = tempRootDir;
121 } else if (endsWith(root, ".tar")) {
122 args[0] = (char*)"/usr/bin/tar";
123 args[1] = (char*)"xf";
124 args[2] = (char*)root.c_str();
125 args[3] = (char*)"-C";
126 args[4] = tempRootDir;
128 } else if (endsWith(root, ".tar.gz") || endsWith(root, ".tgz")) {
129 args[0] = (char*)"/usr/bin/tar";
130 args[1] = (char*)"xzf";
131 args[2] = (char*)root.c_str();
132 args[3] = (char*)"-C";
133 args[4] = tempRootDir;
135 } else if (endsWith(root, ".tar.bz2")
136 || endsWith(root, ".tbz2")
137 || endsWith(root, ".tbz")) {
138 args[0] = (char*)"/usr/bin/tar";
139 args[1] = (char*)"xjf";
140 args[2] = (char*)root.c_str();
141 args[3] = (char*)"-C";
142 args[4] = tempRootDir;
144 } else if (endsWith(root, ".xar")) {
145 args[0] = (char*)"/usr/bin/xar";
146 args[1] = (char*)"-xf";
147 args[2] = (char*)root.c_str();
148 args[3] = (char*)"-C";
149 args[4] = tempRootDir;
151 } else if (endsWith(root, ".zip")) {
152 args[0] = (char*)"/usr/bin/ditto";
153 args[1] = (char*)"-xk";
154 args[2] = (char*)root.c_str();
155 args[3] = tempRootDir;
158 diags.error("unknown archive type: %s", root.c_str());
162 if (res != runCommandAndWait(diags, args)) {
163 fprintf(stderr, "Could not expand archive %s: %s (%d)", root.c_str(), strerror(res), res);
166 for (auto& existingRoot : processedRoots) {
167 if (existingRoot == tempRootDir)
171 processedRoots.insert(tempRootDir);
174 roots = processedRoots;
177 bool writeRootList(const std::string& dstRoot, const std::set<std::string>& roots)
179 if (roots.size() == 0)
182 std::string rootFile = dstRoot + "/roots.txt";
183 FILE* froots = ::fopen(rootFile.c_str(), "w");
187 for (auto& root : roots) {
188 fprintf(froots, "%s\n", root.c_str());
195 std::set<std::string> cachePaths;
197 BOMCopierCopyOperation filteredCopy(BOMCopier copier, const char* path, BOMFSObjType type, off_t size)
199 std::string absolutePath = &path[1];
200 if (cachePaths.count(absolutePath)) {
201 return BOMCopierSkipFile;
203 return BOMCopierContinue;
206 int main(int argc, const char* argv[])
209 __block Diagnostics diags;
210 std::set<std::string> roots;
211 std::string dylibCacheDir;
213 bool emitDevCaches = true;
214 bool emitElidedDylibs = true;
215 bool listConfigs = false;
216 bool copyRoots = false;
219 std::string configuration;
220 std::string resultPath;
222 tempRootDir = strdup(tempRootDirTemplate);
223 mkdtemp(tempRootDir);
225 for (int i = 1; i < argc; ++i) {
226 const char* arg = argv[i];
228 if (strcmp(arg, "-debug") == 0) {
229 diags = Diagnostics(true);
231 } else if (strcmp(arg, "-list_configs") == 0) {
233 } else if (strcmp(arg, "-root") == 0) {
234 roots.insert(realPath(argv[++i]));
235 } else if (strcmp(arg, "-copy_roots") == 0) {
237 } else if (strcmp(arg, "-dylib_cache") == 0) {
238 dylibCacheDir = realPath(argv[++i]);
239 } else if (strcmp(arg, "-no_development_cache") == 0) {
240 emitDevCaches = false;
241 } else if (strcmp(arg, "-no_overflow_dylibs") == 0) {
242 emitElidedDylibs = false;
243 } else if (strcmp(arg, "-development_cache") == 0) {
244 emitDevCaches = true;
245 } else if (strcmp(arg, "-overflow_dylibs") == 0) {
246 emitElidedDylibs = true;
247 } else if (strcmp(arg, "-dst_root") == 0) {
248 dstRoot = realPath(argv[++i]);
249 } else if (strcmp(arg, "-release") == 0) {
251 } else if (strcmp(arg, "-results") == 0) {
252 resultPath = realPath(argv[++i]);
255 diags.error("unknown option: %s\n", arg);
258 if (!configuration.empty()) {
259 diags.error("You may only specify one configuration");
261 configuration = argv[i];
265 time_t mytime = time(0);
266 fprintf(stderr, "Started: %s", asctime(localtime(&mytime)));
267 processRoots(diags, roots);
269 struct rlimit rl = { OPEN_MAX, OPEN_MAX };
270 (void)setrlimit(RLIMIT_NOFILE, &rl);
272 if (dylibCacheDir.empty() && release.empty()) {
273 fprintf(stderr, "you must specify either -dylib_cache or -release");
275 } else if (!dylibCacheDir.empty() && !release.empty()) {
276 fprintf(stderr, "you may not use -dylib_cache and -release at the same time");
280 if ((configuration.empty() || dstRoot.empty()) && !listConfigs) {
281 fprintf(stderr, "Must specify a configuration and a valid -dst_root OR -list_configs\n");
285 if (dylibCacheDir.empty()) {
286 dylibCacheDir = std::string("/AppleInternal/Developer/DylibCaches/") + release + ".dlc";
289 //Move into the dir so we can use relative path manifests
290 chdir(dylibCacheDir.c_str());
292 dispatch_async(dispatch_get_main_queue(), ^{
293 auto manifest = dyld3::Manifest(diags, dylibCacheDir + "/Manifest.plist", roots);
295 if (manifest.build().empty()) {
296 fprintf(stderr, "No manifest found at '%s/Manifest.plist'\n", dylibCacheDir.c_str());
299 fprintf(stderr, "Building Caches for %s\n", manifest.build().c_str());
302 manifest.forEachConfiguration([](const std::string& configName) {
303 printf("%s\n", configName.c_str());
307 if (!manifest.filterForConfig(configuration)) {
308 fprintf(stderr, "No config %s. Please run with -list_configs to see configurations available for this %s.\n",
309 configuration.c_str(), manifest.build().c_str());
312 manifest.calculateClosure();
314 std::vector<dyld3::BuildQueueEntry> buildQueue;
316 bool cacheBuildSuccess = build(diags, manifest, dstRoot, false, debug, false, false);
318 if (!cacheBuildSuccess) {
322 writeRootList(dstRoot, roots);
325 manifest.forEachConfiguration([&manifest](const std::string& configName) {
326 for (auto& arch : manifest.configuration(configName).architectures) {
327 for (auto& dylib : arch.second.results.dylibs) {
328 if (dylib.second.included) {
329 dyld3::MachOParser parser = manifest.parserForUUID(dylib.first);
330 cachePaths.insert(parser.installName());
336 BOMCopier copier = BOMCopierNewWithSys(BomSys_default());
337 BOMCopierSetCopyFileStartedHandler(copier, filteredCopy);
338 for (auto& root : roots) {
339 BOMCopierCopy(copier, root.c_str(), dstRoot.c_str());
341 BOMCopierFree(copier);
347 int err = sync_volume_np(dstRoot.c_str(), SYNC_VOLUME_FULLSYNC | SYNC_VOLUME_WAIT);
349 fprintf(stderr, "Volume sync failed errnor=%d (%s)\n", err, strerror(err));
352 // Create an empty FIPS data in the root
353 (void)mkpath_np((dstRoot + "/private/var/db/FIPS/").c_str(), 0755);
354 int fd = open((dstRoot + "/private/var/db/FIPS/fips_data").c_str(), O_CREAT | O_TRUNC, 0644);
357 // Now that all the build commands have been issued lets put a barrier in after then which can tear down the app after
358 // everything is written.
360 if (!resultPath.empty()) {
361 manifest.write(resultPath);
365 args[0] = (char*)"/bin/rm";
366 args[1] = (char*)"-rf";
367 args[2] = (char*)tempRootDir;
369 (void)runCommandAndWait(diags, args);
371 for (const std::string& warn : diags.warnings()) {
372 fprintf(stderr, "dyld_shared_cache_builder: warning: %s\n", warn.c_str());