-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathOutputFile.cpp
8118 lines (7673 loc) · 310 KB
/
OutputFile.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-*
*
* Copyright (c) 2009-2011 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/sysctl.h>
#include <sys/param.h>
#include <sys/mount.h>
#include <fcntl.h>
#include <errno.h>
#include <limits.h>
#include <unistd.h>
#include <mach/mach_time.h>
#include <mach/vm_statistics.h>
#include <mach/mach_init.h>
#include <mach/mach_host.h>
#include <uuid/uuid.h>
#include <dlfcn.h>
#include <mach-o/dyld.h>
#include <mach-o/fat.h>
#include <dispatch/dispatch.h>
#include <os/lock_private.h>
extern "C" {
#include <corecrypto/ccsha2.h>
}
#include <string>
#include <string>
#include <list>
#include <algorithm>
#include <utility>
#include <iostream>
#include <fstream>
#include <CommonCrypto/CommonDigest.h>
#include <AvailabilityMacros.h>
#include <System/machine/cpu_capabilities.h>
#include "ExportsTrie.h"
#include "Options.h"
#include "OutputFile.h"
#include "Architectures.hpp"
#include "HeaderAndLoadCommands.hpp"
#include "LinkEdit.hpp"
#include "LinkEditClassic.hpp"
#include "generic_dylib_file.hpp"
#include "Containers.h"
namespace ld {
namespace tool {
uint32_t sAdrpNA = 0;
uint32_t sAdrpNoped = 0;
uint32_t sAdrpNotNoped = 0;
OutputFile::OutputFile(const Options& opts, ld::Internal& state)
:
usesWeakExternalSymbols(false), overridesWeakExternalSymbols(false), reExportsWeakDefSymbols(false),
_noReExportedDylibs(false), pieDisabled(false),
headerAndLoadCommandsSection(NULL),
rebaseSection(NULL), bindingSection(NULL), weakBindingSection(NULL),
lazyBindingSection(NULL), exportSection(NULL),
splitSegInfoSection(NULL), functionStartsSection(NULL),
dataInCodeSection(NULL), optimizationHintsSection(NULL),
symbolTableSection(NULL), stringPoolSection(NULL),
localRelocationsSection(NULL), externalRelocationsSection(NULL),
sectionRelocationsSection(NULL),
indirectSymbolTableSection(NULL),
threadedPageStartsSection(NULL), codeSignatureSection(NULL),
_options(opts),
_hasDyldInfo(opts.makeCompressedDyldInfo() || state.cantUseChainedFixups),
_hasExportsTrie(opts.makeChainedFixups() && !state.cantUseChainedFixups && _options.dyldLoadsOutput()),
_hasChainedFixups(opts.makeChainedFixups() && _options.outputSlidable() && (!_options.dyldOrKernelLoadsOutput() || !state.cantUseChainedFixups) ),
_hasThreadedPageStarts(opts.makeThreadedStartsSection()),
_hasSymbolTable(true),
_hasSectionRelocations(opts.outputKind() == Options::kObjectFile),
_hasSplitSegInfo(opts.sharedRegionEligible()),
_hasFunctionStartsInfo(opts.addFunctionStarts()),
_hasDataInCodeInfo(opts.addDataInCodeInfo()),
_hasDynamicSymbolTable(true),
_hasLocalRelocations(!_hasDyldInfo && !_hasChainedFixups && !opts.makeThreadedStartsSection() && !_options.makeRebaseSection()),
_hasExternalRelocations(!_hasDyldInfo && !_hasChainedFixups && !opts.makeThreadedStartsSection()),
_hasOptimizationHints(opts.outputKind() == Options::kObjectFile),
_hasCodeSignature(opts.adHocSign()),
_encryptedTEXTstartOffset(0),
_encryptedTEXTendOffset(0),
_localSymbolsStartIndex(0),
_localSymbolsCount(0),
_globalSymbolsStartIndex(0),
_globalSymbolsCount(0),
_importSymbolsStartIndex(0),
_importSymbolsCount(0),
_sectionsRelocationsAtom(NULL),
_localRelocsAtom(NULL),
_externalRelocsAtom(NULL),
_symbolTableAtom(NULL),
_indirectSymbolTableAtom(NULL),
_rebasingInfoAtom(NULL),
_bindingInfoAtom(NULL),
_lazyBindingInfoAtom(NULL),
_weakBindingInfoAtom(NULL),
_exportInfoAtom(NULL),
_splitSegInfoAtom(NULL),
_functionStartsAtom(NULL),
_dataInCodeAtom(NULL),
_optimizationHintsAtom(NULL),
_chainedInfoAtom(NULL),
_codeSignatureAtom(NULL)
{
}
void OutputFile::dumpAtomsBySection(ld::Internal& state, bool printAtoms)
{
fprintf(stderr, "SORTED:\n");
for (std::vector<ld::Internal::FinalSection*>::iterator it = state.sections.begin(); it != state.sections.end(); ++it) {
fprintf(stderr, "final section %p %s/%s %s start addr=0x%08llX, size=0x%08llX, alignment=%02d, fileOffset=0x%08llX\n",
(*it), (*it)->segmentName(), (*it)->sectionName(), (*it)->isSectionHidden() ? "(hidden)" : "",
(*it)->address, (*it)->size, (*it)->alignment, (*it)->fileOffset);
if ( printAtoms ) {
std::vector<const ld::Atom*>& atoms = (*it)->atoms;
for (const ld::Atom* atom : atoms) {
fprintf(stderr, " %p (size=0x%04llX) %s from %s\n", atom, atom->size(), atom->name(), atom->safeFilePath());
}
}
}
fprintf(stderr, "DYLIBS:\n");
for (std::vector<ld::dylib::File*>::iterator it=state.dylibs.begin(); it != state.dylibs.end(); ++it )
fprintf(stderr, " %s\n", (*it)->installPath());
}
void OutputFile::write(ld::Internal& state)
{
this->buildDylibOrdinalMapping(state);
this->addLoadCommands(state);
this->addLinkEdit(state);
state.setSectionSizesAndAlignments();
this->setLoadCommandsPadding(state);
_fileSize = state.assignFileOffsets();
this->assignAtomAddresses(state);
this->buildLINKEDITContent(state);
this->updateLINKEDITAddresses(state);
//this->dumpAtomsBySection(state, false);
this->writeOutputFile(state);
this->writeMapFile(state);
this->writeJSONEntry(state);
}
bool OutputFile::findSegment(ld::Internal& state, uint64_t addr, uint64_t* start, uint64_t* end, uint32_t* index)
{
uint32_t segIndex = 0;
ld::Internal::FinalSection* segFirstSection = NULL;
ld::Internal::FinalSection* lastSection = NULL;
for (std::vector<ld::Internal::FinalSection*>::iterator it = state.sections.begin(); it != state.sections.end(); ++it) {
ld::Internal::FinalSection* sect = *it;
if ( (segFirstSection == NULL ) || strcmp(segFirstSection->segmentName(), sect->segmentName()) != 0 ) {
if ( segFirstSection != NULL ) {
//fprintf(stderr, "findSegment(0x%llX) seg changed to %s\n", addr, sect->segmentName());
if ( (addr >= segFirstSection->address) && (addr < lastSection->address+lastSection->size) ) {
*start = segFirstSection->address;
*end = lastSection->address+lastSection->size;
*index = segIndex;
return true;
}
++segIndex;
}
segFirstSection = sect;
}
lastSection = sect;
}
return false;
}
void OutputFile::assignAtomAddresses(ld::Internal& state)
{
const bool log = false;
if ( log ) fprintf(stderr, "assignAtomAddresses()\n");
uint64_t lastAddress = 0;
for (std::vector<ld::Internal::FinalSection*>::iterator sit = state.sections.begin(); sit != state.sections.end(); ++sit) {
ld::Internal::FinalSection* sect = *sit;
if ( log ) fprintf(stderr, " section=%s/%s\n", sect->segmentName(), sect->sectionName());
for (std::vector<const ld::Atom*>::iterator ait = sect->atoms.begin(); ait != sect->atoms.end(); ++ait) {
const ld::Atom* atom = *ait;
switch ( sect-> type() ) {
case ld::Section::typeImportProxies:
// want finalAddress() of all proxy atoms to be zero
(const_cast<ld::Atom*>(atom))->setSectionStartAddress(0);
break;
case ld::Section::typeAbsoluteSymbols:
// want finalAddress() of all absolute atoms to be value of abs symbol
(const_cast<ld::Atom*>(atom))->setSectionStartAddress(0);
break;
case ld::Section::typeLinkEdit:
// linkedit layout is assigned later
break;
default:
(const_cast<ld::Atom*>(atom))->setSectionStartAddress(sect->address);
lastAddress = atom->finalAddress() + atom->size();
if ( log ) fprintf(stderr, " atom=%p, addr=0x%08llX, name=%s\n", atom, atom->finalAddress(), atom->name());
break;
}
}
}
// remember largest legal rebase target
uint64_t maxRebaseAddress = (lastAddress - _options.baseAddress() + 0x00100000-1) & -0x00100000; // align to 1MB
_chainedFixupBinds.setMaxRebase(maxRebaseAddress);
}
void OutputFile::updateLINKEDITAddresses(ld::Internal& state)
{
// update address and file offsets now that linkedit content has been generated
uint64_t curLinkEditAddress = 0;
uint64_t curLinkEditfileOffset = 0;
for (std::vector<ld::Internal::FinalSection*>::iterator sit = state.sections.begin(); sit != state.sections.end(); ++sit) {
ld::Internal::FinalSection* sect = *sit;
if ( sect->type() != ld::Section::typeLinkEdit )
continue;
if ( curLinkEditAddress == 0 ) {
curLinkEditAddress = sect->address;
curLinkEditfileOffset = sect->fileOffset;
}
uint16_t maxAlignment = 0;
uint64_t offset = 0;
for (std::vector<const ld::Atom*>::iterator ait = sect->atoms.begin(); ait != sect->atoms.end(); ++ait) {
const ld::Atom* atom = *ait;
//fprintf(stderr, "setting linkedit atom offset for %s\n", atom->name());
if ( atom->alignment().powerOf2 > maxAlignment )
maxAlignment = atom->alignment().powerOf2;
// calculate section offset for this atom
uint64_t alignment = 1 << atom->alignment().powerOf2;
uint64_t currentModulus = (curLinkEditAddress % alignment);
uint64_t requiredModulus = atom->alignment().modulus;
if ( currentModulus != requiredModulus ) {
if ( requiredModulus > currentModulus ) {
curLinkEditAddress += requiredModulus-currentModulus;
curLinkEditfileOffset += requiredModulus-currentModulus;
}
else {
curLinkEditAddress += requiredModulus+alignment-currentModulus;
curLinkEditfileOffset += requiredModulus+alignment-currentModulus;
}
}
(const_cast<ld::Atom*>(atom))->setSectionOffset(offset);
(const_cast<ld::Atom*>(atom))->setSectionStartAddress(curLinkEditAddress);
offset += atom->size();
}
sect->size = offset;
// section alignment is that of a contained atom with the greatest alignment
sect->alignment = maxAlignment;
sect->address = curLinkEditAddress;
sect->fileOffset = curLinkEditfileOffset;
curLinkEditAddress += sect->size;
curLinkEditfileOffset += sect->size;
}
if ( _hasCodeSignature ) {
assert(_codeSignatureAtom != NULL);
_codeSignatureAtom->encode();
}
_fileSize = state.sections.back()->fileOffset + state.sections.back()->size;
}
void OutputFile::setLoadCommandsPadding(ld::Internal& state)
{
// In other sections, any extra space is put and end of segment.
// In __TEXT segment, any extra space is put after load commands to allow post-processing of load commands
// Do a reverse layout of __TEXT segment to determine padding size and adjust section size
uint64_t paddingSize = 0;
switch ( _options.outputKind() ) {
case Options::kDyld:
// dyld itself has special padding requirements. We want the beginning __text section to start at a stable address
assert(strcmp(state.sections[1]->sectionName(),"__text") == 0);
state.sections[1]->alignment = 12; // page align __text
break;
case Options::kObjectFile:
// mach-o .o files need no padding between load commands and first section
// but leave enough room that the object file could be signed
paddingSize = 32;
break;
case Options::kPreload:
// mach-o MH_PRELOAD files need no padding between load commands and first section
paddingSize = 0;
break;
case Options::kKextBundle:
if ( _options.useTextExecSegment() ) {
paddingSize = 32;
break;
}
// else fall into default case
[[clang::fallthrough]];
default:
// work backwards from end of segment and lay out sections so that extra room goes to padding atom
uint64_t addr = 0;
uint64_t textSegPageSize = _options.segPageSize("__TEXT");
if ( _options.sharedRegionEligible() && _options.platforms().minOS(ld::iOS_8_0) && (textSegPageSize == 0x4000) )
textSegPageSize = 0x1000;
for (std::vector<ld::Internal::FinalSection*>::reverse_iterator it = state.sections.rbegin(); it != state.sections.rend(); ++it) {
ld::Internal::FinalSection* sect = *it;
if ( strcmp(sect->segmentName(), "__TEXT") != 0 )
continue;
if ( sect == headerAndLoadCommandsSection ) {
addr -= headerAndLoadCommandsSection->size;
paddingSize = addr % textSegPageSize;
break;
}
addr -= sect->size;
addr = addr & (0 - (1 << sect->alignment));
}
// if command line requires more padding than this
uint32_t minPad = _options.minimumHeaderPad();
if ( _options.maxMminimumHeaderPad() ) {
// -headerpad_max_install_names means there should be room for every path load command to grow to 1204 bytes
uint32_t altMin = _dylibsToLoad.size() * MAXPATHLEN;
if ( _options.outputKind() == Options::kDynamicLibrary )
altMin += MAXPATHLEN;
if ( altMin > minPad )
minPad = altMin;
}
if ( paddingSize < minPad ) {
int extraPages = (minPad - paddingSize + _options.segmentAlignment() - 1)/_options.segmentAlignment();
paddingSize += extraPages * _options.segmentAlignment();
}
if ( _options.makeEncryptable() ) {
// load commands must be on a separate non-encrypted page
int loadCommandsPage = (headerAndLoadCommandsSection->size + minPad)/_options.segmentAlignment();
int textPage = (headerAndLoadCommandsSection->size + paddingSize)/_options.segmentAlignment();
if ( loadCommandsPage == textPage ) {
paddingSize += _options.segmentAlignment();
textPage += 1;
}
// remember start for later use by load command
_encryptedTEXTstartOffset = textPage*_options.segmentAlignment();
}
break;
}
// add padding to size of section
headerAndLoadCommandsSection->size += paddingSize;
}
uint64_t OutputFile::pageAlign(uint64_t addr)
{
const uint64_t alignment = _options.segmentAlignment();
return ((addr+alignment-1) & (-alignment));
}
uint64_t OutputFile::pageAlign(uint64_t addr, uint64_t pageSize)
{
return ((addr+pageSize-1) & (-pageSize));
}
static const char* makeName(const ld::Atom& atom)
{
static char buffer[4096];
switch ( atom.symbolTableInclusion() ) {
case ld::Atom::symbolTableNotIn:
case ld::Atom::symbolTableNotInFinalLinkedImages:
sprintf(buffer, "%s@0x%08llX", atom.name(), atom.objectAddress());
break;
case ld::Atom::symbolTableIn:
case ld::Atom::symbolTableInAndNeverStrip:
case ld::Atom::symbolTableInAsAbsolute:
case ld::Atom::symbolTableInWithRandomAutoStripLabel:
strlcpy(buffer, atom.name(), 4096);
break;
}
return buffer;
}
static const char* referenceTargetAtomName(ld::Internal& state, const ld::Fixup* ref)
{
switch ( ref->binding ) {
case ld::Fixup::bindingNone:
return "NO BINDING";
case ld::Fixup::bindingByNameUnbound:
return (char*)(ref->u.target);
case ld::Fixup::bindingByContentBound:
case ld::Fixup::bindingDirectlyBound:
return makeName(*((ld::Atom*)(ref->u.target)));
case ld::Fixup::bindingsIndirectlyBound:
return makeName(*state.indirectBindingTable[ref->u.bindingIndex]);
}
return "BAD BINDING";
}
bool OutputFile::targetIsThumb(ld::Internal& state, const ld::Fixup* fixup)
{
switch ( fixup->binding ) {
case ld::Fixup::bindingByContentBound:
case ld::Fixup::bindingDirectlyBound:
return fixup->u.target->isThumb();
case ld::Fixup::bindingsIndirectlyBound:
return state.indirectBindingTable[fixup->u.bindingIndex]->isThumb();
default:
break;
}
throw "unexpected binding";
}
uint64_t OutputFile::addressOf(const ld::Internal& state, const ld::Fixup* fixup, const ld::Atom** target)
{
// FIXME: Is this right for makeThreadedStartsSection?
if ( !_options.makeCompressedDyldInfo() && !_options.makeThreadedStartsSection() && !_options.makeChainedFixups() ) {
// For external relocations the classic mach-o format
// has addend only stored in the content. That means
// that the address of the target is not used.
if ( fixup->contentAddendOnly )
return 0;
}
switch ( fixup->binding ) {
case ld::Fixup::bindingNone:
throw "unexpected bindingNone";
case ld::Fixup::bindingByNameUnbound:
throw "unexpected bindingByNameUnbound";
case ld::Fixup::bindingByContentBound:
case ld::Fixup::bindingDirectlyBound:
*target = fixup->u.target;
if ( !(*target)->finalAddressMode() && ((*target)->contentType() == ld::Atom::typeLTOtemporary) )
throwf("reference to bitcode symbol '%s' which LTO has not compiled", (*target)->name());
return (*target)->finalAddress();
case ld::Fixup::bindingsIndirectlyBound:
*target = state.indirectBindingTable[fixup->u.bindingIndex];
if ( ! (*target)->finalAddressMode() ) {
if ( (*target)->contentType() == ld::Atom::typeLTOtemporary )
throwf("reference to bitcode symbol '%s' which LTO has not compiled", (*target)->name());
else
throwf("reference to symbol (which has not been assigned an address) %s", (*target)->name());
}
return (*target)->finalAddress();
}
throw "unexpected binding";
}
uint64_t OutputFile::addressAndTarget(const ld::Internal& state, const ld::Fixup* fixup, const ld::Atom** target)
{
switch ( fixup->binding ) {
case ld::Fixup::bindingNone:
throw "unexpected bindingNone";
case ld::Fixup::bindingByNameUnbound:
throw "unexpected bindingByNameUnbound";
case ld::Fixup::bindingByContentBound:
case ld::Fixup::bindingDirectlyBound:
*target = fixup->u.target;
return (*target)->finalAddress();
case ld::Fixup::bindingsIndirectlyBound:
*target = state.indirectBindingTable[fixup->u.bindingIndex];
#ifndef NDEBUG
if ( ! (*target)->finalAddressMode() ) {
throwf("reference to symbol (which has not been assigned an address) %s", (*target)->name());
}
#endif
return (*target)->finalAddress();
}
throw "unexpected binding";
}
uint64_t OutputFile::sectionOffsetOf(const ld::Internal& state, const ld::Fixup* fixup)
{
const ld::Atom* target = NULL;
switch ( fixup->binding ) {
case ld::Fixup::bindingNone:
throw "unexpected bindingNone";
case ld::Fixup::bindingByNameUnbound:
throw "unexpected bindingByNameUnbound";
case ld::Fixup::bindingByContentBound:
case ld::Fixup::bindingDirectlyBound:
target = fixup->u.target;
break;
case ld::Fixup::bindingsIndirectlyBound:
target = state.indirectBindingTable[fixup->u.bindingIndex];
break;
}
assert(target != NULL);
uint64_t targetAddress = target->finalAddress();
for (std::vector<ld::Internal::FinalSection*>::const_iterator it = state.sections.begin(); it != state.sections.end(); ++it) {
const ld::Internal::FinalSection* sect = *it;
if ( (sect->address <= targetAddress) && (targetAddress < (sect->address+sect->size)) )
return targetAddress - sect->address;
}
throw "section not found for section offset";
}
uint64_t OutputFile::tlvTemplateOffsetOf(const ld::Internal& state, const ld::Fixup* fixup)
{
const ld::Atom* target = NULL;
switch ( fixup->binding ) {
case ld::Fixup::bindingNone:
throw "unexpected bindingNone";
case ld::Fixup::bindingByNameUnbound:
throw "unexpected bindingByNameUnbound";
case ld::Fixup::bindingByContentBound:
case ld::Fixup::bindingDirectlyBound:
target = fixup->u.target;
break;
case ld::Fixup::bindingsIndirectlyBound:
target = state.indirectBindingTable[fixup->u.bindingIndex];
break;
}
assert(target != NULL);
for (std::vector<ld::Internal::FinalSection*>::const_iterator it = state.sections.begin(); it != state.sections.end(); ++it) {
const ld::Internal::FinalSection* sect = *it;
switch ( sect->type() ) {
case ld::Section::typeTLVInitialValues:
case ld::Section::typeTLVZeroFill:
return target->finalAddress() - sect->address;
default:
break;
}
}
throw "section not found for tlvTemplateOffsetOf";
}
void OutputFile::printSectionLayout(ld::Internal& state)
{
// show layout of final image
fprintf(stderr, "final section layout:\n");
for (std::vector<ld::Internal::FinalSection*>::iterator it = state.sections.begin(); it != state.sections.end(); ++it) {
if ( (*it)->isSectionHidden() )
continue;
fprintf(stderr, " %s/%s addr=0x%08llX, size=0x%08llX, fileOffset=0x%08llX, type=%d\n",
(*it)->segmentName(), (*it)->sectionName(),
(*it)->address, (*it)->size, (*it)->fileOffset, (*it)->type());
}
}
void OutputFile::rangeCheck8(int64_t displacement, ld::Internal& state, const ld::Atom* atom, const ld::Fixup* fixup)
{
if ( (displacement > 127) || (displacement < -128) ) {
// show layout of final image
printSectionLayout(state);
const ld::Atom* target;
throwf("8-bit reference out of range (%lld max is +/-127B): from %s (0x%08llX) to %s (0x%08llX)",
displacement, atom->name(), atom->finalAddress(), referenceTargetAtomName(state, fixup),
addressOf(state, fixup, &target));
}
}
void OutputFile::rangeCheck16(int64_t displacement, ld::Internal& state, const ld::Atom* atom, const ld::Fixup* fixup)
{
const int64_t thirtyTwoKLimit = 0x00007FFF;
if ( (displacement > thirtyTwoKLimit) || (displacement < (-thirtyTwoKLimit)) ) {
// show layout of final image
printSectionLayout(state);
const ld::Atom* target;
throwf("16-bit reference out of range (%lld max is +/-32KB): from %s (0x%08llX) to %s (0x%08llX)",
displacement, atom->name(), atom->finalAddress(), referenceTargetAtomName(state, fixup),
addressOf(state, fixup, &target));
}
}
void OutputFile::rangeCheckBranch32(int64_t displacement, ld::Internal& state, const ld::Atom* atom, const ld::Fixup* fixup)
{
const int64_t twoGigLimit = 0x7FFFFFFF;
if ( (displacement > twoGigLimit) || (displacement < (-twoGigLimit)) ) {
// show layout of final image
printSectionLayout(state);
const ld::Atom* target;
throwf("32-bit branch out of range (%lld max is +/-2GB): from %s (0x%08llX) to %s (0x%08llX)",
displacement, atom->name(), atom->finalAddress(), referenceTargetAtomName(state, fixup),
addressOf(state, fixup, &target));
}
}
void OutputFile::rangeCheckAbsolute32(int64_t displacement, ld::Internal& state, const ld::Atom* atom, const ld::Fixup* fixup)
{
const int64_t fourGigLimit = 0xFFFFFFFF;
if ( displacement > fourGigLimit ) {
// <rdar://problem/9610466> cannot enforce 32-bit range checks on 32-bit archs because assembler loses sign information
// .long _foo - 0xC0000000
// is encoded in mach-o the same as:
// .long _foo + 0x40000000
// so if _foo lays out to 0xC0000100, the first is ok, but the second is not.
if ( (_options.architecture() == CPU_TYPE_ARM) || (_options.architecture() == CPU_TYPE_I386) ) {
// Unlikely userland code does funky stuff like this, so warn for them, but not warn for -preload or -static
if ( (_options.outputKind() != Options::kPreload) && (_options.outputKind() != Options::kStaticExecutable) ) {
warning("32-bit absolute address out of range (0x%08llX max is 4GB): from %s + 0x%08X (0x%08llX) to 0x%08llX",
displacement, atom->name(), fixup->offsetInAtom, atom->finalAddress(), displacement);
}
return;
}
// show layout of final image
printSectionLayout(state);
const ld::Atom* target;
if ( fixup->binding == ld::Fixup::bindingNone )
throwf("32-bit absolute address out of range (0x%08llX max is 4GB): from %s + 0x%08X (0x%08llX) to 0x%08llX",
displacement, atom->name(), fixup->offsetInAtom, atom->finalAddress(), displacement);
else
throwf("32-bit absolute address out of range (0x%08llX max is 4GB): from %s + 0x%08X (0x%08llX) to %s (0x%08llX)",
displacement, atom->name(), fixup->offsetInAtom, atom->finalAddress(), referenceTargetAtomName(state, fixup),
addressOf(state, fixup, &target));
}
}
void OutputFile::rangeCheckRIP32(int64_t displacement, ld::Internal& state, const ld::Atom* atom, const ld::Fixup* fixup)
{
const int64_t twoGigLimit = 0x7FFFFFFF;
if ( (displacement > twoGigLimit) || (displacement < (-twoGigLimit)) ) {
// show layout of final image
printSectionLayout(state);
const ld::Atom* target;
throwf("32-bit RIP relative reference out of range (%lld max is +/-2GB): from %s (0x%08llX) to %s (0x%08llX)",
displacement, atom->name(), atom->finalAddress(), referenceTargetAtomName(state, fixup),
addressOf(state, fixup, &target));
}
}
void OutputFile::rangeCheckARM12(int64_t displacement, ld::Internal& state, const ld::Atom* atom, const ld::Fixup* fixup)
{
if ( (displacement > 4092LL) || (displacement < (-4092LL)) ) {
// show layout of final image
printSectionLayout(state);
const ld::Atom* target;
throwf("ARM ldr 12-bit displacement out of range (%lld max is +/-4096B): from %s (0x%08llX) to %s (0x%08llX)",
displacement, atom->name(), atom->finalAddress(), referenceTargetAtomName(state, fixup),
addressOf(state, fixup, &target));
}
}
bool OutputFile::checkArmBranch24Displacement(int64_t displacement)
{
return ( (displacement < 33554428LL) && (displacement > (-33554432LL)) );
}
void OutputFile::rangeCheckARMBranch24(int64_t displacement, ld::Internal& state, const ld::Atom* atom, const ld::Fixup* fixup)
{
if ( checkArmBranch24Displacement(displacement) )
return;
// show layout of final image
printSectionLayout(state);
const ld::Atom* target;
throwf("b/bl/blx ARM branch out of range (%lld max is +/-32MB): from %s (0x%08llX) to %s (0x%08llX)",
displacement, atom->name(), atom->finalAddress(), referenceTargetAtomName(state, fixup),
addressOf(state, fixup, &target));
}
bool OutputFile::checkThumbBranch22Displacement(int64_t displacement)
{
// thumb2 supports +/- 16MB displacement
if ( _options.archThumb2Support() >= Thumb2Support::branch24 ) {
if ( (displacement > 16777214LL) || (displacement < (-16777216LL)) ) {
return false;
}
}
else {
// thumb1 supports +/- 4MB displacement
if ( (displacement > 4194302LL) || (displacement < (-4194304LL)) ) {
return false;
}
}
return true;
}
void OutputFile::rangeCheckThumbBranch22(int64_t displacement, ld::Internal& state, const ld::Atom* atom, const ld::Fixup* fixup)
{
if ( checkThumbBranch22Displacement(displacement) )
return;
// show layout of final image
printSectionLayout(state);
const ld::Atom* target;
if ( _options.archThumb2Support() >= Thumb2Support::branch24 ) {
throwf("b/bl/blx thumb2 branch out of range (%lld max is +/-16MB): from %s (0x%08llX) to %s (0x%08llX)",
displacement, atom->name(), atom->finalAddress(), referenceTargetAtomName(state, fixup),
addressOf(state, fixup, &target));
}
else {
throwf("b/bl/blx thumb1 branch out of range (%lld max is +/-4MB): from %s (0x%08llX) to %s (0x%08llX)",
displacement, atom->name(), atom->finalAddress(), referenceTargetAtomName(state, fixup),
addressOf(state, fixup, &target));
}
}
void OutputFile::rangeCheckARM64Branch26(int64_t displacement, ld::Internal& state, const ld::Atom* atom, const ld::Fixup* fixup)
{
const int64_t bl_128MegLimit = 0x07FFFFFF;
if ( (displacement > bl_128MegLimit) || (displacement < (-bl_128MegLimit)) ) {
// show layout of final image
printSectionLayout(state);
const ld::Atom* target;
throwf("b(l) ARM64 branch out of range (%lld max is +/-128MB): from %s (0x%08llX) to %s (0x%08llX)",
displacement, atom->name(), atom->finalAddress(), referenceTargetAtomName(state, fixup),
addressOf(state, fixup, &target));
}
}
void OutputFile::rangeCheckARM64Page21(int64_t displacement, ld::Internal& state, const ld::Atom* atom, const ld::Fixup* fixup)
{
const int64_t adrp_4GigLimit = 0x100000000ULL;
if ( (displacement > adrp_4GigLimit) || (displacement < (-adrp_4GigLimit)) ) {
// show layout of final image
printSectionLayout(state);
const ld::Atom* target;
throwf("ARM64 ADRP out of range (%lld max is +/-4GB): from %s (0x%08llX) to %s (0x%08llX)",
displacement, atom->name(), atom->finalAddress(), referenceTargetAtomName(state, fixup),
addressOf(state, fixup, &target));
}
}
uint16_t OutputFile::get16LE(uint8_t* loc) { return LittleEndian::get16(*(uint16_t*)loc); }
void OutputFile::set16LE(uint8_t* loc, uint16_t value) { LittleEndian::set16(*(uint16_t*)loc, value); }
uint32_t OutputFile::get32LE(uint8_t* loc) { return LittleEndian::get32(*(uint32_t*)loc); }
void OutputFile::set32LE(uint8_t* loc, uint32_t value) { LittleEndian::set32(*(uint32_t*)loc, value); }
uint64_t OutputFile::get64LE(uint8_t* loc) { return LittleEndian::get64(*(uint64_t*)loc); }
void OutputFile::set64LE(uint8_t* loc, uint64_t value) { LittleEndian::set64(*(uint64_t*)loc, value); }
uint16_t OutputFile::get16BE(uint8_t* loc) { return BigEndian::get16(*(uint16_t*)loc); }
void OutputFile::set16BE(uint8_t* loc, uint16_t value) { BigEndian::set16(*(uint16_t*)loc, value); }
uint32_t OutputFile::get32BE(uint8_t* loc) { return BigEndian::get32(*(uint32_t*)loc); }
void OutputFile::set32BE(uint8_t* loc, uint32_t value) { BigEndian::set32(*(uint32_t*)loc, value); }
uint64_t OutputFile::get64BE(uint8_t* loc) { return BigEndian::get64(*(uint64_t*)loc); }
void OutputFile::set64BE(uint8_t* loc, uint64_t value) { BigEndian::set64(*(uint64_t*)loc, value); }
#if SUPPORT_ARCH_arm64
static uint32_t makeNOP() {
return 0xD503201F;
}
enum SignExtension { signedNot, signed32, signed64 };
struct LoadStoreInfo {
uint32_t reg;
uint32_t baseReg;
uint32_t offset; // after scaling
uint32_t size; // 1,2,4,8, or 16
bool isStore;
bool isFloat; // if destReg is FP/SIMD
SignExtension signEx; // if load is sign extended
};
static uint32_t makeLDR_literal(const LoadStoreInfo& info, uint64_t targetAddress, uint64_t instructionAddress)
{
int64_t delta = targetAddress - instructionAddress;
assert(delta < 1024*1024);
assert(delta > -1024*1024);
assert((info.reg & 0xFFFFFFE0) == 0);
assert((targetAddress & 0x3) == 0);
assert((instructionAddress & 0x3) == 0);
assert(!info.isStore);
uint32_t imm19 = (delta << 3) & 0x00FFFFE0;
uint32_t instruction = 0;
switch ( info.size ) {
case 4:
if ( info.isFloat ) {
assert(info.signEx == signedNot);
instruction = 0x1C000000;
}
else {
if ( info.signEx == signed64 )
instruction = 0x98000000;
else
instruction = 0x18000000;
}
break;
case 8:
assert(info.signEx == signedNot);
instruction = info.isFloat ? 0x5C000000 : 0x58000000;
break;
case 16:
assert(info.signEx == signedNot);
instruction = 0x9C000000;
break;
default:
assert(0 && "invalid load size for literal");
}
return (instruction | imm19 | info.reg);
}
static uint32_t makeADR(uint32_t destReg, uint64_t targetAddress, uint64_t instructionAddress)
{
assert((destReg & 0xFFFFFFE0) == 0);
assert((instructionAddress & 0x3) == 0);
uint32_t instruction = 0x10000000;
int64_t delta = targetAddress - instructionAddress;
assert(delta < 1024*1024);
assert(delta > -1024*1024);
uint32_t immhi = (delta & 0x001FFFFC) << 3;
uint32_t immlo = (delta & 0x00000003) << 29;
return (instruction | immhi | immlo | destReg);
}
static uint32_t makeLoadOrStore(const LoadStoreInfo& info)
{
uint32_t instruction = 0x39000000;
if ( info.isFloat )
instruction |= 0x04000000;
instruction |= info.reg;
instruction |= (info.baseReg << 5);
uint32_t sizeBits = 0;
uint32_t opcBits = 0;
uint32_t imm12Bits = 0;
switch ( info.size ) {
case 1:
sizeBits = 0;
imm12Bits = info.offset;
if ( info.isStore ) {
opcBits = 0;
}
else {
switch ( info.signEx ) {
case signedNot:
opcBits = 1;
break;
case signed32:
opcBits = 3;
break;
case signed64:
opcBits = 2;
break;
}
}
break;
case 2:
sizeBits = 1;
assert((info.offset % 2) == 0);
imm12Bits = info.offset/2;
if ( info.isStore ) {
opcBits = 0;
}
else {
switch ( info.signEx ) {
case signedNot:
opcBits = 1;
break;
case signed32:
opcBits = 3;
break;
case signed64:
opcBits = 2;
break;
}
}
break;
case 4:
sizeBits = 2;
assert((info.offset % 4) == 0);
imm12Bits = info.offset/4;
if ( info.isStore ) {
opcBits = 0;
}
else {
switch ( info.signEx ) {
case signedNot:
opcBits = 1;
break;
case signed32:
assert(0 && "cannot use signed32 with 32-bit load/store");
break;
case signed64:
opcBits = 2;
break;
}
}
break;
case 8:
sizeBits = 3;
assert((info.offset % 8) == 0);
imm12Bits = info.offset/8;
if ( info.isStore ) {
opcBits = 0;
}
else {
opcBits = 1;
assert(info.signEx == signedNot);
}
break;
case 16:
sizeBits = 0;
assert((info.offset % 16) == 0);
imm12Bits = info.offset/16;
assert(info.isFloat);
if ( info.isStore ) {
opcBits = 2;
}
else {
opcBits = 3;
}
break;
default:
assert(0 && "bad load/store size");
break;
}
assert(imm12Bits < 4096);
return (instruction | (sizeBits << 30) | (opcBits << 22) | (imm12Bits << 10));
}
static bool parseLoadOrStore(uint32_t instruction, LoadStoreInfo& info)
{
if ( (instruction & 0x3B000000) != 0x39000000 )
return false;
info.isFloat = ( (instruction & 0x04000000) != 0 );
info.reg = (instruction & 0x1F);
info.baseReg = ((instruction>>5) & 0x1F);
switch (instruction & 0xC0C00000) {
case 0x00000000:
info.size = 1;
info.isStore = true;
info.signEx = signedNot;
break;
case 0x00400000:
info.size = 1;
info.isStore = false;
info.signEx = signedNot;
break;
case 0x00800000:
if ( info.isFloat ) {
info.size = 16;
info.isStore = true;
info.signEx = signedNot;
}
else {
info.size = 1;
info.isStore = false;
info.signEx = signed64;
}
break;
case 0x00C00000:
if ( info.isFloat ) {
info.size = 16;
info.isStore = false;
info.signEx = signedNot;
}
else {
info.size = 1;
info.isStore = false;
info.signEx = signed32;
}
break;
case 0x40000000:
info.size = 2;
info.isStore = true;
info.signEx = signedNot;
break;
case 0x40400000:
info.size = 2;
info.isStore = false;
info.signEx = signedNot;
break;
case 0x40800000:
info.size = 2;
info.isStore = false;
info.signEx = signed64;
break;