Repository navigation
Expand file tree
/
Copy pathClrLirAssemblyEmitter.cs
More file actions
1018 lines (953 loc) · 50.9 KB
/
Copy pathClrLirAssemblyEmitter.cs
File metadata and controls
1018 lines (953 loc) · 50.9 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
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
using System.Collections.Immutable;
using System.Buffers.Binary;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
using System.Text;
using RustSharp.Syntax;
namespace RustSharp.CodeGen.IL;
/// <summary>
/// Emits executable PE images from validated CLR LIR, including direct calls
/// between generated static methods and the supported Console.WriteLine overloads.
/// </summary>
public static partial class ClrLirAssemblyEmitter
{
private const string EmitterIdentity = "RustSharp.CodeGen.IL/ClrLir/0.1.0";
private const string RuntimeConfig = """
{
"runtimeOptions": {
"tfm": "net10.0",
"framework": {
"name": "Microsoft.NETCore.App",
"version": "10.0.0"
}
}
}
""";
private static readonly Version RuntimeAssemblyVersion = new(10, 0, 0, 0);
private static readonly ImmutableArray<byte> RuntimePublicKeyToken =
[0xb0, 0x3f, 0x5f, 0x7f, 0x11, 0xd5, 0x0a, 0x3a];
/// <summary>
/// Emits an executable PE whose entry point is <paramref name="method"/>.
/// The currently supported call-site names are <c>Console.WriteLine</c>
/// and <c>System.Console.WriteLine</c>.
/// </summary>
public static GeneratedAssembly Emit(
ClrLirMethod method,
string assemblyName,
RustSharpMetadataDocument? metadataDocument = null)
{
ArgumentNullException.ThrowIfNull(method);
return EmitCore([method], method.Name, assemblyName, null, null, null, default,
metadataDocument: metadataDocument);
}
public static GeneratedAssembly Emit(ClrLirMethod method, string assemblyName,
IEnumerable<ClrLirValueType> valueTypes, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(method);
ArgumentNullException.ThrowIfNull(valueTypes);
return EmitCore([method], method.Name, assemblyName, null, null, null, default,
cancellationToken: cancellationToken, valueTypes: valueTypes);
}
public static GeneratedAssembly EmitProgram(
SafeCoreClrResult program,
string assemblyName,
string sourceText,
string sourcePath,
string pdbFileName,
ReadOnlyMemory<byte> sourceBytes = default,
SafeCoreSourceMap? sourceMap = null,
CancellationToken cancellationToken = default) =>
EmitProgram(program, assemblyName, sourceText, sourcePath, pdbFileName, sourceBytes, sourceMap,
metadataDocument: null, cancellationToken: cancellationToken);
public static GeneratedAssembly EmitProgram(
SafeCoreClrResult program,
string assemblyName,
string sourceText,
string sourcePath,
string pdbFileName,
ReadOnlyMemory<byte> sourceBytes,
SafeCoreSourceMap? sourceMap,
RustSharpMetadataDocument? metadataDocument,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(program);
if (!program.IsSuccessful) throw new ArgumentException("A successful lowered program is required.", nameof(program));
return EmitCore(program.Methods, "Main", assemblyName, sourceText, sourcePath,
pdbFileName, sourceBytes, program.MethodSpans, sourceMap, metadataDocument,
program.ValueTypes, program.GenericMetadata, cancellationToken: cancellationToken);
}
private static GeneratedAssembly EmitCore(
IReadOnlyList<ClrLirMethod> methods,
string entryPointName,
string assemblyName,
string? sourceText,
string? sourcePath,
string? pdbFileName,
ReadOnlyMemory<byte> sourceBytes,
IReadOnlyList<TextSpan>? methodSpans = null,
SafeCoreSourceMap? sourceMap = null,
RustSharpMetadataDocument? metadataDocument = null,
IEnumerable<ClrLirValueType>? valueTypes = null,
ReadOnlyMemory<byte> genericMetadata = default,
bool stampMethodBodies = true,
CancellationToken cancellationToken = default)
{
var sourceMapClock = Stopwatch.StartNew();
cancellationToken.ThrowIfCancellationRequested();
if (stampMethodBodies && metadataDocument is not null)
{
ImmutableArray<ClrLirValueType> stableLayouts = new ClrLirValueTypeSet(valueTypes ?? [], CheckSourceMapBudget).Definitions;
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
deadline.CancelAfter(TimeSpan.FromSeconds(20));
try
{
GeneratedAssembly first = EmitCore(methods, entryPointName, assemblyName, sourceText, sourcePath,
pdbFileName, sourceBytes, methodSpans, sourceMap, metadataDocument, stableLayouts, genericMetadata,
stampMethodBodies: false, cancellationToken: deadline.Token);
RustSharpMetadataDocument stamped = RustSharpMetadataDocument.Parse(first.RustSharpMetadataJson!)
.WithMethodBodies(RustSharpMetadataMethodBodies.Capture(first.PeImage, deadline.Token));
GeneratedAssembly final = EmitCore(methods, entryPointName, assemblyName, sourceText, sourcePath,
pdbFileName, sourceBytes, methodSpans, sourceMap, stamped, stableLayouts, genericMetadata,
stampMethodBodies: false, cancellationToken: deadline.Token);
if (!RustSharpMetadataMethodBodies.Capture(final.PeImage, deadline.Token).SequenceEqual(stamped.EmittedMethodBodies))
throw new InvalidOperationException("The final PE method bodies disagree with their stamped source evidence.");
return final;
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
throw new TimeoutException("The two-pass method body evidence emission exceeded its twenty second budget.");
}
}
ArgumentException.ThrowIfNullOrWhiteSpace(assemblyName);
if (genericMetadata.Length > 8 * 1024 * 1024)
throw new ArgumentException("Generic metadata exceeds the 8 MiB resource limit.", nameof(genericMetadata));
byte[] genericResource = genericMetadata.ToArray();
if (methods.Count is < 1 or > 128) throw new ArgumentException("Expected 1 to 128 methods.", nameof(methods));
if (sourceMap is not null && sourceMap.Documents.Count is (< 1 or > 1024))
throw new ArgumentException("Expected 1 to 1024 source documents.", nameof(sourceMap));
var layouts = new ClrLirValueTypeSet(valueTypes ?? [], CheckSourceMapBudget);
ImmutableArray<ClrLirValueType> localLayouts = [.. layouts.Definitions.Where(static layout => layout.ExternalAssemblyName is null)];
// Value layouts are part of the source package contract. Reconcile the
// caller-supplied document with the actual emitted definitions before
// embedding it, so consumers can validate nominal MemberRefs without
// loading or executing producer code.
if (metadataDocument is not null && localLayouts.Length != 0)
{
var metadataLayouts = localLayouts.Select(static layout =>
new RustSharpMetadataValueType(layout.Name,
layout.Fields.Select(static field => new RustSharpMetadataField(field.Name, field.Type.ToString()))));
metadataDocument = metadataDocument.WithValueTypes(metadataLayouts);
}
var definitions = new Dictionary<string, (ClrLirMethod Method, MethodDefinitionHandle Handle)>(StringComparer.Ordinal);
for (int index = 0; index < methods.Count; index++)
{
ClrLirMethod method = methods[index];
ArgumentNullException.ThrowIfNull(method);
CheckSourceMapBudget();
ClrLirValidationResult validation = method.Validate(cancellationToken);
if (!validation.IsValid)
throw new InvalidOperationException($"Cannot emit invalid CLR LIR: {string.Join("; ", validation.Diagnostics)}");
layouts.ValidateMethod(method);
if (!definitions.TryAdd(method.Name, (method, MetadataTokens.MethodDefinitionHandle(index + 1))))
throw new ArgumentException("Duplicate method name.", nameof(methods));
}
if (!definitions.TryGetValue(entryPointName, out var entry) || entry.Method.Parameters.Length != 0 ||
entry.Method.ReturnType.Kind is not (ClrLirTypeKind.Void or ClrLirTypeKind.I32))
throw new ArgumentException("The entry point must have no parameters and return void or i32.", nameof(entryPointName));
if (assemblyName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 ||
!string.Equals(assemblyName, Path.GetFileName(assemblyName), StringComparison.Ordinal))
{
throw new ArgumentException("The assembly name must be a simple file name.", nameof(assemblyName));
}
var metadata = new MetadataBuilder();
var ilStream = new BlobBuilder();
var methodBodyStream = new MethodBodyStreamEncoder(ilStream);
using var identity = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
foreach (ClrLirMethod method in methods)
identity.AppendData(CreateModuleVersionId(assemblyName, method, CheckSourceMapBudget).ToByteArray());
foreach (ClrLirValueType layout in localLayouts)
{
CheckSourceMapBudget();
identity.AppendData(Encoding.UTF8.GetBytes("\0value\0" + layout.Name));
identity.AppendData(layout.ImplementsMirValue ? "\0mir-accessors\0"u8 : "\0plain-value\0"u8);
foreach (ClrLirField field in layout.Fields)
identity.AppendData(Encoding.UTF8.GetBytes("\0" + field.Name + ":" + field.Type));
}
if (genericResource.Length != 0)
{
identity.AppendData("\0RustSharp.Generics.v1.json\0"u8);
identity.AppendData(genericResource);
}
identity.AppendData(sourceBytes.Span);
if (metadataDocument is not null)
{
byte[] metadataBytes = Encoding.UTF8.GetBytes(metadataDocument.Json);
Span<byte> encodedLength = stackalloc byte[sizeof(int)];
BinaryPrimitives.WriteInt32LittleEndian(encodedLength, metadataBytes.Length);
identity.AppendData(encodedLength);
identity.AppendData(metadataBytes);
}
if (sourceMap is not null)
{
Span<byte> encodedLength = stackalloc byte[sizeof(int)];
BinaryPrimitives.WriteInt32LittleEndian(encodedLength, sourceMap.Documents.Count);
identity.AppendData(encodedLength);
for (int index = 0; index < sourceMap.Documents.Count; index++)
{
CheckSourceMapBudget();
SafeCoreSourceDocument sourceDocument = sourceMap.Documents[index];
byte[] pathBytes = Encoding.UTF8.GetBytes(sourceDocument.Path);
BinaryPrimitives.WriteInt32LittleEndian(encodedLength, pathBytes.Length);
identity.AppendData(encodedLength);
identity.AppendData(pathBytes);
BinaryPrimitives.WriteInt32LittleEndian(encodedLength, sourceDocument.Bytes.Length);
identity.AppendData(encodedLength);
identity.AppendData(sourceDocument.Bytes.Span);
}
}
Guid moduleVersionId = new(identity.GetHashAndReset().AsSpan(0, 16));
metadata.AddModule(
generation: 0,
moduleName: metadata.GetOrAddString(assemblyName + ".dll"),
mvid: metadata.GetOrAddGuid(moduleVersionId),
encId: default,
encBaseId: default);
AssemblyDefinitionHandle assemblyDefinition = metadata.AddAssembly(
name: metadata.GetOrAddString(assemblyName),
version: new Version(1, 0, 0, 0),
culture: default,
publicKey: default,
flags: default,
hashAlgorithm: AssemblyHashAlgorithm.Sha256);
BlobHandle runtimePublicKeyToken = metadata.GetOrAddBlob(RuntimePublicKeyToken);
AssemblyReferenceHandle systemRuntime = AddFrameworkReference(
metadata,
"System.Runtime",
runtimePublicKeyToken);
AssemblyReferenceHandle systemConsole = AddFrameworkReference(
metadata,
"System.Console",
runtimePublicKeyToken);
if (metadataDocument is not null)
{
AddRustSharpMetadataAttribute(metadata, assemblyDefinition, systemRuntime, metadataDocument.Json);
}
if (methods.Any(static method => method.PanicHandling?.DropCleanupProfile == SafeCoreDropCleanupProfile.NativeV2))
AddAssemblyMetadataAttribute(metadata, assemblyDefinition, systemRuntime, SafeCoreDropCleanupProfiles.MetadataKey,
SafeCoreDropCleanupProfiles.NativeV2MetadataValue);
TypeReferenceHandle objectType = metadata.AddTypeReference(
resolutionScope: systemRuntime,
@namespace: metadata.GetOrAddString("System"),
name: metadata.GetOrAddString("Object"));
TypeReferenceHandle consoleType = metadata.AddTypeReference(
resolutionScope: systemConsole,
@namespace: metadata.GetOrAddString("System"),
name: metadata.GetOrAddString("Console"));
var externalAssemblies = new Dictionary<string, AssemblyReferenceHandle>(StringComparer.Ordinal);
var externalTypes = new Dictionary<(string Assembly, string Namespace, string Name), TypeReferenceHandle>();
var valueHandles = new Dictionary<string, EntityHandle>(StringComparer.Ordinal);
var constructorHandles = new Dictionary<string, EntityHandle>(StringComparer.Ordinal);
var fieldHandles = new Dictionary<string, ImmutableArray<FieldDefinitionHandle>>(StringComparer.Ordinal);
var externalFieldHandles = new Dictionary<(string Name, int Index), EntityHandle>();
int fieldRow = 1;
int valueMethodRow = methods.Count + 1;
foreach (ClrLirValueType imported in layouts.Definitions.Where(static layout => layout.ExternalAssemblyName is not null))
{
CheckSourceMapBudget();
TypeReferenceHandle typeHandle = AddExternalValueTypeReference(metadata, externalAssemblies, externalTypes,
new(imported.ExternalAssemblyName!, "RustSharp.Generated.Values", imported.ExternalClrName!, ".ctor"),
imported.ExternalClrName!);
valueHandles.Add(imported.Name, typeHandle);
constructorHandles.Add(imported.Name, metadata.AddMemberReference(typeHandle, metadata.GetOrAddString(".ctor"),
CreateMethodSignature(metadata, ClrLirType.Void, imported.Fields.Select(static field => field.Type).ToArray(),
valueHandles, isInstanceMethod: true,
externalValueResolver: name => AddExternalValueTypeReference(metadata, externalAssemblies, externalTypes,
new(imported.ExternalAssemblyName!, "RustSharp.Generated.Values", imported.ExternalClrName!, ".ctor"), name))));
for (int fieldIndex = 0; fieldIndex < imported.Fields.Length; fieldIndex++)
{
CheckSourceMapBudget();
ClrLirField field = imported.Fields[fieldIndex];
var signature = new BlobBuilder();
EncodeSignatureType(new BlobEncoder(signature).FieldSignature(), field.Type, valueHandles,
name => AddExternalValueTypeReference(metadata, externalAssemblies, externalTypes,
new(imported.ExternalAssemblyName!, "RustSharp.Generated.Values", imported.ExternalClrName!, ".ctor"), name));
externalFieldHandles.Add((imported.Name, fieldIndex), metadata.AddMemberReference(typeHandle,
metadata.GetOrAddString(field.Name), metadata.GetOrAddBlob(signature)));
}
}
for (int index = 0; index < localLayouts.Length; index++)
{
CheckSourceMapBudget();
ClrLirValueType layout = localLayouts[index];
valueHandles.Add(layout.Name, MetadataTokens.TypeDefinitionHandle(index + 3));
constructorHandles.Add(layout.Name, MetadataTokens.MethodDefinitionHandle(valueMethodRow));
valueMethodRow += layout.ImplementsMirValue ? 3 : 1;
var fields = ImmutableArray.CreateBuilder<FieldDefinitionHandle>(layout.Fields.Length);
for (int fieldIndex = 0; fieldIndex < layout.Fields.Length; fieldIndex++)
fields.Add(MetadataTokens.FieldDefinitionHandle(fieldRow++));
fieldHandles.Add(layout.Name, fields.ToImmutable());
}
var localSignatures = new List<StandaloneSignatureHandle>();
foreach (ClrLirMethod method in methods)
{
var methodCode = new BlobBuilder();
var controlFlow = new ControlFlowBuilder();
var instructionEncoder = new InstructionEncoder(methodCode, controlFlow);
int maxStack = ClrLirEmitter.EncodeInstructions(
method,
metadata,
site => ResolveCall(metadata, consoleType, definitions, externalAssemblies, externalTypes, site),
instructionEncoder,
layout => constructorHandles[layout.Name], (layout, index) => layout.ExternalAssemblyName is null
? fieldHandles[layout.Name][index] : externalFieldHandles[(layout.Name, index)],
CheckSourceMapBudget, type => valueHandles[type.Name!], cancellationToken);
StandaloneSignatureHandle localSignature = AddLocalSignature(metadata, method.Locals, valueHandles);
localSignatures.Add(localSignature);
int methodBodyOffset = methodBodyStream.AddMethodBody(instructionEncoder, maxStack, localSignature);
MethodAttributes visibility = method.IsPublic
? MethodAttributes.Public
: MethodAttributes.Assembly;
metadata.AddMethodDefinition(
attributes: visibility | MethodAttributes.Static | MethodAttributes.HideBySig,
implAttributes: MethodImplAttributes.IL | MethodImplAttributes.Managed,
name: metadata.GetOrAddString(method.Name),
signature: CreateMethodSignature(metadata, method.ReturnType, method.Parameters, valueHandles),
bodyOffset: methodBodyOffset,
parameterList: MetadataTokens.ParameterHandle(1));
}
MethodDefinitionHandle entryPoint = entry.Handle;
MethodDefinitionHandle firstMethod = MetadataTokens.MethodDefinitionHandle(1);
FieldDefinitionHandle firstField = MetadataTokens.FieldDefinitionHandle(1);
metadata.AddTypeDefinition(
attributes: TypeAttributes.NotPublic,
@namespace: default,
name: metadata.GetOrAddString("<Module>"),
baseType: default,
fieldList: firstField,
methodList: firstMethod);
metadata.AddTypeDefinition(
attributes: TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit,
@namespace: metadata.GetOrAddString("RustSharp.Generated"),
name: metadata.GetOrAddString("Program"),
baseType: objectType,
fieldList: firstField,
methodList: firstMethod);
if (!localLayouts.IsEmpty)
{
TypeReferenceHandle valueTypeBase = metadata.AddTypeReference(systemRuntime,
metadata.GetOrAddString("System"), metadata.GetOrAddString("ValueType"));
int nextFieldRow = 1;
foreach (ClrLirValueType layout in localLayouts)
{
CheckSourceMapBudget();
FieldDefinitionHandle firstValueField = MetadataTokens.FieldDefinitionHandle(nextFieldRow);
var constructorCode = new BlobBuilder();
var constructorEncoder = new InstructionEncoder(constructorCode);
for (int index = 0; index < layout.Fields.Length; index++)
{
CheckSourceMapBudget();
ClrLirField field = layout.Fields[index];
var signature = new BlobBuilder();
EncodeSignatureType(new BlobEncoder(signature).FieldSignature(), field.Type, valueHandles);
FieldDefinitionHandle handle = metadata.AddFieldDefinition(FieldAttributes.Public,
metadata.GetOrAddString(field.Name), metadata.GetOrAddBlob(signature));
if (handle != fieldHandles[layout.Name][index]) throw new InvalidOperationException("Unstable CLR field order.");
nextFieldRow++;
constructorEncoder.LoadArgument(0);
constructorEncoder.LoadArgument(index + 1);
constructorEncoder.OpCode(ILOpCode.Stfld);
constructorEncoder.Token(handle);
}
constructorEncoder.OpCode(ILOpCode.Ret);
int bodyOffset = methodBodyStream.AddMethodBody(constructorEncoder, 2);
MethodDefinitionHandle constructor = metadata.AddMethodDefinition(
MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
MethodImplAttributes.IL | MethodImplAttributes.Managed,
metadata.GetOrAddString(".ctor"),
CreateMethodSignature(metadata, ClrLirType.Void, [.. layout.Fields.Select(static field => field.Type)],
valueHandles, isInstanceMethod: true), bodyOffset, MetadataTokens.ParameterHandle(1));
if (constructor != constructorHandles[layout.Name]) throw new InvalidOperationException("Unstable CLR constructor order.");
TypeDefinitionHandle handleType = metadata.AddTypeDefinition(
TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.SequentialLayout | TypeAttributes.BeforeFieldInit,
metadata.GetOrAddString("RustSharp.Generated.Values"), metadata.GetOrAddString(layout.Name),
valueTypeBase, firstValueField, constructor);
if (handleType != valueHandles[layout.Name]) throw new InvalidOperationException("Unstable CLR value type order.");
if (layout.ImplementsMirValue)
EmitMirValueAccessors(metadata, methodBodyStream, layout, handleType,
constructor, fieldHandles[layout.Name], valueHandles, CheckSourceMapBudget);
}
}
BlobBuilder? managedResources = null;
if (genericResource.Length != 0)
{
CheckSourceMapBudget();
managedResources = new BlobBuilder();
managedResources.WriteInt32(genericResource.Length);
managedResources.WriteBytes(genericResource);
managedResources.Align(8);
metadata.AddManifestResource(ManifestResourceAttributes.Public,
metadata.GetOrAddString("RustSharp.Generics.v1.json"), default, 0);
}
byte[]? pdbBytes = null;
DebugDirectoryBuilder? debugDirectory = null;
if (sourcePath is not null && sourceText is not null && pdbFileName is not null && methodSpans is not null)
{
ReadOnlyMemory<byte> effectiveBytes = sourceBytes.IsEmpty ? Encoding.UTF8.GetBytes(sourceText) : sourceBytes;
var pdbMetadata = new MetadataBuilder();
var sourceDocuments = new Dictionary<string, DocumentHandle>(StringComparer.Ordinal);
DocumentHandle document = default;
if (sourceMap is null)
{
document = AddSourceDocument(sourcePath, effectiveBytes);
}
else
{
for (int index = 0; index < sourceMap.Documents.Count; index++)
{
CheckSourceMapBudget();
SafeCoreSourceDocument sourceDocument = sourceMap.Documents[index];
sourceDocuments.Add(sourceDocument.Path, AddSourceDocument(sourceDocument.Path, sourceDocument.Bytes));
}
}
for (int index = 0; index < methods.Count; index++)
{
CheckSourceMapBudget();
string methodSource = sourceText;
TextSpan methodSpan = methodSpans[index];
DocumentHandle methodDocument = document;
if (sourceMap is not null)
{
SafeCoreSourceLocation location = sourceMap.MapSpan(methodSpan);
methodSource = location.Document.Text;
methodSpan = location.Span;
methodDocument = sourceDocuments[location.Document.Path];
}
BlobHandle points = IlAssemblyEmitter.CreateSequencePointsBlob(pdbMetadata, methodSource,
[new IlAssemblyEmitter.SequencePointData(0, methodSpan)],
MetadataTokens.GetRowNumber(localSignatures[index]));
pdbMetadata.AddMethodDebugInformation(points.IsNil ? default : methodDocument, points);
}
foreach (ClrLirValueType layout in localLayouts)
{
pdbMetadata.AddMethodDebugInformation(default, default);
if (layout.ImplementsMirValue)
{
pdbMetadata.AddMethodDebugInformation(default, default);
pdbMetadata.AddMethodDebugInformation(default, default);
}
}
var pdbImage = new BlobBuilder();
BlobContentId pdbId = new PortablePdbBuilder(pdbMetadata, metadata.GetRowCounts(), entryPoint, ComputeContentId).Serialize(pdbImage);
pdbBytes = pdbImage.ToArray();
debugDirectory = new DebugDirectoryBuilder();
debugDirectory.AddCodeViewEntry(pdbFileName, pdbId, 0x0100);
DocumentHandle AddSourceDocument(string path, ReadOnlyMemory<byte> bytes) => pdbMetadata.AddDocument(
pdbMetadata.GetOrAddDocumentName(path),
pdbMetadata.GetOrAddGuid(new Guid("8829d00f-11b8-4213-878b-770e8597ac16")),
pdbMetadata.GetOrAddBlob(SHA256.HashData(bytes.Span)), default);
}
var peHeader = new PEHeaderBuilder(
imageCharacteristics: Characteristics.ExecutableImage | Characteristics.LargeAddressAware,
subsystem: Subsystem.WindowsCui);
var peBuilder = new ManagedPEBuilder(
peHeader,
new MetadataRootBuilder(metadata),
ilStream,
managedResources: managedResources,
debugDirectoryBuilder: debugDirectory,
entryPoint: entryPoint,
flags: CorFlags.ILOnly,
deterministicIdProvider: ComputeContentId);
var peImage = new BlobBuilder();
peBuilder.Serialize(peImage);
return new GeneratedAssembly(peImage.ToArray(), pdbBytes, RuntimeConfig, metadataDocument?.Json)
{
RequiresMirRuntime = localLayouts.Any(static layout => layout.ImplementsMirValue) ||
methods.Any(static method => method.PanicHandling is not null || method.Blocks.Any(static block => block.Instructions.Any(static instruction =>
instruction is ClrLirCall { Site.ExternalCall.AssemblyName: "RustSharp.Runtime" }))),
};
void CheckSourceMapBudget()
{
cancellationToken.ThrowIfCancellationRequested();
if (sourceMapClock.Elapsed > TimeSpan.FromSeconds(10))
throw new TimeoutException("CLR assembly emission exceeded its time limit.");
}
}
private static void AddRustSharpMetadataAttribute(
MetadataBuilder metadata,
AssemblyDefinitionHandle assembly,
AssemblyReferenceHandle runtime,
string json) => AddAssemblyMetadataAttribute(metadata, assembly, runtime, RustSharpMetadataReader.AttributeKey, json);
private static void AddAssemblyMetadataAttribute(MetadataBuilder metadata, AssemblyDefinitionHandle assembly,
AssemblyReferenceHandle systemRuntime, string key, string text)
{
TypeReferenceHandle attributeType = metadata.AddTypeReference(
resolutionScope: systemRuntime,
@namespace: metadata.GetOrAddString("System.Reflection"),
name: metadata.GetOrAddString("AssemblyMetadataAttribute"));
var signature = new BlobBuilder();
new BlobEncoder(signature)
.MethodSignature(isInstanceMethod: true)
.Parameters(
parameterCount: 2,
returnType => returnType.Void(),
parameters =>
{
parameters.AddParameter().Type().String();
parameters.AddParameter().Type().String();
});
MemberReferenceHandle constructor = metadata.AddMemberReference(
attributeType,
metadata.GetOrAddString(".ctor"),
metadata.GetOrAddBlob(signature));
var value = new BlobBuilder();
value.WriteUInt16(1);
value.WriteSerializedString(key);
value.WriteSerializedString(text);
// ECMA-335 II.23.3 requires NumNamed even when it is zero. NativeAOT
// decodes assembly attributes while rooting reflected value layouts.
value.WriteUInt16(0);
metadata.AddCustomAttribute(assembly, constructor, metadata.GetOrAddBlob(value));
}
private static EntityHandle ResolveCall(
MetadataBuilder metadata,
TypeReferenceHandle consoleType,
Dictionary<string, (ClrLirMethod Method, MethodDefinitionHandle Handle)> definitions,
Dictionary<string, AssemblyReferenceHandle> externalAssemblies,
Dictionary<(string Assembly, string Namespace, string Name), TypeReferenceHandle> externalTypes,
ClrLirCallSite site)
{
if (site.ExternalCall is { } external)
{
return AddExternalCallReference(metadata, externalAssemblies, externalTypes, external, site);
}
if (definitions.TryGetValue(site.Name, out var definition))
{
if (site.ReturnType != definition.Method.ReturnType || !site.ParameterTypes.SequenceEqual(definition.Method.Parameters))
throw new InvalidOperationException("Generated call signature does not match its target.");
return definition.Handle;
}
return AddCallReference(metadata, consoleType, site);
}
private static MemberReferenceHandle AddExternalCallReference(
MetadataBuilder metadata,
Dictionary<string, AssemblyReferenceHandle> externalAssemblies,
Dictionary<(string Assembly, string Namespace, string Name), TypeReferenceHandle> externalTypes,
ClrLirExternalCall external,
ClrLirCallSite site)
{
if (!externalAssemblies.TryGetValue(external.AssemblyName, out AssemblyReferenceHandle assembly))
{
assembly = metadata.AddAssemblyReference(
name: metadata.GetOrAddString(external.AssemblyName),
version: external.AssemblyName == "RustSharp.Runtime" ? new Version(0, 1, 0, 0) : new Version(1, 0, 0, 0),
culture: default,
publicKeyOrToken: default,
flags: default,
hashValue: default);
externalAssemblies.Add(external.AssemblyName, assembly);
}
var typeKey = (external.AssemblyName, external.TypeNamespace, external.TypeName);
if (!externalTypes.TryGetValue(typeKey, out TypeReferenceHandle type))
{
type = metadata.AddTypeReference(
resolutionScope: assembly,
@namespace: metadata.GetOrAddString(external.TypeNamespace),
name: metadata.GetOrAddString(external.TypeName));
externalTypes.Add(typeKey, type);
}
return metadata.AddMemberReference(
parent: type,
name: metadata.GetOrAddString(external.MethodName),
// A value in an imported signature belongs to the producer
// assembly. Encoding it with the consumer's local value handles
// would create a same-named but different CLR type and makes the
// MemberRef unverifiable at runtime. Resolve every aggregate in
// this signature through a TypeRef scoped to the producer.
signature: CreateMethodSignature(metadata, site.ReturnType, site.ParameterTypes,
externalValueResolver: name => AddExternalValueTypeReference(
metadata, externalAssemblies, externalTypes, external, name)));
}
private static TypeReferenceHandle AddExternalValueTypeReference(
MetadataBuilder metadata,
Dictionary<string, AssemblyReferenceHandle> externalAssemblies,
Dictionary<(string Assembly, string Namespace, string Name), TypeReferenceHandle> externalTypes,
ClrLirExternalCall external,
string name)
{
int separator = name.IndexOf("::", StringComparison.Ordinal);
if (separator > 0)
{
external = new(name[..separator], "RustSharp.Generated.Values", name[(separator + 2)..], ".ctor");
name = name[(separator + 2)..];
}
if (!externalAssemblies.TryGetValue(external.AssemblyName, out AssemblyReferenceHandle assembly))
{
assembly = metadata.AddAssemblyReference(
name: metadata.GetOrAddString(external.AssemblyName),
version: new Version(1, 0, 0, 0),
culture: default,
publicKeyOrToken: default,
flags: default,
hashValue: default);
externalAssemblies.Add(external.AssemblyName, assembly);
}
var key = (external.AssemblyName, "RustSharp.Generated.Values", name);
if (!externalTypes.TryGetValue(key, out TypeReferenceHandle type))
{
type = metadata.AddTypeReference(
resolutionScope: assembly,
@namespace: metadata.GetOrAddString(key.Item2),
name: metadata.GetOrAddString(name));
externalTypes.Add(key, type);
}
return type;
}
private static AssemblyReferenceHandle AddFrameworkReference(
MetadataBuilder metadata,
string name,
BlobHandle publicKeyToken) =>
metadata.AddAssemblyReference(
name: metadata.GetOrAddString(name),
version: RuntimeAssemblyVersion,
culture: default,
publicKeyOrToken: publicKeyToken,
flags: default,
hashValue: default);
private static MemberReferenceHandle AddCallReference(
MetadataBuilder metadata,
TypeReferenceHandle consoleType,
ClrLirCallSite site)
{
if (!string.Equals(site.Name, "Console.WriteLine", StringComparison.Ordinal) &&
!string.Equals(site.Name, "System.Console.WriteLine", StringComparison.Ordinal))
{
throw new NotSupportedException(
$"The CLR LIR PE spike does not support call site '{site.Name}'.");
}
if (site.ReturnType != ClrLirType.Void || site.ParameterTypes.Length != 1 ||
site.ParameterTypes[0].Kind is not (ClrLirTypeKind.I32 or ClrLirTypeKind.Bool or ClrLirTypeKind.Text or ClrLirTypeKind.Any))
{
throw new NotSupportedException(
"The CLR LIR PE spike supports only one-argument void Console.WriteLine overloads.");
}
return metadata.AddMemberReference(
parent: consoleType,
name: metadata.GetOrAddString("WriteLine"),
signature: CreateMethodSignature(metadata, site.ReturnType, site.ParameterTypes));
}
private static BlobHandle CreateMethodSignature(
MetadataBuilder metadata,
ClrLirType methodReturnType,
IReadOnlyList<ClrLirType> parameterTypes,
IReadOnlyDictionary<string, EntityHandle>? valueHandles = null,
bool isInstanceMethod = false,
Func<string, EntityHandle>? externalValueResolver = null)
{
var signature = new BlobBuilder();
new BlobEncoder(signature)
.MethodSignature(isInstanceMethod: isInstanceMethod)
.Parameters(
parameterCount: parameterTypes.Count,
returnTypeEncoder => EncodeReturnType(returnTypeEncoder, methodReturnType, valueHandles, externalValueResolver),
parameters =>
{
foreach (ClrLirType parameterType in parameterTypes)
{
EncodeParameterType(parameters.AddParameter().Type(
isByRef: parameterType.Kind == ClrLirTypeKind.ByReference), parameterType,
valueHandles, externalValueResolver);
}
});
return metadata.GetOrAddBlob(signature);
}
private static void EncodeReturnType(
System.Reflection.Metadata.Ecma335.ReturnTypeEncoder encoder,
ClrLirType type,
IReadOnlyDictionary<string, EntityHandle>? valueHandles,
Func<string, EntityHandle>? externalValueResolver = null)
{
if (type == ClrLirType.Void)
{
encoder.Void();
return;
}
if (type.Kind == ClrLirTypeKind.ByReference)
{
if (!type.TryGetByReferenceElement(out ClrLirType element))
throw new ArgumentException("Invalid by-reference return type.", nameof(type));
EncodeSignatureType(encoder.Type(isByRef: true), element, valueHandles, externalValueResolver);
return;
}
EncodeSignatureType(encoder.Type(isByRef: false), type, valueHandles, externalValueResolver);
}
private static void EncodeParameterType(
System.Reflection.Metadata.Ecma335.SignatureTypeEncoder encoder,
ClrLirType type,
IReadOnlyDictionary<string, EntityHandle>? valueHandles,
Func<string, EntityHandle>? externalValueResolver = null)
{
if (type == ClrLirType.Void)
{
throw new ArgumentException("Void is not a valid parameter type.", nameof(type));
}
if (type.Kind == ClrLirTypeKind.ByReference)
{
if (!type.TryGetByReferenceElement(out ClrLirType element))
throw new ArgumentException("Invalid by-reference parameter type.", nameof(type));
EncodeSignatureType(encoder, element, valueHandles, externalValueResolver);
return;
}
EncodeSignatureType(encoder, type, valueHandles, externalValueResolver);
}
private static void EncodeSignatureType(
System.Reflection.Metadata.Ecma335.SignatureTypeEncoder encoder,
ClrLirType type,
IReadOnlyDictionary<string, EntityHandle>? valueHandles,
Func<string, EntityHandle>? externalValueResolver = null)
{
switch (type.Kind)
{
case ClrLirTypeKind.I32:
encoder.Int32();
break;
case ClrLirTypeKind.Bool:
encoder.Boolean();
break;
case ClrLirTypeKind.Text:
encoder.String();
break;
case ClrLirTypeKind.Any:
encoder.Object();
break;
case ClrLirTypeKind.Value when type.Name is not null && valueHandles is not null && valueHandles.TryGetValue(type.Name, out EntityHandle handle):
encoder.Type(handle, isValueType: true);
break;
case ClrLirTypeKind.Value when type.Name is not null && externalValueResolver is not null:
encoder.Type(externalValueResolver(type.Name), isValueType: true);
break;
case ClrLirTypeKind.ByReference:
throw new ArgumentException("By-reference encoding requires a parameter or return signature encoder.", nameof(type));
default:
throw new ArgumentException($"Unsupported CLR LIR signature type '{type}'.", nameof(type));
}
}
private static StandaloneSignatureHandle AddLocalSignature(
MetadataBuilder metadata,
ImmutableArray<ClrLirLocal> locals,
IReadOnlyDictionary<string, EntityHandle> valueHandles)
{
if (locals.IsEmpty)
{
return default;
}
var signature = new BlobBuilder();
LocalVariablesEncoder variables = new BlobEncoder(signature).LocalVariableSignature(locals.Length);
foreach (ClrLirLocal local in locals)
{
if (local.Type == ClrLirType.Void)
{
throw new ArgumentException("Void is not a valid local type.", nameof(locals));
}
if (local.Type.Kind == ClrLirTypeKind.ByReference)
{
if (!local.Type.TryGetByReferenceElement(out ClrLirType element))
throw new ArgumentException("Invalid managed by-reference local.", nameof(locals));
EncodeSignatureType(variables.AddVariable().Type(isByRef: true, isPinned: false), element, valueHandles);
continue;
}
EncodeSignatureType(variables.AddVariable().Type(isByRef: false, isPinned: false), local.Type, valueHandles);
}
return metadata.AddStandaloneSignature(metadata.GetOrAddBlob(signature));
}
private static Guid CreateModuleVersionId(string assemblyName, ClrLirMethod method, Action checkBudget)
{
var descriptor = new StringBuilder(EmitterIdentity)
.Append('\0')
.Append(assemblyName)
.Append('\0')
.Append(method.Name)
.Append('\0')
.Append(method.ReturnType);
_ = descriptor.Append('\0').Append("params");
foreach (ClrLirType parameter in method.Parameters)
{
_ = descriptor.Append('\0').Append(parameter);
}
_ = descriptor.Append('\0').Append("locals");
foreach (ClrLirLocal local in method.Locals)
{
_ = descriptor.Append('\0').Append(local.Name).Append(':').Append(local.Type);
}
foreach (ClrLirBlock block in method.Blocks)
{
_ = descriptor.Append('\0').Append(block.Label);
foreach (ClrLirInstruction instruction in block.Instructions)
{
checkBudget();
_ = descriptor.Append('\0').Append(instruction.GetType().Name);
switch (instruction)
{
case ClrLirBox box:
descriptor.Append(box.Type);
break;
case ClrLirLoadType loadType:
descriptor.Append(loadType.Type);
break;
case ClrLirUnbox unbox:
descriptor.Append(unbox.Type);
break;
case ClrLirLoadInt32 loadInt32:
_ = descriptor.Append(':').Append(loadInt32.Value.ToString(System.Globalization.CultureInfo.InvariantCulture));
break;
case ClrLirLoadBoolean loadBoolean:
_ = descriptor.Append(':').Append(loadBoolean.Value ? '1' : '0');
break;
case ClrLirLoadString loadString:
_ = descriptor.Append(':').Append(loadString.Value);
break;
case ClrLirLoadLocal loadLocal:
_ = descriptor.Append(':').Append(loadLocal.Index);
break;
case ClrLirLoadLocalAddress address:
descriptor.Append(address.Index).Append(':').Append(address.IsMutable);
break;
case ClrLirFieldAddress address:
descriptor.Append(address.Definition.Name).Append(':').Append(address.FieldIndex).Append(':').Append(address.IsMutable);
break;
case ClrLirLoadIndirect load:
descriptor.Append(load.Type);
break;
case ClrLirStoreIndirect store:
descriptor.Append(store.Type);
break;
case ClrLirReadOnlyReference readOnly:
descriptor.Append(readOnly.ElementType);
break;
case ClrLirStoreLocal storeLocal:
_ = descriptor.Append(':').Append(storeLocal.Index);
break;
case ClrLirLoadArgument argument:
_ = descriptor.Append(':').Append(argument.Index);
break;
case ClrLirDiscard discard:
_ = descriptor.Append(':').Append(discard.Type);
break;
case ClrLirConstructValue construct:
_ = descriptor.Append(':').Append(construct.Definition.Name);
break;
case ClrLirReadField field:
_ = descriptor.Append(':').Append(field.Definition.Name).Append(':').Append(field.FieldIndex);
break;
case ClrLirBinary binary:
_ = descriptor.Append(':').Append(binary.Operator).Append(':').Append(binary.OperandType.Kind);
break;
case ClrLirCall call:
_ = descriptor.Append(':').Append(call.Site.Name).Append(':').Append(call.Site.ReturnType);
if (call.Site.ExternalCall is { } external)
{
_ = descriptor.Append(":external:").Append(external.AssemblyName)
.Append(':').Append(external.TypeNamespace)
.Append(':').Append(external.TypeName)
.Append(':').Append(external.MethodName);
if (external.PanicStrategy is { } panic)
_ = descriptor.Append(":panic:").Append(panic);
if (external.ReturnContract is { } resultContract)
_ = descriptor.Append(":return:").Append(resultContract);
foreach (string parameterContract in external.ParameterContracts)
_ = descriptor.Append(":param:").Append(parameterContract);
}
foreach (ClrLirType parameterType in call.Site.ParameterTypes)
{
_ = descriptor.Append(':').Append(parameterType);
}
break;
case ClrLirBranch branch:
_ = descriptor.Append(':').Append(branch.Target);
break;
case ClrLirLeave leave:
_ = descriptor.Append(':').Append(leave.Target);
break;
case ClrLirBranchTrue branchTrue:
_ = descriptor.Append(':').Append(branchTrue.Target);
break;
}
}
}
if (method.HasExceptionCleanup)
{
_ = descriptor.Append('\0').Append("fault-cleanup");
if (method.PanicHandling is { } panic)
{
_ = descriptor.Append(':').Append(panic.PanicLocalIndex).Append(':').Append(panic.CleanupFailureLocalIndex)
.Append(':').Append(panic.NormalCleanupLocalIndex).Append(':').Append(panic.IsEntryBoundary)
.Append(':').Append(panic.AbortWithoutUnwind).Append(':').Append(panic.UnwindStateLocalIndex);
if (panic.DropCleanupProfile != SafeCoreDropCleanupProfile.LegacyV1)
_ = descriptor.Append(":drop-profile:").Append(panic.DropCleanupProfile).Append(':').Append(panic.IsDestructorBody);
}
foreach (ClrLirCallSite cleanup in method.ExceptionCleanup)
{
_ = descriptor.Append('\0');
AppendCleanupCall(cleanup);
}
foreach (ClrLirGuardedCleanup cleanup in method.GuardedExceptionCleanup)
{
_ = descriptor.Append('\0').Append("guard:").Append(cleanup.FlagLocalIndex)
.Append(':').Append(cleanup.ReceiverLocalIndex).Append(':');
AppendCleanupCall(cleanup.Site);
foreach (int flag in cleanup.ConsumedFlagLocalIndices)
_ = descriptor.Append(":consume:").Append(flag);
_ = descriptor.Append(":receiver:").Append(cleanup.ReceiverInstructions.Length);
AppendCleanupInstructions(cleanup.ReceiverInstructions);
_ = descriptor.Append(":guards:").Append(cleanup.GuardInstructions.Length);
foreach (var guard in cleanup.GuardInstructions)
{
checkBudget();
_ = descriptor.Append(":guard-group:").Append(guard.Length);
AppendCleanupInstructions(guard);
}
}
}
byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(descriptor.ToString()));
return new Guid(hash.AsSpan(0, 16));
void AppendCleanupInstructions(IEnumerable<ClrLirInstruction> instructions)
{
foreach (ClrLirInstruction instruction in instructions)
{
checkBudget();
_ = descriptor.Append(':').Append(instruction.GetType().Name);
switch (instruction)
{
case ClrLirLoadLocal local: _ = descriptor.Append(':').Append(local.Index); break;
case ClrLirLoadInt32 integer: _ = descriptor.Append(':').Append(integer.Value); break;
case ClrLirUnbox unbox: _ = descriptor.Append(':').Append(unbox.Type); break;
case ClrLirCall call: AppendCleanupCall(call.Site); break;
}
}
}
void AppendCleanupCall(ClrLirCallSite site)
{
checkBudget();
_ = descriptor.Append(site.Name).Append(':').Append(site.ReturnType);
foreach (ClrLirType parameter in site.ParameterTypes) _ = descriptor.Append(':').Append(parameter);
if (site.ExternalCall is not { } external) return;