forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 41
/
objwriter.cpp
1277 lines (1118 loc) · 46 KB
/
objwriter.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
//===---- objwriter.cpp -----------------------------------------*- C++ -*-===//
//
// object writer
//
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Implementation of object writer API for JIT/AOT
///
//===----------------------------------------------------------------------===//
#include "objwriter.h"
#include "debugInfo/dwarf/dwarfTypeBuilder.h"
#include "debugInfo/codeView/codeViewTypeBuilder.h"
#include "cvconst.h"
#include "llvm/DebugInfo/CodeView/CodeView.h"
#include "llvm/DebugInfo/CodeView/Line.h"
#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCParser/AsmLexer.h"
#include "llvm/MC/MCParser/MCTargetAsmParser.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSectionCOFF.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/MC/MCObjectStreamer.h"
#include "llvm/MC/MCObjectWriter.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCTargetOptionsCommandFlags.h"
#include "llvm/MC/MCELFStreamer.h"
#include "llvm/MC/TargetRegistry.h"
#include "llvm/BinaryFormat/COFF.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compression.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/Win64EH.h"
#include "llvm/Target/TargetMachine.h"
#include "../../lib/Target/AArch64/MCTargetDesc/AArch64MCExpr.h"
using namespace llvm;
using namespace llvm::codeview;
bool error(const Twine &Error) {
errs() << Twine("error: ") + Error + "\n";
return false;
}
void ObjectWriter::InitTripleName(const char* tripleName) {
TripleName = tripleName != nullptr ? tripleName : sys::getDefaultTargetTriple();
}
bool ObjectWriter::Init(llvm::StringRef ObjectFilePath, const char* tripleName) {
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
// Initialize targets
InitializeAllTargetInfos();
InitializeAllTargetMCs();
InitTripleName(tripleName);
Triple TheTriple(TripleName);
// Get the target specific parser.
std::string TargetError;
const Target *TheTarget =
TargetRegistry::lookupTarget(TripleName, TargetError);
if (!TheTarget) {
return error("Unable to create target for " + ObjectFilePath + ": " +
TargetError);
}
std::error_code EC;
OS.reset(new raw_fd_ostream(ObjectFilePath, EC, sys::fs::OF_None));
if (EC)
return error("Unable to create file for " + ObjectFilePath + ": " +
EC.message());
RegisterInfo.reset(TheTarget->createMCRegInfo(TripleName));
if (!RegisterInfo)
return error("Unable to create target register info!");
AsmInfo.reset(TheTarget->createMCAsmInfo(*RegisterInfo, TripleName, TargetMOptions));
if (!AsmInfo)
return error("Unable to create target asm info!");
InstrInfo.reset(TheTarget->createMCInstrInfo());
if (!InstrInfo)
return error("no instr info info for target " + TripleName);
std::string FeaturesStr;
std::string MCPU;
SubtargetInfo.reset(
TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
if (!SubtargetInfo)
return error("no subtarget info for target " + TripleName);
OutContext.reset(
new MCContext(TheTriple, AsmInfo.get(), RegisterInfo.get(), SubtargetInfo.get()));
ObjFileInfo.reset(TheTarget->createMCObjectFileInfo(*OutContext, false));
OutContext->setObjectFileInfo(ObjFileInfo.get());
CodeEmitter =
TheTarget->createMCCodeEmitter(*InstrInfo, *OutContext);
if (!CodeEmitter)
return error("no code emitter for target " + TripleName);
AsmBackend = TheTarget->createMCAsmBackend(*SubtargetInfo, *RegisterInfo, TargetMOptions);
if (!AsmBackend)
return error("no asm backend for target " + TripleName);
Streamer = (MCObjectStreamer *)TheTarget->createMCObjectStreamer(
TheTriple, *OutContext, std::unique_ptr<MCAsmBackend>(AsmBackend), AsmBackend->createObjectWriter(*OS),
std::unique_ptr<MCCodeEmitter>(CodeEmitter), *SubtargetInfo,
/*RelaxAll*/ true,
/*IncrementalLinkerCompatible*/ false,
/*DWARFMustBeAtTheEnd*/ false);
if (!Streamer)
return error("no object streamer for target " + TripleName);
Streamer->initSections(/* NoExecStack */ true, *SubtargetInfo);
Assembler = &Streamer->getAssembler();
FrameOpened = false;
FuncId = 1;
if (OutContext->getObjectFileType() == MCContext::IsCOFF) {
TypeBuilder.reset(new UserDefinedCodeViewTypesBuilder());
} else {
TypeBuilder.reset(new UserDefinedDwarfTypesBuilder());
}
TypeBuilder->SetStreamer(Streamer);
unsigned TargetPointerSize = Streamer->getContext().getAsmInfo()->getCodePointerSize();
TypeBuilder->SetTargetPointerSize(TargetPointerSize);
DwarfGenerator.reset(new DwarfGen());
DwarfGenerator->SetTypeBuilder(static_cast<UserDefinedDwarfTypesBuilder*>(TypeBuilder.get()));
CFIsPerOffset.truncate(0);
if (OutContext->getObjectFileType() == MCContext::IsMachO) {
Streamer->emitAssemblerFlag(MCAF_SubsectionsViaSymbols);
}
return true;
}
void ObjectWriter::Finish() {
if (OutContext->getObjectFileType() == MCContext::IsCOFF
&& AddressTakenFunctions.size() > 0) {
// Emit all address-taken functions into the GFIDs section
// to support control flow guard.
Streamer->switchSection(ObjFileInfo->getGFIDsSection());
for (const MCSymbol* S : AddressTakenFunctions) {
Streamer->emitCOFFSymbolIndex(S);
}
// Emit the feat.00 symbol that controls various linker behaviors
MCSymbol* S = OutContext->getOrCreateSymbol(StringRef("@feat.00"));
Streamer->beginCOFFSymbolDef(S);
Streamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
Streamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
Streamer->endCOFFSymbolDef();
int64_t Feat00Flags = 0;
Feat00Flags |= 0x800; // cfGuardCF flags this object as control flow guard aware
Streamer->emitSymbolAttribute(S, MCSA_Global);
Streamer->emitAssignment(
S, MCConstantExpr::create(Feat00Flags, *OutContext));
}
Streamer->finish();
}
void ObjectWriter::SetDwarfVersion(uint16_t v) {
Streamer->getContext().setDwarfVersion(v);
}
void ObjectWriter::SwitchSection(const char *SectionName,
CustomSectionAttributes attributes,
const char *ComdatName) {
MCSection *Section = GetSection(SectionName, attributes, ComdatName);
Streamer->switchSection(Section);
if (Sections.count(Section) == 0) {
Sections.insert(Section);
if (OutContext->getObjectFileType() == MCContext::IsMachO) {
assert(!Section->getBeginSymbol());
// Output a DWARF linker-local symbol.
// This symbol is used as a base for other symbols in a section.
MCSymbol *SectionStartSym = OutContext->createLinkerPrivateTempSymbol();
Streamer->emitLabel(SectionStartSym);
Section->setBeginSymbol(SectionStartSym);
}
}
}
MCSection *ObjectWriter::GetSection(const char *SectionName,
CustomSectionAttributes attributes,
const char *ComdatName) {
MCSection *Section = nullptr;
if (strcmp(SectionName, "text") == 0) {
Section = ObjFileInfo->getTextSection();
} else if (strcmp(SectionName, "data") == 0) {
Section = ObjFileInfo->getDataSection();
} else if (strcmp(SectionName, "rdata") == 0) {
Section = ObjFileInfo->getReadOnlySection();
} else if (strcmp(SectionName, "xdata") == 0) {
Section = ObjFileInfo->getXDataSection();
} else if (strcmp(SectionName, "tdata") == 0) {
Section = ObjFileInfo->getTLSDataSection();
} else if (strcmp(SectionName, "tbss") == 0) {
Section = ObjFileInfo->getTLSBSSSection();
} else if (strcmp(SectionName, "bss") == 0) {
if (OutContext->getObjectFileType() == MCContext::IsMachO) {
Section = ObjFileInfo->getDataBSSSection();
} else {
Section = ObjFileInfo->getBSSSection();
}
} else if (strcmp(SectionName, "comment") == 0 && OutContext->getObjectFileType() == MCContext::IsELF) {
Section = OutContext->getELFSection(".comment", ELF::SHT_PROGBITS, ELF::SHF_MERGE | ELF::SHF_STRINGS | ELF::SHF_GNU_RETAIN, 1);
} else {
Section = GetSpecificSection(SectionName, attributes, ComdatName);
}
assert(Section);
return Section;
}
MCSection *ObjectWriter::GetSpecificSection(const char *SectionName,
CustomSectionAttributes attributes,
const char *ComdatName) {
Triple TheTriple(TripleName);
MCSection *Section = nullptr;
SectionKind Kind;
if (attributes & CustomSectionAttributes_Executable)
Kind = SectionKind::getText();
else if (attributes & CustomSectionAttributes_Uninitialized)
Kind = SectionKind::getBSS();
else if (attributes & CustomSectionAttributes_Writeable)
Kind = SectionKind::getData();
else
Kind = SectionKind::getReadOnly();
switch (TheTriple.getObjectFormat()) {
case Triple::MachO: {
unsigned typeAndAttributes = 0;
if (attributes & CustomSectionAttributes_MachO_Init_Func_Pointers) {
typeAndAttributes |= MachO::SectionType::S_MOD_INIT_FUNC_POINTERS;
}
if (attributes & CustomSectionAttributes_Executable) {
// Needs to be set on sections with actual code. The linker uses
// it to determine code sections and emit information about function
// boundaries.
typeAndAttributes |= MachO::S_ATTR_PURE_INSTRUCTIONS;
}
if (attributes & CustomSectionAttributes_Uninitialized) {
typeAndAttributes |= MachO::S_ZEROFILL;
}
Section = OutContext->getMachOSection(
(attributes & CustomSectionAttributes_Executable) ? "__TEXT" : "__DATA",
SectionName, typeAndAttributes, Kind);
break;
}
case Triple::COFF: {
unsigned Characteristics = COFF::IMAGE_SCN_MEM_READ;
if (attributes & CustomSectionAttributes_Executable) {
Characteristics |= COFF::IMAGE_SCN_CNT_CODE | COFF::IMAGE_SCN_MEM_EXECUTE;
} else if (attributes & CustomSectionAttributes_Writeable) {
Characteristics |= COFF::IMAGE_SCN_MEM_WRITE;
if (attributes & CustomSectionAttributes_Uninitialized)
Characteristics |= COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
else
Characteristics |= COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
} else {
Characteristics |= COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
}
if (ComdatName != nullptr) {
Section = OutContext->getCOFFSection(
SectionName, Characteristics | COFF::IMAGE_SCN_LNK_COMDAT, Kind,
ComdatName, COFF::COMDATType::IMAGE_COMDAT_SELECT_ANY);
} else {
Section = OutContext->getCOFFSection(SectionName, Characteristics, Kind);
}
break;
}
case Triple::ELF: {
unsigned Flags = ELF::SHF_ALLOC;
if (ComdatName != nullptr) {
MCSymbolELF *GroupSym =
cast<MCSymbolELF>(OutContext->getOrCreateSymbol(ComdatName));
OutContext->createELFGroupSection(GroupSym, true);
Flags |= ELF::SHF_GROUP;
}
if (attributes & CustomSectionAttributes_Executable) {
Flags |= ELF::SHF_EXECINSTR;
} else if (attributes & CustomSectionAttributes_Writeable) {
Flags |= ELF::SHF_WRITE;
}
unsigned SectionType = (attributes & CustomSectionAttributes_Uninitialized)
? ELF::SHT_NOBITS
: ELF::SHT_PROGBITS;
Section =
OutContext->getELFSection(SectionName, SectionType, Flags, 0,
ComdatName != nullptr ? ComdatName : "",
ComdatName != nullptr);
break;
}
default:
error("Unknown output format for target " + TripleName);
break;
}
return Section;
}
void ObjectWriter::SetCodeSectionAttribute(const char *SectionName,
CustomSectionAttributes attributes,
const char *ComdatName) {
MCSection *Section = GetSection(SectionName, attributes, ComdatName);
assert(!Section->hasInstructions());
Section->setHasInstructions(true);
if (OutContext->getObjectFileType() != MCContext::IsCOFF) {
OutContext->addGenDwarfSection(Section);
}
}
void ObjectWriter::EmitAlignment(int ByteAlignment) {
int64_t fillValue = 0;
if (Streamer->getCurrentSectionOnly()->getKind().isText()) {
if (OutContext->getTargetTriple().getArch() == llvm::Triple::ArchType::x86 ||
OutContext->getTargetTriple().getArch() == llvm::Triple::ArchType::x86_64) {
fillValue = 0x90; // x86 nop
}
}
Streamer->emitValueToAlignment(Align(ByteAlignment), fillValue);
}
void ObjectWriter::EmitBlob(int BlobSize, const char *Blob) {
if (Streamer->getCurrentSectionOnly()->getKind().isText()) {
Streamer->emitInstructionBytes(StringRef(Blob, BlobSize));
} else {
Streamer->emitBytes(StringRef(Blob, BlobSize));
}
}
void ObjectWriter::EmitIntValue(uint64_t Value, unsigned Size) {
Streamer->emitIntValue(Value, Size);
}
void ObjectWriter::EmitSymbolDef(const char *SymbolName, bool global) {
MCSymbol *Sym = OutContext->getOrCreateSymbol(Twine(SymbolName));
Streamer->emitSymbolAttribute(Sym, MCSA_Global);
Triple TheTriple = OutContext->getTargetTriple();
if (TheTriple.getObjectFormat() == Triple::ELF) {
// An ARM function symbol should be marked with an appropriate ELF attribute
// to make later computation of a relocation address value correct
if (Streamer->getCurrentSectionOnly()->getKind().isText()) {
switch (TheTriple.getArch()) {
case Triple::arm:
case Triple::armeb:
case Triple::thumb:
case Triple::thumbeb:
case Triple::aarch64:
case Triple::aarch64_be:
Streamer->emitSymbolAttribute(Sym, MCSA_ELF_TypeFunction);
break;
default:
break;
}
}
// Mark the symbol hidden if requested
if (!global) {
Streamer->emitSymbolAttribute(Sym, MCSA_Hidden);
}
}
Streamer->emitLabel(Sym);
}
const MCSymbolRefExpr *
ObjectWriter::GetSymbolRefExpr(const char *SymbolName,
MCSymbolRefExpr::VariantKind Kind) {
// Create symbol reference
MCSymbol *T = OutContext->getOrCreateSymbol(SymbolName);
Assembler->registerSymbol(*T);
return MCSymbolRefExpr::create(T, Kind, *OutContext);
}
unsigned ObjectWriter::GetDFSize() {
return Streamer->getOrCreateDataFragment()->getContents().size();
}
void ObjectWriter::EmitRelocDirective(const int Offset, StringRef Name, const MCExpr *Expr) {
const MCExpr *OffsetExpr = MCConstantExpr::create(Offset, *OutContext);
std::optional<std::pair<bool, std::string>> result = Streamer->emitRelocDirective(*OffsetExpr, Name, Expr, SMLoc(), *SubtargetInfo);
assert(!result.hasValue());
}
const MCExpr *ObjectWriter::GenTargetExpr(const MCSymbol* Symbol, MCSymbolRefExpr::VariantKind Kind,
int Delta, bool IsPCRel, int Size) {
const MCExpr *TargetExpr = MCSymbolRefExpr::create(Symbol, Kind, *OutContext);
if (IsPCRel && Size != 0) {
// If the fixup is pc-relative, we need to bias the value to be relative to
// the start of the field, not the end of the field
TargetExpr = MCBinaryExpr::createSub(
TargetExpr, MCConstantExpr::create(Size, *OutContext), *OutContext);
}
if (Delta != 0) {
TargetExpr = MCBinaryExpr::createAdd(
TargetExpr, MCConstantExpr::create(Delta, *OutContext), *OutContext);
}
return TargetExpr;
}
int ObjectWriter::EmitSymbolRef(const char *SymbolName,
RelocType RelocationType, int Delta, SymbolRefFlags Flags) {
bool IsPCRel = false;
int Size = 0;
MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None;
MCSymbol* Symbol = OutContext->getOrCreateSymbol(SymbolName);
Assembler->registerSymbol(*Symbol);
if ((int)Flags & (int)SymbolRefFlags::SymbolRefFlags_AddressTakenFunction) {
AddressTakenFunctions.insert(Symbol);
}
// Convert RelocationType to MCSymbolRefExpr
switch (RelocationType) {
case RelocType::IMAGE_REL_BASED_ABSOLUTE:
assert(OutContext->getObjectFileType() == MCContext::IsCOFF);
Kind = MCSymbolRefExpr::VK_COFF_IMGREL32;
Size = 4;
break;
case RelocType::IMAGE_REL_BASED_HIGHLOW:
Size = 4;
break;
case RelocType::IMAGE_REL_BASED_DIR64:
Size = 8;
break;
case RelocType::IMAGE_REL_SECREL:
Kind = MCSymbolRefExpr::VK_SECREL;
Size = 4;
break;
case RelocType::IMAGE_REL_TLSGD:
Kind = MCSymbolRefExpr::VK_TLSGD;
Size = 4;
break;
case RelocType::IMAGE_REL_TPOFF:
Kind = MCSymbolRefExpr::VK_TPOFF;
Size = 4;
break;
case RelocType::IMAGE_REL_AARCH64_TLSLE_ADD_TPREL_HI12: {
const MCExpr* TargetExpr = GenTargetExpr(Symbol, Kind, Delta);
TargetExpr =
AArch64MCExpr::create(TargetExpr, AArch64MCExpr::VK_TPREL_HI12, *OutContext);
EmitRelocDirective(GetDFSize(), "R_AARCH64_TLSLE_ADD_TPREL_HI12", TargetExpr);
return 4;
}
case RelocType::IMAGE_REL_AARCH64_TLSLE_ADD_TPREL_LO12_NC: {
const MCExpr* TargetExpr = GenTargetExpr(Symbol, Kind, Delta);
TargetExpr =
AArch64MCExpr::create(TargetExpr, AArch64MCExpr::VK_TPREL_LO12_NC, *OutContext);
EmitRelocDirective(GetDFSize(), "R_AARCH64_TLSLE_ADD_TPREL_LO12_NC", TargetExpr);
return 4;
}
case RelocType::IMAGE_REL_AARCH64_TLSDESC_ADR_PAGE21: {
const MCExpr* TargetExpr = GenTargetExpr(Symbol, Kind, Delta);
TargetExpr =
AArch64MCExpr::create(TargetExpr, AArch64MCExpr::VK_TLSDESC_PAGE, *OutContext);
EmitRelocDirective(GetDFSize(), "R_AARCH64_TLSDESC_ADR_PAGE21", TargetExpr);
return 4;
}
case RelocType::IMAGE_REL_AARCH64_TLSDESC_LD64_LO12: {
const MCExpr* TargetExpr = GenTargetExpr(Symbol, Kind, Delta);
TargetExpr =
AArch64MCExpr::create(TargetExpr, AArch64MCExpr::VK_TLSDESC_LO12, *OutContext);
EmitRelocDirective(GetDFSize(), "R_AARCH64_TLSDESC_LD64_LO12", TargetExpr);
return 4;
}
case RelocType::IMAGE_REL_AARCH64_TLSDESC_ADD_LO12: {
const MCExpr* TargetExpr = GenTargetExpr(Symbol, Kind, Delta);
TargetExpr =
AArch64MCExpr::create(TargetExpr, AArch64MCExpr::VK_TLSDESC_LO12, *OutContext);
EmitRelocDirective(GetDFSize(), "R_AARCH64_TLSDESC_ADD_LO12", TargetExpr);
return 4;
}
case RelocType::IMAGE_REL_AARCH64_TLSDESC_CALL: {
const MCExpr* TargetExpr = GenTargetExpr(Symbol, Kind, Delta);
EmitRelocDirective(GetDFSize(), "R_AARCH64_TLSDESC_CALL", TargetExpr);
return 4;
}
case RelocType::IMAGE_REL_BASED_REL32:
if (OutContext->getObjectFileType() == MCContext::IsMachO &&
OutContext->getTargetTriple().getArch() == Triple::aarch64) {
MCSymbol *TempSymbol = OutContext->createTempSymbol();
Streamer->emitLabel(TempSymbol);
const MCExpr *TargetExpr = MCSymbolRefExpr::create(Symbol, Kind, *OutContext);
const MCSymbolRefExpr *SectionExpr = MCSymbolRefExpr::create(TempSymbol, Kind, *OutContext);
TargetExpr = MCBinaryExpr::createSub(
TargetExpr, SectionExpr, *OutContext);
// If the fixup is pc-relative, we need to bias the value to be relative to
// the start of the field, not the end of the field
TargetExpr = MCBinaryExpr::createSub(
TargetExpr, MCConstantExpr::create(4, *OutContext), *OutContext);
if (Delta != 0) {
TargetExpr = MCBinaryExpr::createAdd(
TargetExpr, MCConstantExpr::create(Delta, *OutContext), *OutContext);
}
Streamer->emitValueImpl(TargetExpr, 4, SMLoc(), false);
return 4;
}
Size = 4;
IsPCRel = true;
if (OutContext->getObjectFileType() == MCContext::IsELF) {
// PLT is valid only for code symbols,
// but there shouldn't be references to global data symbols
Kind = MCSymbolRefExpr::VK_PLT;
}
break;
case RelocType::IMAGE_REL_BASED_RELPTR32:
if (OutContext->getObjectFileType() == MCContext::IsMachO &&
OutContext->getTargetTriple().getArch() == Triple::aarch64) {
MCSymbol *TempSymbol = OutContext->createTempSymbol();
Streamer->emitLabel(TempSymbol);
const MCExpr *TargetExpr = MCSymbolRefExpr::create(Symbol, Kind, *OutContext);
const MCSymbolRefExpr *SectionExpr = MCSymbolRefExpr::create(TempSymbol, Kind, *OutContext);
TargetExpr = MCBinaryExpr::createSub(
TargetExpr, SectionExpr, *OutContext);
if (Delta != 0) {
TargetExpr = MCBinaryExpr::createAdd(
TargetExpr, MCConstantExpr::create(Delta, *OutContext), *OutContext);
}
Streamer->emitValueImpl(TargetExpr, 4, SMLoc(), false);
return 4;
}
Size = 4;
IsPCRel = true;
Delta += 4;
break;
case RelocType::IMAGE_REL_BASED_THUMB_MOV32: {
const unsigned Offset = GetDFSize();
const MCExpr *TargetExpr = GenTargetExpr(Symbol, Kind, Delta);
EmitRelocDirective(Offset, "R_ARM_THM_MOVW_ABS_NC", TargetExpr);
EmitRelocDirective(Offset + 4, "R_ARM_THM_MOVT_ABS", TargetExpr);
return 8;
}
case RelocType::IMAGE_REL_BASED_THUMB_BRANCH24: {
const MCExpr *TargetExpr = GenTargetExpr(Symbol, Kind, Delta);
EmitRelocDirective(GetDFSize(), "R_ARM_THM_CALL", TargetExpr);
return 4;
}
case RelocType::IMAGE_REL_BASED_ARM64_BRANCH26: {
const MCExpr *TargetExpr = GenTargetExpr(Symbol, Kind, Delta);
EmitRelocDirective(GetDFSize(), "R_AARCH64_CALL26", TargetExpr);
return 4;
}
case RelocType::IMAGE_REL_BASED_ARM64_PAGEBASE_REL21: {
if (OutContext->getObjectFileType() == MCContext::IsMachO) {
Kind = MCSymbolRefExpr::VK_PAGE;
}
const MCExpr *TargetExpr = GenTargetExpr(Symbol, Kind, Delta);
TargetExpr =
AArch64MCExpr::create(TargetExpr, AArch64MCExpr::VK_CALL, *OutContext);
EmitRelocDirective(GetDFSize(), "R_AARCH64_ADR_PREL_PG_HI21", TargetExpr);
return 4;
}
case RelocType::IMAGE_REL_BASED_ARM64_PAGEOFFSET_12A: {
if (OutContext->getObjectFileType() == MCContext::IsMachO) {
Kind = MCSymbolRefExpr::VK_PAGEOFF;
}
const MCExpr *TargetExpr = GenTargetExpr(Symbol, Kind, Delta);
TargetExpr =
AArch64MCExpr::create(TargetExpr, AArch64MCExpr::VK_LO12, *OutContext);
EmitRelocDirective(GetDFSize(), "R_AARCH64_ADD_ABS_LO12_NC", TargetExpr);
return 4;
}
}
const MCExpr *TargetExpr = GenTargetExpr(Symbol, Kind, Delta, IsPCRel, Size);
Streamer->emitValueImpl(TargetExpr, Size, SMLoc(), IsPCRel);
return Size;
}
void ObjectWriter::EmitWinFrameInfo(const char *FunctionName, int StartOffset,
int EndOffset, const char *BlobSymbolName) {
assert(OutContext->getObjectFileType() == MCContext::IsCOFF);
// .pdata emission
MCSection *Section = ObjFileInfo->getPDataSection();
// If the function was emitted to a Comdat section, create an associative
// section to place the frame info in. This is due to the Windows linker
// requirement that a function and its unwind info come from the same
// object file.
MCSymbol *Fn = OutContext->getOrCreateSymbol(Twine(FunctionName));
const MCSectionCOFF *FunctionSection = cast<MCSectionCOFF>(&Fn->getSection());
if (FunctionSection->getCharacteristics() & COFF::IMAGE_SCN_LNK_COMDAT) {
Section = OutContext->getAssociativeCOFFSection(
cast<MCSectionCOFF>(Section), FunctionSection->getCOMDATSymbol());
}
Streamer->switchSection(Section);
Streamer->emitValueToAlignment(Align(4));
const MCExpr *BaseRefRel =
GetSymbolRefExpr(FunctionName, MCSymbolRefExpr::VK_COFF_IMGREL32);
Triple::ArchType Arch = OutContext->getTargetTriple().getArch();
if (Arch == Triple::thumb || Arch == Triple::thumbeb) {
StartOffset |= 1;
}
// start Offset
const MCExpr *StartOfs = MCConstantExpr::create(StartOffset, *OutContext);
Streamer->emitValue(
MCBinaryExpr::createAdd(BaseRefRel, StartOfs, *OutContext), 4);
if (Arch == Triple::x86 || Arch == Triple::x86_64) {
// end Offset
const MCExpr *EndOfs = MCConstantExpr::create(EndOffset, *OutContext);
Streamer->emitValue(
MCBinaryExpr::createAdd(BaseRefRel, EndOfs, *OutContext), 4);
}
// frame symbol reference
Streamer->emitValue(
GetSymbolRefExpr(BlobSymbolName, MCSymbolRefExpr::VK_COFF_IMGREL32), 4);
}
void ObjectWriter::EmitCFIStart(int Offset) {
assert(!FrameOpened && "frame should be closed before CFIStart");
Streamer->emitCFIStartProc(false);
FrameOpened = true;
FrameHasCompactEncoding = false;
}
void ObjectWriter::EmitCFIEnd(int Offset) {
assert(FrameOpened && "frame should be opened before CFIEnd");
// If compact unwinding was not set through EmitCFICompactUnwindEncoding
// force compact unwinding to use DWARF references which allow unwinding
// prologs and epilogs correctly.
if (!FrameHasCompactEncoding) {
Streamer->emitCFICompactUnwindEncoding(ObjFileInfo->getCompactUnwindDwarfEHFrameOnly());
}
Streamer->emitCFIEndProc();
FrameOpened = false;
}
void ObjectWriter::EmitCFILsda(const char *LsdaBlobSymbolName) {
assert(FrameOpened && "frame should be opened before CFILsda");
// Create symbol reference
MCSymbol *T = OutContext->getOrCreateSymbol(LsdaBlobSymbolName);
Assembler->registerSymbol(*T);
if (OutContext->getObjectFileType() == MCContext::IsMachO) {
Streamer->emitCFILsda(T, llvm::dwarf::Constants::DW_EH_PE_pcrel);
} else {
Streamer->emitCFILsda(T, llvm::dwarf::Constants::DW_EH_PE_pcrel |
llvm::dwarf::Constants::DW_EH_PE_sdata4);
}
}
void ObjectWriter::EmitCFICode(int Offset, const char *Blob) {
assert(FrameOpened && "frame should be opened before CFICode");
const CFI_CODE *CfiCode = (const CFI_CODE *)Blob;
switch (CfiCode->CfiOpCode) {
case CFI_ADJUST_CFA_OFFSET:
assert(CfiCode->DwarfReg == DWARF_REG_ILLEGAL &&
"Unexpected Register Value for OpAdjustCfaOffset");
Streamer->emitCFIAdjustCfaOffset(CfiCode->Offset);
break;
case CFI_REL_OFFSET:
Streamer->emitCFIRelOffset(CfiCode->DwarfReg, CfiCode->Offset);
break;
case CFI_DEF_CFA_REGISTER:
assert(CfiCode->Offset == 0 &&
"Unexpected Offset Value for OpDefCfaRegister");
Streamer->emitCFIDefCfaRegister(CfiCode->DwarfReg);
break;
case CFI_DEF_CFA:
assert(CfiCode->Offset != 0 &&
"Unexpected Offset Value for OpDefCfa");
Streamer->emitCFIDefCfa(CfiCode->DwarfReg, CfiCode->Offset);
break;
default:
assert(false && "Unrecognized CFI");
break;
}
}
void ObjectWriter::EmitCFICompactUnwindEncoding(unsigned int Encoding)
{
// Emits architecture specific compact unwinding encoding for MachO
// files on Apple platforms. Currently that's the only platform where
// compact unwinding tables are used.
//
// If EmitCFICompactUnwindEncoding is never called then EmitCFIEnd
// will cause compact unwinding to reference DWARF CFI info. It
// essentially turns the compact unwinding tables into an index for
// the DWARF CFI data, much like .eh_frame_hdr works in ELF files.
//
// If Encoding is set to zero it instructs LLVM to infer the compact
// unwinding encoding from the DWARF CFI data.
//
// Any non-zero value in Encoding is emitted directly into the
// __compact_unwind section and then processed by the linker.
//
// See generateCompactUnwindEncoding in AArch64AsmBackend.cpp and
// X86AsmBackend.cpp for specific encodings for a given architecture.
FrameHasCompactEncoding = true;
Streamer->emitCFICompactUnwindEncoding(Encoding);
}
void ObjectWriter::EmitLabelDiff(const MCSymbol *From, const MCSymbol *To,
unsigned int Size) {
MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
const MCExpr *FromRef = MCSymbolRefExpr::create(From, Variant, *OutContext),
*ToRef = MCSymbolRefExpr::create(To, Variant, *OutContext);
const MCExpr *AddrDelta =
MCBinaryExpr::create(MCBinaryExpr::Sub, ToRef, FromRef, *OutContext);
Streamer->emitValue(AddrDelta, Size);
}
void ObjectWriter::EmitSymRecord(int Size, SymbolRecordKind SymbolKind) {
RecordPrefix Rec;
Rec.RecordLen = ulittle16_t(Size + sizeof(ulittle16_t));
Rec.RecordKind = ulittle16_t((uint16_t)SymbolKind);
Streamer->emitBytes(StringRef((char *)&Rec, sizeof(Rec)));
}
void ObjectWriter::EmitCOFFSecRel32Value(MCExpr const *Value) {
MCDataFragment *DF = Streamer->getOrCreateDataFragment();
MCFixup Fixup = MCFixup::create(DF->getContents().size(), Value, FK_SecRel_4);
DF->getFixups().push_back(Fixup);
DF->getContents().resize(DF->getContents().size() + 4, 0);
}
void ObjectWriter::EmitVarDefRange(const MCSymbol *Fn,
const LocalVariableAddrRange &Range) {
const MCSymbolRefExpr *BaseSym = MCSymbolRefExpr::create(Fn, *OutContext);
const MCExpr *Offset = MCConstantExpr::create(Range.OffsetStart, *OutContext);
const MCExpr *Expr = MCBinaryExpr::createAdd(BaseSym, Offset, *OutContext);
EmitCOFFSecRel32Value(Expr);
Streamer->emitCOFFSectionIndex(Fn);
Streamer->emitIntValue(Range.Range, 2);
}
// Maps an ICorDebugInfo register number to the corresponding CodeView
// register number
CVRegNum ObjectWriter::GetCVRegNum(unsigned RegNum) {
static const CVRegNum CVRegMapAmd64[] = {
CV_AMD64_RAX, CV_AMD64_RCX, CV_AMD64_RDX, CV_AMD64_RBX,
CV_AMD64_RSP, CV_AMD64_RBP, CV_AMD64_RSI, CV_AMD64_RDI,
CV_AMD64_R8, CV_AMD64_R9, CV_AMD64_R10, CV_AMD64_R11,
CV_AMD64_R12, CV_AMD64_R13, CV_AMD64_R14, CV_AMD64_R15,
};
switch (OutContext->getTargetTriple().getArch()) {
case Triple::x86:
if (X86::ICorDebugInfo::REGNUM_EAX <= RegNum &&
RegNum <= X86::ICorDebugInfo::REGNUM_EDI) {
return RegNum - X86::ICorDebugInfo::REGNUM_EAX + CV_REG_EAX;
}
break;
case Triple::x86_64:
if (RegNum < sizeof(CVRegMapAmd64) / sizeof(CVRegMapAmd64[0])) {
return CVRegMapAmd64[RegNum];
}
break;
case Triple::arm:
case Triple::armeb:
case Triple::thumb:
case Triple::thumbeb:
if (Arm::ICorDebugInfo::REGNUM_R0 <= RegNum &&
RegNum <= Arm::ICorDebugInfo::REGNUM_PC) {
return RegNum - Arm::ICorDebugInfo::REGNUM_R0 + CV_ARM_R0;
}
break;
case Triple::aarch64:
case Triple::aarch64_be:
if (Arm64::ICorDebugInfo::REGNUM_X0 <= RegNum &&
RegNum < Arm64::ICorDebugInfo::REGNUM_PC) {
return RegNum - Arm64::ICorDebugInfo::REGNUM_X0 + CV_ARM64_X0;
}
// Special registers are ordered FP, LR, SP, PC in ICorDebugInfo's
// enumeration and FP, LR, SP, *ZR*, PC in CodeView's enumeration.
// For that reason handle the PC register separately.
if (RegNum == Arm64::ICorDebugInfo::REGNUM_PC) {
return CV_ARM64_PC;
}
break;
default:
assert(false && "Unexpected architecture");
break;
}
return CV_REG_NONE;
}
void ObjectWriter::EmitCVDebugVarInfo(const MCSymbol *Fn,
const DebugVarInfo LocInfos[],
int NumVarInfos) {
for (int I = 0; I < NumVarInfos; I++) {
// Emit an S_LOCAL record
DebugVarInfo Var = LocInfos[I];
TypeIndex Type = TypeIndex(Var.TypeIndex);
LocalSymFlags Flags = LocalSymFlags::None;
unsigned SizeofSym = sizeof(Type) + sizeof(Flags);
unsigned NameLength = Var.Name.length() + 1;
EmitSymRecord(SizeofSym + NameLength, SymbolRecordKind::LocalSym);
if (Var.IsParam) {
Flags |= LocalSymFlags::IsParameter;
}
Streamer->emitBytes(StringRef((char *)&Type, sizeof(Type)));
Streamer->emitIntValue(static_cast<uint16_t>(Flags), sizeof(Flags));
Streamer->emitBytes(StringRef(Var.Name.c_str(), NameLength));
for (const auto &Range : Var.Ranges) {
// Emit a range record
switch (Range.loc.vlType) {
case ICorDebugInfo::VLT_REG:
case ICorDebugInfo::VLT_REG_FP: {
// Currently only support integer registers.
// TODO: support xmm registers
CVRegNum CVReg = GetCVRegNum(Range.loc.vlReg.vlrReg);
if (CVReg == CV_REG_NONE) {
break;
}
SymbolRecordKind SymbolKind = SymbolRecordKind::DefRangeRegisterSym;
unsigned SizeofDefRangeRegisterSym = sizeof(DefRangeRegisterSym::Hdr) +
sizeof(DefRangeRegisterSym::Range);
EmitSymRecord(SizeofDefRangeRegisterSym, SymbolKind);
DefRangeRegisterSym DefRangeRegisterSymbol(SymbolKind);
DefRangeRegisterSymbol.Range.OffsetStart = Range.startOffset;
DefRangeRegisterSymbol.Range.Range =
Range.endOffset - Range.startOffset;
DefRangeRegisterSymbol.Range.ISectStart = 0;
DefRangeRegisterSymbol.Hdr.Register = CVReg;
DefRangeRegisterSymbol.Hdr.MayHaveNoName = 0;
unsigned Length = sizeof(DefRangeRegisterSymbol.Hdr);
Streamer->emitBytes(
StringRef((char *)&DefRangeRegisterSymbol.Hdr, Length));
EmitVarDefRange(Fn, DefRangeRegisterSymbol.Range);
break;
}
case ICorDebugInfo::VLT_STK: {
// TODO: support REGNUM_AMBIENT_SP
CVRegNum CVReg = GetCVRegNum(Range.loc.vlStk.vlsBaseReg);
if (CVReg == CV_REG_NONE) {
break;
}
SymbolRecordKind SymbolKind = SymbolRecordKind::DefRangeRegisterRelSym;
unsigned SizeofDefRangeRegisterRelSym =
sizeof(DefRangeRegisterRelSym::Hdr) +
sizeof(DefRangeRegisterRelSym::Range);
EmitSymRecord(SizeofDefRangeRegisterRelSym, SymbolKind);
DefRangeRegisterRelSym DefRangeRegisterRelSymbol(SymbolKind);
DefRangeRegisterRelSymbol.Range.OffsetStart = Range.startOffset;
DefRangeRegisterRelSymbol.Range.Range =
Range.endOffset - Range.startOffset;
DefRangeRegisterRelSymbol.Range.ISectStart = 0;
DefRangeRegisterRelSymbol.Hdr.Register = CVReg;
DefRangeRegisterRelSymbol.Hdr.Flags = 0;
DefRangeRegisterRelSymbol.Hdr.BasePointerOffset =
Range.loc.vlStk.vlsOffset;
unsigned Length = sizeof(DefRangeRegisterRelSymbol.Hdr);
Streamer->emitBytes(
StringRef((char *)&DefRangeRegisterRelSymbol.Hdr, Length));
EmitVarDefRange(Fn, DefRangeRegisterRelSymbol.Range);
break;
}
case ICorDebugInfo::VLT_REG_BYREF:
case ICorDebugInfo::VLT_STK_BYREF:
case ICorDebugInfo::VLT_REG_REG:
case ICorDebugInfo::VLT_REG_STK:
case ICorDebugInfo::VLT_STK_REG:
case ICorDebugInfo::VLT_STK2:
case ICorDebugInfo::VLT_FPSTK:
case ICorDebugInfo::VLT_FIXED_VA:
// TODO: for optimized debugging
break;
default:
assert(false && "Unknown varloc type!");
break;
}
}
}
}
void ObjectWriter::EmitCVDebugFunctionInfo(const char *FunctionName,
int FunctionSize) {
assert(OutContext->getObjectFileType() == MCContext::IsCOFF);
// Mark the end of function.
MCSymbol *FnEnd = OutContext->createTempSymbol();
Streamer->emitLabel(FnEnd);
MCSection *Section = ObjFileInfo->getCOFFDebugSymbolsSection();
Streamer->switchSection(Section);
// Emit debug section magic before the first entry.
if (FuncId == 1) {
Streamer->emitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
}
MCSymbol *Fn = OutContext->getOrCreateSymbol(Twine(FunctionName));
// Emit a symbol subsection, required by VS2012+ to find function boundaries.
MCSymbol *SymbolsBegin = OutContext->createTempSymbol(),
*SymbolsEnd = OutContext->createTempSymbol();
Streamer->emitIntValue(unsigned(DebugSubsectionKind::Symbols), 4);
EmitLabelDiff(SymbolsBegin, SymbolsEnd);
Streamer->emitLabel(SymbolsBegin);
{
ProcSym ProcSymbol(SymbolRecordKind::GlobalProcIdSym);
ProcSymbol.CodeSize = FunctionSize;
ProcSymbol.DbgEnd = FunctionSize;
unsigned FunctionNameLength = strlen(FunctionName) + 1;
unsigned HeaderSize =
sizeof(ProcSymbol.Parent) + sizeof(ProcSymbol.End) +
sizeof(ProcSymbol.Next) + sizeof(ProcSymbol.CodeSize) +
sizeof(ProcSymbol.DbgStart) + sizeof(ProcSymbol.DbgEnd) +
sizeof(ProcSymbol.FunctionType);
unsigned SymbolSize = HeaderSize + 4 + 2 + 1 + FunctionNameLength;
EmitSymRecord(SymbolSize, SymbolRecordKind::GlobalProcIdSym);
Streamer->emitBytes(StringRef((char *)&ProcSymbol.Parent, HeaderSize));
// Emit relocation
Streamer->emitCOFFSecRel32(Fn, 0);
Streamer->emitCOFFSectionIndex(Fn);
// Emit flags
Streamer->emitIntValue(0, 1);
// Emit the function display name as a null-terminated string.
Streamer->emitBytes(StringRef(FunctionName, FunctionNameLength));
// Emit local var info
int NumVarInfos = DebugVarInfos.size();
if (NumVarInfos > 0) {
EmitCVDebugVarInfo(Fn, &DebugVarInfos[0], NumVarInfos);
DebugVarInfos.clear();
}
// We're done with this function.
EmitSymRecord(0, SymbolRecordKind::ProcEnd);
}
Streamer->emitLabel(SymbolsEnd);
// Every subsection must be aligned to a 4-byte boundary.
Streamer->emitValueToAlignment(Align(4));
// We have an assembler directive that takes care of the whole line table.
// We also increase function id for the next function.