Loading...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 | /* * Copyright (c) 2017 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #include <stdio.h> #include <unistd.h> #include <sys/stat.h> #include <string.h> #include <dlfcn.h> #include <fcntl.h> #include <stdlib.h> #include <errno.h> #include <sys/mman.h> #include <sys/syslimits.h> #include <mach-o/arch.h> #include <mach-o/loader.h> #include <mach-o/dyld_priv.h> #include <bootstrap.h> #include <mach/mach.h> #include <dispatch/dispatch.h> #include <map> #include <vector> #include "DyldSharedCache.h" #include "FileUtils.h" #include "StringUtils.h" #include "ClosureFileSystemPhysical.h" #include "PrebuiltLoader.h" #include "DyldProcessConfig.h" #include "DyldRuntimeState.h" #include "JSONWriter.h" using dyld3::Array; using namespace dyld4; static void usage() { printf("dyld_closure_util program to create or view dyld3 closures\n"); printf(" mode:\n"); printf(" -create_closure <prog-path> # create a closure for the specified main executable\n"); printf(" -list_dyld_cache_closures # list all launch closures in the dyld shared cache with size\n"); printf(" -print_dyld_cache_closure <prog-path> # find closure for specified program in dyld cache and print as JSON\n"); printf(" -print_dyld_cache_dylib <dylib-path> # print specified cached dylib as JSON\n"); printf(" -print_dyld_cache_dylibs # print all cached dylibs as JSON\n"); printf(" -print_closure_file <closure-path> # print specified program closure as JSON\n"); printf(" options:\n"); printf(" -cache_file <cache-path> # path to cache file to use (default is current cache)\n"); printf(" -build_root <path-prefix> # when building a closure, the path prefix when runtime volume is not current boot volume\n"); printf(" -env <var=value> # when building a closure, DYLD_* env vars to assume\n"); printf(" -verbose_fixups # for use with -print* options to force printing fixups\n"); printf(" -no_at_paths # when building a closure, simulate security not allowing @path expansion\n"); printf(" -no_fallback_paths # when building a closure, simulate security not allowing default fallback paths\n"); printf(" -allow_insertion_failures # when building a closure, simulate security allowing unloadable DYLD_INSERT_LIBRARIES to be ignored\n"); } int main(int argc, const char* argv[]) { const char* cacheFilePath = nullptr; const char* inputMainExecutablePath = nullptr; const char* printCacheClosure = nullptr; const char* printCachedDylib = nullptr; const char* fsRootPath = nullptr; const char* fsOverlayPath = nullptr; const char* printClosureFile = nullptr; bool listCacheClosures = false; bool printCachedDylibs = false; std::vector<const char*> envArgs; char fsRootRealPath[PATH_MAX]; char fsOverlayRealPath[PATH_MAX]; if ( argc == 1 ) { usage(); return 0; } for (int i = 1; i < argc; ++i) { const char* arg = argv[i]; if ( strcmp(arg, "-cache_file") == 0 ) { cacheFilePath = argv[++i]; if ( cacheFilePath == nullptr ) { fprintf(stderr, "-cache_file option requires path to cache file\n"); return 1; } } else if ( strcmp(arg, "-create_closure") == 0 ) { inputMainExecutablePath = argv[++i]; if ( inputMainExecutablePath == nullptr ) { fprintf(stderr, "-create_closure option requires a path to an executable\n"); return 1; } } else if ( strcmp(arg, "-fs_root") == 0 ) { fsRootPath = argv[++i]; if ( fsRootPath == nullptr ) { fprintf(stderr, "-fs_root option requires a path\n"); return 1; } if ( realpath(fsRootPath, fsRootRealPath) == nullptr ) { fprintf(stderr, "-fs_root option requires a real path\n"); return 1; } fsRootPath = fsRootRealPath; } else if ( strcmp(arg, "-fs_overlay") == 0 ) { fsOverlayPath = argv[++i]; if ( fsOverlayPath == nullptr ) { fprintf(stderr, "-fs_overlay option requires a path\n"); return 1; } if ( realpath(fsOverlayPath, fsOverlayRealPath) == nullptr ) { fprintf(stderr, "-fs_root option requires a real path\n"); return 1; } fsOverlayPath = fsOverlayRealPath; } else if ( strcmp(arg, "-list_dyld_cache_closures") == 0 ) { listCacheClosures = true; } else if ( strcmp(arg, "-print_dyld_cache_closure") == 0 ) { printCacheClosure = argv[++i]; if ( printCacheClosure == nullptr ) { fprintf(stderr, "-print_dyld_cache_closure option requires a path \n"); return 1; } } else if ( strcmp(arg, "-print_closure_file") == 0 ) { printClosureFile = argv[++i]; if ( printClosureFile == nullptr ) { fprintf(stderr, "-print_closure_file option requires a path \n"); return 1; } } else if ( strcmp(arg, "-print_dyld_cache_dylibs") == 0 ) { printCachedDylibs = true; } else if ( strcmp(arg, "-print_dyld_cache_dylib") == 0 ) { printCachedDylib = argv[++i]; if ( printCachedDylib == nullptr ) { fprintf(stderr, "-print_dyld_cache_dylib option requires a path \n"); return 1; } } else if ( strcmp(arg, "-env") == 0 ) { const char* envArg = argv[++i]; if ( (envArg == nullptr) || (strchr(envArg, '=') == nullptr) ) { fprintf(stderr, "-env option requires KEY=VALUE\n"); return 1; } envArgs.push_back(envArg); } else { fprintf(stderr, "unknown option %s\n", arg); return 1; } } envArgs.push_back(nullptr); std::vector<const DyldSharedCache*> dyldCaches; const DyldSharedCache* dyldCache = nullptr; if ( cacheFilePath != nullptr ) { dyldCaches = DyldSharedCache::mapCacheFiles(cacheFilePath); // mapCacheFile prints an error if something goes wrong, so just return in that case. if ( dyldCaches.empty() ) return 1; dyldCache = dyldCaches.front(); } else { size_t len; dyldCache = (DyldSharedCache*)_dyld_get_shared_cache_range(&len); } const MachOAnalyzer* mainMA = nullptr; if ( dyldCache ) { // gracefully handling older dyld caches if ( dyldCache->header.mappingOffset < 0x170 ) { fprintf(stderr, "dyld_closure_util: can't operate against an old (pre-dyld4) dyld cache\n"); exit(1); } std::string_view libSystemPath; if ( dyldCache->platform() == mach_o::Platform::driverKit ) { libSystemPath = "/System/DriverKit/usr/lib/libSystem.dylib"; } else if ( dyldCache->platform().isExclaveKit() ) { libSystemPath = "/System/ExclaveKit/usr/lib/libSystem.dylib"; } else { libSystemPath = "/usr/lib/libSystem.B.dylib"; } // HACK: use libSystem.dylib from cache as main executable to bootstrap state uint32_t imageIndex; if ( dyldCache->hasImagePath(libSystemPath.data(), imageIndex) ) { uint64_t ignore1; uint64_t ignore2; mainMA = (MachOAnalyzer*)dyldCache->getIndexedImageEntry(imageIndex, ignore1, ignore2); } if ( mainMA == nullptr ) { fprintf(stderr, "dyld_closure_util: can't find libSystem in dyld cache\n"); exit(1); } } KernelArgs kernArgs(mainMA, {"test.exe"}, {}, {}); SyscallDelegate osDelegate; osDelegate._dyldCache = dyldCache; osDelegate._rootPath = fsRootPath; osDelegate._overlayPath = fsOverlayPath; Allocator& alloc = MemoryManager::memoryManager().defaultAllocator(); __block ProcessConfig config(&kernArgs, osDelegate, alloc); RuntimeLocks locks; RuntimeState state(config, locks, alloc); if ( inputMainExecutablePath != nullptr ) { config.reset(mainMA, inputMainExecutablePath, osDelegate._dyldCache); state.resetCachedDylibsArrays(dyldCache->dylibsLoaderSet()); // Load the executable from disk Diagnostics launchDiag; Loader::LoadOptions options; options.staticLinkage = true; options.launching = true; options.canBeExecutable = true; if ( Loader* mainLoader = JustInTimeLoader::makeJustInTimeLoaderDisk(launchDiag, state, inputMainExecutablePath, options, false, 0, nullptr) ) { state.setMainLoader(mainLoader); // platform was a guess from libSystem.dylib, now we have the actual binary loaded, use its platform mach_o::PlatformAndVersions pvs = ((mach_o::Header*)mainLoader->loadAddress(state))->platformAndVersions(); config.process.platform = pvs.platform; // now that main executable is loaded, use its actual platform as the global platform if ( state.config.process.platform == mach_o::Platform::macOS ) { mach_o::PlatformAndVersions pvsExe = ((mach_o::Header*)mainLoader->loadAddress(state))->platformAndVersions(); config.process.platform = pvsExe.platform; } __block MissingPaths missingPaths; auto missingLogger = ^(const char* mustBeMissingPath) { missingPaths.addPath(mustBeMissingPath); }; Loader::LoadChain loadChainMain { nullptr, mainLoader }; options.canBeDylib = true; options.canBeExecutable = false; options.rpathStack = &loadChainMain; options.pathNotFoundHandler = missingLogger; mainLoader->loadDependents(launchDiag, state, options); if ( launchDiag.hasError() ) { fprintf(stderr, "dyld_closure_util: can't build PrebuiltLoader for '%s': %s\n", inputMainExecutablePath, launchDiag.errorMessageCStr()); exit(1); } const PrebuiltLoaderSet* prebuiltAppSet = PrebuiltLoaderSet::makeLaunchSet(launchDiag, state, missingPaths); if ( launchDiag.hasError() ) { fprintf(stderr, "dyld_closure_util: can't build PrebuiltLoaderSet for '%s': %s\n", inputMainExecutablePath, launchDiag.errorMessageCStr()); exit(1); } if ( prebuiltAppSet != nullptr ) { state.setProcessPrebuiltLoaderSet(prebuiltAppSet); // Note dyld_closure_builder parses the JSON, so we can't print comments by default here prebuiltAppSet->print(state, stdout, /* printComments */ false); } } else { fprintf(stderr, "dyld_closure_util: can't find '%s'\n", inputMainExecutablePath); exit(1); } if ( launchDiag.hasError() ) { fprintf(stderr, "dyld_closure_util: can't build PrebuiltLoaderSet for '%s': %s\n", inputMainExecutablePath, launchDiag.errorMessageCStr()); exit(1); } } else if ( printCacheClosure ) { if ( const dyld4::PrebuiltLoaderSet* pbls = config.dyldCache.addr->findLaunchLoaderSet(printCacheClosure) ) { state.setProcessPrebuiltLoaderSet(pbls); pbls->print(state, stdout, /* printComments */ true); } else { fprintf(stderr, "dyld_closure_util: no PrebuiltLoaderSet in cache for %s\n", printCacheClosure); } } else if ( printClosureFile ) { size_t mappedSize; Diagnostics diag; if ( const dyld4::PrebuiltLoaderSet* pbls = (dyld4::PrebuiltLoaderSet*)config.syscall.mapFileReadOnly(diag, printClosureFile, nullptr /* fd */, &mappedSize) ) { if ( pbls->validHeader(state) ) { state.setProcessPrebuiltLoaderSet(pbls); pbls->print(state, stdout, /* printComments */ true); } else { fprintf(stderr, "dyld_closure_util: invalid closure file '%s'\n", printClosureFile); } config.syscall.unmapFile(pbls, mappedSize); } else { fprintf(stderr, "dyld_closure_util: no PrebuiltLoaderSet at %s\n", printClosureFile); } } else if ( printCachedDylibs ) { state.resetCachedDylibsArrays(config.dyldCache.addr->dylibsLoaderSet()); if ( const dyld4::PrebuiltLoaderSet* pbls = state.cachedDylibsPrebuiltLoaderSet()) { for (int i=0; i < pbls->loaderCount(); ++i) { const dyld4::PrebuiltLoader* pldr = pbls->atIndex(i); pldr->print(state, stdout, /* printComments */ true); } } } else if ( printCachedDylib != nullptr ) { state.resetCachedDylibsArrays(config.dyldCache.addr->dylibsLoaderSet()); if ( const dyld4::PrebuiltLoader* pldr = config.dyldCache.addr->findPrebuiltLoader(printCachedDylib) ) { pldr->print(state, stdout, /* printComments */ true); } else { fprintf(stderr, "no such image found\n"); } } else if ( listCacheClosures ) { config.dyldCache.addr->forEachLaunchLoaderSet(^(const char* runtimePath, const PrebuiltLoaderSet* pbls) { printf("%6lu %s\n", pbls->size(), runtimePath); }); } return 0; } |