-
Notifications
You must be signed in to change notification settings - Fork 167
/
Options.cpp
7033 lines (6557 loc) · 228 KB
/
Options.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) 2005-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 <ctype.h> // ld64-port
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <mach/vm_prot.h>
#ifdef __APPLE__ // ld64-port
#include <sys/sysctl.h>
#endif
#include <mach-o/dyld.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#ifndef __ANDROID__ // ld64-port
#include <spawn.h>
#endif
#include <cxxabi.h>
#include <Availability.h>
#ifdef TAPI_SUPPORT
#include <tapi/tapi.h>
#endif /* TAPI_SUPPORT */
#include <vector>
#include <map>
#include <sstream>
#include "ld.hpp"
#include "Options.h"
#include "Architectures.hpp"
#include "MachOFileAbstraction.hpp"
#include "Snapshot.h"
#include "macho_relocatable_file.h"
#include "ResponseFiles.h"
// from FunctionNameDemangle.h
extern "C" size_t fnd_get_demangled_name(const char *mangledName, char *outputBuffer, size_t length);
#define VAL(x) #x
#define STRINGIFY(x) VAL(x)
// upward dependency on lto::version()
namespace lto {
extern const char* version();
extern unsigned static_api_version();
extern unsigned runtime_api_version();
}
// magic to place command line in crash reports
const int crashreporterBufferSize = 2000;
static char crashreporterBuffer[crashreporterBufferSize];
#if defined(__has_include) && __has_include(<CrashReporterClient.h>) // ld64-port
#define HAVE_CRASHREPORTER_HEADER 1
#else
#define HAVE_CRASHREPORTER_HEADER 0
#endif
#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 && HAVE_CRASHREPORTER_HEADER
#include <CrashReporterClient.h>
// hack until ld does not need to build on 10.6 anymore
struct crashreporter_annotations_t gCRAnnotations
__attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION)))
= { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0 };
#else
extern "C" char* __crashreporter_info__;
__attribute__((used))
char* __crashreporter_info__ = crashreporterBuffer;
#endif
static bool sEmitWarnings = true;
static bool sFatalWarnings = false;
static const char* sWarningsSideFilePath = NULL;
static FILE* sWarningsSideFile = NULL;
static int sWarningsCount = 0;
void warning(const char* format, ...)
{
++sWarningsCount;
if ( sEmitWarnings ) {
va_list list;
if ( sWarningsSideFilePath != NULL ) {
if ( sWarningsSideFile == NULL )
sWarningsSideFile = fopen(sWarningsSideFilePath, "a");
}
va_start(list, format);
fprintf(stderr, "ld: warning: ");
vfprintf(stderr, format, list);
fprintf(stderr, "\n");
if ( sWarningsSideFile != NULL ) {
fprintf(sWarningsSideFile, "ld: warning: ");
vfprintf(sWarningsSideFile, format, list);
fprintf(sWarningsSideFile, "\n");
fflush(sWarningsSideFile);
}
va_end(list);
}
}
void throwf(const char* format, ...)
{
va_list list;
char* p;
va_start(list, format);
vasprintf(&p, format, list);
va_end(list);
const char* t = p;
throw t;
}
std::vector<std::string> Options::FileInfo::lib_cli_argument() const
{
// fIndirectDylib unused
bool special = options.fReExport || options.fUpward;
if (options.fBundleLoader) {
if (special) throw "internal error; bundle loader cannot have these extra attributes";
return {"-bundle-loader", path};
} else {
std::vector<std::string> args = {};
if (options.fReExport) {
args.push_back("-reexport_library");
args.push_back(path);
}
else if (options.fUpward) {
args.push_back("-upward_library");
args.push_back(path);
}
else {
// bare path
args.push_back(path);
}
// This one alone can be combined with the others
if (options.fWeakImport) {
args.push_back("-weak_library");
args.push_back(path);
}
return args;
}
}
bool Options::FileInfo::checkFileExists(const Options& options, const char *p)
{
if (isInlined) {
modTime = 0;
return true;
}
struct stat statBuffer;
if (p == NULL)
p = path;
if ( stat(p, &statBuffer) == 0 ) {
if (p != path) path = strdup(p);
modTime = statBuffer.st_mtime;
return true;
}
options.addDependency(Options::depNotFound, p);
// fprintf(stderr, "not found: %s\n", p);
return false;
}
Options::Options(int argc, const char* argv[])
: fOutputFile("a.out"), fArchitecture(0), fSubArchitecture(0),
fFallbackArchitecture(0), fFallbackSubArchitecture(0), fArchitectureName("unknown"), fOutputKind(kDynamicExecutable),
fHasPreferredSubType(false), fArchThumb2Support(Thumb2Support::none), fBindAtLoad(false), fKeepPrivateExterns(false),
fIgnoreOtherArchFiles(false), fErrorOnOtherArchFiles(false), fForceSubtypeAll(false),
fInterposeMode(kInterposeNone), fDeadStrip(false), fNameSpace(kTwoLevelNameSpace),
fDylibCompatVersion(0), fDylibCurrentVersion(0), fDylibInstallName(NULL), fFinalName(NULL), fEntryName(NULL),
fBaseAddress(0), fMaxAddress(0xFFFFFFFFFFFFFFFFULL),
fBaseWritableAddress(0),
fExportMode(kExportDefault), fLibrarySearchMode(kSearchDylibAndArchiveInEachDir),
fUndefinedTreatment(kUndefinedError), fMessagesPrefixedWithArchitecture(true),
fWeakReferenceMismatchTreatment(kWeakReferenceMismatchNonWeak),
fClientName(NULL),
fUmbrellaName(NULL), fInitFunctionName(NULL), fDotOutputFile(NULL), fExecutablePath(NULL),
fBundleLoader(NULL), fDtraceScriptName(NULL), fMapPath(NULL),
fDyldInstallPath("/usr/lib/dyld"), fLtoCachePath(NULL), fTempLtoObjectPath(NULL), fOverridePathlibLTO(NULL), fLtoCpu(NULL),
fKextObjectsEnable(-1),fKextObjectsDirPath(NULL),fToolchainPath(NULL),fOrderFilePath(NULL),
fZeroPageSize(ULLONG_MAX), fStackSize(0), fStackAddr(0), fSourceVersion(0), fSDKVersion(0), fExecutableStack(false),
fNonExecutableHeap(false), fDisableNonExecutableHeap(false),
fMinimumHeaderPad(32), fSegmentAlignment(LD_PAGE_SIZE), fForceAlignment(false),
fCommonsMode(kCommonsIgnoreDylibs), fUUIDMode(kUUIDContent), fLocalSymbolHandling(kLocalSymbolsAll), fWarnCommons(false),
fVerbose(false), fKeepRelocations(false), fWarnStabs(false),
fTraceDylibSearching(false), fPause(false), fStatistics(false), fPrintOptions(false),
fSharedRegionEligible(false), fSharedRegionEligibleForceOff(false), fPrintOrderFileStatistics(false),
fReadOnlyx86Stubs(false), fPositionIndependentExecutable(false), fPIEOnCommandLine(false),
fDisablePositionIndependentExecutable(false), fMaxMinimumHeaderPad(false),
fDeadStripDylibs(false), fAllowTextRelocs(false), fWarnTextRelocs(false), fKextsUseStubs(false),
fEncryptable(true), fEncryptableForceOn(false), fEncryptableForceOff(false),
fMarkDeadStrippableDylib(false),
fMakeCompressedDyldInfo(true), fMakeCompressedDyldInfoForceOff(false),
fMakeThreadedStartsSection(false), fNoEHLabels(false),
fAllowCpuSubtypeMismatches(false), fAllowCpuSubtypeMismatchesForceOn(false), fEnforceDylibSubtypesMatch(false),
fWarnOnSwiftABIVersionMismatches(false), fUseSimplifiedDylibReExports(false),
fObjCABIVersion2Override(false), fObjCABIVersion1Override(false), fCanUseUpwardDylib(false),
fFullyLoadArchives(false), fLoadAllObjcObjectsFromArchives(false), fFlatNamespace(false),
fLinkingMainExecutable(false), fForFinalLinkedImage(false), fForStatic(false),
fForDyld(false), fMakeTentativeDefinitionsReal(false), fWhyLoad(false), fRootSafe(false),
fSetuidSafe(false), fSearchInSparseFrameworks(false), fImplicitlyLinkPublicDylibs(true), fAddCompactUnwindEncoding(true),
fWarnCompactUnwind(false), fRemoveDwarfUnwindIfCompactExists(false),
fAutoOrderInitializers(true), fOptimizeZeroFill(true), fMergeZeroFill(false),
fLogAllFiles(false), fTraceDylibs(false), fTraceIndirectDylibs(false), fTraceArchives(false), fTraceEmitJSON(false),
fOutputSlidable(false), fWarnWeakExports(false), fNoWeakExports(false),
fObjcGcCompaction(false), fObjCGc(false), fObjCGcOnly(false),
fDemangle(false), fTLVSupport(false),
fVersionLoadCommand(false), fVersionLoadCommandForcedOn(false),
fVersionLoadCommandForcedOff(false), fForceLegacyVersionLoadCommands(false), fFunctionStartsLoadCommand(false),
fFunctionStartsForcedOn(false), fFunctionStartsForcedOff(false),
fDataInCodeInfoLoadCommand(false), fDataInCodeInfoLoadCommandForcedOn(false), fDataInCodeInfoLoadCommandForcedOff(false),
fCanReExportSymbols(false), fObjcCategoryMerging(true), fPageAlignDataAtoms(false),
fNeedsThreadLoadCommand(false), fEntryPointLoadCommand(false),
fSourceVersionLoadCommand(false),
fSourceVersionLoadCommandForceOn(false), fSourceVersionLoadCommandForceOff(false),
fExportDynamic(false), fAbsoluteSymbols(false),
fAllowSimulatorToLinkWithMacOSX(false), fSimulatorSupportDylib(false), fKeepDwarfUnwind(true),
fKeepDwarfUnwindForcedOn(false), fKeepDwarfUnwindForcedOff(false),
fVerboseOptimizationHints(false), fIgnoreOptimizationHints(false),
fGenerateDtraceDOF(true), fAllowBranchIslands(true), fTraceSymbolLayout(false),
fMarkAppExtensionSafe(false), fCheckAppExtensionSafe(false), fForceLoadSwiftLibs(false),
fSharedRegionEncodingV2(false), fUseDataConstSegment(false),
fUseDataConstSegmentForceOn(false), fUseDataConstSegmentForceOff(false), fUseTextExecSegment(false),
fBundleBitcode(false), fHideSymbols(false), fVerifyBitcode(false),
fReverseMapUUIDRename(false), fDeDupe(true), fVerboseDeDupe(false), fMakeInitializersIntoOffsets(false),
fUseLinkedListBinding(false), fMakeChainedFixupsForceOn(false), fMakeChainedFixupsForceOff(false), fMakeChainedFixups(false),
fMakeChainedFixupsSection(false), fNoLazyBinding(false), fDebugVariant(false),
fReverseMapPath(NULL), fLTOCodegenOnly(false),
fIgnoreAutoLink(false), fAllowDeadDups(false), fAllowWeakImports(true), fInitializersTreatment(Options::kInvalid),
fZeroModTimeInDebugMap(false), fBitcodeKind(kBitcodeProcess),
fDebugInfoStripping(kDebugInfoMinimal), fTraceOutputFile(NULL), fPlatfromVersionCmdFound(false), fInternalSDK(false),
fWarnUnusedDylibs(false), fWarnUnusedDylibsForceOn(false), fWarnUnusedDylibsForceOff(false),
fAdHocSign(false), fAdHocSignForceOn(false), fAdHocSignForceOff(false),
fPlatformMismatchesAreWarning(false),
fForceObjCRelativeMethodListsOn(false), fForceObjCRelativeMethodListsOff(false), fUseObjCRelativeMethodLists(false),
fSaveTempFiles(false), fLinkSnapshot(this), fSnapshotRequested(false), fPipelineFifo(NULL),
fDependencyInfoPath(NULL), fBuildContextName(NULL), fTraceFileDescriptor(-1), fMaxDefaultCommonAlign(0),
fUnalignedPointerTreatment(kUnalignedPointerIgnore),
#ifdef TAPI_SUPPORT // ld64-port
fPreferTAPIFile(false),
#endif
fOSOPrefixPath(NULL), fImageSuffix(NULL)
{
this->expandResponseFiles(argc, argv);
this->checkForClassic(argc, argv);
this->parsePreCommandLineEnvironmentSettings();
this->parse(argc, argv);
this->parsePostCommandLineEnvironmentSettings();
this->reconfigureDefaults();
this->checkIllegalOptionCombinations();
this->addDependency(depOutputFile, fOutputFile);
if ( fMapPath != NULL )
this->addDependency(depOutputFile, fMapPath);
}
Options::~Options()
{
if ( fTraceFileDescriptor != -1 )
::close(fTraceFileDescriptor);
}
bool Options::errorBecauseOfWarnings() const
{
return (sFatalWarnings && (sWarningsCount > 0));
}
const char* Options::installPath() const
{
if ( fDylibInstallName != NULL )
return fDylibInstallName;
else if ( fFinalName != NULL )
return fFinalName;
else
return fOutputFile;
}
bool Options::interposable(const char* name) const
{
switch ( fInterposeMode ) {
case kInterposeNone:
return false;
case kInterposeAllExternal:
return true;
case kInterposeSome:
return fInterposeList.contains(name);
}
throw "internal error";
}
bool Options::printWhyLive(const char* symbolName) const
{
return fWhyLive.contains(symbolName);
}
const char* Options::dotOutputFile()
{
return fDotOutputFile;
}
bool Options::hasWildCardExportRestrictList() const
{
// has -exported_symbols_list which contains some wildcards
return ((fExportMode == kExportSome) && fExportSymbols.hasWildCards());
}
bool Options::hasWeakBitTweaks() const
{
// has -exported_symbols_list which contains some wildcards
return (!fForceWeakSymbols.empty() || !fForceNotWeakSymbols.empty());
}
bool Options::allGlobalsAreDeadStripRoots() const
{
// -exported_symbols_list means globals are not exported by default
if ( fExportMode == kExportSome )
return false;
//
switch ( fOutputKind ) {
case Options::kDynamicExecutable:
// <rdar://problem/12839986> Add the -export_dynamic flag
return fExportDynamic;
case Options::kStaticExecutable:
// <rdar://problem/13361218> Support the -export_dynamic flag for xnu
return fExportDynamic;
case Options::kPreload:
// by default unused globals in a main executable are stripped
return false;
case Options::kDynamicLibrary:
case Options::kDynamicBundle:
case Options::kObjectFile:
case Options::kDyld:
case Options::kKextBundle:
return true;
}
return false;
}
bool Options::dyldLoadsOutput() const
{
switch ( fOutputKind ) {
case Options::kStaticExecutable:
case Options::kPreload:
case Options::kObjectFile:
case Options::kKextBundle:
return false;
case Options::kDynamicExecutable:
case Options::kDynamicLibrary:
case Options::kDynamicBundle:
case Options::kDyld:
return true;
}
}
bool Options::dyldOrKernelLoadsOutput() const
{
switch ( fOutputKind ) {
case Options::kStaticExecutable:
return fKernel;
case Options::kPreload:
case Options::kObjectFile:
return false;
case Options::kDynamicExecutable:
case Options::kDynamicLibrary:
case Options::kDynamicBundle:
case Options::kDyld:
case Options::kKextBundle:
return true;
}
}
bool Options::keepRelocations()
{
return fKeepRelocations;
}
bool Options::warnStabs()
{
return fWarnStabs;
}
const char* Options::executablePath()
{
return fExecutablePath;
}
uint32_t Options::initialSegProtection(const char* segName) const
{
for(std::vector<Options::SegmentProtect>::const_iterator it = fCustomSegmentProtections.begin(); it != fCustomSegmentProtections.end(); ++it) {
if ( strcmp(it->name, segName) == 0 ) {
return it->init;
}
}
if ( strcmp(segName, "__TEXT") == 0 ) {
return ( fUseTextExecSegment ? VM_PROT_READ : (VM_PROT_READ | VM_PROT_EXECUTE) );
}
else if ( strcmp(segName, "__TEXT_EXEC") == 0 ) {
return VM_PROT_READ | VM_PROT_EXECUTE;
}
else if ( strcmp(segName, "__PAGEZERO") == 0 ) {
return 0;
}
else if ( strcmp(segName, "__LINKEDIT") == 0 ) {
return VM_PROT_READ;
}
// all others default to read-write
return VM_PROT_READ | VM_PROT_WRITE;
}
bool Options::readOnlyDataSegment(const char* name) const
{
// set SG_READ_ONLY on segment
// but not for shared cache dylibs (because __objc_const is not read-only)
return ( fUseDataConstSegment && (strcmp(name, "__DATA_CONST") == 0) && (!fSharedRegionEligible || (fOutputKind == Options::kDyld)) );
}
uint32_t Options::maxSegProtection(const char* segName) const
{
// allow macOS binaries to set alternate max-prot
if ( fArchitecture == CPU_TYPE_X86_64 ) {
for (const Options::SegmentProtect& info : fCustomSegmentProtections) {
if ( strcmp(info.name, segName) == 0 ) {
return info.max;
}
}
}
// i386 uses text-relocations so, need max prot to be rwx. All others have max==init
if ( fArchitecture != CPU_TYPE_I386 )
return initialSegProtection(segName);
if ( strcmp(segName, "__PAGEZERO") == 0 ) {
return 0;
}
// all others default to all
return VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
}
uint64_t Options::segPageSize(const char* segName) const
{
for(std::vector<SegmentSize>::const_iterator it=fCustomSegmentSizes.begin(); it != fCustomSegmentSizes.end(); ++it) {
if ( strcmp(it->name, segName) == 0 )
return it->size;
}
return fSegmentAlignment;
}
uint64_t Options::customSegmentAddress(const char* segName) const
{
for(std::vector<SegmentStart>::const_iterator it=fCustomSegmentAddresses.begin(); it != fCustomSegmentAddresses.end(); ++it) {
if ( strcmp(it->name, segName) == 0 )
return it->address;
}
// if custom stack in use, model as segment with custom address
if ( (fStackSize != 0) && (strcmp("__UNIXSTACK", segName) == 0) )
return fStackAddr - fStackSize;
return 0;
}
bool Options::hasCustomSegmentAddress(const char* segName) const
{
for(std::vector<SegmentStart>::const_iterator it=fCustomSegmentAddresses.begin(); it != fCustomSegmentAddresses.end(); ++it) {
if ( strcmp(it->name, segName) == 0 )
return true;
}
// if custom stack in use, model as segment with custom address
if ( (fStackSize != 0) && (strcmp("__UNIXSTACK", segName) == 0) )
return true;
return false;
}
bool Options::hasCustomSectionAlignment(const char* segName, const char* sectName) const
{
for (std::vector<SectionAlignment>::const_iterator it = fSectionAlignments.begin(); it != fSectionAlignments.end(); ++it) {
if ( (strcmp(it->segmentName, segName) == 0) && (strcmp(it->sectionName, sectName) == 0) )
return true;
}
if ( fEncryptable && (strcmp(sectName, "__oslogstring") == 0) && (strcmp(segName, "__TEXT") == 0) )
return true;
return false;
}
uint8_t Options::customSectionAlignment(const char* segName, const char* sectName) const
{
for (std::vector<SectionAlignment>::const_iterator it = fSectionAlignments.begin(); it != fSectionAlignments.end(); ++it) {
if ( (strcmp(it->segmentName, segName) == 0) && (strcmp(it->sectionName, sectName) == 0) )
return it->alignment;
}
if ( fEncryptable && (strcmp(sectName, "__oslogstring") == 0) && (strcmp(segName, "__TEXT") == 0) )
return __builtin_ctz(fSegmentAlignment);
return 0;
}
bool Options::segmentOrderAfterFixedAddressSegment(const char* segName) const
{
bool nowPinned = false;
for (std::vector<const char*>::const_iterator it=fSegmentOrder.begin(); it != fSegmentOrder.end(); ++it) {
if ( strcmp(*it, segName) == 0 )
return nowPinned;
if ( hasCustomSegmentAddress(*it) )
nowPinned = true;
}
return false;
}
bool Options::hasExportedSymbolOrder()
{
return (fExportSymbolsOrder.size() > 0);
}
bool Options::exportedSymbolOrder(const char* sym, unsigned int* order) const
{
NameToOrder::const_iterator pos = fExportSymbolsOrder.find(sym);
if ( pos != fExportSymbolsOrder.end() ) {
*order = pos->second;
return true;
}
else {
*order = 0xFFFFFFFF;
return false;
}
}
void Options::loadSymbolOrderFile(const char* fileOfExports, NameToOrder& orderMapping)
{
// read in whole file
int fd = ::open(fileOfExports, O_RDONLY, 0);
if ( fd == -1 )
throwf("can't open -exported_symbols_order file: %s", fileOfExports);
struct stat stat_buf;
::fstat(fd, &stat_buf);
char* p = (char*)malloc(stat_buf.st_size);
if ( p == NULL )
throwf("can't process -exported_symbols_order file: %s", fileOfExports);
if ( read(fd, p, stat_buf.st_size) != stat_buf.st_size )
throwf("can't read -exported_symbols_order file: %s", fileOfExports);
::close(fd);
// parse into symbols and add to unordered_set
unsigned int count = 0;
char * const end = &p[stat_buf.st_size];
enum { lineStart, inSymbol, inComment } state = lineStart;
char* symbolStart = NULL;
for (char* s = p; s < end; ++s ) {
switch ( state ) {
case lineStart:
if ( *s =='#' ) {
state = inComment;
}
else if ( !isspace(*s) ) {
state = inSymbol;
symbolStart = s;
}
break;
case inSymbol:
if ( (*s == '\n') || (*s == '\r') ) {
*s = '\0';
// removing any trailing spaces
char* last = s-1;
while ( isspace(*last) ) {
*last = '\0';
--last;
}
orderMapping[symbolStart] = ++count;
symbolStart = NULL;
state = lineStart;
}
break;
case inComment:
if ( (*s == '\n') || (*s == '\r') )
state = lineStart;
break;
}
}
if ( state == inSymbol ) {
warning("missing line-end at end of file \"%s\"", fileOfExports);
int len = end-symbolStart+1;
char* temp = new char[len];
strlcpy(temp, symbolStart, len);
// remove any trailing spaces
char* last = &temp[len-2];
while ( isspace(*last) ) {
*last = '\0';
--last;
}
orderMapping[temp] = ++count;
}
// Note: we do not free() the malloc buffer, because the strings are used by the export-set hash table
}
void Options::loadImplictZipperFile(const char *path, std::vector<const char*>& paths)
{
// read in whole file
int fd = ::open(path, O_RDONLY, 0);
if ( fd == -1 ) return; // Early exist if the file is not present
struct stat stat_buf;
::fstat(fd, &stat_buf);
char* p = (char*)malloc(stat_buf.st_size);
if ( p == NULL )
throwf("can't process auto zipper file: %s", path);
if ( read(fd, p, stat_buf.st_size) != stat_buf.st_size )
throwf("can't process auto zipper file: %s", path);
::close(fd);
// parse into paths and add to a vector
char * const end = &p[stat_buf.st_size];
enum { lineStart, inInstallname, inComment } state = lineStart;
char* installnameStart = NULL;
for (char* s = p; s < end; ++s ) {
switch ( state ) {
case lineStart:
if ( *s =='#' ) {
state = inComment;
}
else if ( !isspace(*s) ) {
state = inInstallname;
installnameStart = s;
}
break;
case inInstallname:
if ( (*s == '\n') || (*s == '\r') ) {
*s = '\0';
// removing any trailing spaces
char* last = s-1;
while ( isspace(*last) ) {
*last = '\0';
--last;
}
paths.push_back(installnameStart);
state = lineStart;
}
break;
case inComment:
if ( (*s == '\n') || (*s == '\r') )
state = lineStart;
break;
}
}
if ( state == inInstallname ) {
warning("missing line-end at end of file \"%s\"", path);
int len = end-installnameStart+1;
char* temp = new char[len];
strlcpy(temp, installnameStart, len);
// remove any trailing spaces
char* last = &temp[len-2];
while ( isspace(*last) ) {
*last = '\0';
--last;
}
paths.push_back(installnameStart);
}
// Note: we do not free() the malloc buffer, because the strings are returned out via paths
}
bool Options::forceWeak(const char* symbolName) const
{
return fForceWeakSymbols.contains(symbolName);
}
bool Options::forceNotWeak(const char* symbolName) const
{
return fForceNotWeakSymbols.contains(symbolName);
}
bool Options::forceWeakNonWildCard(const char* symbolName) const
{
return fForceWeakSymbols.containsNonWildcard(symbolName);
}
bool Options::forceNotWeakNonWildcard(const char* symbolName) const
{
return fForceNotWeakSymbols.containsNonWildcard(symbolName);
}
bool Options::forceCoalesce(const char* symbolName) const
{
return fForceCoalesceSymbols.contains(symbolName);
}
bool Options::shouldExport(const char* symbolName) const
{
switch (fExportMode) {
case kExportSome:
return fExportSymbols.contains(symbolName);
case kDontExportSome:
return ! fDontExportSymbols.contains(symbolName);
case kExportDefault:
return true;
}
throw "internal error";
}
bool Options::shouldReExport(const char* symbolName) const
{
return fReExportSymbols.contains(symbolName);
}
bool Options::keepLocalSymbol(const char* symbolName) const
{
switch (fLocalSymbolHandling) {
case kLocalSymbolsAll:
return true;
case kLocalSymbolsNone:
return false;
case kLocalSymbolsSelectiveInclude:
return fLocalSymbolsIncluded.contains(symbolName);
case kLocalSymbolsSelectiveExclude:
return ! fLocalSymbolsExcluded.contains(symbolName);
}
throw "internal error";
}
const std::vector<const char*>* Options::sectionOrder(const char* segName) const
{
for (std::vector<SectionOrderList>::const_iterator it=fSectionOrder.begin(); it != fSectionOrder.end(); ++it) {
if ( strcmp(it->segmentName, segName) == 0 )
return &it->sectionOrder;
}
return NULL;
}
void Options::setInferredArch(cpu_type_t type, cpu_subtype_t subtype)
{
assert(fArchitecture == 0);
for (const ArchInfo* t=archInfoArray; t->archName != NULL; ++t) {
if ( (type == t->cpuType) && (subtype == t->cpuSubType) ) {
fArchitecture = type;
fSubArchitecture = subtype;
fArchitectureName = t->archName;
fHasPreferredSubType = t->isSubType;
fArchThumb2Support = t->thumb2Support;
#if SUPPORT_ARCH_arm64e
if ( (fArchitecture == CPU_TYPE_ARM64) && (fSubArchitecture == CPU_SUBTYPE_ARM64E) ) {
fSupportsAuthenticatedPointers = true;
}
#endif
break;
}
}
if ( fArchitecture == 0 ) {
// some arch not in our table
fArchitecture = type;
fSubArchitecture = subtype;
fArchitectureName = "unknown";
}
fLinkSnapshot.recordArch(fArchitectureName);
}
bool Options::armFirmwareVariant() const {
if ( fArchitecture != CPU_TYPE_ARM )
return false;
switch ( fSubArchitecture ) {
case CPU_SUBTYPE_ARM_V6M:
case CPU_SUBTYPE_ARM_V7M:
case CPU_SUBTYPE_ARM_V7EM:
return true;
default:
break;
}
return false;
}
bool Options::armUsesZeroCostExceptions() const
{
return ( (fArchitecture == CPU_TYPE_ARM) && (fSubArchitecture == CPU_SUBTYPE_ARM_V7K) );
}
void Options::selectFallbackArch(const char *arch)
{
// Should have the format "desired_arch:fallback_arch", for example "arm64_32:armv7k" to allow an armv7k
// slice to substitute for arm64_32 if the latter isn't present.
if (const char* fallbackEnv = getenv("LD_DYLIB_ARCH_FALLBACK") ) {
std::string fallback(fallbackEnv);
auto delimPos = fallback.find(':');
// Check we've got a potentially valid fallback string and that it's this architecture we're falling back from.
if ( delimPos == std::string::npos || fallback.substr(0, delimPos) != arch )
return;
std::string fallbackTo = fallback.substr(delimPos + 1);
for (const ArchInfo *t = archInfoArray; t->archName != nullptr; ++t) {
if ( fallbackTo == t->archName ) {
fFallbackArchitecture = t->cpuType;
fFallbackSubArchitecture = t->cpuSubType;
}
}
}
else {
// <rdar://problem/39797337> let x86_64h fallback and use x86_64 slice
if ( (fArchitecture == CPU_TYPE_X86_64) && (fSubArchitecture == CPU_SUBTYPE_X86_64_H) ) {
fFallbackArchitecture = CPU_TYPE_X86_64;
fFallbackSubArchitecture = CPU_SUBTYPE_X86_ALL;
}
}
}
void Options::parseArch(const char* arch)
{
if ( arch == NULL )
throw "-arch must be followed by an architecture string";
for (const ArchInfo* t=archInfoArray; t->archName != NULL; ++t) {
if ( strcmp(t->archName,arch) == 0 ) {
fArchitectureName = arch;
fArchitecture = t->cpuType;
fSubArchitecture = t->cpuSubType;
fHasPreferredSubType = t->isSubType;
fArchThumb2Support = t->thumb2Support;
selectFallbackArch(arch);
return;
}
}
throwf("unknown/unsupported architecture name for: -arch %s", arch);
}
static std::string addSuffix(const std::string &path, const std::string &suffix)
{
auto result = path;
auto lastSlashIdx = result.find_last_of('/');
auto lastDotIdx = result.find_last_of('.');
if ( lastDotIdx != std::string::npos && lastSlashIdx != std::string::npos && lastDotIdx > lastSlashIdx ) {
// /path/foo.dylib _debug => /path/foo_debug.dylib
result.insert(lastDotIdx, suffix);
} else if ( lastDotIdx != std::string::npos && lastSlashIdx == std::string::npos ) {
// foo.dylib _debug => foo_debug.dylib
result.insert(lastDotIdx, suffix);
} else {
// /path.foo/bar _debug => /path.foo/bar_debug
// /path/bar _debug => /path/bar_debug
result.append(suffix);
}
return result;
}
bool Options::checkForFileWithSuffix(const char* possiblePath, FileInfo& result) const
{
bool found = result.checkFileExists(*this, possiblePath);
if ( fTraceDylibSearching )
printf("[Logging for XBS]%sfound library: '%s'\n", (found ? " " : " not "), possiblePath);
return found;
}
bool Options::checkForFile(const char* format, const char* dir, const char* rootName, FileInfo& result) const
{
char possiblePath[strlen(dir)+strlen(rootName)+strlen(format)+8];
sprintf(possiblePath, format, dir, rootName);
if ( fImageSuffix != NULL ) {
auto possiblePathWithSuffix = addSuffix(possiblePath, fImageSuffix);
if ( checkForFileWithSuffix(possiblePathWithSuffix.c_str(), result) ) {
return true;
}
}
return checkForFileWithSuffix(possiblePath, result);
}
Options::FileInfo Options::findLibrary(const char* rootName, bool dylibsOnly) const
{
FileInfo result;
const int rootNameLen = strlen(rootName);
// if rootName ends in .o there is no .a vs .dylib choice
if ( (rootNameLen > 3) && (strcmp(&rootName[rootNameLen-2], ".o") == 0) ) {
for (std::vector<const char*>::const_iterator it = fLibrarySearchPaths.begin();
it != fLibrarySearchPaths.end();
it++) {
const char* dir = *it;
if ( checkForFile("%s/%s", dir, rootName, result) )
return result;
}
}
else {
bool lookForDylibs = false;
switch ( fOutputKind ) {
case Options::kDynamicExecutable:
case Options::kDynamicLibrary:
case Options::kDynamicBundle:
case Options::kObjectFile: // <rdar://problem/15914513>
lookForDylibs = true;
break;
case Options::kStaticExecutable:
case Options::kDyld:
case Options::kPreload:
case Options::kKextBundle:
lookForDylibs = false;
break;
}
switch ( fLibrarySearchMode ) {
case kSearchAllDirsForDylibsThenAllDirsForArchives:
// first look in all directories for just for dylibs
if ( lookForDylibs ) {
for (std::vector<const char*>::const_iterator it = fLibrarySearchPaths.begin();
it != fLibrarySearchPaths.end();
it++) {
const char* dir = *it;
auto path = std::string(dir) + "/lib" + rootName + ".dylib";
if ( findFile(path, {".tbd"}, result) )
return result;
}
for (std::vector<const char*>::const_iterator it = fLibrarySearchPaths.begin();
it != fLibrarySearchPaths.end();
it++) {
const char* dir = *it;
if ( checkForFile("%s/lib%s.so", dir, rootName, result) )
return result;
}
}
// next look in all directories for just for archives
if ( !dylibsOnly ) {
for (std::vector<const char*>::const_iterator it = fLibrarySearchPaths.begin();
it != fLibrarySearchPaths.end();
it++) {
const char* dir = *it;
if ( checkForFile("%s/lib%s.a", dir, rootName, result) )
return result;
}
}
break;
case kSearchDylibAndArchiveInEachDir:
// look in each directory for just for a dylib then for an archive
for (std::vector<const char*>::const_iterator it = fLibrarySearchPaths.begin();
it != fLibrarySearchPaths.end();
it++) {
const char* dir = *it;
auto path = std::string(dir) + "/lib" + rootName + ".dylib";
if ( lookForDylibs && findFile(path, {".tbd"}, result) )
return result;
if ( lookForDylibs && checkForFile("%s/lib%s.so", dir, rootName, result) )
return result;
if ( !dylibsOnly && checkForFile("%s/lib%s.a", dir, rootName, result) )
return result;
}
break;
}
}
throwf("library not found for -l%s", rootName);
}
Options::FileInfo Options::findFramework(const char* frameworkName) const
{
if ( frameworkName == NULL )
throw "-framework missing next argument";
char temp[strlen(frameworkName)+1];
strcpy(temp, frameworkName);
const char* name = temp;
const char* suffix = NULL;
char* comma = strchr(temp, ',');
if ( comma != NULL ) {
*comma = '\0';
suffix = &comma[1];
}
return findFramework(name, suffix);
}
Options::FileInfo Options::findFramework(const char* rootName, const char* suffix, bool useCurrentVersion) const
{
for (const auto* path : fFrameworkSearchPaths) {
auto possiblePath = std::string(path).append("/").append(rootName).append(".framework/");
if ( useCurrentVersion )