]> git.saurik.com Git - apple/dyld.git/blob - dyld3/shared-cache/OptimizerBranches.cpp
dyld-519.2.1.tar.gz
[apple/dyld.git] / dyld3 / shared-cache / OptimizerBranches.cpp
1 /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
2 *
3 * Copyright (c) 2015 Apple Inc. All rights reserved.
4 *
5 * @APPLE_LICENSE_HEADER_START@
6 *
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
12 * file.
13 *
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.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24
25
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <sys/mman.h>
29 #include <limits.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <unistd.h>
33 #include <CommonCrypto/CommonDigest.h>
34
35 #include <string>
36 #include <unordered_map>
37 #include <unordered_set>
38
39 #include "StringUtils.h"
40 #include "Trie.hpp"
41 #include "MachOFileAbstraction.hpp"
42 #include "MachOParser.h"
43 #include "Diagnostics.h"
44 #include "DyldSharedCache.h"
45 #include "CacheBuilder.h"
46
47 static const bool verbose = false;
48
49 // These are functions that are interposed by Instruments.app or ASan
50 static const char* sNeverStubEliminateSymbols[] = {
51 "___bzero",
52 "___cxa_atexit",
53 "___cxa_throw",
54 "__longjmp",
55 "__objc_autoreleasePoolPop",
56 "_accept",
57 "_access",
58 "_asctime",
59 "_asctime_r",
60 "_asprintf",
61 "_atoi",
62 "_atol",
63 "_atoll",
64 "_calloc",
65 "_chmod",
66 "_chown",
67 "_close",
68 "_confstr",
69 "_ctime",
70 "_ctime_r",
71 "_dispatch_after",
72 "_dispatch_after_f",
73 "_dispatch_async",
74 "_dispatch_async_f",
75 "_dispatch_barrier_async_f",
76 "_dispatch_group_async",
77 "_dispatch_group_async_f",
78 "_dispatch_source_set_cancel_handler",
79 "_dispatch_source_set_event_handler",
80 "_dispatch_sync_f",
81 "_dlclose",
82 "_dlopen",
83 "_dup",
84 "_dup2",
85 "_endgrent",
86 "_endpwent",
87 "_ether_aton",
88 "_ether_hostton",
89 "_ether_line",
90 "_ether_ntoa",
91 "_ether_ntohost",
92 "_fchmod",
93 "_fchown",
94 "_fclose",
95 "_fdopen",
96 "_fflush",
97 "_fopen",
98 "_fork",
99 "_fprintf",
100 "_free",
101 "_freopen",
102 "_frexp",
103 "_frexpf",
104 "_frexpl",
105 "_fscanf",
106 "_fstat",
107 "_fstatfs",
108 "_fstatfs64",
109 "_fsync",
110 "_ftime",
111 "_getaddrinfo",
112 "_getattrlist",
113 "_getcwd",
114 "_getgrent",
115 "_getgrgid",
116 "_getgrgid_r",
117 "_getgrnam",
118 "_getgrnam_r",
119 "_getgroups",
120 "_gethostbyaddr",
121 "_gethostbyname",
122 "_gethostbyname2",
123 "_gethostent",
124 "_getifaddrs",
125 "_getitimer",
126 "_getnameinfo",
127 "_getpass",
128 "_getpeername",
129 "_getpwent",
130 "_getpwnam",
131 "_getpwnam_r",
132 "_getpwuid",
133 "_getpwuid_r",
134 "_getsockname",
135 "_getsockopt",
136 "_gmtime",
137 "_gmtime_r",
138 "_if_indextoname",
139 "_if_nametoindex",
140 "_index",
141 "_inet_aton",
142 "_inet_ntop",
143 "_inet_pton",
144 "_initgroups",
145 "_ioctl",
146 "_lchown",
147 "_lgamma",
148 "_lgammaf",
149 "_lgammal",
150 "_link",
151 "_listxattr",
152 "_localtime",
153 "_localtime_r",
154 "_longjmp",
155 "_lseek",
156 "_lstat",
157 "_malloc",
158 "_malloc_create_zone",
159 "_malloc_default_purgeable_zone",
160 "_malloc_default_zone",
161 "_malloc_good_size",
162 "_malloc_make_nonpurgeable",
163 "_malloc_make_purgeable",
164 "_malloc_set_zone_name",
165 "_mbsnrtowcs",
166 "_mbsrtowcs",
167 "_mbstowcs",
168 "_memchr",
169 "_memcmp",
170 "_memcpy",
171 "_memmove",
172 "_memset",
173 "_mktime",
174 "_mlock",
175 "_mlockall",
176 "_modf",
177 "_modff",
178 "_modfl",
179 "_munlock",
180 "_munlockall",
181 "_objc_autoreleasePoolPop",
182 "_objc_setProperty",
183 "_objc_setProperty_atomic",
184 "_objc_setProperty_atomic_copy",
185 "_objc_setProperty_nonatomic",
186 "_objc_setProperty_nonatomic_copy",
187 "_objc_storeStrong",
188 "_open",
189 "_opendir",
190 "_poll",
191 "_posix_memalign",
192 "_pread",
193 "_printf",
194 "_pthread_attr_getdetachstate",
195 "_pthread_attr_getguardsize",
196 "_pthread_attr_getinheritsched",
197 "_pthread_attr_getschedparam",
198 "_pthread_attr_getschedpolicy",
199 "_pthread_attr_getscope",
200 "_pthread_attr_getstack",
201 "_pthread_attr_getstacksize",
202 "_pthread_condattr_getpshared",
203 "_pthread_create",
204 "_pthread_getschedparam",
205 "_pthread_join",
206 "_pthread_mutex_lock",
207 "_pthread_mutex_unlock",
208 "_pthread_mutexattr_getprioceiling",
209 "_pthread_mutexattr_getprotocol",
210 "_pthread_mutexattr_getpshared",
211 "_pthread_mutexattr_gettype",
212 "_pthread_rwlockattr_getpshared",
213 "_pwrite",
214 "_rand_r",
215 "_read",
216 "_readdir",
217 "_readdir_r",
218 "_readv",
219 "_readv$UNIX2003",
220 "_realloc",
221 "_realpath",
222 "_recv",
223 "_recvfrom",
224 "_recvmsg",
225 "_remquo",
226 "_remquof",
227 "_remquol",
228 "_scanf",
229 "_send",
230 "_sendmsg",
231 "_sendto",
232 "_setattrlist",
233 "_setgrent",
234 "_setitimer",
235 "_setlocale",
236 "_setpwent",
237 "_shm_open",
238 "_shm_unlink",
239 "_sigaction",
240 "_sigemptyset",
241 "_sigfillset",
242 "_siglongjmp",
243 "_signal",
244 "_sigpending",
245 "_sigprocmask",
246 "_sigwait",
247 "_snprintf",
248 "_sprintf",
249 "_sscanf",
250 "_stat",
251 "_statfs",
252 "_statfs64",
253 "_strcasecmp",
254 "_strcat",
255 "_strchr",
256 "_strcmp",
257 "_strcpy",
258 "_strdup",
259 "_strerror",
260 "_strerror_r",
261 "_strlen",
262 "_strncasecmp",
263 "_strncat",
264 "_strncmp",
265 "_strncpy",
266 "_strptime",
267 "_strtoimax",
268 "_strtol",
269 "_strtoll",
270 "_strtoumax",
271 "_tempnam",
272 "_time",
273 "_times",
274 "_tmpnam",
275 "_tsearch",
276 "_unlink",
277 "_valloc",
278 "_vasprintf",
279 "_vfprintf",
280 "_vfscanf",
281 "_vprintf",
282 "_vscanf",
283 "_vsnprintf",
284 "_vsprintf",
285 "_vsscanf",
286 "_wait",
287 "_wait$UNIX2003",
288 "_wait3",
289 "_wait4",
290 "_waitid",
291 "_waitid$UNIX2003",
292 "_waitpid",
293 "_waitpid$UNIX2003",
294 "_wcslen",
295 "_wcsnrtombs",
296 "_wcsrtombs",
297 "_wcstombs",
298 "_wordexp",
299 "_write",
300 "_writev",
301 "_writev$UNIX2003",
302 // <rdar://problem/22050956> always use stubs for C++ symbols that can be overridden
303 "__ZdaPv",
304 "__ZdlPv",
305 "__Znam",
306 "__Znwm",
307
308 nullptr
309 };
310
311
312 static uint64_t branchPoolTextSize(const std::string& archName)
313 {
314 if ( startsWith(archName, "arm64") )
315 return 0x0000C000; // 48KB
316 else
317 return 0;
318 }
319
320 static uint64_t branchPoolLinkEditSize(const std::string& archName)
321 {
322 if ( startsWith(archName, "arm64") )
323 return 0x00100000; // 1MB
324 else
325 return 0;
326 }
327
328
329 template <typename P>
330 class BranchPoolDylib {
331 public:
332 BranchPoolDylib(DyldSharedCache* cache, uint64_t startAddr,
333 uint64_t textRegionStartAddr, uint64_t poolLinkEditStartAddr, uint64_t poolLinkEditStartOffset, Diagnostics& diags);
334
335 uint64_t addr() { return _startAddr; }
336 uint64_t getForwardBranch(uint64_t finalTargetAddr, const char* name, std::vector<BranchPoolDylib<P>*>& branchIslandPools);
337 uint64_t getBackBranch(uint64_t finalTargetAddr, const char* name, std::vector<BranchPoolDylib<P>*>& branchIslandPools);
338 void finalizeLoadCommands();
339 void printStats();
340
341 private:
342 Diagnostics& _diagnostics;
343 uint64_t indexToAddr(uint32_t index) { return _startAddr + _firstStubOffset + sizeof(uint32_t)*index; }
344
345 static const int64_t b128MegLimit = 0x07FFFFFF;
346
347 typedef typename P::uint_t pint_t;
348 typedef typename P::E E;
349
350 DyldSharedCache* _cacheBuffer;
351 uint64_t _startAddr;
352 std::unordered_map<uint64_t, uint32_t> _targetToIslandIndex;
353 std::unordered_map<uint32_t, const char*> _islandIndexToName;
354 macho_symtab_command<P>* _symbolTableCmd;
355 macho_dysymtab_command<P>* _dynamicSymbolTableCmd;
356 macho_uuid_command<P>* _uuidCmd;
357 uint32_t _maxStubs;
358 uint32_t _nextIndex;
359 uint32_t _firstStubOffset;
360 uint32_t* _stubInstructions;
361 macho_nlist<P>* _symbolTable;
362 char* _nextString;
363 char* _stringPoolStart;
364 char* _stringPoolEnd;
365 };
366
367 template <typename P>
368 BranchPoolDylib<P>::BranchPoolDylib(DyldSharedCache* cache, uint64_t poolStartAddr,
369 uint64_t textRegionStartAddr, uint64_t poolLinkEditStartAddr, uint64_t poolLinkEditStartOffset, Diagnostics& diags)
370 : _cacheBuffer(cache), _startAddr(poolStartAddr), _nextIndex(0), _firstStubOffset(0x280), _diagnostics(diags)
371 {
372 std::string archName = cache->archName();
373 bool is64 = (sizeof(typename P::uint_t) == 8);
374
375 const uint64_t textSegSize = branchPoolTextSize(archName);
376 const uint64_t linkEditSegSize = branchPoolLinkEditSize(archName);
377 const unsigned stubCount = (unsigned)((textSegSize - _firstStubOffset)/4);
378 const uint32_t linkeditOffsetSymbolTable = 0;
379 const uint32_t linkeditOffsetIndirectSymbolTable = stubCount*sizeof(macho_nlist<P>);
380 const uint32_t linkeditOffsetSymbolPoolOffset = linkeditOffsetIndirectSymbolTable + stubCount*sizeof(uint32_t);
381 _maxStubs = stubCount;
382
383 // write mach_header and load commands for pseudo dylib
384 macho_header<P>* mh = (macho_header<P>*)((uint8_t*)cache + poolStartAddr - textRegionStartAddr);
385 mh->set_magic(is64 ? MH_MAGIC_64 : MH_MAGIC);
386 mh->set_cputype(dyld3::MachOParser::cpuTypeFromArchName(archName));
387 mh->set_cpusubtype(dyld3::MachOParser::cpuSubtypeFromArchName(archName));
388 mh->set_filetype(MH_DYLIB);
389 mh->set_ncmds(6);
390 mh->set_sizeofcmds(is64 ? 0x210 : 100); // FIXME: 32-bit size
391 mh->set_flags(0x80000000);
392 // LC_SEGMENT
393 macho_load_command<P>* cmd = (macho_load_command<P>*)((uint8_t*)mh + sizeof(macho_header<P>));
394 macho_segment_command<P>* textSegCmd = (macho_segment_command<P>*)cmd;
395 textSegCmd->set_cmd(is64 ? LC_SEGMENT_64 : LC_SEGMENT);
396 textSegCmd->set_cmdsize(sizeof(macho_segment_command<P>)*2+sizeof(macho_section<P>));
397 textSegCmd->set_segname("__TEXT");
398 textSegCmd->set_vmaddr(poolStartAddr);
399 textSegCmd->set_vmsize(textSegSize);
400 textSegCmd->set_fileoff(poolStartAddr - textRegionStartAddr);
401 textSegCmd->set_filesize(branchPoolTextSize(archName));
402 textSegCmd->set_maxprot(PROT_READ|PROT_EXEC);
403 textSegCmd->set_initprot(PROT_READ|PROT_EXEC);
404 textSegCmd->set_nsects(1);
405 textSegCmd->set_flags(0);
406 macho_section<P>* stubSection = (macho_section<P>*)((uint8_t*)textSegCmd + sizeof(macho_segment_command<P>));
407 stubSection->set_sectname("__stubs");
408 stubSection->set_segname("__TEXT");
409 stubSection->set_addr(poolStartAddr + _firstStubOffset);
410 stubSection->set_size(textSegSize - _firstStubOffset);
411 stubSection->set_offset((uint32_t)(poolStartAddr + _firstStubOffset - textRegionStartAddr));
412 stubSection->set_align(2);
413 stubSection->set_reloff(0);
414 stubSection->set_nreloc(0);
415 stubSection->set_flags(S_SYMBOL_STUBS | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS);
416 stubSection->set_reserved1(0); // start index in indirect table
417 stubSection->set_reserved2(4); // size of stubs
418 // LC_SEGMENT
419 cmd = (macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
420 macho_segment_command<P>* linkEditSegCmd = (macho_segment_command<P>*)cmd;
421 linkEditSegCmd->set_cmd(is64 ? LC_SEGMENT_64 : LC_SEGMENT);
422 linkEditSegCmd->set_cmdsize(sizeof(macho_segment_command<P>));
423 linkEditSegCmd->set_segname("__LINKEDIT");
424 linkEditSegCmd->set_vmaddr(poolLinkEditStartAddr);
425 linkEditSegCmd->set_vmsize(linkEditSegSize);
426 linkEditSegCmd->set_fileoff(poolLinkEditStartOffset);
427 linkEditSegCmd->set_filesize(linkEditSegSize);
428 linkEditSegCmd->set_maxprot(PROT_READ);
429 linkEditSegCmd->set_initprot(PROT_READ);
430 linkEditSegCmd->set_nsects(0);
431 linkEditSegCmd->set_flags(0);
432 // LC_ID_DYLIB
433 cmd = (macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
434 macho_dylib_command<P>* installNameCmd = (macho_dylib_command<P>*)cmd;
435 installNameCmd->set_cmd(LC_ID_DYLIB);
436 installNameCmd->set_cmdsize(sizeof(macho_dylib_command<P>) + 48);
437 installNameCmd->set_timestamp(2);
438 installNameCmd->set_current_version(0x10000);
439 installNameCmd->set_compatibility_version(0x10000);
440 installNameCmd->set_name_offset();
441 strcpy((char*)cmd + sizeof(macho_dylib_command<P>), "dyld_shared_cache_branch_islands");
442 // LC_SYMTAB
443 cmd = (macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
444 _symbolTableCmd = (macho_symtab_command<P>*)cmd;
445 _symbolTableCmd->set_cmd(LC_SYMTAB);
446 _symbolTableCmd->set_cmdsize(sizeof(macho_symtab_command<P>));
447 _symbolTableCmd->set_nsyms(stubCount);
448 _symbolTableCmd->set_symoff((uint32_t)(poolLinkEditStartOffset + linkeditOffsetSymbolTable));
449 _symbolTableCmd->set_stroff((uint32_t)(poolLinkEditStartOffset + linkeditOffsetSymbolPoolOffset));
450 _symbolTableCmd->set_strsize((uint32_t)(linkEditSegSize - linkeditOffsetSymbolPoolOffset));
451 // LC_DYSYMTAB
452 cmd = (macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
453 _dynamicSymbolTableCmd = (macho_dysymtab_command<P>*)cmd;
454 _dynamicSymbolTableCmd->set_cmd(LC_DYSYMTAB);
455 _dynamicSymbolTableCmd->set_cmdsize(sizeof(macho_dysymtab_command<P>));
456 _dynamicSymbolTableCmd->set_ilocalsym(0);
457 _dynamicSymbolTableCmd->set_nlocalsym(0);
458 _dynamicSymbolTableCmd->set_iextdefsym(0);
459 _dynamicSymbolTableCmd->set_nextdefsym(0);
460 _dynamicSymbolTableCmd->set_iundefsym(0);
461 _dynamicSymbolTableCmd->set_nundefsym(stubCount);
462 _dynamicSymbolTableCmd->set_tocoff(0);
463 _dynamicSymbolTableCmd->set_ntoc(0);
464 _dynamicSymbolTableCmd->set_modtaboff(0);
465 _dynamicSymbolTableCmd->set_nmodtab(0);
466 _dynamicSymbolTableCmd->set_extrefsymoff(0);
467 _dynamicSymbolTableCmd->set_nextrefsyms(0);
468 _dynamicSymbolTableCmd->set_indirectsymoff((uint32_t)(poolLinkEditStartOffset + linkeditOffsetIndirectSymbolTable));
469 _dynamicSymbolTableCmd->set_nindirectsyms(stubCount);
470 _dynamicSymbolTableCmd->set_extreloff(0);
471 _dynamicSymbolTableCmd->set_nextrel(0);
472 _dynamicSymbolTableCmd->set_locreloff(0);
473 _dynamicSymbolTableCmd->set_nlocrel(0);
474 cmd = (macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
475 // LC_UUID
476 _uuidCmd = (macho_uuid_command<P>*)cmd;
477 _uuidCmd->set_cmd(LC_UUID);
478 _uuidCmd->set_cmdsize(sizeof(macho_uuid_command<P>));
479 cmd = (macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
480
481 // write stubs section content
482 _stubInstructions = (uint32_t*)((uint8_t*)mh + _firstStubOffset);
483 for (int i=0; i < stubCount; ++i) {
484 E::set32(_stubInstructions[i], 0xD4200000);
485 }
486
487 // write linkedit content
488 uint8_t* linkeditBufferStart = (uint8_t*)cache + poolLinkEditStartOffset;
489 // write symbol table
490 _symbolTable = (macho_nlist<P>*)(linkeditBufferStart);
491 for (int i=0; i < stubCount; ++i) {
492 _symbolTable[i].set_n_strx(1);
493 _symbolTable[i].set_n_type(N_UNDF | N_EXT);
494 _symbolTable[i].set_n_sect(0);
495 _symbolTable[i].set_n_desc(0);
496 _symbolTable[i].set_n_value(0);
497 }
498 // write indirect symbol table
499 uint32_t* indirectSymboTable = (uint32_t*)(linkeditBufferStart + linkeditOffsetIndirectSymbolTable);
500 for (int i=0; i < stubCount; ++i) {
501 P::E::set32(indirectSymboTable[i], i);
502 }
503 // write string pool
504 _stringPoolStart = (char*)(linkeditBufferStart + linkeditOffsetSymbolPoolOffset);
505 _stringPoolEnd = _stringPoolStart + linkEditSegSize - linkeditOffsetSymbolPoolOffset;
506 _stringPoolStart[0] = '\0';
507 strcpy(&_stringPoolStart[1], "<unused>");
508 _nextString = &_stringPoolStart[10];
509 }
510
511
512 template <typename P>
513 void BranchPoolDylib<P>::finalizeLoadCommands()
514 {
515 _symbolTableCmd->set_nsyms(_nextIndex);
516 _symbolTableCmd->set_strsize((uint32_t)(_nextString - _stringPoolStart));
517 _dynamicSymbolTableCmd->set_nundefsym(_nextIndex);
518
519 uint8_t digest[CC_MD5_DIGEST_LENGTH];
520 CC_MD5(_stubInstructions, _maxStubs*sizeof(uint64_t), digest);
521 _uuidCmd->set_uuid(digest);
522
523 if ( verbose ) {
524 _diagnostics.verbose("branch islands in image at 0x%0llX:\n", _startAddr);
525 for (uint32_t i=0; i < _nextIndex; ++i) {
526 _diagnostics.verbose(" 0x%llX %s\n", indexToAddr(i), _islandIndexToName[i]);
527 }
528 }
529 }
530
531 template <typename P>
532 uint64_t BranchPoolDylib<P>::getForwardBranch(uint64_t finalTargetAddr, const char* name, std::vector<BranchPoolDylib<P>*>& branchIslandPools)
533 {
534 // check if we can re-used existing branch island
535 const auto& pos = _targetToIslandIndex.find(finalTargetAddr);
536 if ( pos != _targetToIslandIndex.end() )
537 return indexToAddr(pos->second);
538
539 // skip if instruction pool is full
540 if ( _nextIndex >= _maxStubs )
541 return 0;
542
543 // skip if string pool is full
544 if ( (_nextString + strlen(name)+1) >= _stringPoolEnd )
545 return 0;
546
547 uint64_t branchIslandTargetAddr = finalTargetAddr;
548 // if final target is too far, we need to use branch island in next pool
549 if ( (finalTargetAddr - _startAddr) > b128MegLimit ) {
550 BranchPoolDylib<P>* nextPool = nullptr;
551 for (size_t i=0; i < branchIslandPools.size()-1; ++i) {
552 if ( branchIslandPools[i] == this ) {
553 nextPool = branchIslandPools[i+1];
554 break;
555 }
556 }
557
558 if (nextPool == nullptr) {
559 _diagnostics.warning("BranchPoolDylib<P>::getForwardBranch: nextPool unreachable");
560 return 0;
561 }
562
563 branchIslandTargetAddr = nextPool->getForwardBranch(finalTargetAddr, name, branchIslandPools);
564 if ( branchIslandTargetAddr == 0 )
565 return 0; // next pool is full
566 }
567
568 // write branch instruction in stubs section
569 uint32_t index = _nextIndex++;
570 int64_t branchDelta = branchIslandTargetAddr - indexToAddr(index);
571 uint32_t branchInstr = 0x14000000 + ((branchDelta/4) & 0x03FFFFFF);
572 E::set32(_stubInstructions[index], branchInstr);
573
574 // update symbol table
575 _symbolTable[index].set_n_strx((uint32_t)(_nextString - _stringPoolStart));
576 strcpy(_nextString, name);
577 _nextString += (strlen(name) +1);
578
579 // record island
580 _targetToIslandIndex[finalTargetAddr] = index;
581 _islandIndexToName[index] = name;
582 return indexToAddr(index);
583 }
584
585 template <typename P>
586 uint64_t BranchPoolDylib<P>::getBackBranch(uint64_t finalTargetAddr, const char* name, std::vector<BranchPoolDylib<P>*>& branchIslandPools)
587 {
588 // check if we can re-used existing branch island
589 const auto& pos = _targetToIslandIndex.find(finalTargetAddr);
590 if ( pos != _targetToIslandIndex.end() )
591 return indexToAddr(pos->second);
592
593 // skip if instruction pool is full
594 if ( _nextIndex >= _maxStubs )
595 return 0;
596
597 // skip if string pool is full
598 if ( (_nextString + strlen(name)+1) >= _stringPoolEnd )
599 return 0;
600
601 uint64_t branchIslandTargetAddr = finalTargetAddr;
602 // if final target is too far, we need to use branch island in next pool
603 if ( (indexToAddr(_nextIndex) - finalTargetAddr) > b128MegLimit ) {
604 BranchPoolDylib<P>* nextPool = nullptr;
605 for (long i=branchIslandPools.size()-1; i > 0; --i) {
606 if ( branchIslandPools[i] == this ) {
607 nextPool = branchIslandPools[i-1];
608 break;
609 }
610 }
611
612 if (nextPool == nullptr) {
613 _diagnostics.warning("BranchPoolDylib<P>::getBackBranch: nextPool unreachable");
614 return 0;
615 }
616
617 branchIslandTargetAddr = nextPool->getBackBranch(finalTargetAddr, name, branchIslandPools);
618 if ( branchIslandTargetAddr == 0 )
619 return 0; // next pool is full
620 }
621
622 // write branch instruction in stubs section
623 uint32_t index = _nextIndex++;
624 int64_t branchDelta = branchIslandTargetAddr - indexToAddr(index);
625 uint32_t branchInstr = 0x14000000 + ((branchDelta/4) & 0x03FFFFFF);
626 E::set32(_stubInstructions[index], branchInstr);
627
628 // update symbol table
629 _symbolTable[index].set_n_strx((uint32_t)(_nextString - _stringPoolStart));
630 strcpy(_nextString, name);
631 _nextString += (strlen(name) +1);
632
633 // record island
634 _targetToIslandIndex[finalTargetAddr] = index;
635 _islandIndexToName[index] = name;
636 return indexToAddr(index);
637 }
638
639 template <typename P>
640 void BranchPoolDylib<P>::printStats()
641 {
642 _diagnostics.verbose(" island pool at 0x%0llX has %u stubs and stringPool size=%lu\n", _startAddr, _nextIndex, _nextString - _stringPoolStart);
643 }
644
645
646
647 template <typename P>
648 class StubOptimizer {
649 public:
650 StubOptimizer(void* cacheBuffer, macho_header<P>* mh, Diagnostics& diags);
651 void buildStubMap(const std::unordered_set<std::string>& neverStubEliminate);
652 void optimizeStubs(std::unordered_map<uint64_t,std::vector<uint64_t>>& targetToBranchIslands);
653 void bypassStubs(std::unordered_map<uint64_t,std::vector<uint64_t>>& targetToBranchIslands);
654 void optimizeCallSites(std::vector<BranchPoolDylib<P>*>& branchIslandPools);
655 const char* installName() { return _installName; }
656 const uint8_t* exportsTrie() { return (uint8_t*)_cacheBuffer + _dyldInfo->export_off(); }
657 uint32_t exportsTrieSize() { return _dyldInfo->export_size(); }
658
659 uint32_t _stubCount = 0;
660 uint32_t _stubOptimizedCount = 0;
661 uint32_t _branchesCount = 0;
662 uint32_t _branchesModifiedCount = 0;
663 uint32_t _branchesDirectCount = 0;
664 uint32_t _branchesIslandCount = 0;
665
666 private:
667 Diagnostics _diagnostics;
668 typedef std::function<bool(uint8_t callSiteKind, uint64_t callSiteAddr, uint64_t stubAddr, uint32_t& instruction)> CallSiteHandler;
669 typedef typename P::uint_t pint_t;
670 typedef typename P::E E;
671
672 void forEachCallSiteToAStub(CallSiteHandler);
673 void optimizeArm64CallSites(std::vector<BranchPoolDylib<P>*>& branchIslandPools);
674 void optimizeArmCallSites();
675 void optimizeArmStubs();
676 uint64_t lazyPointerAddrFromArm64Stub(const uint8_t* stubInstructions, uint64_t stubVMAddr);
677 uint32_t lazyPointerAddrFromArmStub(const uint8_t* stubInstructions, uint32_t stubVMAddr);
678 int32_t getDisplacementFromThumbBranch(uint32_t instruction, uint32_t instrAddr);
679 uint32_t setDisplacementInThumbBranch(uint32_t instruction, uint32_t instrAddr,
680 int32_t displacement, bool targetIsThumb);
681
682
683 struct AddressAndName { pint_t targetVMAddr; const char* targetName; };
684 typedef std::unordered_map<pint_t, AddressAndName> StubVMAddrToTarget;
685
686 static const int64_t b128MegLimit = 0x07FFFFFF;
687 static const int64_t b16MegLimit = 0x00FFFFFF;
688
689
690 macho_header<P>* _mh;
691 void* _cacheBuffer;
692 uint32_t _linkeditSize = 0;
693 uint32_t _linkeditCacheOffset = 0;
694 uint64_t _linkeditAddr = 0;
695 const uint8_t* _linkeditBias = nullptr;
696 const char* _installName = nullptr;
697 const macho_symtab_command<P>* _symTabCmd = nullptr;
698 const macho_dysymtab_command<P>* _dynSymTabCmd = nullptr;
699 const macho_dyld_info_command<P>* _dyldInfo = nullptr;
700 macho_linkedit_data_command<P>* _splitSegInfoCmd = nullptr;
701 const macho_section<P>* _textSection = nullptr;
702 const macho_section<P>* _stubSection = nullptr;
703 uint32_t _textSectionIndex = 0;
704 uint32_t _stubSectionIndex = 0;
705 pint_t _textSegStartAddr = 0;
706 uint32_t _textSegCacheOffset = 0;
707 std::vector<macho_segment_command<P>*> _segCmds;
708 std::unordered_map<pint_t, pint_t> _stubAddrToLPAddr;
709 std::unordered_map<pint_t, pint_t> _lpAddrToTargetAddr;
710 std::unordered_map<pint_t, const char*> _targetAddrToName;
711 };
712
713 template <typename P>
714 StubOptimizer<P>::StubOptimizer(void* cacheBuffer, macho_header<P>* mh, Diagnostics& diags)
715 : _mh(mh), _cacheBuffer(cacheBuffer), _diagnostics(diags)
716 {
717 _linkeditBias = (uint8_t*)cacheBuffer;
718 const macho_load_command<P>* const cmds = (macho_load_command<P>*)((uint8_t*)mh + sizeof(macho_header<P>));
719 const uint32_t cmd_count = mh->ncmds();
720 macho_segment_command<P>* segCmd;
721 uint32_t sectionIndex = 0;
722 const macho_load_command<P>* cmd = cmds;
723 for (uint32_t i = 0; i < cmd_count; ++i) {
724 switch (cmd->cmd()) {
725 case LC_ID_DYLIB:
726 _installName = ((macho_dylib_command<P>*)cmd)->name();
727 break;
728 case LC_SYMTAB:
729 _symTabCmd = (macho_symtab_command<P>*)cmd;
730 break;
731 case LC_DYSYMTAB:
732 _dynSymTabCmd = (macho_dysymtab_command<P>*)cmd;
733 break;
734 case LC_SEGMENT_SPLIT_INFO:
735 _splitSegInfoCmd = (macho_linkedit_data_command<P>*)cmd;
736 break;
737 case LC_DYLD_INFO:
738 case LC_DYLD_INFO_ONLY:
739 _dyldInfo = (macho_dyld_info_command<P>*)cmd;
740 break;
741 case macho_segment_command<P>::CMD:
742 segCmd =( macho_segment_command<P>*)cmd;
743 _segCmds.push_back(segCmd);
744 if ( strcmp(segCmd->segname(), "__LINKEDIT") == 0 ) {
745 _linkeditSize = (uint32_t)segCmd->vmsize();
746 _linkeditCacheOffset = (uint32_t)segCmd->fileoff();
747 _linkeditAddr = segCmd->vmaddr();
748 }
749 else if ( strcmp(segCmd->segname(), "__TEXT") == 0 ) {
750 _textSegStartAddr = (pint_t)segCmd->vmaddr();
751 _textSegCacheOffset = (uint32_t)((uint8_t*)mh - (uint8_t*)cacheBuffer);
752 const macho_section<P>* const sectionsStart = (macho_section<P>*)((char*)segCmd + sizeof(macho_segment_command<P>));
753 const macho_section<P>* const sectionsEnd = &sectionsStart[segCmd->nsects()];
754 for (const macho_section<P>* sect = sectionsStart; sect < sectionsEnd; ++sect) {
755 ++sectionIndex;
756 if ( strcmp(sect->sectname(), "__text") == 0 ) {
757 _textSection = sect;
758 _textSectionIndex = sectionIndex;
759 }
760 else if ( ((sect->flags() & SECTION_TYPE) == S_SYMBOL_STUBS) && (sect->size() != 0) ) {
761 _stubSection = sect;
762 _stubSectionIndex = sectionIndex;
763 }
764 }
765 }
766 break;
767 }
768 cmd = (const macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
769 }
770 }
771
772
773
774 template <typename P>
775 uint32_t StubOptimizer<P>::lazyPointerAddrFromArmStub(const uint8_t* stubInstructions, uint32_t stubVMAddr)
776 {
777 uint32_t stubInstr1 = E::get32(*(uint32_t*)stubInstructions);
778 uint32_t stubInstr2 = E::get32(*(uint32_t*)(stubInstructions+4));
779 uint32_t stubInstr3 = E::get32(*(uint32_t*)(stubInstructions+8));
780 int32_t stubData = E::get32(*(uint32_t*)(stubInstructions+12));
781 if ( stubInstr1 != 0xe59fc004 ) {
782 _diagnostics.warning("first instruction of stub (0x%08X) is not 'ldr ip, pc + 12' for stub at addr 0x%0llX in %s",
783 stubInstr1, (uint64_t)stubVMAddr, _installName);
784 return 0;
785 }
786 if ( stubInstr2 != 0xe08fc00c ) {
787 _diagnostics.warning("second instruction of stub (0x%08X) is not 'add ip, pc, ip' for stub at addr 0x%0llX in %s",
788 stubInstr1, (uint64_t)stubVMAddr, _installName);
789 return 0;
790 }
791 if ( stubInstr3 != 0xe59cf000 ) {
792 _diagnostics.warning("third instruction of stub (0x%08X) is not 'ldr pc, [ip]' for stub at addr 0x%0llX in %s",
793 stubInstr1, (uint64_t)stubVMAddr, _installName);
794 return 0;
795 }
796 return stubVMAddr + 12 + stubData;
797 }
798
799
800 template <typename P>
801 uint64_t StubOptimizer<P>::lazyPointerAddrFromArm64Stub(const uint8_t* stubInstructions, uint64_t stubVMAddr)
802 {
803 uint32_t stubInstr1 = E::get32(*(uint32_t*)stubInstructions);
804 if ( (stubInstr1 & 0x9F00001F) != 0x90000010 ) {
805 _diagnostics.warning("first instruction of stub (0x%08X) is not ADRP for stub at addr 0x%0llX in %s",
806 stubInstr1, (uint64_t)stubVMAddr, _installName);
807 return 0;
808 }
809 int32_t adrpValue = ((stubInstr1 & 0x00FFFFE0) >> 3) | ((stubInstr1 & 0x60000000) >> 29);
810 if ( stubInstr1 & 0x00800000 )
811 adrpValue |= 0xFFF00000;
812 uint32_t stubInstr2 = E::get32(*(uint32_t*)(stubInstructions + 4));
813 if ( (stubInstr2 & 0xFFC003FF) != 0xF9400210 ) {
814 _diagnostics.warning("second instruction of stub (0x%08X) is not LDR for stub at addr 0x%0llX in %s",
815 stubInstr2, (uint64_t)stubVMAddr, _installName);
816 return 0;
817 }
818 uint32_t ldrValue = ((stubInstr2 >> 10) & 0x00000FFF);
819 return (stubVMAddr & (-4096)) + adrpValue*4096 + ldrValue*8;
820 }
821
822
823
824 template <typename P>
825 void StubOptimizer<P>::buildStubMap(const std::unordered_set<std::string>& neverStubEliminate)
826 {
827 // find all stubs and lazy pointers
828 const macho_nlist<P>* symbolTable = (const macho_nlist<P>*)(((uint8_t*)_cacheBuffer) + _symTabCmd->symoff());
829 const char* symbolStrings = (char*)_cacheBuffer + _symTabCmd->stroff();
830 const uint32_t* const indirectTable = (uint32_t*)(((uint8_t*)_cacheBuffer) + _dynSymTabCmd->indirectsymoff());
831 const macho_load_command<P>* const cmds = (macho_load_command<P>*)((uint8_t*)_mh + sizeof(macho_header<P>));
832 const uint32_t cmd_count = _mh->ncmds();
833 const macho_load_command<P>* cmd = cmds;
834 for (uint32_t i = 0; i < cmd_count; ++i) {
835 if ( cmd->cmd() == macho_segment_command<P>::CMD ) {
836 macho_segment_command<P>* seg = (macho_segment_command<P>*)cmd;
837 macho_section<P>* const sectionsStart = (macho_section<P>*)((char*)seg + sizeof(macho_segment_command<P>));
838 macho_section<P>* const sectionsEnd = &sectionsStart[seg->nsects()];
839 for(macho_section<P>* sect = sectionsStart; sect < sectionsEnd; ++sect) {
840 if ( sect->size() == 0 )
841 continue;
842 unsigned sectionType = (sect->flags() & SECTION_TYPE);
843 const uint32_t indirectTableOffset = sect->reserved1();
844 if ( sectionType == S_SYMBOL_STUBS ) {
845 const uint32_t stubSize = sect->reserved2();
846 _stubCount = (uint32_t)(sect->size() / stubSize);
847 pint_t stubVMAddr = (pint_t)sect->addr();
848 for (uint32_t j=0; j < _stubCount; ++j, stubVMAddr += stubSize) {
849 uint32_t symbolIndex = E::get32(indirectTable[indirectTableOffset + j]);
850 switch ( symbolIndex ) {
851 case INDIRECT_SYMBOL_ABS:
852 case INDIRECT_SYMBOL_LOCAL:
853 break;
854 default:
855 if ( symbolIndex >= _symTabCmd->nsyms() ) {
856 _diagnostics.warning("symbol index out of range (%d of %d) for stub at addr 0x%0llX in %s",
857 symbolIndex, _symTabCmd->nsyms(), (uint64_t)stubVMAddr, _installName);
858 continue;
859 }
860 const macho_nlist<P>* sym = &symbolTable[symbolIndex];
861 uint32_t stringOffset = sym->n_strx();
862 if ( stringOffset > _symTabCmd->strsize() ) {
863 _diagnostics.warning("symbol string offset out of range (%u of %u) for stub at addr 0x%0llX in %s",
864 stringOffset, sym->n_strx(), (uint64_t)stubVMAddr, _installName);
865 continue;
866 }
867 const char* symName = &symbolStrings[stringOffset];
868 if ( neverStubEliminate.count(symName) ) {
869 //verboseLog("not bypassing stub to %s in %s because target is interposable\n", symName, _installName);
870 continue;
871 }
872 const uint8_t* stubInstrs = (uint8_t*)_cacheBuffer + sect->offset() + stubVMAddr - sect->addr();
873 pint_t targetLPAddr = 0;
874 switch ( _mh->cputype() ) {
875 case CPU_TYPE_ARM64:
876 targetLPAddr = (pint_t)lazyPointerAddrFromArm64Stub(stubInstrs, stubVMAddr);
877 break;
878 case CPU_TYPE_ARM:
879 targetLPAddr = (pint_t)lazyPointerAddrFromArmStub(stubInstrs, (uint32_t)stubVMAddr);
880 break;
881 }
882 if ( targetLPAddr != 0 )
883 _stubAddrToLPAddr[stubVMAddr] = targetLPAddr;
884 break;
885 }
886 }
887 }
888 else if ( sectionType == S_LAZY_SYMBOL_POINTERS ) {
889 pint_t lpVMAddr;
890 pint_t* lpContent = (pint_t*)(((uint8_t*)_cacheBuffer) + sect->offset());
891 uint32_t elementCount = (uint32_t)(sect->size() / sizeof(pint_t));
892 uint64_t textSegStartAddr = _segCmds[0]->vmaddr();
893 uint64_t textSegEndAddr = _segCmds[0]->vmaddr() + _segCmds[0]->vmsize();
894 pint_t lpValue;
895 for (uint32_t j=0; j < elementCount; ++j) {
896 uint32_t symbolIndex = E::get32(indirectTable[indirectTableOffset + j]);
897 switch ( symbolIndex ) {
898 case INDIRECT_SYMBOL_ABS:
899 case INDIRECT_SYMBOL_LOCAL:
900 break;
901 default:
902 lpValue = (pint_t)P::getP(lpContent[j]);
903 lpVMAddr = (pint_t)sect->addr() + j * sizeof(pint_t);
904 if ( symbolIndex >= _symTabCmd->nsyms() ) {
905 _diagnostics.warning("symbol index out of range (%d of %d) for lazy pointer at addr 0x%0llX in %s",
906 symbolIndex, _symTabCmd->nsyms(), (uint64_t)lpVMAddr, _installName);
907 continue;
908 }
909 const macho_nlist<P>* sym = &symbolTable[symbolIndex];
910 uint32_t stringOffset = sym->n_strx();
911 if ( stringOffset > _symTabCmd->strsize() ) {
912 _diagnostics.warning("symbol string offset out of range (%u of %u) for lazy pointer at addr 0x%0llX in %s",
913 stringOffset, sym->n_strx(), (uint64_t)lpVMAddr, _installName);
914 continue;
915 }
916 const char* symName = &symbolStrings[stringOffset];
917 if ( (lpValue > textSegStartAddr) && (lpValue< textSegEndAddr) ) {
918 //verboseLog("skipping lazy pointer at 0x%0lX to %s in %s because target is within dylib\n", lpVMAddr, symName, _installName);
919 }
920 else if ( (sizeof(pint_t) == 8) && ((lpValue % 4) != 0) ) {
921 _diagnostics.warning("lazy pointer at 0x%0llX does not point to 4-byte aligned address(0x%0llX) in %s",
922 (uint64_t)lpVMAddr, (uint64_t)lpValue, _installName);
923 }
924 else {
925 _lpAddrToTargetAddr[lpVMAddr] = lpValue;
926 _targetAddrToName[lpValue] = symName;
927 }
928 break;
929 }
930 }
931 }
932 }
933 }
934 cmd = (const macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
935 }
936 }
937
938
939 template <typename P>
940 void StubOptimizer<P>::forEachCallSiteToAStub(CallSiteHandler handler)
941 {
942 if (_diagnostics.hasError())
943 return;
944 const uint8_t* infoStart = &_linkeditBias[_splitSegInfoCmd->dataoff()];
945 const uint8_t* infoEnd = &infoStart[_splitSegInfoCmd->datasize()];
946 if ( *infoStart++ != DYLD_CACHE_ADJ_V2_FORMAT ) {
947 _diagnostics.error("malformed split seg info in %s", _installName);
948 return;
949 }
950
951 uint8_t* textSectionContent = (uint8_t*)_cacheBuffer + _textSegCacheOffset + _textSection->addr() -_textSegStartAddr;
952
953 // Whole :== <count> FromToSection+
954 // FromToSection :== <from-sect-index> <to-sect-index> <count> ToOffset+
955 // ToOffset :== <to-sect-offset-delta> <count> FromOffset+
956 // FromOffset :== <kind> <count> <from-sect-offset-delta>
957 const uint8_t* p = infoStart;
958 uint64_t sectionCount = read_uleb128(p, infoEnd);
959 for (uint64_t i=0; i < sectionCount; ++i) {
960 uint64_t fromSectionIndex = read_uleb128(p, infoEnd);
961 uint64_t toSectionIndex = read_uleb128(p, infoEnd);
962 uint64_t toOffsetCount = read_uleb128(p, infoEnd);
963 uint64_t toSectionOffset = 0;
964 for (uint64_t j=0; j < toOffsetCount; ++j) {
965 uint64_t toSectionDelta = read_uleb128(p, infoEnd);
966 uint64_t fromOffsetCount = read_uleb128(p, infoEnd);
967 toSectionOffset += toSectionDelta;
968 for (uint64_t k=0; k < fromOffsetCount; ++k) {
969 uint64_t kind = read_uleb128(p, infoEnd);
970 if (kind > 12) {
971 _diagnostics.error("bad kind (%llu) value in %s", kind, _installName);
972 }
973 uint64_t fromSectDeltaCount = read_uleb128(p, infoEnd);
974 uint64_t fromSectionOffset = 0;
975 for (uint64_t l=0; l < fromSectDeltaCount; ++l) {
976 uint64_t delta = read_uleb128(p, infoEnd);
977 fromSectionOffset += delta;
978 if ( (fromSectionIndex == _textSectionIndex) && (toSectionIndex == _stubSectionIndex) ) {
979 uint32_t* instrPtr = (uint32_t*)(textSectionContent + fromSectionOffset);
980 uint64_t instrAddr = _textSection->addr() + fromSectionOffset;
981 uint64_t stubAddr = _stubSection->addr() + toSectionOffset;
982 uint32_t instruction = E::get32(*instrPtr);
983 _branchesCount++;
984 if ( handler(kind, instrAddr, stubAddr, instruction) ) {
985 _branchesModifiedCount++;
986 E::set32(*instrPtr, instruction);
987 }
988 }
989 }
990 }
991 }
992 }
993 }
994
995
996 /// Extract displacement from a thumb b/bl/blx instruction.
997 template <typename P>
998 int32_t StubOptimizer<P>::getDisplacementFromThumbBranch(uint32_t instruction, uint32_t instrAddr)
999 {
1000 bool is_blx = ((instruction & 0xD000F800) == 0xC000F000);
1001 uint32_t s = (instruction >> 10) & 0x1;
1002 uint32_t j1 = (instruction >> 29) & 0x1;
1003 uint32_t j2 = (instruction >> 27) & 0x1;
1004 uint32_t imm10 = instruction & 0x3FF;
1005 uint32_t imm11 = (instruction >> 16) & 0x7FF;
1006 uint32_t i1 = (j1 == s);
1007 uint32_t i2 = (j2 == s);
1008 uint32_t dis = (s << 24) | (i1 << 23) | (i2 << 22) | (imm10 << 12) | (imm11 << 1);
1009 int32_t sdis = dis;
1010 int32_t result = s ? (sdis | 0xFE000000) : sdis;
1011 if ( is_blx && (instrAddr & 0x2) ) {
1012 // The thumb blx instruction always has low bit of imm11 as zero. The way
1013 // a 2-byte aligned blx can branch to a 4-byte aligned ARM target is that
1014 // the blx instruction always 4-byte aligns the pc before adding the
1015 // displacement from the blx. We must emulate that when decoding this.
1016 result -= 2;
1017 }
1018 return result;
1019 }
1020
1021 /// Update a thumb b/bl/blx instruction, switching bl <-> blx as needed.
1022 template <typename P>
1023 uint32_t StubOptimizer<P>::setDisplacementInThumbBranch(uint32_t instruction, uint32_t instrAddr,
1024 int32_t displacement, bool targetIsThumb) {
1025 if ( (displacement > 16777214) || (displacement < (-16777216)) ) {
1026 _diagnostics.error("thumb branch out of range at 0x%0X in %s", instrAddr, _installName);
1027 return 0;
1028 }
1029 bool is_bl = ((instruction & 0xD000F800) == 0xD000F000);
1030 bool is_blx = ((instruction & 0xD000F800) == 0xC000F000);
1031 bool is_b = ((instruction & 0xD000F800) == 0x9000F000);
1032 uint32_t newInstruction = (instruction & 0xD000F800);
1033 if (is_bl || is_blx) {
1034 if (targetIsThumb) {
1035 newInstruction = 0xD000F000; // Use bl
1036 }
1037 else {
1038 newInstruction = 0xC000F000; // Use blx
1039 // See note in getDisplacementFromThumbBranch() about blx.
1040 if (instrAddr & 0x2)
1041 displacement += 2;
1042 }
1043 }
1044 else if (is_b) {
1045 if ( !targetIsThumb ) {
1046 _diagnostics.error("no pc-rel thumb branch instruction that switches to arm mode at 0x%0X in %s", instrAddr, _installName);
1047 return 0;
1048 }
1049 }
1050 else {
1051 _diagnostics.error("not b/bl/blx at 0x%0X in %s", instrAddr, _installName);
1052 return 0;
1053 }
1054 uint32_t s = (uint32_t)(displacement >> 24) & 0x1;
1055 uint32_t i1 = (uint32_t)(displacement >> 23) & 0x1;
1056 uint32_t i2 = (uint32_t)(displacement >> 22) & 0x1;
1057 uint32_t imm10 = (uint32_t)(displacement >> 12) & 0x3FF;
1058 uint32_t imm11 = (uint32_t)(displacement >> 1) & 0x7FF;
1059 uint32_t j1 = (i1 == s);
1060 uint32_t j2 = (i2 == s);
1061 uint32_t nextDisp = (j1 << 13) | (j2 << 11) | imm11;
1062 uint32_t firstDisp = (s << 10) | imm10;
1063 newInstruction |= (nextDisp << 16) | firstDisp;
1064 return newInstruction;
1065 }
1066
1067
1068 template <typename P>
1069 void StubOptimizer<P>::optimizeArmCallSites()
1070 {
1071 forEachCallSiteToAStub([&](uint8_t kind, uint64_t callSiteAddr, uint64_t stubAddr, uint32_t& instruction) -> bool {
1072 if ( kind == DYLD_CACHE_ADJ_V2_THUMB_BR22 ) {
1073 bool is_bl = ((instruction & 0xD000F800) == 0xD000F000);
1074 bool is_blx = ((instruction & 0xD000F800) == 0xC000F000);
1075 bool is_b = ((instruction & 0xD000F800) == 0x9000F000);
1076 if ( !is_bl && !is_blx && !is_b ){
1077 _diagnostics.warning("non-branch instruction at 0x%0llX in %s", callSiteAddr, _installName);
1078 return false;
1079 }
1080 int32_t brDelta = getDisplacementFromThumbBranch(instruction, (uint32_t)callSiteAddr);
1081 pint_t targetAddr = (pint_t)callSiteAddr + 4 + brDelta;
1082 if ( targetAddr != stubAddr ) {
1083 _diagnostics.warning("stub target mismatch at callsite 0x%0llX in %s", callSiteAddr, _installName);
1084 return false;
1085 }
1086 // ignore branch if not to a known stub
1087 const auto& pos = _stubAddrToLPAddr.find(targetAddr);
1088 if ( pos == _stubAddrToLPAddr.end() )
1089 return false;
1090 // ignore branch if lazy pointer is not known (could be resolver based)
1091 pint_t lpAddr = pos->second;
1092 const auto& pos2 = _lpAddrToTargetAddr.find(lpAddr);
1093 if ( pos2 == _lpAddrToTargetAddr.end() )
1094 return false;
1095 uint64_t finalTargetAddr = pos2->second;
1096 int64_t deltaToFinalTarget = finalTargetAddr - (callSiteAddr + 4);
1097 // if final target within range, change to branch there directly
1098 if ( (deltaToFinalTarget > -b16MegLimit) && (deltaToFinalTarget < b16MegLimit) ) {
1099 bool targetIsThumb = finalTargetAddr & 1;
1100 instruction = setDisplacementInThumbBranch(instruction, (uint32_t)callSiteAddr, (int32_t)deltaToFinalTarget, targetIsThumb);
1101 if (_diagnostics.hasError())
1102 return false;
1103 _branchesDirectCount++;
1104 return true;
1105 }
1106 }
1107 else if ( kind == DYLD_CACHE_ADJ_V2_ARM_BR24 ) {
1108 // too few of these to be worth trying to optimize
1109 }
1110
1111 return false;
1112 });
1113 if (_diagnostics.hasError())
1114 return;
1115 }
1116
1117
1118 template <typename P>
1119 void StubOptimizer<P>::optimizeArmStubs()
1120 {
1121 for (const auto& stubEntry : _stubAddrToLPAddr) {
1122 pint_t stubVMAddr = stubEntry.first;
1123 pint_t lpVMAddr = stubEntry.second;
1124 const auto& pos = _lpAddrToTargetAddr.find(lpVMAddr);
1125 if ( pos == _lpAddrToTargetAddr.end() )
1126 return;
1127 pint_t targetVMAddr = pos->second;
1128
1129 int32_t delta = (int32_t)(targetVMAddr - (stubVMAddr + 12));
1130 const uint32_t* stubInstructions = (uint32_t*)((uint8_t*)_cacheBuffer + _stubSection->offset() + stubVMAddr - _stubSection->addr());
1131 E::set32(*(uint32_t*)&stubInstructions[0], 0xe59fc000); // ldr ip, L0
1132 E::set32(*(uint32_t*)&stubInstructions[1], 0xe08ff00c); // add pc, pc, ip
1133 E::set32(*(uint32_t*)&stubInstructions[2], delta); // L0: .long xxxx
1134 E::set32(*(uint32_t*)&stubInstructions[3], 0xe7ffdefe); // trap
1135 _stubOptimizedCount++;
1136 }
1137 }
1138
1139
1140
1141
1142 template <typename P>
1143 void StubOptimizer<P>::optimizeArm64CallSites(std::vector<BranchPoolDylib<P>*>& branchIslandPools)
1144 {
1145 forEachCallSiteToAStub([&](uint8_t kind, uint64_t callSiteAddr, uint64_t stubAddr, uint32_t& instruction) -> bool {
1146 if ( kind != DYLD_CACHE_ADJ_V2_ARM64_BR26 )
1147 return false;
1148 // skip all but BL or B
1149 if ( (instruction & 0x7C000000) != 0x14000000 )
1150 return false;
1151 // compute target of branch instruction
1152 int32_t brDelta = (instruction & 0x03FFFFFF) << 2;
1153 if ( brDelta & 0x08000000 )
1154 brDelta |= 0xF0000000;
1155 uint64_t targetAddr = callSiteAddr + (int64_t)brDelta;
1156 if ( targetAddr != stubAddr ) {
1157 _diagnostics.warning("stub target mismatch");
1158 return false;
1159 }
1160 // ignore branch if not to a known stub
1161 const auto& pos = _stubAddrToLPAddr.find((pint_t)targetAddr);
1162 if ( pos == _stubAddrToLPAddr.end() )
1163 return false;
1164 // ignore branch if lazy pointer is not known (could be resolver based)
1165 uint64_t lpAddr = pos->second;
1166 const auto& pos2 = _lpAddrToTargetAddr.find((pint_t)lpAddr);
1167 if ( pos2 == _lpAddrToTargetAddr.end() )
1168 return false;
1169 uint64_t finalTargetAddr = pos2->second;
1170 int64_t deltaToFinalTarget = finalTargetAddr - callSiteAddr;
1171 // if final target within range, change to branch there directly
1172 if ( (deltaToFinalTarget > -b128MegLimit) && (deltaToFinalTarget < b128MegLimit) ) {
1173 instruction= (instruction & 0xFC000000) | ((deltaToFinalTarget >> 2) & 0x03FFFFFF);
1174 _branchesDirectCount++;
1175 return true;
1176 }
1177 // find closest branch island pool between instruction and target and get island
1178 const auto& pos3 = _targetAddrToName.find((pint_t)finalTargetAddr);
1179 if ( pos3 == _targetAddrToName.end() )
1180 return false;
1181 const char* targetName = pos3->second;
1182 if ( finalTargetAddr > callSiteAddr ) {
1183 // target is after branch so find first pool after branch
1184 for ( BranchPoolDylib<P>* pool : branchIslandPools ) {
1185 if ( (pool->addr() > callSiteAddr) && (pool->addr() < finalTargetAddr) ) {
1186 uint64_t brIslandAddr = pool->getForwardBranch(finalTargetAddr, targetName, branchIslandPools);
1187 if ( brIslandAddr == 0 ) {
1188 // branch island pool full
1189 _diagnostics.warning("pool full. Can't optimizer branch to %s from 0x%llX in %s\n", targetName, callSiteAddr, _installName);
1190 break;
1191 }
1192 int64_t deltaToTarget = brIslandAddr - callSiteAddr;
1193 instruction = (instruction & 0xFC000000) | ((deltaToTarget >> 2) & 0x03FFFFFF);
1194 _branchesIslandCount++;
1195 return true;
1196 }
1197 }
1198 }
1199 else {
1200 // target is before branch so find closest pool before branch
1201 for (size_t j = branchIslandPools.size(); j > 0; --j) {
1202 BranchPoolDylib<P>* pool = branchIslandPools[j-1];
1203 if ( (pool->addr() < callSiteAddr) && (pool->addr() > finalTargetAddr) ) {
1204 uint64_t brIslandAddr = pool->getBackBranch(finalTargetAddr, targetName, branchIslandPools);
1205 if ( brIslandAddr == 0 ) {
1206 // branch island pool full
1207 _diagnostics.warning("pool full. Can't optimizer branch to %s from 0x%llX in %s\n", targetName, callSiteAddr, _installName);
1208 break;
1209 }
1210 int64_t deltaToTarget = brIslandAddr - callSiteAddr;
1211 instruction = (instruction & 0xFC000000) | ((deltaToTarget >> 2) & 0x03FFFFFF);
1212 _branchesIslandCount++;
1213 return true;
1214 }
1215 }
1216 }
1217 return false;
1218 });
1219 if (_diagnostics.hasError())
1220 return;
1221 }
1222
1223
1224 template <typename P>
1225 void StubOptimizer<P>::optimizeCallSites(std::vector<BranchPoolDylib<P>*>& branchIslandPools)
1226 {
1227 if ( _textSection == NULL )
1228 return;
1229 if ( _stubSection == NULL )
1230 return;
1231
1232
1233 switch ( _mh->cputype() ) {
1234 case CPU_TYPE_ARM64:
1235 optimizeArm64CallSites(branchIslandPools);
1236 if ( verbose ) {
1237 _diagnostics.verbose("%5u branches in __text, %5u changed to direct branches, %5u changed to use islands for %s\n",
1238 _branchesCount, _branchesDirectCount, _branchesIslandCount, _installName);
1239 }
1240 break;
1241 case CPU_TYPE_ARM:
1242 optimizeArmCallSites();
1243 optimizeArmStubs();
1244 if ( verbose ) {
1245 _diagnostics.verbose("%3u of %3u stubs optimized. %5u branches in __text, %5u changed to direct branches for %s\n",
1246 _stubOptimizedCount, _stubCount, _branchesCount, _branchesDirectCount, _installName);
1247 }
1248 break;
1249 }
1250 }
1251
1252 template <typename P>
1253 void bypassStubs(DyldSharedCache* cache, const std::string& archName, const std::vector<uint64_t>& branchPoolStartAddrs,
1254 const char* const neverStubEliminateDylibs[], Diagnostics& diags)
1255 {
1256 diags.verbose("Stub elimination optimization:\n");
1257
1258 // construct a StubOptimizer for each image
1259 __block std::vector<StubOptimizer<P>*> optimizers;
1260 cache->forEachImage(^(const mach_header* mh, const char* installName) {
1261 optimizers.push_back(new StubOptimizer<P>((void*)cache, (macho_header<P>*)mh, diags));
1262 });
1263
1264 // construct a BranchPoolDylib for each pool
1265 std::vector<BranchPoolDylib<P>*> pools;
1266
1267 if ( startsWith(archName, "arm64") ) {
1268 // Find hole at end of linkedit region for branch pool linkedits
1269 __block uint64_t textRegionStartAddr = 0;
1270 __block uint64_t linkEditRegionStartAddr = 0;
1271 __block uint64_t linkEditRegionEndAddr = 0;
1272 __block uint64_t linkEditRegionStartCacheOffset = 0;
1273 cache->forEachRegion(^(const void* content, uint64_t vmAddr, uint64_t size, uint32_t permissions) {
1274 if ( permissions == (PROT_READ|PROT_EXEC) ) {
1275 textRegionStartAddr = vmAddr;
1276 }
1277 else if ( permissions == PROT_READ ) {
1278 linkEditRegionStartAddr = vmAddr;
1279 linkEditRegionEndAddr = vmAddr + size;
1280 linkEditRegionStartCacheOffset = (char*)content - (char*)cache;
1281 }
1282 });
1283 __block uint64_t lastLinkEditRegionUsedOffset = 0;
1284 cache->forEachImage(^(const mach_header* mh, const char* installName) {
1285 dyld3::MachOParser parser(mh);
1286 parser.forEachSegment(^(const char* segName, uint32_t fileOffset, uint32_t fileSize, uint64_t vmAddr, uint64_t vmSize, uint8_t protections, bool& stop) {
1287 if ( strcmp(segName, "__LINKEDIT") == 0 ) {
1288 if ( fileOffset >= lastLinkEditRegionUsedOffset )
1289 lastLinkEditRegionUsedOffset = fileOffset + vmSize;
1290 }
1291 });
1292 });
1293 uint64_t allPoolsLinkEditStartOffset = lastLinkEditRegionUsedOffset;
1294 uint64_t allPoolsLinkEditStartAddr = linkEditRegionStartAddr + allPoolsLinkEditStartOffset - linkEditRegionStartCacheOffset;
1295 uint64_t allPoolsLinkEditSize = linkEditRegionEndAddr - allPoolsLinkEditStartAddr;
1296 if ( !branchPoolStartAddrs.empty() ) {
1297 uint64_t poolLinkEditStartAddr = allPoolsLinkEditStartAddr;
1298 uint64_t poolLinkEditStartOffset = allPoolsLinkEditStartOffset;
1299 const uint64_t poolSize = (allPoolsLinkEditSize/branchPoolStartAddrs.size()) & (-4096);
1300 for (uint64_t poolAddr : branchPoolStartAddrs) {
1301 pools.push_back(new BranchPoolDylib<P>(cache, poolAddr, textRegionStartAddr, poolLinkEditStartAddr, poolLinkEditStartOffset, diags));
1302 poolLinkEditStartAddr += poolSize;
1303 poolLinkEditStartOffset += poolSize;
1304 }
1305 }
1306 }
1307
1308 // build set of functions to never stub-eliminate because tools may need to override them
1309 std::unordered_set<std::string> neverStubEliminate;
1310 for (const char** p=sNeverStubEliminateSymbols; *p != nullptr; ++p) {
1311 neverStubEliminate.insert(*p);
1312 }
1313 for (const char* const* d=neverStubEliminateDylibs; *d != nullptr; ++d) {
1314 for (StubOptimizer<P>* op : optimizers) {
1315 if ( strcmp(op->installName(), *d) == 0 ) {
1316 // add all exports
1317 const uint8_t* exportsStart = op->exportsTrie();
1318 const uint8_t* exportsEnd = exportsStart + op->exportsTrieSize();
1319 std::vector<ExportInfoTrie::Entry> exports;
1320 if ( !ExportInfoTrie::parseTrie(exportsStart, exportsEnd, exports) ) {
1321 diags.error("malformed exports trie in %s", *d);
1322 return;
1323 }
1324 for(const ExportInfoTrie::Entry& entry : exports) {
1325 neverStubEliminate.insert(entry.name);
1326 }
1327 }
1328 }
1329 }
1330
1331 // build maps of stubs-to-lp and lp-to-target
1332 for (StubOptimizer<P>* op : optimizers)
1333 op->buildStubMap(neverStubEliminate);
1334
1335 // optimize call sites to by-pass stubs or jump through island
1336 for (StubOptimizer<P>* op : optimizers)
1337 op->optimizeCallSites(pools);
1338
1339 // final fix ups in branch pools
1340 for (BranchPoolDylib<P>* pool : pools) {
1341 pool->finalizeLoadCommands();
1342 pool->printStats();
1343 }
1344
1345 // write total optimization info
1346 uint32_t callSiteCount = 0;
1347 uint32_t callSiteDirectOptCount = 0;
1348 uint32_t callSiteOneHopOptCount = 0;
1349 for (StubOptimizer<P>* op : optimizers) {
1350 callSiteCount += op->_branchesCount;
1351 callSiteDirectOptCount += op->_branchesDirectCount;
1352 callSiteOneHopOptCount += op->_branchesIslandCount;
1353 }
1354 diags.verbose(" cache contains %u call sites of which %u were direct bound and %u were bound through islands\n", callSiteCount, callSiteDirectOptCount, callSiteOneHopOptCount);
1355
1356 // clean up
1357 for (StubOptimizer<P>* op : optimizers)
1358 delete op;
1359 for (BranchPoolDylib<P>* p : pools)
1360 delete p;
1361
1362 }
1363
1364 void bypassStubs(DyldSharedCache* cache, const std::vector<uint64_t>& branchPoolStartAddrs, const char* const neverStubEliminateDylibs[], Diagnostics& diags)
1365 {
1366 std::string archName = cache->archName();
1367 if ( startsWith(archName, "arm64") )
1368 bypassStubs<Pointer64<LittleEndian>>(cache, archName, branchPoolStartAddrs, neverStubEliminateDylibs, diags);
1369 else if ( archName == "armv7k" )
1370 bypassStubs<Pointer32<LittleEndian>>(cache, archName, branchPoolStartAddrs, neverStubEliminateDylibs, diags);
1371 // no stub optimization done for other arches
1372 }
1373
1374
1375 /*
1376 template <typename P>
1377 void StubOptimizer<P>::optimizeStubs(std::unordered_map<uint64_t,std::vector<uint64_t>>& targetToBranchIslands)
1378 {
1379 for (const auto& stubEntry : _stubAddrToLPAddr) {
1380 pint_t stubVMAddr = stubEntry.first;
1381 pint_t lpVMAddr = stubEntry.second;
1382 const auto& pos = _lpAddrToTargetAddr.find(lpVMAddr);
1383 if ( pos == _lpAddrToTargetAddr.end() )
1384 continue;
1385 pint_t targetVMAddr = pos->second;
1386 int64_t delta = targetVMAddr - stubVMAddr;
1387 if ( (delta > -b128MegLimit) && (delta < b128MegLimit) ) {
1388 // target within reach, change stub to direct branch
1389 uint32_t* stubInstructions = (uint32_t*)((uint8_t*)_cacheBuffer + _textSegCacheOffset + stubVMAddr -_textSegStartAddr);
1390 uint32_t stubInstr1 = E::get32(stubInstructions[0]);
1391 if ( (stubInstr1 & 0x9F00001F) != 0x90000010 ) {
1392 warning("first instruction of stub (0x%08X) is no longer ADRP for stub at addr 0x%0X in %s\n",
1393 stubInstr1, stubVMAddr, _installName);
1394 continue;
1395 }
1396 uint32_t directBranchInstr = 0x14000000 + ((delta/4) & 0x03FFFFFF);
1397 E::set32(stubInstructions[0], directBranchInstr);
1398 uint32_t brkInstr = 0xD4200000;
1399 E::set32(stubInstructions[1], brkInstr);
1400 E::set32(stubInstructions[2], brkInstr);
1401 _stubOptimizedCount++;
1402 targetToBranchIslands[targetVMAddr].push_back(stubVMAddr);
1403 }
1404 }
1405 verboseLog("%3u of %3u stubs optimized for %s\n", _stubOptimizedCount, _stubCount, _installName);
1406 }
1407
1408
1409 template <typename P>
1410 void StubOptimizer<P>::bypassStubs(std::unordered_map<uint64_t,std::vector<uint64_t>>& targetToBranchIslands)
1411 {
1412 if ( _textSection == NULL )
1413 return;
1414
1415 // scan __text section looking for B(L) instructions that branch to a stub
1416 unsigned instructionCount = (unsigned)(_textSection->size() / 4);
1417 uint32_t* instructions = (uint32_t*)((uint8_t*)_cacheBuffer + _textSegCacheOffset + _textSection->addr() -_textSegStartAddr);
1418 for (unsigned i=0; i < instructionCount; ++i) {
1419 uint32_t instr = E::get32(instructions[i]);
1420 // skip all but BL or B
1421 if ( (instr & 0x7C000000) != 0x14000000 )
1422 continue;
1423 // compute target of branch instruction
1424 int32_t brDelta = (instr & 0x03FFFFFF) << 2;
1425 if ( brDelta & 0x08000000 )
1426 brDelta |= 0xF0000000;
1427 uint64_t branchAddr = _textSection->addr() + i*4;
1428 uint64_t targetAddr = branchAddr + (int64_t)brDelta;
1429 // ignore branch if not to a known stub
1430 const auto& pos = _stubAddrToLPAddr.find(targetAddr);
1431 if ( pos == _stubAddrToLPAddr.end() )
1432 continue;
1433 _branchesCount++;
1434 // ignore branch if lazy pointer is not known (could be resolver based)
1435 const auto& pos2 = _lpAddrToTargetAddr.find(pos->second);
1436 if ( pos2 == _lpAddrToTargetAddr.end() )
1437 continue;
1438 uint64_t finalTargetAddr = pos2->second;
1439 int64_t deltaToFinalTarget = finalTargetAddr - branchAddr;
1440 // if final target within range, change to branch there directly
1441 if ( (deltaToFinalTarget > -b128MegLimit) && (deltaToFinalTarget < b128MegLimit) ) {
1442 uint32_t newInstr = (instr & 0xFC000000) | ((deltaToFinalTarget >> 2) & 0x03FFFFFF);
1443 E::set32(instructions[i], newInstr);
1444 _branchesDirectCount++;
1445 continue;
1446 }
1447 // see if there is an existing branch island in range that can be used
1448 std::vector<uint64_t>& existingBranchIslands = targetToBranchIslands[finalTargetAddr];
1449 for (uint64_t branchIslandAddr : existingBranchIslands) {
1450 int64_t deltaToBranchIsland = branchIslandAddr - branchAddr;
1451 // if final target within range, change to branch deltaToBranchIsland directly
1452 if ( (deltaToBranchIsland > -b128MegLimit) && (deltaToFinalTarget < b128MegLimit) ) {
1453 uint32_t newInstr = (instr & 0xFC000000) | ((deltaToBranchIsland >> 2) & 0x03FFFFFF);
1454 E::set32(instructions[i], newInstr);
1455 _branchesIslandCount++;
1456 break;
1457 }
1458 }
1459 }
1460 if ( verbose ) {
1461 verboseLog("%5u branches in __text, %5u changed to direct branches, %5u changed to indirect for %s\n",
1462 _branchesCount, _branchesDirectCount, _branchesIslandCount, _installName);
1463 }
1464 }
1465 */
1466