-
Notifications
You must be signed in to change notification settings - Fork 14
/
Resolver.cpp
2045 lines (1857 loc) · 78.5 KB
/
Resolver.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-2010 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 <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 <dlfcn.h>
#include <mach-o/dyld.h>
#include <mach-o/fat.h>
#include <string>
#include <map>
#include <set>
#include <string>
#include <vector>
#include <list>
#include <algorithm>
#include <dlfcn.h>
#include <AvailabilityMacros.h>
#include "Options.h"
#include "ld.hpp"
#include "Bitcode.hpp"
#include "InputFiles.h"
#include "SymbolTable.h"
#include "Resolver.h"
#include "parsers/lto_file.h"
#include "configure.h"
#define VAL(x) #x
#define STRINGIFY(x) VAL(x)
namespace ld {
namespace tool {
//
// An ExportAtom has no content. It exists so that the linker can track which imported
// symbols came from which dynamic libraries.
//
class UndefinedProxyAtom : public ld::Atom
{
public:
UndefinedProxyAtom(const char* nm)
: ld::Atom(_s_section, ld::Atom::definitionProxy,
ld::Atom::combineNever, ld::Atom::scopeLinkageUnit,
ld::Atom::typeUnclassified,
ld::Atom::symbolTableIn, false, false, false, ld::Atom::Alignment(0)),
_name(nm) {}
// overrides of ld::Atom
virtual const ld::File* file() const { return NULL; }
virtual const char* name() const { return _name; }
virtual uint64_t size() const { return 0; }
virtual uint64_t objectAddress() const { return 0; }
virtual void copyRawContent(uint8_t buffer[]) const { }
virtual void setScope(Scope) { }
protected:
virtual ~UndefinedProxyAtom() {}
const char* _name;
static ld::Section _s_section;
};
ld::Section UndefinedProxyAtom::_s_section("__TEXT", "__import", ld::Section::typeImportProxies, true);
class AliasAtom : public ld::Atom
{
public:
AliasAtom(const ld::Atom& target, const char* nm) :
ld::Atom(target.section(), target.definition(), ld::Atom::combineNever,
ld::Atom::scopeGlobal, target.contentType(),
target.symbolTableInclusion(), target.dontDeadStrip(),
target.isThumb(), true, target.alignment()),
_name(nm),
_aliasOf(target),
_fixup(0, ld::Fixup::k1of1, ld::Fixup::kindNoneFollowOn, &target) { }
// overrides of ld::Atom
virtual const ld::File* file() const { return _aliasOf.file(); }
virtual const char* translationUnitSource() const
{ return _aliasOf.translationUnitSource(); }
virtual const char* name() const { return _name; }
virtual uint64_t size() const { return 0; }
virtual uint64_t objectAddress() const { return _aliasOf.objectAddress(); }
virtual void copyRawContent(uint8_t buffer[]) const { }
virtual const uint8_t* rawContentPointer() const { return NULL; }
virtual unsigned long contentHash(const class ld::IndirectBindingTable& ibt) const
{ return _aliasOf.contentHash(ibt); }
virtual bool canCoalesceWith(const ld::Atom& rhs, const class ld::IndirectBindingTable& ibt) const
{ return _aliasOf.canCoalesceWith(rhs,ibt); }
virtual ld::Fixup::iterator fixupsBegin() const { return (ld::Fixup*)&_fixup; }
virtual ld::Fixup::iterator fixupsEnd() const { return &((ld::Fixup*)&_fixup)[1]; }
virtual ld::Atom::UnwindInfo::iterator beginUnwind() const { return NULL; }
virtual ld::Atom::UnwindInfo::iterator endUnwind() const { return NULL; }
virtual ld::Atom::LineInfo::iterator beginLineInfo() const { return NULL; }
virtual ld::Atom::LineInfo::iterator endLineInfo() const { return NULL; }
void setFinalAliasOf() const {
(const_cast<AliasAtom*>(this))->setAttributesFromAtom(_aliasOf);
(const_cast<AliasAtom*>(this))->setScope(ld::Atom::scopeGlobal);
}
private:
const char* _name;
const ld::Atom& _aliasOf;
ld::Fixup _fixup;
};
class SectionBoundaryAtom : public ld::Atom
{
public:
static SectionBoundaryAtom* makeSectionBoundaryAtom(const char* name, bool start, const char* segSectName, const Options& opts);
static SectionBoundaryAtom* makeOldSectionBoundaryAtom(const char* name, bool start);
// overrides of ld::Atom
virtual const ld::File* file() const { return NULL; }
virtual const char* name() const { return _name; }
virtual uint64_t size() const { return 0; }
virtual void copyRawContent(uint8_t buffer[]) const { }
virtual const uint8_t* rawContentPointer() const { return NULL; }
virtual uint64_t objectAddress() const { return 0; }
private:
SectionBoundaryAtom(const char* nm, const ld::Section& sect,
ld::Atom::ContentType cont) :
ld::Atom(sect,
ld::Atom::definitionRegular,
ld::Atom::combineNever,
ld::Atom::scopeLinkageUnit,
cont,
ld::Atom::symbolTableNotIn,
false, false, true, ld::Atom::Alignment(0)),
_name(nm) { }
const char* _name;
};
SectionBoundaryAtom* SectionBoundaryAtom::makeSectionBoundaryAtom(const char* name, bool start, const char* segSectName, const Options& opts)
{
const char* segSectDividor = strrchr(segSectName, '$');
if ( segSectDividor == NULL )
throwf("malformed section$ symbol name: %s", name);
const char* sectionName = segSectDividor + 1;
int segNameLen = segSectDividor - segSectName;
if ( segNameLen > 16 )
throwf("malformed section$ symbol name: %s", name);
char segName[18];
strlcpy(segName, segSectName, segNameLen+1);
ld::Section::Type sectType = ld::Section::typeUnclassified;
if (!strcmp(segName, "__TEXT") && !strcmp(sectionName, "__thread_starts"))
sectType = ld::Section::typeThreadStarts;
else if (!strcmp(segName, "__TEXT") && !strcmp(sectionName, "__chain_starts"))
sectType = ld::Section::typeChainStarts;
else if (!strcmp(segName, "__DATA") && !strcmp(sectionName, "__zerofill")) {
if ( opts.mergeZeroFill() )
sectType = ld::Section::typeZeroFill;
else
warning("reference to non-existent __zerofill section because -merge_zero_fill_sections option not used");
}
const ld::Section* section = new ld::Section(strdup(segName), sectionName, sectType);
return new SectionBoundaryAtom(name, *section, (start ? ld::Atom::typeSectionStart : typeSectionEnd));
}
SectionBoundaryAtom* SectionBoundaryAtom::makeOldSectionBoundaryAtom(const char* name, bool start)
{
// e.g. __DATA__bss__begin
char segName[18];
strlcpy(segName, name, 7);
char sectName[18];
int nameLen = strlen(name);
strlcpy(sectName, &name[6], (start ? nameLen-12 : nameLen-10));
warning("grandfathering in old symbol '%s' as alias for 'section$%s$%s$%s'", name, start ? "start" : "end", segName, sectName);
const ld::Section* section = new ld::Section(strdup(segName), strdup(sectName), ld::Section::typeUnclassified);
return new SectionBoundaryAtom(name, *section, (start ? ld::Atom::typeSectionStart : typeSectionEnd));
}
class SegmentBoundaryAtom : public ld::Atom
{
public:
static SegmentBoundaryAtom* makeSegmentBoundaryAtom(const char* name, bool start, const char* segName);
static SegmentBoundaryAtom* makeOldSegmentBoundaryAtom(const char* name, bool start);
// overrides of ld::Atom
virtual const ld::File* file() const { return NULL; }
virtual const char* name() const { return _name; }
virtual uint64_t size() const { return 0; }
virtual void copyRawContent(uint8_t buffer[]) const { }
virtual const uint8_t* rawContentPointer() const { return NULL; }
virtual uint64_t objectAddress() const { return 0; }
private:
SegmentBoundaryAtom(const char* nm, const ld::Section& sect,
ld::Atom::ContentType cont) :
ld::Atom(sect,
ld::Atom::definitionRegular,
ld::Atom::combineNever,
ld::Atom::scopeLinkageUnit,
cont,
ld::Atom::symbolTableNotIn,
false, false, true, ld::Atom::Alignment(0)),
_name(nm) { }
const char* _name;
};
SegmentBoundaryAtom* SegmentBoundaryAtom::makeSegmentBoundaryAtom(const char* name, bool start, const char* segName)
{
if ( *segName == '\0' )
throwf("malformed segment$ symbol name: %s", name);
if ( strlen(segName) > 16 )
throwf("malformed segment$ symbol name: %s", name);
if ( start ) {
const ld::Section* section = new ld::Section(segName, "__start", ld::Section::typeFirstSection, true);
return new SegmentBoundaryAtom(name, *section, ld::Atom::typeSectionStart);
}
else {
const ld::Section* section = new ld::Section(segName, "__end", ld::Section::typeLastSection, true);
return new SegmentBoundaryAtom(name, *section, ld::Atom::typeSectionEnd);
}
}
SegmentBoundaryAtom* SegmentBoundaryAtom::makeOldSegmentBoundaryAtom(const char* name, bool start)
{
// e.g. __DATA__begin
char temp[18];
strlcpy(temp, name, 7);
char* segName = strdup(temp);
warning("grandfathering in old symbol '%s' as alias for 'segment$%s$%s'", name, start ? "start" : "end", segName);
if ( start ) {
const ld::Section* section = new ld::Section(segName, "__start", ld::Section::typeFirstSection, true);
return new SegmentBoundaryAtom(name, *section, ld::Atom::typeSectionStart);
}
else {
const ld::Section* section = new ld::Section(segName, "__end", ld::Section::typeLastSection, true);
return new SegmentBoundaryAtom(name, *section, ld::Atom::typeSectionEnd);
}
}
void Resolver::initializeState()
{
_internal.cpuSubType = _options.subArchitecture();
// In -r mode, look for -linker_option additions
if ( _options.outputKind() == Options::kObjectFile ) {
ld::relocatable::File::LinkerOptionsList lo = _options.linkerOptions();
for (relocatable::File::LinkerOptionsList::const_iterator it=lo.begin(); it != lo.end(); ++it) {
doLinkerOption(*it, "command line");
}
}
#ifdef LD64_VERSION_NUM
uint32_t packedNum = Options::parseVersionNumber32(STRINGIFY(LD64_VERSION_NUM));
uint64_t combined = (uint64_t)TOOL_LD << 32 | packedNum;
_internal.toolsVersions.insert(combined);
#endif
}
void Resolver::buildAtomList()
{
// each input files contributes initial atoms
_atoms.reserve(1024);
_inputFiles.forEachInitialAtom(*this, _internal);
_completedInitialObjectFiles = true;
//_symbolTable.printStatistics();
}
void Resolver::doLinkerOption(const std::vector<const char*>& linkerOption, const char* fileName)
{
if ( linkerOption.size() == 1 ) {
const char* lo1 = linkerOption.front();
if ( strncmp(lo1, "-l", 2) == 0) {
if (_internal.linkerOptionLibraries.count(&lo1[2]) == 0) {
_internal.unprocessedLinkerOptionLibraries.insert(&lo1[2]);
}
}
else if ( strncmp(lo1, "-needed-l", 9) == 0) {
const char* libName = &lo1[9];
if (_internal.linkerOptionLibraries.count(libName) == 0) {
_internal.unprocessedLinkerOptionLibraries.insert(libName);
}
_internal.linkerOptionNeededLibraries.insert(libName);
}
else {
warning("unknown linker option from object file ignored: '%s' in %s", lo1, fileName);
}
}
else if ( linkerOption.size() == 2 ) {
const char* lo2a = linkerOption[0];
const char* lo2b = linkerOption[1];
if ( strcmp(lo2a, "-framework") == 0) {
if (_internal.linkerOptionFrameworks.count(lo2b) == 0) {
_internal.unprocessedLinkerOptionFrameworks.insert(lo2b);
}
}
else if ( strcmp(lo2a, "-needed_framework") == 0 ) {
if (_internal.linkerOptionFrameworks.count(lo2b) == 0) {
_internal.unprocessedLinkerOptionFrameworks.insert(lo2b);
}
_internal.linkerOptionNeededFrameworks.insert(lo2b);
}
else {
warning("unknown linker option from object file ignored: '%s' '%s' from %s", lo2a, lo2b, fileName);
}
}
else {
warning("unknown linker option from object file ignored, starting with: '%s' from %s", linkerOption.front(), fileName);
}
}
void Resolver::doFile(const ld::File& file)
{
const ld::relocatable::File* objFile = dynamic_cast<const ld::relocatable::File*>(&file);
const ld::dylib::File* dylibFile = dynamic_cast<const ld::dylib::File*>(&file);
if ( objFile != NULL ) {
// if file has linker options, process them
ld::relocatable::File::LinkerOptionsList* lo = objFile->linkerOptions();
if ( lo != NULL && !_options.ignoreAutoLink() ) {
for (relocatable::File::LinkerOptionsList::const_iterator it=lo->begin(); it != lo->end(); ++it) {
this->doLinkerOption(*it, file.path());
}
// <rdar://problem/23053404> process any additional linker-options introduced by this new archive member being loaded
if ( _completedInitialObjectFiles ) {
_inputFiles.addLinkerOptionLibraries(_internal, *this);
_inputFiles.createIndirectDylibs();
}
}
// update which form of ObjC is being used
if ( objFile->hasObjC() )
_internal.hasObjC = true;
// Resolve bitcode section in the object file
if ( _options.bundleBitcode() ) {
if ( objFile->getBitcode() == NULL ) {
// Handle the special case for compiler_rt objects. Add the file to the list to be process.
if ( objFile->sourceKind() == ld::relocatable::File::kSourceCompilerArchive ) {
_internal.filesFromCompilerRT.push_back(objFile);
}
else if (objFile->sourceKind() != ld::relocatable::File::kSourceLTO ) {
// No bitcode section, figure out if the object file comes from LTO/compiler static library
_options.platforms().forEach(^(ld::Platform platform, uint32_t minVersion, uint32_t sdkVersion, bool &stop) {
if ( platformInfo(platform).supportsEmbeddedBitcode ) {
throwf("'%s' does not contain bitcode. "
"You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target.", file.path());
}
else {
warning("all bitcode will be dropped because '%s' was built without bitcode. "
"You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target. ", file.path());
_internal.filesWithBitcode.clear();
_internal.dropAllBitcode = true;
}
});
}
} else {
// contains bitcode, check if it is just a marker
if ( objFile->getBitcode()->isMarker() ) {
// if -bitcode_verify_bundle is used, check if all the object files participate in the linking have full bitcode embedded.
// error on any marker encountered.
if ( _options.verifyBitcode() )
throwf("bitcode bundle could not be generated because '%s' was built without full bitcode. "
"All object files and libraries for bitcode must be generated from Xcode Archive or Install build",
objFile->path());
// update the internal state that marker is encountered.
_internal.embedMarkerOnly = true;
_internal.filesWithBitcode.clear();
_internal.dropAllBitcode = true;
} else if ( !_internal.dropAllBitcode )
_internal.filesWithBitcode.push_back(objFile);
}
}
// verify all files use same version of Swift language
if ( file.swiftVersion() != 0 ) {
_internal.someObjectFileHasSwift = true;
if ( _internal.swiftVersion == 0 ) {
_internal.swiftVersion = file.swiftVersion();
}
else if ( file.swiftVersion() != _internal.swiftVersion ) {
char fileVersion[64];
char otherVersion[64];
Options::userReadableSwiftVersion(file.swiftVersion(), fileVersion);
Options::userReadableSwiftVersion(_internal.swiftVersion, otherVersion);
if ( file.swiftVersion() > _internal.swiftVersion ) {
if ( _options.warnOnSwiftABIVersionMismatches() ) {
warning("%s compiled with newer version of Swift language (%s) than previous files (%s)",
file.path(), fileVersion, otherVersion);
} else {
throwf("not all .o files built with same Swift language version. Started with (%s), now found (%s) in",
otherVersion, fileVersion);
}
}
else {
if ( _options.warnOnSwiftABIVersionMismatches() ) {
warning("%s compiled with older version of Swift language (%s) than previous files (%s)",
file.path(), fileVersion, otherVersion);
} else {
throwf("not all .o files built with same Swift language version. Started with (%s), now found (%s) in",
otherVersion, fileVersion);
}
}
}
}
// record minimums swift language version used
if ( file.swiftLanguageVersion() != 0 ) {
if ( (_internal.swiftLanguageVersion == 0) || (_internal.swiftLanguageVersion > file.swiftLanguageVersion()) )
_internal.swiftLanguageVersion = file.swiftLanguageVersion();
}
// in -r mode, if any .o files have dwarf then add UUID to output .o file
if ( objFile->debugInfo() == ld::relocatable::File::kDebugInfoDwarf )
_internal.someObjectFileHasDwarf = true;
// remember if any .o file did not have MH_SUBSECTIONS_VIA_SYMBOLS bit set
if ( ! objFile->canScatterAtoms() )
_internal.allObjectFilesScatterable = false;
// remember if building for profiling (so we don't warn about initializers)
if ( objFile->hasllvmProfiling() )
_havellvmProfiling = true;
// remember if we found .o without platform info
if ( objFile->platforms().empty() )
_internal.objectFileFoundWithNoVersion = true;
// update set of known tools used
for (const std::pair<uint32_t,uint32_t>& entry : objFile->toolVersions()) {
uint64_t combined = (uint64_t)entry.first << 32 | entry.second;
_internal.toolsVersions.insert(combined);
}
// update cpu-sub-type
cpu_subtype_t nextObjectSubType = file.cpuSubType();
switch ( _options.architecture() ) {
case CPU_TYPE_ARM:
if ( _options.subArchitecture() != nextObjectSubType ) {
if ( (_options.subArchitecture() == CPU_SUBTYPE_ARM_ALL) && _options.forceCpuSubtypeAll() ) {
// hack to support gcc multillib build that tries to make sub-type-all slice
}
else if ( nextObjectSubType == CPU_SUBTYPE_ARM_ALL ) {
warning("CPU_SUBTYPE_ARM_ALL subtype is deprecated: %s", file.path());
}
else if ( _options.allowSubArchitectureMismatches() ) {
//warning("object file %s was built for different arm sub-type (%d) than link command line (%d)",
// file.path(), nextObjectSubType, _options.subArchitecture());
}
else {
throwf("object file %s was built for different arm sub-type (%d) than link command line (%d)",
file.path(), nextObjectSubType, _options.subArchitecture());
}
}
break;
case CPU_TYPE_I386:
_internal.cpuSubType = CPU_SUBTYPE_I386_ALL;
break;
case CPU_TYPE_X86_64:
if ( _options.subArchitecture() != nextObjectSubType ) {
// <rdar://problem/47240066> allow x86_64h to link with x86_64 .o files
if ( (_options.subArchitecture() == CPU_SUBTYPE_X86_64_H) && (nextObjectSubType == CPU_SUBTYPE_X86_64_ALL) )
break;
if ( _options.allowSubArchitectureMismatches() ) {
warning("object file %s was built for different x86_64 sub-type (%d) than link command line (%d)",
file.path(), nextObjectSubType, _options.subArchitecture());
}
else {
throwf("object file %s was built for different x86_64 sub-type (%d) than link command line (%d)",
file.path(), nextObjectSubType, _options.subArchitecture());
}
}
break;
case CPU_TYPE_ARM64:
if (_options.subArchitecture() == CPU_SUBTYPE_ARM64E) {
if ((file.cpuSubTypeFlags() & 0x80) == 0) {
warning("object file %s was built with an incompatible arm64e ABI compiler", file.path());
break;
}
if (!_internal.hasArm64eABIVersion) {
_internal.arm64eABIVersion = file.cpuSubTypeFlags();
_internal.hasArm64eABIVersion = true;
} else {
// The compilers that generate ABI versions have not been submitted yet, so only warn about old .o files
// when we have already seen a new one.
if ( _internal.arm64eABIVersion != file.cpuSubTypeFlags()) {
const char * originalVersion = (_internal.arm64eABIVersion & 0x40) ? "kernel" : "user";
const char * fileVersion = (file.cpuSubTypeFlags() & 0x40) ? "kernel" : "user";
warning("object file %s was built for different arm64e ABI (%s version %u) than earlier object files (%s version %u)",
file.path(), fileVersion, (file.cpuSubTypeFlags() & 0x3f), originalVersion, (_internal.arm64eABIVersion & 0x3f));
}
}
}
break;
}
}
if ( dylibFile != NULL ) {
// Check dylib for bitcode, if the library install path is relative path or @rpath, it has to contain bitcode
if ( _options.bundleBitcode() ) {
bool isSystemFramework = ( dylibFile->installPath() != NULL ) && ( dylibFile->installPath()[0] == '/' );
if (!isSystemFramework) {
// rdar://52804818 The swift dylibs in the SDK do not have absolute installnames in order to support
// back deployment
for (const auto& sdkPath : _options.sdkPaths()) {
char swiftPath[MAXPATHLEN];
strlcpy(swiftPath, sdkPath, MAXPATHLEN);
strlcat(swiftPath, "/usr/lib/swift/", MAXPATHLEN);
if (strncmp(swiftPath, dylibFile->path(), strlen(swiftPath)) == 0) {
isSystemFramework = true;
break;
}
}
}
if ( dylibFile->getBitcode() == NULL && !isSystemFramework ) {
// Check if the dylib is from toolchain by checking the path
char tcLibPath[PATH_MAX];
char ldPath[PATH_MAX];
char tempPath[PATH_MAX];
uint32_t bufSize = PATH_MAX;
// toolchain library path should pointed to *.xctoolchain/usr/lib
if ( _NSGetExecutablePath(ldPath, &bufSize) != -1 ) {
if ( realpath(ldPath, tempPath) != NULL ) {
char* lastSlash = strrchr(tempPath, '/');
if ( lastSlash != NULL )
strcpy(lastSlash, "/../lib");
}
}
// Compare toolchain library path to the dylib path
if ( realpath(tempPath, tcLibPath) == NULL ||
realpath(dylibFile->path(), tempPath) == NULL ||
strncmp(tcLibPath, tempPath, strlen(tcLibPath)) != 0 ) {
_options.platforms().forEach(^(ld::Platform platform, uint32_t minVersion, uint32_t sdkVersion, bool &stop) {
if ( platformInfo(platform).supportsEmbeddedBitcode ) {
throwf("'%s' does not contain bitcode. "
"You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target.", file.path());
}
else {
warning("all bitcode will be dropped because '%s' was built without bitcode. "
"You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target.", file.path());
_internal.filesWithBitcode.clear();
_internal.dropAllBitcode = true;
}
});
}
}
// Error on bitcode marker in non-system frameworks if -bitcode_verify is used
if ( _options.verifyBitcode() && !isSystemFramework &&
dylibFile->getBitcode() != NULL && dylibFile->getBitcode()->isMarker() )
throwf("bitcode bundle could not be generated because '%s' was built without full bitcode. "
"All frameworks and dylibs for bitcode must be generated from Xcode Archive or Install build",
dylibFile->path());
}
// Don't allow swift frameworks to link other swift frameworks.
if ( !_internal.firstSwiftDylibFile && _options.outputKind() == Options::kDynamicLibrary
&& file.swiftVersion() != 0 && getenv("LD_DISALLOW_SWIFT_LINKING_SWIFT")) {
// Check that we aren't a whitelisted path.
bool inWhiteList = false;
const char *whitelistedPaths[] = { "/System/Library/PrivateFrameworks/Swift" };
for (auto whitelistedPath : whitelistedPaths) {
if (!strncmp(whitelistedPath, dylibFile->installPath(), strlen(whitelistedPath))) {
inWhiteList = true;
break;
}
}
if (!inWhiteList) {
_internal.firstSwiftDylibFile = dylibFile;
}
}
// <rdar://problem/25680358> verify dylibs use same version of Swift language
if ( file.swiftVersion() != 0 ) {
if ( (_internal.swiftVersion != 0) && (file.swiftVersion() != _internal.swiftVersion) ) {
char fileVersion[64];
char otherVersion[64];
Options::userReadableSwiftVersion(file.swiftVersion(), fileVersion);
Options::userReadableSwiftVersion(_internal.swiftVersion, otherVersion);
if ( file.swiftVersion() > _internal.swiftVersion ) {
if ( _options.warnOnSwiftABIVersionMismatches() ) {
warning("%s compiled with newer version of Swift language (%s) than previous files (%s)",
file.path(), fileVersion, otherVersion);
} else {
throwf("%s compiled with newer version of Swift language (%s) than previous files (%s)",
file.path(), fileVersion, otherVersion);
}
}
else {
if ( _options.warnOnSwiftABIVersionMismatches() ) {
warning("%s compiled with older version of Swift language (%s) than previous files (%s)",
file.path(), fileVersion, otherVersion);
} else {
throwf("%s compiled with older version of Swift language (%s) than previous files (%s)",
file.path(), fileVersion, otherVersion);
}
}
}
}
if ( _options.checkDylibsAreAppExtensionSafe() && !dylibFile->appExtensionSafe() ) {
warning("linking against a dylib which is not safe for use in application extensions: %s", file.path());
}
const char* depInstallName = dylibFile->installPath();
// <rdar://problem/17229513> embedded frameworks are only supported on iOS 8 and later
if ( (depInstallName != NULL) && (depInstallName[0] != '/') ) {
if ( _options.platforms().contains(ld::Platform::iOS) && !_options.platforms().minOS(iOS_8_0) ) {
// <rdar://problem/17598404> only warn about linking against embedded dylib if it is built for iOS 8 or later
if ( dylibFile->platforms().minOS(ld::iOS_8_0) )
throwf("embedded dylibs/frameworks are only supported on iOS 8.0 and later (%s)", depInstallName);
}
}
if ( _options.sharedRegionEligible() && !_options.debugVariant() ) {
assert(depInstallName != NULL);
if ( depInstallName[0] == '@' ) {
warning("invalid -install_name (%s) in dependent dylib (%s). Dylibs/frameworks which might go in dyld shared cache "
"cannot link with dylib that uses @rpath, @loader_path, etc.", depInstallName, dylibFile->path());
}
else if ( !_options.sharedCacheEligiblePath(depInstallName) ) {
warning("invalid -install_name (%s) in dependent dylib (%s). Dylibs/frameworks which might go in dyld shared cache "
"cannot link with dylibs that won't be in the shared cache", depInstallName, dylibFile->path());
}
}
}
}
void Resolver::doAtom(const ld::Atom& atom)
{
//fprintf(stderr, "Resolver::doAtom(%p), name=%s, sect=%s, scope=%d\n", &atom, atom.name(), atom.section().sectionName(), atom.scope());
if ( _ltoCodeGenFinished && (atom.contentType() == ld::Atom::typeLTOtemporary) && (atom.scope() != ld::Atom::scopeTranslationUnit) )
warning("'%s' is implemented in bitcode, but it was loaded too late", atom.name());
// add to list of known atoms
_atoms.push_back(&atom);
// adjust scope
if ( _options.hasExportRestrictList() || _options.hasReExportList() ) {
const char* name = atom.name();
switch ( atom.scope() ) {
case ld::Atom::scopeTranslationUnit:
break;
case ld::Atom::scopeLinkageUnit:
if ( _options.hasExportMaskList() && _options.shouldExport(name) ) {
// <rdar://problem/5062685> ld does not report error when -r is used and exported symbols are not defined.
if ( _options.outputKind() == Options::kObjectFile )
throwf("cannot export hidden symbol %s", name);
// .objc_class_name_* symbols are special
if ( atom.section().type() != ld::Section::typeObjC1Classes ) {
if ( atom.definition() == ld::Atom::definitionProxy ) {
// .exp file says to export a symbol, but that symbol is in some dylib being linked
if ( _options.canReExportSymbols() ) {
// marking proxy atom as global triggers the re-export
(const_cast<ld::Atom*>(&atom))->setScope(ld::Atom::scopeGlobal);
}
else if ( _options.outputKind() == Options::kDynamicLibrary ) {
if ( atom.file() != NULL )
warning("target OS does not support re-exporting symbol %s from %s\n", _options.demangleSymbol(name), atom.safeFilePath());
else
warning("target OS does not support re-exporting symbol %s\n", _options.demangleSymbol(name));
}
}
else {
if ( atom.file() != NULL )
warning("cannot export hidden symbol %s from %s", _options.demangleSymbol(name), atom.safeFilePath());
else
warning("cannot export hidden symbol %s", _options.demangleSymbol(name));
}
}
}
else if ( _options.shouldReExport(name) && _options.canReExportSymbols() ) {
if ( atom.definition() == ld::Atom::definitionProxy ) {
// marking proxy atom as global triggers the re-export
(const_cast<ld::Atom*>(&atom))->setScope(ld::Atom::scopeGlobal);
}
else {
throwf("requested re-export symbol %s is not from a dylib, but from %s\n", _options.demangleSymbol(name), atom.safeFilePath());
}
}
break;
case ld::Atom::scopeGlobal:
// check for globals that are downgraded to hidden
if ( ! _options.shouldExport(name) ) {
(const_cast<ld::Atom*>(&atom))->setScope(ld::Atom::scopeLinkageUnit);
//fprintf(stderr, "demote %s to hidden\n", name);
}
if ( _options.canReExportSymbols() && _options.shouldReExport(name) && (atom.definition() != ld::Atom::definitionProxy) ) {
throwf("requested re-export symbol %s is not from a dylib, but from %s\n", _options.demangleSymbol(name), atom.safeFilePath());
}
break;
}
}
// work around for kernel that uses 'l' labels in assembly code
if ( (atom.symbolTableInclusion() == ld::Atom::symbolTableNotInFinalLinkedImages)
&& (atom.name()[0] == 'l') && (_options.outputKind() == Options::kStaticExecutable)
&& (strncmp(atom.name(), "ltmp", 4) != 0) )
(const_cast<ld::Atom*>(&atom))->setSymbolTableInclusion(ld::Atom::symbolTableIn);
// tell symbol table about non-static atoms
if ( atom.scope() != ld::Atom::scopeTranslationUnit ) {
Options::Treatment duplicates = Options::Treatment::kError;
if (_options.deadCodeStrip() ) {
if ( _options.allowDeadDuplicates() )
duplicates = Options::Treatment::kSuppress;
else if ( _completedInitialObjectFiles )
duplicates = Options::Treatment::kWarning;
}
_symbolTable.add(atom, duplicates);
// add symbol aliases defined on the command line
if ( _options.haveCmdLineAliases() ) {
const std::vector<Options::AliasPair>& aliases = _options.cmdLineAliases();
for (std::vector<Options::AliasPair>::const_iterator it=aliases.begin(); it != aliases.end(); ++it) {
if ( strcmp(it->realName, atom.name()) == 0 ) {
if ( strcmp(it->realName, it->alias) == 0 ) {
warning("ignoring alias of itself '%s'", it->realName);
}
else {
const AliasAtom* alias = new AliasAtom(atom, it->alias);
_aliasesFromCmdLine.push_back(alias);
this->doAtom(*alias);
}
}
}
}
}
// convert references by-name or by-content to by-slot
this->convertReferencesToIndirect(atom);
// remember if any atoms are proxies that require LTO
if ( atom.contentType() == ld::Atom::typeLTOtemporary )
_haveLLVMObjs = true;
// remember if any atoms are aliases
if ( atom.section().type() == ld::Section::typeTempAlias )
_haveAliases = true;
// error or warn about initializers
if ( (atom.section().type() == ld::Section::typeInitializerPointers) && !_havellvmProfiling ) {
switch ( _options.initializersTreatment() ) {
case Options::kError:
throwf("static initializer found in '%s'",atom.safeFilePath());
case Options::kWarning:
warning("static initializer found in '%s'. Use -no_inits to make this an error. Use -no_warn_inits to suppress warning",atom.safeFilePath());
break;
default:
break;
}
}
if ( _options.deadCodeStrip() ) {
// add to set of dead-strip-roots, all symbols that the compiler marks as don't strip
if ( atom.dontDeadStrip() )
_deadStripRoots.insert(&atom);
else if ( atom.dontDeadStripIfReferencesLive() )
_dontDeadStripIfReferencesLive.push_back(&atom);
if ( atom.scope() == ld::Atom::scopeGlobal ) {
// <rdar://problem/5524973> -exported_symbols_list that has wildcards and -dead_strip
// in dylibs, every global atom in initial .o files is a root
if ( _options.hasWildCardExportRestrictList() || _options.allGlobalsAreDeadStripRoots() ) {
if ( _options.shouldExport(atom.name()) )
_deadStripRoots.insert(&atom);
}
}
}
}
bool Resolver::isDtraceProbe(ld::Fixup::Kind kind)
{
switch (kind) {
case ld::Fixup::kindStoreX86DtraceCallSiteNop:
case ld::Fixup::kindStoreX86DtraceIsEnableSiteClear:
case ld::Fixup::kindStoreARMDtraceCallSiteNop:
case ld::Fixup::kindStoreARMDtraceIsEnableSiteClear:
case ld::Fixup::kindStoreARM64DtraceCallSiteNop:
case ld::Fixup::kindStoreARM64DtraceIsEnableSiteClear:
case ld::Fixup::kindStoreThumbDtraceCallSiteNop:
case ld::Fixup::kindStoreThumbDtraceIsEnableSiteClear:
case ld::Fixup::kindDtraceExtra:
return true;
default:
break;
}
return false;
}
void Resolver::convertReferencesToIndirect(const ld::Atom& atom)
{
// convert references by-name or by-content to by-slot
SymbolTable::IndirectBindingSlot slot;
const ld::Atom* dummy;
ld::Fixup::iterator end = atom.fixupsEnd();
for (ld::Fixup::iterator fit=atom.fixupsBegin(); fit != end; ++fit) {
if ( fit->kind == ld::Fixup::kindLinkerOptimizationHint )
_internal.someObjectHasOptimizationHints = true;
switch ( fit->binding ) {
case ld::Fixup::bindingByNameUnbound:
if ( isDtraceProbe(fit->kind) && (_options.outputKind() != Options::kObjectFile ) ) {
// in final linked images, remove reference
fit->binding = ld::Fixup::bindingNone;
}
else {
slot = _symbolTable.findSlotForName(fit->u.name);
fit->binding = ld::Fixup::bindingsIndirectlyBound;
fit->u.bindingIndex = slot;
}
break;
case ld::Fixup::bindingByContentBound:
switch ( fit->u.target->combine() ) {
case ld::Atom::combineNever:
case ld::Atom::combineByName:
assert(0 && "wrong combine type for bind by content");
break;
case ld::Atom::combineByNameAndContent:
slot = _symbolTable.findSlotForContent(fit->u.target, &dummy);
fit->binding = ld::Fixup::bindingsIndirectlyBound;
fit->u.bindingIndex = slot;
break;
case ld::Atom::combineByNameAndReferences:
slot = _symbolTable.findSlotForReferences(fit->u.target, &dummy);
fit->binding = ld::Fixup::bindingsIndirectlyBound;
fit->u.bindingIndex = slot;
break;
}
break;
case ld::Fixup::bindingNone:
case ld::Fixup::bindingDirectlyBound:
case ld::Fixup::bindingsIndirectlyBound:
break;
}
}
}
void Resolver::addInitialUndefines()
{
// add initial undefines from -u option
for (Options::UndefinesIterator it=_options.initialUndefinesBegin(); it != _options.initialUndefinesEnd(); ++it) {
_symbolTable.findSlotForName(*it);
}
}
void Resolver::resolveUndefines()
{
// keep looping until no more undefines were added in last loop
unsigned int undefineGenCount = 0xFFFFFFFF;
while ( undefineGenCount != _symbolTable.updateCount() ) {
undefineGenCount = _symbolTable.updateCount();
std::vector<const char*> undefineNames;
_symbolTable.undefines(undefineNames);
for(std::vector<const char*>::iterator it = undefineNames.begin(); it != undefineNames.end(); ++it) {
const char* undef = *it;
// load for previous undefine may also have loaded this undefine, so check again
if ( ! _symbolTable.hasName(undef) ) {
_inputFiles.searchLibraries(undef, true, true, false, *this);
if ( !_symbolTable.hasName(undef) && (_options.outputKind() != Options::kObjectFile) ) {
if ( strncmp(undef, "section$", 8) == 0 ) {
if ( strncmp(undef, "section$start$", 14) == 0 ) {
this->doAtom(*SectionBoundaryAtom::makeSectionBoundaryAtom(undef, true, &undef[14], _options));
}
else if ( strncmp(undef, "section$end$", 12) == 0 ) {
this->doAtom(*SectionBoundaryAtom::makeSectionBoundaryAtom(undef, false, &undef[12], _options));
}
}
else if ( strncmp(undef, "segment$", 8) == 0 ) {
if ( strncmp(undef, "segment$start$", 14) == 0 ) {
this->doAtom(*SegmentBoundaryAtom::makeSegmentBoundaryAtom(undef, true, &undef[14]));
}
else if ( strncmp(undef, "segment$end$", 12) == 0 ) {
this->doAtom(*SegmentBoundaryAtom::makeSegmentBoundaryAtom(undef, false, &undef[12]));
}
}
else if ( _options.outputKind() == Options::kPreload ) {
// for iBoot grandfather in old style section labels
int undefLen = strlen(undef);
if ( strcmp(&undef[undefLen-7], "__begin") == 0 ) {
if ( undefLen > 13 )
this->doAtom(*SectionBoundaryAtom::makeOldSectionBoundaryAtom(undef, true));
else
this->doAtom(*SegmentBoundaryAtom::makeOldSegmentBoundaryAtom(undef, true));
}
else if ( strcmp(&undef[undefLen-5], "__end") == 0 ) {
if ( undefLen > 11 )
this->doAtom(*SectionBoundaryAtom::makeOldSectionBoundaryAtom(undef, false));
else
this->doAtom(*SegmentBoundaryAtom::makeOldSegmentBoundaryAtom(undef, false));
}
}
}
}
}
// <rdar://problem/5894163> need to search archives for overrides of common symbols
if ( _symbolTable.hasExternalTentativeDefinitions() ) {
bool searchDylibs = (_options.commonsMode() == Options::kCommonsOverriddenByDylibs);
std::vector<const char*> tents;
_symbolTable.tentativeDefs(tents);
for(std::vector<const char*>::iterator it = tents.begin(); it != tents.end(); ++it) {
// load for previous tentative may also have loaded this tentative, so check again
const ld::Atom* curAtom = _symbolTable.atomForSlot(_symbolTable.findSlotForName(*it));
assert(curAtom != NULL);
if ( curAtom->definition() == ld::Atom::definitionTentative ) {
_inputFiles.searchLibraries(*it, searchDylibs, true, true, *this);
}
}
}
}
// Use linker options to resolve any remaining undefined symbols
if ( !_internal.linkerOptionLibraries.empty() || !_internal.linkerOptionFrameworks.empty() ) {
std::vector<const char*> undefineNames;
_symbolTable.undefines(undefineNames);
if ( undefineNames.size() != 0 ) {
for (std::vector<const char*>::iterator it = undefineNames.begin(); it != undefineNames.end(); ++it) {
const char* undef = *it;
if ( ! _symbolTable.hasName(undef) ) {
_inputFiles.searchLibraries(undef, true, true, false, *this);
}
}
}
}
// create proxies as needed for undefined symbols
if ( (_options.undefinedTreatment() != Options::kUndefinedError) || (_options.outputKind() == Options::kObjectFile) ) {
std::vector<const char*> undefineNames;
_symbolTable.undefines(undefineNames);
for(std::vector<const char*>::iterator it = undefineNames.begin(); it != undefineNames.end(); ++it) {
const char* undefName = *it;
// <rdar://problem/14547001> "ld -r -exported_symbol _foo" has wrong error message if _foo is undefined
bool makeProxy = true;
if ( (_options.outputKind() == Options::kObjectFile) && _options.hasExportMaskList() && _options.shouldExport(undefName) )
makeProxy = false;
if ( makeProxy )
this->doAtom(*new UndefinedProxyAtom(undefName));
}
}
// support -U option
if ( _options.someAllowedUndefines() ) {
std::vector<const char*> undefineNames;
_symbolTable.undefines(undefineNames);
for(std::vector<const char*>::iterator it = undefineNames.begin(); it != undefineNames.end(); ++it) {
if ( _options.allowedUndefined(*it) ) {