1 /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
3 * Copyright (c) 2015 Apple Inc. All rights reserved.
5 * @APPLE_LICENSE_HEADER_START@
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
22 * @APPLE_LICENSE_HEADER_END@
26 #include <sys/types.h>
33 #include <CommonCrypto/CommonDigest.h>
36 #include <unordered_map>
37 #include <unordered_set>
39 #include "StringUtils.h"
41 #include "MachOFileAbstraction.hpp"
42 #include "MachOParser.h"
43 #include "Diagnostics.h"
44 #include "DyldSharedCache.h"
45 #include "CacheBuilder.h"
47 static const bool verbose
= false;
49 // These are functions that are interposed by Instruments.app or ASan
50 static const char* sNeverStubEliminateSymbols
[] = {
55 "__objc_autoreleasePoolPop",
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",
158 "_malloc_create_zone",
159 "_malloc_default_purgeable_zone",
160 "_malloc_default_zone",
162 "_malloc_make_nonpurgeable",
163 "_malloc_make_purgeable",
164 "_malloc_set_zone_name",
181 "_objc_autoreleasePoolPop",
183 "_objc_setProperty_atomic",
184 "_objc_setProperty_atomic_copy",
185 "_objc_setProperty_nonatomic",
186 "_objc_setProperty_nonatomic_copy",
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",
204 "_pthread_getschedparam",
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",
302 // <rdar://problem/22050956> always use stubs for C++ symbols that can be overridden
312 static uint64_t branchPoolTextSize(const std::string
& archName
)
314 if ( startsWith(archName
, "arm64") )
315 return 0x0000C000; // 48KB
320 static uint64_t branchPoolLinkEditSize(const std::string
& archName
)
322 if ( startsWith(archName
, "arm64") )
323 return 0x00100000; // 1MB
329 template <typename P
>
330 class BranchPoolDylib
{
332 BranchPoolDylib(DyldSharedCache
* cache
, uint64_t startAddr
,
333 uint64_t textRegionStartAddr
, uint64_t poolLinkEditStartAddr
, uint64_t poolLinkEditStartOffset
, Diagnostics
& diags
);
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();
342 Diagnostics
& _diagnostics
;
343 uint64_t indexToAddr(uint32_t index
) { return _startAddr
+ _firstStubOffset
+ sizeof(uint32_t)*index
; }
345 static const int64_t b128MegLimit
= 0x07FFFFFF;
347 typedef typename
P::uint_t pint_t
;
348 typedef typename
P::E E
;
350 DyldSharedCache
* _cacheBuffer
;
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
;
359 uint32_t _firstStubOffset
;
360 uint32_t* _stubInstructions
;
361 macho_nlist
<P
>* _symbolTable
;
363 char* _stringPoolStart
;
364 char* _stringPoolEnd
;
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
)
372 std::string archName
= cache
->archName();
373 bool is64
= (sizeof(typename
P::uint_t
) == 8);
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
;
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
);
390 mh
->set_sizeofcmds(is64
? 0x210 : 100); // FIXME: 32-bit size
391 mh
->set_flags(0x80000000);
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
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);
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");
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
));
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());
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());
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);
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);
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
);
504 _stringPoolStart
= (char*)(linkeditBufferStart
+ linkeditOffsetSymbolPoolOffset
);
505 _stringPoolEnd
= _stringPoolStart
+ linkEditSegSize
- linkeditOffsetSymbolPoolOffset
;
506 _stringPoolStart
[0] = '\0';
507 strcpy(&_stringPoolStart
[1], "<unused>");
508 _nextString
= &_stringPoolStart
[10];
512 template <typename P
>
513 void BranchPoolDylib
<P
>::finalizeLoadCommands()
515 _symbolTableCmd
->set_nsyms(_nextIndex
);
516 _symbolTableCmd
->set_strsize((uint32_t)(_nextString
- _stringPoolStart
));
517 _dynamicSymbolTableCmd
->set_nundefsym(_nextIndex
);
519 uint8_t digest
[CC_MD5_DIGEST_LENGTH
];
520 CC_MD5(_stubInstructions
, _maxStubs
*sizeof(uint64_t), digest
);
521 _uuidCmd
->set_uuid(digest
);
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
]);
531 template <typename P
>
532 uint64_t BranchPoolDylib
<P
>::getForwardBranch(uint64_t finalTargetAddr
, const char* name
, std::vector
<BranchPoolDylib
<P
>*>& branchIslandPools
)
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
);
539 // skip if instruction pool is full
540 if ( _nextIndex
>= _maxStubs
)
543 // skip if string pool is full
544 if ( (_nextString
+ strlen(name
)+1) >= _stringPoolEnd
)
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];
558 if (nextPool
== nullptr) {
559 _diagnostics
.warning("BranchPoolDylib<P>::getForwardBranch: nextPool unreachable");
563 branchIslandTargetAddr
= nextPool
->getForwardBranch(finalTargetAddr
, name
, branchIslandPools
);
564 if ( branchIslandTargetAddr
== 0 )
565 return 0; // next pool is full
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
);
574 // update symbol table
575 _symbolTable
[index
].set_n_strx((uint32_t)(_nextString
- _stringPoolStart
));
576 strcpy(_nextString
, name
);
577 _nextString
+= (strlen(name
) +1);
580 _targetToIslandIndex
[finalTargetAddr
] = index
;
581 _islandIndexToName
[index
] = name
;
582 return indexToAddr(index
);
585 template <typename P
>
586 uint64_t BranchPoolDylib
<P
>::getBackBranch(uint64_t finalTargetAddr
, const char* name
, std::vector
<BranchPoolDylib
<P
>*>& branchIslandPools
)
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
);
593 // skip if instruction pool is full
594 if ( _nextIndex
>= _maxStubs
)
597 // skip if string pool is full
598 if ( (_nextString
+ strlen(name
)+1) >= _stringPoolEnd
)
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];
612 if (nextPool
== nullptr) {
613 _diagnostics
.warning("BranchPoolDylib<P>::getBackBranch: nextPool unreachable");
617 branchIslandTargetAddr
= nextPool
->getBackBranch(finalTargetAddr
, name
, branchIslandPools
);
618 if ( branchIslandTargetAddr
== 0 )
619 return 0; // next pool is full
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
);
628 // update symbol table
629 _symbolTable
[index
].set_n_strx((uint32_t)(_nextString
- _stringPoolStart
));
630 strcpy(_nextString
, name
);
631 _nextString
+= (strlen(name
) +1);
634 _targetToIslandIndex
[finalTargetAddr
] = index
;
635 _islandIndexToName
[index
] = name
;
636 return indexToAddr(index
);
639 template <typename P
>
640 void BranchPoolDylib
<P
>::printStats()
642 _diagnostics
.verbose(" island pool at 0x%0llX has %u stubs and stringPool size=%lu\n", _startAddr
, _nextIndex
, _nextString
- _stringPoolStart
);
647 template <typename P
>
648 class StubOptimizer
{
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(); }
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;
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
;
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
);
683 struct AddressAndName
{ pint_t targetVMAddr
; const char* targetName
; };
684 typedef std::unordered_map
<pint_t
, AddressAndName
> StubVMAddrToTarget
;
686 static const int64_t b128MegLimit
= 0x07FFFFFF;
687 static const int64_t b16MegLimit
= 0x00FFFFFF;
690 macho_header
<P
>* _mh
;
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
;
713 template <typename P
>
714 StubOptimizer
<P
>::StubOptimizer(void* cacheBuffer
, macho_header
<P
>* mh
, Diagnostics
& diags
)
715 : _mh(mh
), _cacheBuffer(cacheBuffer
), _diagnostics(diags
)
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()) {
726 _installName
= ((macho_dylib_command
<P
>*)cmd
)->name();
729 _symTabCmd
= (macho_symtab_command
<P
>*)cmd
;
732 _dynSymTabCmd
= (macho_dysymtab_command
<P
>*)cmd
;
734 case LC_SEGMENT_SPLIT_INFO
:
735 _splitSegInfoCmd
= (macho_linkedit_data_command
<P
>*)cmd
;
738 case LC_DYLD_INFO_ONLY
:
739 _dyldInfo
= (macho_dyld_info_command
<P
>*)cmd
;
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();
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
= §ionsStart
[segCmd
->nsects()];
754 for (const macho_section
<P
>* sect
= sectionsStart
; sect
< sectionsEnd
; ++sect
) {
756 if ( strcmp(sect
->sectname(), "__text") == 0 ) {
758 _textSectionIndex
= sectionIndex
;
760 else if ( ((sect
->flags() & SECTION_TYPE
) == S_SYMBOL_STUBS
) && (sect
->size() != 0) ) {
762 _stubSectionIndex
= sectionIndex
;
768 cmd
= (const macho_load_command
<P
>*)(((uint8_t*)cmd
)+cmd
->cmdsize());
774 template <typename P
>
775 uint32_t StubOptimizer
<P
>::lazyPointerAddrFromArmStub(const uint8_t* stubInstructions
, uint32_t stubVMAddr
)
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
);
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
);
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
);
796 return stubVMAddr
+ 12 + stubData
;
800 template <typename P
>
801 uint64_t StubOptimizer
<P
>::lazyPointerAddrFromArm64Stub(const uint8_t* stubInstructions
, uint64_t stubVMAddr
)
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
);
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
);
818 uint32_t ldrValue
= ((stubInstr2
>> 10) & 0x00000FFF);
819 return (stubVMAddr
& (-4096)) + adrpValue
*4096 + ldrValue
*8;
824 template <typename P
>
825 void StubOptimizer
<P
>::buildStubMap(const std::unordered_set
<std::string
>& neverStubEliminate
)
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
= §ionsStart
[seg
->nsects()];
839 for(macho_section
<P
>* sect
= sectionsStart
; sect
< sectionsEnd
; ++sect
) {
840 if ( sect
->size() == 0 )
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
:
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
);
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
);
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);
872 const uint8_t* stubInstrs
= (uint8_t*)_cacheBuffer
+ sect
->offset() + stubVMAddr
- sect
->addr();
873 pint_t targetLPAddr
= 0;
874 switch ( _mh
->cputype() ) {
876 targetLPAddr
= (pint_t
)lazyPointerAddrFromArm64Stub(stubInstrs
, stubVMAddr
);
879 targetLPAddr
= (pint_t
)lazyPointerAddrFromArmStub(stubInstrs
, (uint32_t)stubVMAddr
);
882 if ( targetLPAddr
!= 0 )
883 _stubAddrToLPAddr
[stubVMAddr
] = targetLPAddr
;
888 else if ( sectionType
== S_LAZY_SYMBOL_POINTERS
) {
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();
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
:
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
);
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
);
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);
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
);
925 _lpAddrToTargetAddr
[lpVMAddr
] = lpValue
;
926 _targetAddrToName
[lpValue
] = symName
;
934 cmd
= (const macho_load_command
<P
>*)(((uint8_t*)cmd
)+cmd
->cmdsize());
939 template <typename P
>
940 void StubOptimizer
<P
>::forEachCallSiteToAStub(CallSiteHandler handler
)
942 if (_diagnostics
.hasError())
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
);
951 uint8_t* textSectionContent
= (uint8_t*)_cacheBuffer
+ _textSegCacheOffset
+ _textSection
->addr() -_textSegStartAddr
;
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
);
971 _diagnostics
.error("bad kind (%llu) value in %s", kind
, _installName
);
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
);
984 if ( handler(kind
, instrAddr
, stubAddr
, instruction
) ) {
985 _branchesModifiedCount
++;
986 E::set32(*instrPtr
, instruction
);
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
)
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);
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.
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
);
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
1038 newInstruction
= 0xC000F000; // Use blx
1039 // See note in getDisplacementFromThumbBranch() about blx.
1040 if (instrAddr
& 0x2)
1045 if ( !targetIsThumb
) {
1046 _diagnostics
.error("no pc-rel thumb branch instruction that switches to arm mode at 0x%0X in %s", instrAddr
, _installName
);
1051 _diagnostics
.error("not b/bl/blx at 0x%0X in %s", instrAddr
, _installName
);
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
;
1068 template <typename P
>
1069 void StubOptimizer
<P
>::optimizeArmCallSites()
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
);
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
);
1086 // ignore branch if not to a known stub
1087 const auto& pos
= _stubAddrToLPAddr
.find(targetAddr
);
1088 if ( pos
== _stubAddrToLPAddr
.end() )
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() )
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())
1103 _branchesDirectCount
++;
1107 else if ( kind
== DYLD_CACHE_ADJ_V2_ARM_BR24
) {
1108 // too few of these to be worth trying to optimize
1113 if (_diagnostics
.hasError())
1118 template <typename P
>
1119 void StubOptimizer
<P
>::optimizeArmStubs()
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() )
1127 pint_t targetVMAddr
= pos
->second
;
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
++;
1142 template <typename P
>
1143 void StubOptimizer
<P
>::optimizeArm64CallSites(std::vector
<BranchPoolDylib
<P
>*>& branchIslandPools
)
1145 forEachCallSiteToAStub([&](uint8_t kind
, uint64_t callSiteAddr
, uint64_t stubAddr
, uint32_t& instruction
) -> bool {
1146 if ( kind
!= DYLD_CACHE_ADJ_V2_ARM64_BR26
)
1148 // skip all but BL or B
1149 if ( (instruction
& 0x7C000000) != 0x14000000 )
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");
1160 // ignore branch if not to a known stub
1161 const auto& pos
= _stubAddrToLPAddr
.find((pint_t
)targetAddr
);
1162 if ( pos
== _stubAddrToLPAddr
.end() )
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() )
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
++;
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() )
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
);
1192 int64_t deltaToTarget
= brIslandAddr
- callSiteAddr
;
1193 instruction
= (instruction
& 0xFC000000) | ((deltaToTarget
>> 2) & 0x03FFFFFF);
1194 _branchesIslandCount
++;
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
);
1210 int64_t deltaToTarget
= brIslandAddr
- callSiteAddr
;
1211 instruction
= (instruction
& 0xFC000000) | ((deltaToTarget
>> 2) & 0x03FFFFFF);
1212 _branchesIslandCount
++;
1219 if (_diagnostics
.hasError())
1224 template <typename P
>
1225 void StubOptimizer
<P
>::optimizeCallSites(std::vector
<BranchPoolDylib
<P
>*>& branchIslandPools
)
1227 if ( _textSection
== NULL
)
1229 if ( _stubSection
== NULL
)
1233 switch ( _mh
->cputype() ) {
1234 case CPU_TYPE_ARM64
:
1235 optimizeArm64CallSites(branchIslandPools
);
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
);
1242 optimizeArmCallSites();
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
);
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
)
1256 diags
.verbose("Stub elimination optimization:\n");
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
));
1264 // construct a BranchPoolDylib for each pool
1265 std::vector
<BranchPoolDylib
<P
>*> pools
;
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
;
1277 else if ( permissions
== PROT_READ
) {
1278 linkEditRegionStartAddr
= vmAddr
;
1279 linkEditRegionEndAddr
= vmAddr
+ size
;
1280 linkEditRegionStartCacheOffset
= (char*)content
- (char*)cache
;
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
;
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
;
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
);
1313 for (const char* const* d
=neverStubEliminateDylibs
; *d
!= nullptr; ++d
) {
1314 for (StubOptimizer
<P
>* op
: optimizers
) {
1315 if ( strcmp(op
->installName(), *d
) == 0 ) {
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
);
1324 for(const ExportInfoTrie::Entry
& entry
: exports
) {
1325 neverStubEliminate
.insert(entry
.name
);
1331 // build maps of stubs-to-lp and lp-to-target
1332 for (StubOptimizer
<P
>* op
: optimizers
)
1333 op
->buildStubMap(neverStubEliminate
);
1335 // optimize call sites to by-pass stubs or jump through island
1336 for (StubOptimizer
<P
>* op
: optimizers
)
1337 op
->optimizeCallSites(pools
);
1339 // final fix ups in branch pools
1340 for (BranchPoolDylib
<P
>* pool
: pools
) {
1341 pool
->finalizeLoadCommands();
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
;
1354 diags
.verbose(" cache contains %u call sites of which %u were direct bound and %u were bound through islands\n", callSiteCount
, callSiteDirectOptCount
, callSiteOneHopOptCount
);
1357 for (StubOptimizer
<P
>* op
: optimizers
)
1359 for (BranchPoolDylib
<P
>* p
: pools
)
1364 void bypassStubs(DyldSharedCache
* cache
, const std::vector
<uint64_t>& branchPoolStartAddrs
, const char* const neverStubEliminateDylibs
[], Diagnostics
& diags
)
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
1376 template <typename P>
1377 void StubOptimizer<P>::optimizeStubs(std::unordered_map<uint64_t,std::vector<uint64_t>>& targetToBranchIslands)
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() )
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);
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);
1405 verboseLog("%3u of %3u stubs optimized for %s\n", _stubOptimizedCount, _stubCount, _installName);
1409 template <typename P>
1410 void StubOptimizer<P>::bypassStubs(std::unordered_map<uint64_t,std::vector<uint64_t>>& targetToBranchIslands)
1412 if ( _textSection == NULL )
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 )
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() )
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() )
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++;
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++;
1461 verboseLog("%5u branches in __text, %5u changed to direct branches, %5u changed to indirect for %s\n",
1462 _branchesCount, _branchesDirectCount, _branchesIslandCount, _installName);