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 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 | /* * 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 "ClosureBuilder.h" #include "ClosurePrinter.h" #include "ClosureFileSystemPhysical.h" using dyld3::closure::ImageArray; using dyld3::closure::Image; using dyld3::closure::ImageNum; using dyld3::closure::ClosureBuilder; using dyld3::closure::LaunchClosure; using dyld3::closure::DlopenClosure; using dyld3::closure::PathOverrides; using dyld3::Array; // mmap() an shared cache file read/only but laid out like it would be at runtime static const DyldSharedCache* mapCacheFile(const char* path) { struct stat statbuf; if ( ::stat(path, &statbuf) ) { fprintf(stderr, "Error: stat failed for dyld shared cache at %s\n", path); return nullptr; } int cache_fd = ::open(path, O_RDONLY); if (cache_fd < 0) { fprintf(stderr, "Error: failed to open shared cache file at %s\n", path); return nullptr; } uint8_t firstPage[4096]; if ( ::pread(cache_fd, firstPage, 4096, 0) != 4096 ) { fprintf(stderr, "Error: failed to read shared cache file at %s\n", path); return nullptr; } const dyld_cache_header* header = (dyld_cache_header*)firstPage; const dyld_cache_mapping_info* mappings = (dyld_cache_mapping_info*)(firstPage + header->mappingOffset); size_t vmSize = (size_t)(mappings[2].address + mappings[2].size - mappings[0].address); vm_address_t result; kern_return_t r = ::vm_allocate(mach_task_self(), &result, vmSize, VM_FLAGS_ANYWHERE); if ( r != KERN_SUCCESS ) { fprintf(stderr, "Error: failed to allocate space to load shared cache file at %s\n", path); return nullptr; } for (int i=0; i < 3; ++i) { void* mapped_cache = ::mmap((void*)(result + mappings[i].address - mappings[0].address), (size_t)mappings[i].size, PROT_READ, MAP_FIXED | MAP_PRIVATE, cache_fd, mappings[i].fileOffset); if (mapped_cache == MAP_FAILED) { fprintf(stderr, "Error: mmap() for shared cache at %s failed, errno=%d\n", path, errno); return nullptr; } } ::close(cache_fd); return (DyldSharedCache*)result; } 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(" -list_dyld_cache_dlopen_closures # list all dlopen 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_dyld_cache_dlopen <path> # print specified dlopen 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(" -dlopen <path> # for use with -create_closure to simulate that program calling dlopen\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* printOtherDylib = nullptr; bool listCacheClosures = false; bool listCacheDlopenClosures = false; bool printCachedDylibs = false; bool verboseFixups = false; bool allowAtPaths = true; bool allowFallbackPaths = true; bool allowInsertionFailures = false; std::vector<std::string> buildtimePrefixes; std::vector<const char*> envArgs; std::vector<const char*> dlopens; 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, "-dlopen") == 0 ) { const char* path = argv[++i]; if ( path == nullptr ) { fprintf(stderr, "-dlopen option requires a path to a packed closure list\n"); return 1; } dlopens.push_back(path); } else if ( strcmp(arg, "-verbose_fixups") == 0 ) { verboseFixups = true; } else if ( strcmp(arg, "-no_at_paths") == 0 ) { allowAtPaths = false; } else if ( strcmp(arg, "-no_fallback_paths") == 0 ) { allowFallbackPaths = false; } else if ( strcmp(arg, "-allow_insertion_failures") == 0 ) { allowInsertionFailures = true; } else if ( strcmp(arg, "-build_root") == 0 ) { const char* buildRootPath = argv[++i]; if ( buildRootPath == nullptr ) { fprintf(stderr, "-build_root option requires a path \n"); return 1; } buildtimePrefixes.push_back(buildRootPath); } else if ( strcmp(arg, "-list_dyld_cache_closures") == 0 ) { listCacheClosures = true; } else if ( strcmp(arg, "-list_dyld_cache_dlopen_closures") == 0 ) { listCacheDlopenClosures = 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_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, "-print_dyld_cache_dlopen") == 0 ) { printOtherDylib = argv[++i]; if ( printOtherDylib == nullptr ) { fprintf(stderr, "-print_dyld_cache_dlopen 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); const DyldSharedCache* dyldCache = nullptr; bool dyldCacheIsLive = true; if ( cacheFilePath != nullptr ) { dyldCache = mapCacheFile(cacheFilePath); dyldCacheIsLive = false; } else { #if __MAC_OS_X_VERSION_MIN_REQUIRED && (__MAC_OS_X_VERSION_MIN_REQUIRED < 101300) fprintf(stderr, "this tool needs to run on macOS 10.13 or later\n"); return 1; #else size_t cacheLength; dyldCache = (DyldSharedCache*)_dyld_get_shared_cache_range(&cacheLength); #endif } dyld3::Platform platform = dyldCache->platform(); const char* archName = dyldCache->archName(); if ( inputMainExecutablePath != nullptr ) { PathOverrides pathOverrides; pathOverrides.setFallbackPathHandling(allowFallbackPaths ? dyld3::closure::PathOverrides::FallbackPathMode::classic : dyld3::closure::PathOverrides::FallbackPathMode::none); pathOverrides.setEnvVars(&envArgs[0], nullptr, nullptr); const char* prefix = ( buildtimePrefixes.empty() ? nullptr : buildtimePrefixes.front().c_str()); //dyld3::PathOverrides pathStuff(envArgs); STACK_ALLOC_ARRAY(const ImageArray*, imagesArrays, 3+dlopens.size()); STACK_ALLOC_ARRAY(dyld3::LoadedImage, loadedArray, 1024); imagesArrays.push_back(dyldCache->cachedDylibsImageArray()); imagesArrays.push_back(dyldCache->otherOSImageArray()); dyld3::closure::FileSystemPhysical fileSystem(prefix); ClosureBuilder::AtPath atPathHanding = allowAtPaths ? ClosureBuilder::AtPath::all : ClosureBuilder::AtPath::none; ClosureBuilder builder(dyld3::closure::kFirstLaunchClosureImageNum, fileSystem, dyldCache, dyldCacheIsLive, pathOverrides, atPathHanding, nullptr, archName, platform, nullptr); const LaunchClosure* mainClosure = builder.makeLaunchClosure(inputMainExecutablePath, allowInsertionFailures); if ( builder.diagnostics().hasError() ) { fprintf(stderr, "dyld_closure_util: %s\n", builder.diagnostics().errorMessage()); return 1; } ImageNum nextNum = builder.nextFreeImageNum(); if ( !dlopens.empty() ) printf("[\n"); imagesArrays.push_back(mainClosure->images()); dyld3::closure::printClosureAsJSON(mainClosure, imagesArrays, verboseFixups); ClosureBuilder::buildLoadOrder(loadedArray, imagesArrays, mainClosure); for (const char* path : dlopens) { printf(",\n"); // map unloaded mach-o files for use during closure building for (dyld3::LoadedImage& li : loadedArray) { if ( li.loadedAddress() != nullptr ) continue; if ( li.image()->inDyldCache() ) { li.setLoadedAddress((dyld3::MachOLoaded*)((uint8_t*)dyldCache + li.image()->cacheOffset())); } else { Diagnostics diag; dyld3::closure::LoadedFileInfo loadedFileInfo = dyld3::MachOAnalyzer::load(diag, fileSystem, li.image()->path(), archName, platform); li.setLoadedAddress((const dyld3::MachOAnalyzer*)loadedFileInfo.fileContent); } } ClosureBuilder::AtPath atPathHandingDlopen = allowAtPaths ? ClosureBuilder::AtPath::all : ClosureBuilder::AtPath::onlyInRPaths; ClosureBuilder dlopenBuilder(nextNum, fileSystem, dyldCache, dyldCacheIsLive, pathOverrides, atPathHandingDlopen, nullptr, archName, platform, nullptr); ImageNum topImageNum; const DlopenClosure* dlopenClosure = dlopenBuilder.makeDlopenClosure(path, mainClosure, loadedArray, 0, false, false, &topImageNum); if ( dlopenBuilder.diagnostics().hasError() ) { fprintf(stderr, "dyld_closure_util: %s\n", dlopenBuilder.diagnostics().errorMessage()); return 1; } if ( dlopenClosure == nullptr ) { if ( topImageNum == 0 ) { fprintf(stderr, "dyld_closure_util: failed to dlopen %s\n", path); return 1; } printf("{\n \"dyld-cache-image-num\": \"0x%04X\"\n}\n", topImageNum); } else { nextNum += dlopenClosure->images()->imageCount(); imagesArrays.push_back(dlopenClosure->images()); dyld3::closure::printClosureAsJSON(dlopenClosure, imagesArrays, verboseFixups); ClosureBuilder::buildLoadOrder(loadedArray, imagesArrays, dlopenClosure); } } if ( !dlopens.empty() ) printf("]\n"); } else if ( listCacheClosures ) { dyldCache->forEachLaunchClosure(^(const char* runtimePath, const dyld3::closure::LaunchClosure* closure) { printf("%6lu %s\n", closure->size(), runtimePath); }); } else if ( listCacheDlopenClosures ) { dyldCache->forEachDlopenImage(^(const char* runtimePath, const dyld3::closure::Image* image) { printf("%6lu %s\n", image->size(), runtimePath); }); } else if ( printCacheClosure ) { const dyld3::closure::LaunchClosure* closure = dyldCache->findClosure(printCacheClosure); if ( closure != nullptr ) { STACK_ALLOC_ARRAY(const ImageArray*, imagesArrays, 3); imagesArrays.push_back(dyldCache->cachedDylibsImageArray()); imagesArrays.push_back(dyldCache->otherOSImageArray()); imagesArrays.push_back(closure->images()); dyld3::closure::printClosureAsJSON(closure, imagesArrays, verboseFixups); } else { fprintf(stderr, "no closure in cache for %s\n", printCacheClosure); } } else if ( printCachedDylibs ) { dyld3::closure::printDyldCacheImagesAsJSON(dyldCache, verboseFixups); } else if ( printCachedDylib != nullptr ) { const dyld3::closure::ImageArray* dylibs = dyldCache->cachedDylibsImageArray(); STACK_ALLOC_ARRAY(const ImageArray*, imagesArrays, 2); imagesArrays.push_back(dylibs); ImageNum num; if ( dylibs->hasPath(printCachedDylib, num) ) { dyld3::closure::printImageAsJSON(dylibs->imageForNum(num), imagesArrays, verboseFixups); } else { fprintf(stderr, "no such image found\n"); } } else if ( printOtherDylib != nullptr ) { if ( const dyld3::closure::Image* image = dyldCache->findDlopenOtherImage(printOtherDylib) ) { STACK_ALLOC_ARRAY(const ImageArray*, imagesArrays, 2); imagesArrays.push_back(dyldCache->cachedDylibsImageArray()); imagesArrays.push_back(dyldCache->otherOSImageArray()); dyld3::closure::printImageAsJSON(image, imagesArrays, verboseFixups); } else { fprintf(stderr, "no such image found\n"); } } return 0; } |