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 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 | // // SharedCacheBuilder.m // dyld // // Created by Louis Gerbarg on 6/15/15. // // #include <CommonCrypto/CommonCrypto.h> #include <Bom/Bom.h> #include <sys/types.h> #include <sys/sysctl.h> #include <pthread.h> #include <mach/mach.h> #include <unistd.h> #include <cstring> #include <array> #include <sstream> #include <iomanip> // std::setfill, std::setw #include "mega-dylib-utils.h" #include "Logging.h" #include "MultiCacheBuilder.h" namespace { #if BOM_SUPPORT void insertDirInBom( const std::string& path, const std::string& name, BOMBom bom ) { std::string fullPath = path + "/" + name; BOMFSObject fso = BOMFSObjectNew( BOMDirectoryType ); BOMFSObjectSetFlags( fso, B_PATHONLY ); BOMFSObjectSetPathName( fso, fullPath.c_str(), true ); BOMFSObjectSetShortName( fso, name.c_str(), true ); (void)BOMBomInsertFSObject( bom, fso, false ); BOMFSObjectFree( fso ); } void insertFileInBom( const std::string& path, const std::string& name, BOMBom bom ) { std::string fullPath = path + "/" + name; BOMFSObject fso = BOMFSObjectNew( BOMFileType ); BOMFSObjectSetFlags( fso, B_PATHONLY ); BOMFSObjectSetPathName( fso, fullPath.c_str(), true ); BOMFSObjectSetShortName( fso, name.c_str(), true ); (void)BOMBomInsertFSObject( bom, fso, false ); BOMFSObjectFree( fso ); } void insertCacheDirInBom( BOMBom bom ) { BOMFSObject fso = BOMFSObjectNew( BOMDirectoryType ); BOMFSObjectSetFlags( fso, B_PATHONLY ); BOMFSObjectSetPathName( fso, ".", true ); BOMFSObjectSetShortName( fso, ".", true ); (void)BOMBomInsertFSObject( bom, fso, false ); BOMFSObjectFree( fso ); insertDirInBom( ".", "System", bom ); insertDirInBom( "./System", "Library", bom ); insertDirInBom( "./System/Library", "Caches", bom ); insertDirInBom( "./System/Library/Caches", "com.apple.dyld", bom ); } #endif /* BOM_SUPPORT */ } MultiCacheBuilder::MultiCacheBuilder(Manifest& manifest, bool BNI, bool SW, bool buildRoot, bool skipBuilds, bool enforceRootles) : _manifest(manifest), _bniMode(BNI), _skipWrites(SW), _buildRoot(buildRoot), _skipBuilds(skipBuilds), _enforceRootless(enforceRootles), _writeQueue(dispatch_queue_create("com.apple.dyld.cache.writeout", dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, 0))), _writeGroup(dispatch_group_create()), _buildQueue(dispatch_queue_create("com.apple.dyld.cache.multi-build", DISPATCH_QUEUE_CONCURRENT)) { uint64_t thread_count; uint64_t ram_size; size_t len = sizeof(thread_count); sysctlbyname ("hw.logicalcpu",&thread_count,&len,NULL,0); len = sizeof(ram_size); sysctlbyname ("hw.memsize",&ram_size,&len,NULL,0); uint64_t buildCount = MIN((ram_size/(1024*1024*1024)/2), thread_count); uint64_t writerCount = MAX((ram_size/((uint64_t)2*1024*1024*1024)) - buildCount, 1); _buildQueue = dispatch_queue_create("com.apple.dyld.cache.build", DISPATCH_QUEUE_CONCURRENT); _concurrencyLimitingSemaphore = dispatch_semaphore_create(buildCount); _writeLimitingSemaphore = dispatch_semaphore_create(writerCount); if ( _bniMode ) { log("Running: %llu threads", buildCount); log("Queuing: %llu writers", writerCount); } } void MultiCacheBuilder::write_cache(std::string cachePath, const std::set<std::string>& configurations, const std::string& architecture, std::shared_ptr<SharedCache> cache, bool developmentCache) { //FIXME dispatch_semaphore_wait(_writeLimitingSemaphore, DISPATCH_TIME_FOREVER); dispatch_group_enter(_writeGroup); cacheBuilderDispatchAsync(_writeQueue, [=] { if (!_skipWrites) { verboseLog("Queuing write out: %s", cachePath.c_str()); //Turn off file caching since we won't read it back //(void)fcntl(fd, F_NOCACHE, 1); // We should do this after the cache write, but that would involve copying the path string std::string tempPath = cachePath; cache->writeCacheMapFile(cachePath + ".map"); char tempEXT[] = ".XXXXXX"; mktemp(tempEXT); tempPath += tempEXT; int fd = ::open(tempPath.c_str(), O_CREAT | O_RDWR | O_TRUNC, 0644); if (fd == -1) { dispatch_group_leave(_writeGroup); dispatch_semaphore_signal(_writeLimitingSemaphore); terminate("can't create temp file for %s, errnor=%d (%s)", cachePath.c_str(), errno, strerror(errno)); } if (isProtectedBySIP(tempPath, fd) != _enforceRootless) { ::close(fd); ::unlink(tempPath.c_str()); dispatch_group_leave(_writeGroup); dispatch_semaphore_signal(_writeLimitingSemaphore); terminate("SIP protection of output cache file changed (%s)", cachePath.c_str()); } ssize_t writtenSize = pwrite(fd, cache->buffer().get(), cache->fileSize(), 0); if (writtenSize != cache->fileSize()) { ::close(fd); ::unlink(tempPath.c_str()); dispatch_group_leave(_writeGroup); dispatch_semaphore_signal(_writeLimitingSemaphore); terminate("write() failure creating cache file, requested %lld, wrote %ld, errno=%d (%s)", cache->fileSize(), writtenSize, errno, strerror(errno)); } ::close(fd); if (rename(tempPath.c_str(), cachePath.c_str()) != 0) { dispatch_group_leave(_writeGroup); dispatch_semaphore_signal(_writeLimitingSemaphore); terminate("move() failure creating cache file, errno=%d (%s)", errno, strerror(errno)); } if (_bniMode) log("Wrote out: %s", cachePath.c_str()); } else { log("Skipped: %s", cachePath.c_str()); } _filesWritten++; _bytesWritten += cache->fileSize(); dispatch_group_leave(_writeGroup); dispatch_semaphore_signal(_writeLimitingSemaphore); }); } //FIXME (make development a type) void MultiCacheBuilder::buildCache(const std::string cachePath, const std::set<std::string> configurations, const std::string architecture, bool development) { auto& configResults = _manifest.configurations[*configurations.begin()].architectures[architecture].results.dylibs; if ( _skipBuilds ) { log( "Build Skipped" ); for ( auto& config : configurations ) { for ( auto& dylib : configResults ) { _manifest.configurations[config].architectures[architecture].results.dylibs[dylib.first].exclude( "All dylibs excluded" ); } } return; } Manifest::Architecture arch; std::vector<std::unique_ptr<MachOProxy>> dylibs; std::vector<std::string> emptyList; std::shared_ptr<SharedCache> cache = std::make_shared<SharedCache>(_manifest, *configurations.begin(), architecture); for (auto& config : configurations) { auto& results = _manifest.configurations[config].architectures[architecture].results.dylibs; for (auto& dylib : configResults) { if (dylib.second.included == false && results.count(dylib.first) && results[dylib.first].included == true) { results[dylib.first].exclude(dylib.second.exclusionInfo); } } } if (development) { cache->buildForDevelopment(cachePath); } else { cache->buildForProduction(cachePath); } std::vector<uint64_t> regionStartAddresses; std::vector<uint64_t> regionSizes; std::vector<uint64_t> regionFileOffsets; cache->forEachRegion([&] (void* content, uint64_t vmAddr, uint64_t size, uint32_t permissions) { regionStartAddresses.push_back(vmAddr); regionSizes.push_back(size); regionFileOffsets.push_back((uint8_t*)content - (uint8_t*)cache->buffer().get()); const char* prot = "RW"; if ( permissions == (VM_PROT_EXECUTE|VM_PROT_READ) ) prot = "EX"; else if ( permissions == VM_PROT_READ ) prot = "RO"; for (auto& config : configurations) { if (development) { _manifest.configurations[config].architectures[architecture].results.developmentCache.regions.push_back({prot, vmAddr,vmAddr+size }); } else { _manifest.configurations[config].architectures[architecture].results.productionCache.regions.push_back({prot, vmAddr,vmAddr+size }); } } }); cache->forEachImage([&](const void* machHeader, const char* installName, time_t mtime, ino_t inode, const std::vector<MachOProxy::Segment>& segments) { for (auto& seg : segments) { uint64_t vmAddr = 0; for (int i=0; i < regionSizes.size(); ++i) { if ( (seg.fileOffset >= regionFileOffsets[i]) && (seg.fileOffset < (regionFileOffsets[i]+regionSizes[i])) ) { vmAddr = regionStartAddresses[i] + seg.fileOffset - regionFileOffsets[i]; } } for (auto& config : configurations) { _manifest.configurations[config].architectures[architecture].results.dylibs[installName].segments.push_back({seg.name, vmAddr, vmAddr+seg.size}); if (_manifest.configurations[config].architectures[architecture].results.dylibs[installName].segments.size() == 0) { warning("Attempting to write info for excluded dylib"); _manifest.configurations[config].architectures[architecture].results.dylibs[installName].exclude("Internal Error"); } } } }); if (development) { verboseLog("developement cache size = %llu", cache->fileSize()); } else { verboseLog("production cache size = %llu", cache->fileSize()); } if ( cache->vmSize()+align(cache->vmSize()/200, sharedRegionRegionAlignment(archForString(architecture))) > sharedRegionRegionSize(archForString(architecture))) { warning("shared cache will not fit in shared regions address space. Overflow amount: %llu", cache->vmSize() + align(cache->vmSize() / 200, sharedRegionRegionAlignment(archForString(architecture))) - sharedRegionRegionSize(archForString(architecture))); return; } write_cache(cachePath, configurations, architecture, cache, development); for (auto& config : configurations) { if (development) { _manifest.configurations[config].architectures[architecture].results.developmentCache.cdHash = cache->cdHashString(); } else { _manifest.configurations[config].architectures[architecture].results.productionCache.cdHash = cache->cdHashString(); } } } void MultiCacheBuilder::runOnManifestConcurrently(std::function<void(const std::string configuration, const std::string architecture)> lambda) { dispatch_group_t runGroup = dispatch_group_create(); for (auto& config : _manifest.configurations) { for (auto& architecture : config.second.architectures) { dispatch_semaphore_wait(_concurrencyLimitingSemaphore, DISPATCH_TIME_FOREVER); cacheBuilderDispatchGroupAsync(runGroup, _buildQueue, [&] { WarningTargets targets; targets.first = &_manifest; targets.second.insert(std::make_pair(config.first, architecture.first)); auto ctx = std::make_shared<LoggingContext>(config.first + "/" + architecture.first, targets); setLoggingContext(ctx); lambda(config.first, architecture.first); dispatch_semaphore_signal(_concurrencyLimitingSemaphore); }); } } dispatch_group_wait(runGroup, DISPATCH_TIME_FOREVER); } void MultiCacheBuilder::buildCaches(std::string masterDstRoot) { if (_bniMode) { std::vector<std::set<std::string>> dedupedCacheSets; for (auto& config : _manifest.configurations) { bool dupeFound = false; for (auto& cacheSet : dedupedCacheSets) { if (config.second.equivalent(_manifest.configurations[*cacheSet.begin()])) { cacheSet.insert(config.first); dupeFound = true; break; } } if (!dupeFound) { std::set<std::string> temp; temp.insert(config.first); dedupedCacheSets.push_back(temp); } } for (auto& cacheSet : dedupedCacheSets) { //FIXME we may want to consider moving to hashes of UUID sets std::string setName; for (auto &archName : cacheSet) { if (!setName.empty()) { setName += "|"; } setName += archName; } std::stringstream fileNameStream; std::array<uint8_t, CC_SHA1_DIGEST_LENGTH> digest = {0}; CC_SHA1(setName.c_str(), (unsigned int)setName.length(), &digest[0]); fileNameStream << std::hex << std::uppercase << std::setfill( '0' ); for( int c : digest ) { fileNameStream << std::setw( 2 ) << c; } std::string fileName(fileNameStream.str()); for (auto& config : cacheSet) { if (!_skipWrites) { int err = symlink(("DedupedConfigs/" + fileName).c_str(), (masterDstRoot + "/" + config).c_str()); if (err) { warning("Could not create symlink '%s' -> 'DedupedConfigs/%s' (%d)", config.c_str(), fileName.c_str(), err); } } } for (auto& arch : _manifest.configurations[*cacheSet.begin()].architectures) { dispatch_semaphore_wait(_concurrencyLimitingSemaphore, DISPATCH_TIME_FOREVER); cacheBuilderDispatchGroupAsync(_writeGroup, _buildQueue, [=] { WarningTargets targets; targets.first = &_manifest; for (auto& config : cacheSet) { targets.second.insert(std::make_pair(config, arch.first)); } auto ctx = std::make_shared<LoggingContext>(setName + "/" + arch.first, targets); setLoggingContext(ctx); std::string configPath = masterDstRoot + "/DedupedConfigs/" + fileName + "/System/Library/Caches/com.apple.dyld/"; if (!_skipWrites) { int err = mkpath_np(configPath.c_str(), 0755); if (err != 0 && err != EEXIST) { dispatch_semaphore_signal(_concurrencyLimitingSemaphore); terminate("mkpath_np fail: %d", err); } } buildCache(configPath + "dyld_shared_cache_" + arch.first + ".development", cacheSet, arch.first, true); buildCache(configPath + "dyld_shared_cache_" + arch.first, cacheSet, arch.first, false); dispatch_semaphore_signal(_concurrencyLimitingSemaphore); }); } } dispatch_group_wait(_writeGroup, DISPATCH_TIME_FOREVER); #if BOM_SUPPORT if ( !_skipWrites ) { for ( auto& configuration : _manifest.configurations ) { std::vector<std::string> prodBomPaths; std::vector<std::string> devBomPaths; for (auto& arch : configuration.second.architectures) { std::string cachePath = "dyld_shared_cache_" + arch.first; prodBomPaths.push_back(cachePath); cachePath += ".development"; devBomPaths.push_back(cachePath); dispatch_group_enter(_writeGroup); cacheBuilderDispatchAsync(_writeQueue, [=] { char buffer[MAXPATHLEN]; sprintf(buffer, "%s/Boms/%s.prod.bom", masterDstRoot.c_str(), configuration.first.c_str()); BOMBom bom = BOMBomNew(buffer); insertCacheDirInBom(bom); for (auto& path : prodBomPaths) { insertFileInBom("./System/Library/Caches/com.apple.dyld", path, bom); } BOMBomFree(bom); sprintf(buffer, "%s/Boms/%s.dev.bom", masterDstRoot.c_str(), configuration.first.c_str()); bom = BOMBomNew(buffer); insertCacheDirInBom(bom); for (auto& path : devBomPaths) { insertFileInBom("./System/Library/Caches/com.apple.dyld", path, bom); } BOMBomFree(bom); sprintf(buffer, "%s/Boms/%s.full.bom", masterDstRoot.c_str(), configuration.first.c_str()); bom = BOMBomNew(buffer); insertCacheDirInBom(bom); for (auto& path : prodBomPaths) { insertFileInBom("./System/Library/Caches/com.apple.dyld", path, bom); } for (auto& path : devBomPaths) { insertFileInBom("./System/Library/Caches/com.apple.dyld", path, bom); } BOMBomFree(bom); dispatch_group_leave(_writeGroup); }); } } } #endif /* BOM_SUPPORT */ } else { runOnManifestConcurrently( [&](const std::string configuration, const std::string architecture) { cacheBuilderDispatchGroupAsync(_writeGroup, _buildQueue, [=] { std::set<std::string> configurations; configurations.insert( configuration ); // FIXME hacky, we make implicit assumptions about dev vs non-dev and layout depending on the flags if ( _buildRoot ) { int err = mkpath_np( ( masterDstRoot + "/System/Library/Caches/com.apple.dyld/" ).c_str(), 0755 ); if ( err != 0 && err != EEXIST ) { terminate( "mkpath_np fail: %d", err ); } buildCache(masterDstRoot + "/System/Library/Caches/com.apple.dyld/dyld_shared_cache_" + architecture, configurations, architecture, false); buildCache(masterDstRoot + "/System/Library/Caches/com.apple.dyld/dyld_shared_cache_" + architecture + ".development", configurations, architecture, true); } else { buildCache(masterDstRoot + "/dyld_shared_cache_" + architecture, configurations, architecture, true); } }); }); dispatch_group_wait(_writeGroup, DISPATCH_TIME_FOREVER); } int err = sync_volume_np(masterDstRoot.c_str(), SYNC_VOLUME_FULLSYNC | SYNC_VOLUME_WAIT); if (err) { warning("Volume sync failed errnor=%d (%s)", err, strerror(err)); } } void MultiCacheBuilder::logStats(void) { if ( _bniMode ) log("Processed %llu caches (%.2fGB)", _filesWritten, ((float)_bytesWritten)/(1024*1024*1024)); } |