-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathObjectWriter.cs
More file actions
764 lines (641 loc) · 32.4 KB
/
ObjectWriter.cs
File metadata and controls
764 lines (641 loc) · 32.4 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using ILCompiler.DependencyAnalysis;
using ILCompiler.DependencyAnalysis.Wasm;
using ILCompiler.DependencyAnalysisFramework;
using Internal.Text;
using Internal.TypeSystem;
using static ILCompiler.DependencyAnalysis.ObjectNode;
using static ILCompiler.DependencyAnalysis.RelocType;
using ObjectData = ILCompiler.DependencyAnalysis.ObjectNode.ObjectData;
using CodeDataLayout = CodeDataLayoutMode.CodeDataLayout;
namespace ILCompiler.ObjectWriter
{
public abstract partial class ObjectWriter
{
protected virtual CodeDataLayout LayoutMode => CodeDataLayout.Unified;
private protected sealed record SymbolDefinition(int SectionIndex, long Value, int Size = 0, bool Global = false);
protected sealed record SymbolicRelocation(long Offset, RelocType Type, Utf8String SymbolName, long Addend = 0);
private sealed record BlockToRelocate(int SectionIndex, long Offset, byte[] Data, Relocation[] Relocations);
private protected sealed record ChecksumsToCalculate(int SectionIndex, long Offset, Relocation[] ChecksumRelocations);
private protected readonly NodeFactory _nodeFactory;
private protected readonly ObjectWritingOptions _options;
private protected readonly OutputInfoBuilder _outputInfoBuilder;
private readonly bool _isSingleFileCompilation;
protected readonly Utf8StringBuilder _utf8StringBuilder = new();
private readonly Dictionary<ISymbolNode, Utf8String> _mangledNameMap = new();
private readonly byte _insPaddingByte;
// Standard sections
private readonly Dictionary<string, int> _sectionNameToSectionIndex = new(StringComparer.Ordinal);
private readonly List<SectionData> _sectionIndexToData = new();
private readonly List<List<SymbolicRelocation>> _sectionIndexToRelocations = new();
private protected readonly List<OutputSection> _outputSectionLayout = [];
// Symbol table
private readonly Dictionary<Utf8String, SymbolDefinition> _definedSymbols = new();
private protected ObjectWriter(NodeFactory factory, ObjectWritingOptions options, OutputInfoBuilder outputInfoBuilder = null)
{
_nodeFactory = factory;
_options = options;
_outputInfoBuilder = outputInfoBuilder;
_isSingleFileCompilation = _nodeFactory.CompilationModuleGroup.IsSingleFileCompilation;
// Padding byte for code sections (NOP for x86/x64)
_insPaddingByte = factory.Target.Architecture switch
{
TargetArchitecture.X86 => 0x90,
TargetArchitecture.X64 => 0x90,
_ => 0
};
}
private protected virtual bool UsesSubsectionsViaSymbols => false;
private protected abstract void CreateSection(ObjectNodeSection section, Utf8String comdatName, Utf8String symbolName, int sectionIndex, Stream sectionStream);
protected internal abstract void UpdateSectionAlignment(int sectionIndex, int alignment);
/// <summary>
/// Get the section in the image where nodes in the passed in section should actually be emitted.
/// </summary>
/// <param name="section">A node's requested section.</param>
/// <returns>The section to actually emit the node into.</returns>
/// <remarks>
/// Sections in an image can be very expensive, and unlike linkable formats,
/// sections cannot be merged after the fact.
/// This method allows formats that want to merge sections during emit to do so.
/// </remarks>
private protected virtual ObjectNodeSection GetEmitSection(ObjectNodeSection section) => section;
private protected SectionWriter GetOrCreateSection(ObjectNodeSection section)
=> GetOrCreateSection(section, default, default);
/// <summary>
/// Get or creates an object file section.
/// </summary>
/// <param name="section">Base section name and type definition.</param>
/// <param name="comdatName">Name of the COMDAT symbol or null.</param>
/// <param name="symbolName">Name of the section definiting symbol for COMDAT or null</param>
/// <returns>Writer for a given section.</returns>
/// <remarks>
/// When creating a COMDAT section both <paramref name="comdatName"/> and <paramref name="symbolName"/>
/// has to be specified. <paramref name="comdatName"/> specifies the group section. For the primary
/// symbol both <paramref name="comdatName"/> and <paramref name="symbolName"/> will be the same.
/// For associated sections, such as exception or debugging information, the <paramref name="symbolName"/>
/// will be different.
/// </remarks>
private protected SectionWriter GetOrCreateSection(ObjectNodeSection section, Utf8String comdatName, Utf8String symbolName)
{
int sectionIndex;
SectionData sectionData;
section = GetEmitSection(section);
if (!comdatName.IsNull || !_sectionNameToSectionIndex.TryGetValue(section.Name, out sectionIndex))
{
sectionData = new SectionData(section.Type == SectionType.Executable ? _insPaddingByte : (byte)0);
sectionIndex = _sectionIndexToData.Count;
CreateSection(section, comdatName, symbolName, sectionIndex, sectionData.GetReadStream());
_sectionIndexToData.Add(sectionData);
_sectionIndexToRelocations.Add(new());
if (comdatName.IsNull)
{
_sectionNameToSectionIndex.Add(section.Name, sectionIndex);
}
}
else
{
sectionData = _sectionIndexToData[sectionIndex];
}
return new SectionWriter(
this,
sectionIndex,
sectionData);
}
private protected bool ShouldShareSymbol(ObjectNode node)
{
if (UsesSubsectionsViaSymbols)
return false;
return ShouldShareSymbol(node, node.GetSection(_nodeFactory));
}
private protected bool ShouldShareSymbol(ObjectNode node, ObjectNodeSection section)
{
if (UsesSubsectionsViaSymbols)
return false;
// Foldable sections are always COMDATs
if (section == ObjectNodeSection.FoldableReadOnlyDataSection)
return true;
if (_isSingleFileCompilation)
return false;
if (node is not ISymbolNode)
return false;
if (node is IUniqueSymbolNode)
return false;
return true;
}
private unsafe void EmitOrResolveRelocation(
int sectionIndex,
long offset,
Span<byte> data,
RelocType relocType,
Utf8String symbolName,
long addend)
{
if (!UsesSubsectionsViaSymbols &&
relocType is IMAGE_REL_BASED_REL32 or IMAGE_REL_BASED_RELPTR32 or IMAGE_REL_BASED_ARM64_BRANCH26
or IMAGE_REL_BASED_THUMB_BRANCH24 or IMAGE_REL_BASED_THUMB_MOV32_PCREL &&
_definedSymbols.TryGetValue(symbolName, out SymbolDefinition definedSymbol) &&
definedSymbol.SectionIndex == sectionIndex)
{
// Resolve the relocation to already defined symbol and write it into data
fixed (byte* pData = data)
{
// Method symbols should be defined with the thumb bit (+1) set per the AAELF ABI
// convention. For BRANCH24, the encoding cannot represent the thumb bit
// (per AAELF formula ((S + A) | T) – P), so strip it from the symbol value.
long symbolValue = relocType is IMAGE_REL_BASED_THUMB_BRANCH24
? definedSymbol.Value & ~1L
: definedSymbol.Value;
long adjustedAddend = addend;
adjustedAddend -= relocType switch
{
IMAGE_REL_BASED_REL32 => 4,
IMAGE_REL_BASED_THUMB_BRANCH24 => 4,
IMAGE_REL_BASED_THUMB_MOV32_PCREL => 12,
_ => 0
};
adjustedAddend += symbolValue;
adjustedAddend += Relocation.ReadValue(relocType, (void*)pData);
adjustedAddend -= offset;
if (relocType is IMAGE_REL_BASED_THUMB_BRANCH24 && !Relocation.FitsInThumb2BlRel24((int)adjustedAddend))
{
EmitRelocation(sectionIndex, offset, data, relocType, symbolName, addend);
}
else
{
Relocation.WriteValue(relocType, (void*)pData, adjustedAddend);
}
}
}
else if (relocType is IMAGE_REL_SYMBOL_SIZE &&
_definedSymbols.TryGetValue(symbolName, out definedSymbol))
{
fixed (byte* pData = data)
{
long adjustedAddend = addend + Relocation.ReadValue(relocType, (void*)pData);
Relocation.WriteValue(relocType, (void*)pData, definedSymbol.Size + adjustedAddend);
}
}
else
{
EmitRelocation(sectionIndex, offset, data, relocType, symbolName, addend);
}
}
/// <summary>
/// Emits a single relocation into a given section.
/// </summary>
/// <remarks>
/// The relocation is not resolved until <see cref="EmitRelocations" /> is called
/// later when symbol table is already generated.
/// </remarks>
protected internal virtual void EmitRelocation(
int sectionIndex,
long offset,
Span<byte> data,
RelocType relocType,
Utf8String symbolName,
long addend)
{
_sectionIndexToRelocations[sectionIndex].Add(new SymbolicRelocation(offset, relocType, symbolName, addend));
}
private protected bool SectionHasRelocations(int sectionIndex)
{
return _sectionIndexToRelocations[sectionIndex].Count > 0;
}
private protected virtual void EmitReferencedMethod(Utf8String symbolName) { }
/// <summary>
/// Emit symbolic relocations into object file as format specific
/// relocations.
/// </summary>
/// <remarks>
/// This methods is guaranteed to run after <see cref="EmitSymbolTable" />.
/// </remarks>
private protected abstract void EmitRelocations(int sectionIndex, List<SymbolicRelocation> relocationList);
/// <summary>
/// Emit new symbol definition at specified location in a given section.
/// </summary>
/// <remarks>
/// The symbols are emitted into the object file representation later by
/// <see cref="EmitSymbolTable" />. Various formats have restrictions on
/// the order of the symbols so any necessary sorting is done when the
/// symbol table is created.
/// </remarks>
protected internal void EmitSymbolDefinition(
int sectionIndex,
Utf8String symbolName,
long offset = 0,
int size = 0,
bool global = false)
{
_definedSymbols.Add(
symbolName,
new SymbolDefinition(sectionIndex, offset, size, global));
}
/// <summary>
/// Emit symbolic definitions into object file symbols.
/// </summary>
private protected abstract void EmitSymbolTable(
IDictionary<Utf8String, SymbolDefinition> definedSymbols,
SortedSet<Utf8String> undefinedSymbols);
private protected virtual Utf8String ExternCName(Utf8String name) => name;
private protected Utf8String GetMangledName(ISymbolNode symbolNode)
{
Utf8String symbolName;
if (!_mangledNameMap.TryGetValue(symbolNode, out symbolName))
{
symbolNode.AppendMangledName(_nodeFactory.NameMangler, _utf8StringBuilder.Clear());
symbolName = ExternCName(_utf8StringBuilder.ToUtf8String());
_mangledNameMap.Add(symbolNode, symbolName);
}
return symbolName;
}
private protected virtual void EmitSectionsAndLayout()
{
}
private protected abstract void EmitObjectFile(Stream outputFileStream);
partial void EmitDebugInfo(IReadOnlyCollection<DependencyNode> nodes, Logger logger);
private SortedSet<Utf8String> GetUndefinedSymbols()
{
SortedSet<Utf8String> undefinedSymbolSet = new SortedSet<Utf8String>();
foreach (var relocationList in _sectionIndexToRelocations)
{
foreach (var symbolicRelocation in relocationList)
{
if (!_definedSymbols.ContainsKey(symbolicRelocation.SymbolName))
{
undefinedSymbolSet.Add(symbolicRelocation.SymbolName);
}
}
}
return undefinedSymbolSet;
}
public virtual void EmitObject(Stream outputFileStream, IReadOnlyCollection<DependencyNode> nodes, IObjectDumper dumper, Logger logger)
{
// Pre-create some of the sections
GetOrCreateSection(ObjectNodeSection.TextSection);
if (_nodeFactory.Target.OperatingSystem == TargetOS.Windows)
{
GetOrCreateSection(ObjectNodeSection.ManagedCodeWindowsContentSection);
}
else
{
GetOrCreateSection(ObjectNodeSection.ManagedCodeUnixContentSection);
}
// Create sections for exception handling
if (_options.HasFlag(ObjectWritingOptions.GenerateUnwindInfo))
{
PrepareForUnwindInfo();
}
ProgressReporter progressReporter = default;
if (logger.IsVerbose)
{
int count = 0;
foreach (var node in nodes)
if (node is ObjectNode)
count++;
logger.LogMessage($"Writing {count} object nodes...");
progressReporter = new ProgressReporter(logger, count);
}
List<ISymbolRangeNode> symbolRangeNodes = [];
List<BlockToRelocate> blocksToRelocate = [];
List<ChecksumsToCalculate> checksumRelocations = [];
foreach (DependencyNode depNode in nodes)
{
// TODO-WASM: emit symbol ranges properly when code and data are separated
// Right now we still need to determine placements for some traditionally text-placed nodes,
// such as DebugDirectoryEntryNode and AssemblyStubNode
if (depNode is ISymbolRangeNode symbolRange)
{
symbolRangeNodes.Add(symbolRange);
continue;
}
if (depNode is not ObjectNode node)
continue;
if (logger.IsVerbose)
progressReporter.LogProgress();
if (node.ShouldSkipEmittingObjectNode(_nodeFactory))
continue;
ISymbolNode symbolNode = node as ISymbolNode;
if (symbolNode is not null)
{
ISymbolNode deduplicatedSymbolNode = _nodeFactory.ObjectInterner.GetDeduplicatedSymbol(_nodeFactory, symbolNode);
if (deduplicatedSymbolNode != symbolNode)
{
dumper?.ReportFoldedNode(_nodeFactory, node, deduplicatedSymbolNode);
continue;
}
}
ObjectData nodeContents = node.GetData(_nodeFactory);
dumper?.DumpObjectNode(_nodeFactory, node, nodeContents);
Utf8String currentSymbolName = default;
if (symbolNode != null)
{
currentSymbolName = GetMangledName(symbolNode);
}
ObjectNodeSection section = node.GetSection(_nodeFactory);
SectionWriter sectionWriter = ShouldShareSymbol(node, section) ?
GetOrCreateSection(section, currentSymbolName, currentSymbolName) :
GetOrCreateSection(section);
if (section.NeedsAlignment)
{
sectionWriter.EmitAlignment(nodeContents.Alignment);
}
bool isMethod = node is IPCodeSymbolNode;
long thumbBit = _nodeFactory.Target.Architecture == TargetArchitecture.ARM && isMethod ? 1 : 0;
if (node is WasmTypeNode signature)
{
RecordMethodSignature(signature);
}
if (node is INodeWithTypeSignature codeNode && _nodeFactory.Target.IsWasm)
{
Debug.Assert(codeNode.Signature != null, $"Wasm code node {codeNode.GetType()} has null signature");
// Record only information we can get from the MethodDesc here. The actual
// body will be emitted by the call to EmitData() at the end
// of this loop iteration.
RecordMethodDeclaration(codeNode);
}
foreach (ISymbolDefinitionNode n in nodeContents.DefinedSymbols)
{
Utf8String mangledName = n == node ? currentSymbolName : GetMangledName(n);
Debug.Assert(((ulong)thumbBit & (ulong)(uint)n.Offset) == 0);
sectionWriter.EmitSymbolDefinition(
mangledName,
n.Offset + thumbBit,
n.Offset == 0 ? nodeContents.Data.Length : 0);
_outputInfoBuilder?.AddSymbol(new OutputSymbol(sectionWriter.SectionIndex, (ulong)(sectionWriter.Position + n.Offset), mangledName));
Utf8String alternateName = _nodeFactory.GetSymbolAlternateName(n, out bool isHidden);
if (!alternateName.IsNull)
{
Utf8String alternateCName = ExternCName(alternateName);
sectionWriter.EmitSymbolDefinition(
alternateCName,
n.Offset + thumbBit,
n.Offset == 0 ? nodeContents.Data.Length : 0,
global: !isHidden);
if (n is IMethodNode)
{
// https://github.com/dotnet/runtime/issues/105330: consider exports CFG targets
EmitReferencedMethod(alternateCName);
}
_outputInfoBuilder?.AddSymbol(new OutputSymbol(sectionWriter.SectionIndex, (ulong)(sectionWriter.Position + n.Offset), alternateCName));
}
if (node.Phase == (int)SortableDependencyNode.ObjectNodePhase.Ordered)
{
RecordWellKnownSymbol(currentSymbolName, (SortableDependencyNode.ObjectNodeOrder)node.ClassCode);
}
}
if (nodeContents.Relocs is not null)
{
blocksToRelocate.Add(new BlockToRelocate(
sectionWriter.SectionIndex,
sectionWriter.Position,
nodeContents.Data,
nodeContents.Relocs));
#if DEBUG
// Pointer relocs should be aligned at pointer boundaries within the image.
// Processing misaligned relocs (especially relocs that straddle page boundaries) can be
// expensive on Windows. But: we can't guarantee this on x86, and Wasm doesn't have reloc pointer alignment requirements.
if (_nodeFactory.Target.Architecture is not TargetArchitecture.X86 and not TargetArchitecture.Wasm32)
{
bool hasPointerRelocs = false;
foreach (Relocation reloc in nodeContents.Relocs)
{
if ((reloc.RelocType is RelocType.IMAGE_REL_BASED_DIR64 && _nodeFactory.Target.PointerSize == 8) ||
(reloc.RelocType is RelocType.IMAGE_REL_BASED_HIGHLOW && _nodeFactory.Target.PointerSize == 4))
{
hasPointerRelocs = true;
Debug.Assert(reloc.Offset % _nodeFactory.Target.PointerSize == 0);
}
}
Debug.Assert(!hasPointerRelocs || (nodeContents.Alignment % _nodeFactory.Target.PointerSize) == 0);
}
#endif
}
// Emit unwinding frames and LSDA
if (_options.HasFlag(ObjectWritingOptions.GenerateUnwindInfo))
{
EmitUnwindInfoForNode(node, currentSymbolName, sectionWriter);
}
if (_outputInfoBuilder is not null)
{
var outputNode = new OutputNode(sectionWriter.SectionIndex, checked((ulong)sectionWriter.Position), nodeContents.Data.Length, GetNodeTypeName(node.GetType()));
_outputInfoBuilder.AddNode(outputNode, nodeContents.DefinedSymbols[0]);
if (nodeContents.Relocs is not null)
{
foreach (Relocation reloc in nodeContents.Relocs)
{
RelocType fileReloc = Relocation.GetFileRelocationType(reloc.RelocType);
if (fileReloc != RelocType.IMAGE_REL_BASED_ABSOLUTE)
{
_outputInfoBuilder.AddRelocation(outputNode, fileReloc);
}
}
}
}
// Note that this has to be done last as not to advance the section writer position.
sectionWriter.EmitData(nodeContents.Data);
}
foreach (ISymbolRangeNode range in symbolRangeNodes)
{
ISymbolNode startNode = range.StartNode(_nodeFactory);
ISymbolNode endNode = range.EndNode(_nodeFactory);
if (startNode is null != endNode is null)
{
throw new InvalidOperationException("Both or neither of the symbols that define a symbol range must be non-null.");
}
if (startNode is null)
{
// Emit empty symbol ranges as an empty symbol at the end of the text section.
var writer = GetOrCreateSection(ObjectNodeSection.TextSection);
writer.EmitSymbolDefinition(GetMangledName(range));
continue;
}
startNode = _nodeFactory.ObjectInterner.GetDeduplicatedSymbol(_nodeFactory, startNode);
endNode = _nodeFactory.ObjectInterner.GetDeduplicatedSymbol(_nodeFactory, endNode);
Utf8String startNodeName = GetMangledName(startNode);
Utf8String endNodeName = GetMangledName(endNode);
Utf8String rangeNodeName = GetMangledName(range);
if (!_definedSymbols.TryGetValue(endNodeName, out SymbolDefinition endSymbol))
{
throw new InvalidOperationException("The end symbol of the symbol range must be emitted into the same object.");
}
EmitSymbolRangeDefinition(rangeNodeName, startNodeName, endNodeName, endSymbol);
}
foreach (BlockToRelocate blockToRelocate in blocksToRelocate)
{
ArrayBuilder<Relocation> checksumRelocationsBuilder = default;
foreach (Relocation reloc in blockToRelocate.Relocations)
{
ISymbolNode relocTarget = _nodeFactory.ObjectInterner.GetDeduplicatedSymbol(_nodeFactory, reloc.Target);
if (reloc.RelocType == RelocType.IMAGE_REL_FILE_CHECKSUM_CALLBACK)
{
// Checksum relocations don't get emitted into the image.
// We manually proces them after we do all other object emission.
checksumRelocationsBuilder.Add(reloc);
continue;
}
Utf8String relocSymbolName = GetMangledName(relocTarget);
EmitOrResolveRelocation(
blockToRelocate.SectionIndex,
blockToRelocate.Offset + reloc.Offset,
blockToRelocate.Data.AsSpan(reloc.Offset),
reloc.RelocType,
relocSymbolName,
relocTarget.Offset);
if (_options.HasFlag(ObjectWritingOptions.ControlFlowGuard))
{
HandleControlFlowForRelocation(relocTarget, relocSymbolName);
}
}
checksumRelocations.Add(new ChecksumsToCalculate(blockToRelocate.SectionIndex, blockToRelocate.Offset, checksumRelocationsBuilder.ToArray()));
}
blocksToRelocate.Clear();
EmitSectionsAndLayout();
if (_options.HasFlag(ObjectWritingOptions.GenerateDebugInfo))
{
EmitDebugInfo(nodes, logger);
}
EmitSymbolTable(_definedSymbols, GetUndefinedSymbols());
int relocSectionIndex = 0;
foreach (List<SymbolicRelocation> relocationList in _sectionIndexToRelocations)
{
EmitRelocations(relocSectionIndex, relocationList);
relocSectionIndex++;
}
EmitObjectFile(outputFileStream);
if (checksumRelocations.Count > 0)
{
EmitChecksums(outputFileStream, checksumRelocations);
}
if (_outputInfoBuilder is not null)
{
foreach (var outputSection in _outputSectionLayout)
{
_outputInfoBuilder.AddSection(outputSection);
}
}
}
private protected virtual void RecordMethodDeclaration(INodeWithTypeSignature node)
{
Debug.Assert(LayoutMode == CodeDataLayout.Separate);
}
private protected virtual void RecordMethodSignature(WasmTypeNode signature)
{
Debug.Assert(LayoutMode == CodeDataLayout.Separate);
}
private protected virtual void RecordWellKnownSymbol(Utf8String currentSymbolName, SortableDependencyNode.ObjectNodeOrder classCode)
{
}
private protected virtual void EmitSymbolRangeDefinition(Utf8String rangeNodeName, Utf8String startNodeName, Utf8String endNodeName, SymbolDefinition endSymbol)
{
if (!_definedSymbols.TryGetValue(startNodeName, out var startSymbol))
{
throw new InvalidOperationException("The start symbol of the symbol range must be emitted into the same object.");
}
if (startSymbol.SectionIndex != endSymbol.SectionIndex)
{
throw new InvalidOperationException("The symbols that define a symbol range must be in the same section.");
}
// Don't use SectionWriter here as it emits symbols relative to the current writing position.
EmitSymbolDefinition(startSymbol.SectionIndex, rangeNodeName, startSymbol.Value, checked((int)(endSymbol.Value - startSymbol.Value + endSymbol.Size)));
}
private static string GetNodeTypeName(Type nodeType)
{
string name = nodeType.ToString();
int firstGeneric = name.IndexOf('[');
if (firstGeneric < 0)
{
firstGeneric = name.Length;
}
int lastDot = name.LastIndexOf('.', firstGeneric - 1, firstGeneric);
if (lastDot > 0)
{
name = name.Substring(lastDot + 1);
}
return name;
}
private void EmitChecksums(Stream outputFileStream, List<ChecksumsToCalculate> checksumRelocations)
{
// Defer writing the computed values until all checksums are computed so each one is
// calculated over the original image and not a value written by an earlier checksum.
List<(long Offset, byte[] Value)> pendingWrites = ComputeChecksums(outputFileStream, checksumRelocations);
foreach ((long offset, byte[] value) in pendingWrites)
{
outputFileStream.Seek(offset, SeekOrigin.Begin);
outputFileStream.Write(value);
}
}
private protected virtual List<(long Offset, byte[] Value)> ComputeChecksums(Stream outputFileStream, List<ChecksumsToCalculate> checksumRelocations)
{
List<(long Offset, byte[] Value)> pendingWrites = [];
foreach (var block in checksumRelocations)
{
foreach (var reloc in block.ChecksumRelocations)
{
IChecksumNode checksum = (IChecksumNode)reloc.Target;
byte[] checksumValue = new byte[checksum.ChecksumSize];
outputFileStream.Seek(0, SeekOrigin.Begin);
checksum.EmitChecksum(outputFileStream, checksumValue);
var checksumOffset = (long)_outputSectionLayout[block.SectionIndex].FilePosition + block.Offset + reloc.Offset;
pendingWrites.Add((checksumOffset, checksumValue));
}
}
return pendingWrites;
}
partial void HandleControlFlowForRelocation(ISymbolNode relocTarget, Utf8String relocSymbolName);
partial void PrepareForUnwindInfo();
partial void EmitUnwindInfoForNode(ObjectNode node, Utf8String currentSymbolName, SectionWriter sectionWriter);
public static void EmitObject(string objectFilePath, IReadOnlyCollection<DependencyNode> nodes, NodeFactory factory, ObjectWritingOptions options, IObjectDumper dumper, Logger logger)
{
var stopwatch = Stopwatch.StartNew();
ObjectWriter objectWriter =
factory.Target.IsApplePlatform ? new MachObjectWriter(factory, options) :
factory.Target.OperatingSystem == TargetOS.Windows ? new CoffObjectWriter(factory, options) :
new ElfObjectWriter(factory, options);
using Stream outputFileStream = new FileStream(objectFilePath, FileMode.Create);
objectWriter.EmitObject(outputFileStream, nodes, dumper, logger);
stopwatch.Stop();
if (logger.IsVerbose)
logger.LogMessage($"Done writing object file in {stopwatch.Elapsed}");
}
protected static ReadOnlySpan<byte> FormatUtf8Int(Span<byte> buffer, int number)
{
bool b = number.TryFormat(buffer, out int bytesWritten);
Debug.Assert(b);
return buffer.Slice(0, bytesWritten);
}
private struct ProgressReporter
{
private readonly Logger _logger;
private readonly int _total;
private int _current;
private int _lastReportedStep;
// Will report progress every (100 / 10) = 10%
private const int Steps = 10;
public ProgressReporter(Logger logger, int total)
{
_logger = logger;
_total = total;
_current = 0;
_lastReportedStep = 0;
}
public void LogProgress()
{
_current++;
int step = (_current * Steps) / _total;
if (step > _lastReportedStep)
{
_logger.LogMessage($"{step * (100 / Steps)}%...");
_lastReportedStep = step;
}
}
}
}
}