Skip to content
← Back

src/ir/emitter/srm_assembly_emitter.ghul

1
@@IF.dotnet()
2
3
namespace IR.Emitter is
4
use System.Reflection.Metadata.BlobBuilder
5
use System.Reflection.Metadata.EntityHandle
6
use System.Reflection.Metadata.BlobHandle
7
use System.Reflection.Metadata.StringHandle
8
use System.Reflection.Metadata.UserStringHandle
9
use System.Reflection.Metadata.AssemblyReferenceHandle
10
use System.Reflection.Metadata.TypeDefinitionHandle
11
use System.Reflection.Metadata.TypeReferenceHandle
12
use System.Reflection.Metadata.MemberReferenceHandle
13
use System.Reflection.Metadata.InterfaceImplementationHandle
14
use System.Reflection.Metadata.MethodDefinitionHandle
15
use System.Reflection.Metadata.MethodAttributes
16
use System.Reflection.Metadata.MethodImplAttributes
17
use System.Reflection.Metadata.Ecma335.MetadataBuilder
18
use System.Reflection.Metadata.Ecma335.MetadataRootBuilder
19
use System.Reflection.Metadata.Ecma335.MetadataTokens
20
use System.Reflection.Metadata.Ecma335.MethodBodyStreamEncoder
21
use System.Reflection.Metadata.Ecma335.InstructionEncoder
22
use System.Reflection.Metadata.Ecma335.TableIndex
23
24
use System.Reflection.PortableExecutable.ManagedPEBuilder
25
use System.Reflection.PortableExecutable.PEHeaderBuilder
26
use System.Reflection.PortableExecutable.CorFlags
27
28
// Owns the in-flight assembly: the metadata builder, the method body
29
// stream, and the reference/member handle caches. Deduplication is
30
// this layer's job — a metadata table holds one row per distinct
31
// reference, with no merging of repeats after the fact.
32
//
33
// Emission is split across two objects: this one, and
34
// SRM_METHOD_BODY_EMITTER for one method body's instructions. The
35
// structure of the assembly comes from SRM_STRUCTURE_WALK, which
36
// reads it from the symbol table rather than accumulating it here.
37
class SRM_ASSEMBLY_EMITTER is
38
_metadata: MetadataBuilder
39
_il_builder: BlobBuilder
40
_body_stream: MethodBodyStreamEncoder
41
42
_assembly_refs: Collections.MAP[string, AssemblyReferenceHandle]
43
_type_refs: Collections.MAP[Semantic.Symbols.Symbol, TypeReferenceHandle]
44
_named_type_refs: Collections.MAP[string, TypeReferenceHandle]
45
46
47
_entry_point: MethodDefinitionHandle?
48
_want_library: bool
49
50
// Resources the build declared, embedded into the manifest
51
// resource table. Collected here and written into one blob at
52
// `write_to` time, so adding one never needs the offsets of
53
// resources added earlier.
54
_resources: Collections.LIST[(name: string, bytes: ubyte[])]
55
56
// The portable PDB format version the debug directory
57
// advertises: 1.0, as every portable PDB emitted to date is.
58
_PORTABLE_PDB_VERSION: ushort static => 0x100us
59
60
// Non-null only when the build asked for debug information.
61
_pdb: SRM_PDB_BUILDER?
62
63
// The module version id, left empty until the content that
64
// determines it has been written. Reserving the blob rather
65
// than filling it now is what lets the id be a hash of the
66
// assembly: the hash is taken over these bytes as zeros, and
67
// the result is written back into them afterwards.
68
_module_version_id: System.Reflection.Metadata.Blob field
69
70
// What an assembly-level attribute hangs off.
71
assembly_handle: EntityHandle
72
73
// `version` is the colon-separated four-part form ("0:0:0:0")
74
// module_version is already built in, so parsing here avoids a
75
// second version representation at the call site.
76
init(module_name: string, assembly_name: string, version: string, want_library: bool) is
77
let parsed_version = parse_version(version)
78
79
_metadata = MetadataBuilder(0, 0, 0, 0)
80
_il_builder = BlobBuilder(256)
81
_body_stream = MethodBodyStreamEncoder(_il_builder)
82
83
_assembly_refs = Collections.MAP[string, AssemblyReferenceHandle]()
84
_type_refs = Collections.MAP[Semantic.Symbols.Symbol, TypeReferenceHandle]()
85
_named_type_refs = Collections.MAP[string, TypeReferenceHandle]()
86
_named_member_refs = Collections.MAP[(owner: int, name: string, signature: string), MemberReferenceHandle]()
87
_method_specs = Collections.MAP[(method: int, signature: string), System.Reflection.Metadata.MethodSpecificationHandle]()
88
_type_specs = Collections.MAP[string, System.Reflection.Metadata.TypeSpecificationHandle]()
89
_resources = Collections.LIST[(name: string, bytes: ubyte[])]()
90
handles = SRM_HANDLES()
91
92
_want_library = want_library
93
94
_sequence_points = Collections.MAP[int, Collections.List[SRM_SEQUENCE_POINT]]()
95
_module_references = Collections.MAP[string, System.Reflection.Metadata.ModuleReferenceHandle]()
96
97
if IoC.CONTAINER.instance.build_flags.want_debug then
98
_pdb = SRM_PDB_BUILDER()
99
fi
100
101
// TypeDef row 1 must be <Module>, before any user type.
102
_metadata.add_type_definition(
103
_,
104
_,
105
_metadata.get_or_add_string("<Module>"),
106
_,
107
MetadataTokens.field_definition_handle(1),
108
MetadataTokens.method_definition_handle(1))
109
110
let reserved_module_version_id = _metadata.reserve_guid()
111
112
_module_version_id = reserved_module_version_id.content
113
114
_metadata.add_module(
115
0,
116
_metadata.get_or_add_string(module_name),
117
reserved_module_version_id.handle,
118
_,
119
_)
120
121
assembly_handle =
122
cast EntityHandle(
123
_metadata.add_assembly(
124
_metadata.get_or_add_string(assembly_name),
125
parsed_version,
126
_,
127
_,
128
_,
129
_))
130
si
131
132
parse_version(value: string) -> System.Version static is
133
let parts = value.split([':'])
134
135
return System.Version(
136
int.parse(parts[0]),
137
int.parse(parts[1]),
138
int.parse(parts[2]),
139
int.parse(parts[3]))
140
si
141
142
get_or_add_string(value: string) -> StringHandle =>
143
_metadata.get_or_add_string(value)
144
145
get_or_add_user_string(value: string) -> UserStringHandle =>
146
_metadata.get_or_add_user_string(value)
147
148
get_or_add_blob(bytes: ubyte[]) -> BlobHandle =>
149
_metadata.get_or_add_blob(bytes)
150
151
// Declares a managed resource embedded into this assembly,
152
// reachable at runtime through `Assembly.GetManifestResourceStream(logical_name)`.
153
add_resource(logical_name: string, bytes: ubyte[]) is
154
_resources.add((name = logical_name, bytes = bytes))
155
si
156
157
next_field_row: int => _metadata.get_row_count(TableIndex.FIELD) + 1
158
next_method_row: int => _metadata.get_row_count(TableIndex.METHOD_DEF) + 1
159
next_type_row: int => _metadata.get_row_count(TableIndex.TYPE_DEF) + 1
160
next_parameter_row: int => _metadata.get_row_count(TableIndex.PARAM) + 1
161
next_property_row: int => _metadata.get_row_count(TableIndex.PROPERTY) + 1
162
163
// The function the entrypoint pragma named during the tree
164
// walk, so the structure walk can mark its row. Which function
165
// is the entry point is not a naming rule the emitter can
166
// reapply: it can be a global function or a static method, and
167
// `@entry` overrides the name entirely.
168
entry_point_function: Semantic.Symbols.Function? public
169
170
// Every row this assembly has promised a symbol. Held here so
171
// that anything with the emitter can resolve a definition
172
// without being handed a second object.
173
handles: SRM_HANDLES
174
175
// Where the version each reference records comes from. Set before
176
// anything is emitted; without it every reference takes the
177
// registry's default.
178
referenced_assemblies: Semantic.DotNet.REFERENCED_ASSEMBLIES? public
179
180
// A reference to an assembly something being emitted refers to,
181
// written the first time it is asked for, at the version of the
182
// assembly that was loaded under that name.
183
add_assembly_reference(name: string) -> AssemblyReferenceHandle =>
184
add_assembly_reference(
185
name,
186
referenced_assemblies?.version_of(name) ?? Semantic.DotNet.REFERENCED_ASSEMBLIES.DEFAULT_VERSION,
187
referenced_assemblies?.public_key_token_of(name))
188
189
add_assembly_reference(name: string, version: string) -> AssemblyReferenceHandle =>
190
add_assembly_reference(name, version, null)
191
192
add_assembly_reference(
193
name: string, version: string, public_key_token: ubyte[]?
194
) -> AssemblyReferenceHandle is
195
if _assembly_refs.contains_key(name) then
196
return _assembly_refs[name]
197
fi
198
199
let handle = _metadata.add_assembly_reference(
200
_metadata.get_or_add_string(name),
201
parse_version(version),
202
_,
203
if let token = public_key_token then _metadata.get_or_add_blob(token) else _[BlobHandle] fi,
204
_,
205
_)
206
207
_assembly_refs[name] = handle
208
209
return handle
210
si
211
212
add_type_reference(
213
symbol: Semantic.Symbols.Symbol,
214
assembly_name: string,
215
namespace_name: string,
216
simple_name: string
217
) -> TypeReferenceHandle is
218
if _type_refs.contains_key(symbol) then
219
return _type_refs[symbol]
220
fi
221
222
assert _assembly_refs.contains_key(assembly_name) else
223
"assembly reference '{assembly_name}' must be registered before a type reference into it"
224
225
let assembly_ref = _assembly_refs[assembly_name]
226
227
let handle = _metadata.add_type_reference(
228
cast EntityHandle(assembly_ref),
229
_metadata.get_or_add_string(namespace_name),
230
_metadata.get_or_add_string(simple_name))
231
232
_type_refs[symbol] = handle
233
234
return handle
235
si
236
237
// A type nested inside another. Its scope is the enclosing
238
// type's own reference rather than the assembly, and it carries
239
// no namespace of its own — the enclosing reference supplies it.
240
//
241
// Encoded any other way the row names a type that does not
242
// exist: a top-level name containing a separator resolves to
243
// nothing, and the failure surfaces at load as
244
// `Could not load type 'List`1/Enumerator'`.
245
add_nested_type_reference(
246
assembly_name: string,
247
enclosing: TypeReferenceHandle,
248
simple_name: string
249
) -> TypeReferenceHandle is
250
let key = "{assembly_name}|{MetadataTokens.get_token(cast EntityHandle(enclosing))}|{simple_name}"
251
252
if _named_type_refs.contains_key(key) then
253
return _named_type_refs[key]
254
fi
255
256
let handle = _metadata.add_type_reference(
257
cast EntityHandle(enclosing),
258
_,
259
_metadata.get_or_add_string(simple_name))
260
261
_named_type_refs[key] = handle
262
263
return handle
264
si
265
266
// Reference to a type that no symbol names — the framework
267
// types every assembly needs as a base type regardless of what
268
// the source declares.
269
add_type_reference_by_name(
270
assembly_name: string,
271
namespace_name: string,
272
simple_name: string
273
) -> TypeReferenceHandle is
274
let key = "{assembly_name}|{namespace_name}|{simple_name}"
275
276
if _named_type_refs.contains_key(key) then
277
return _named_type_refs[key]
278
fi
279
280
add_assembly_reference(assembly_name)
281
282
let handle = _metadata.add_type_reference(
283
cast EntityHandle(_assembly_refs[assembly_name]),
284
_metadata.get_or_add_string(namespace_name),
285
_metadata.get_or_add_string(simple_name))
286
287
_named_type_refs[key] = handle
288
289
return handle
290
si
291
292
// A TypeSpec names a constructed generic where a table-level
293
// reference is needed. Cached so two references to the same
294
// instantiation are the same row.
295
//
296
// Keyed on the encoded signature rather than on how the type
297
// spells itself: a class type parameter and a method type
298
// parameter of the same name render the same but encode
299
// differently (`!0` against `!!0`), so a spelling key gives
300
// whichever was seen first to both.
301
_type_specs: Collections.MAP[string, System.Reflection.Metadata.TypeSpecificationHandle]
302
303
// The member whose metadata is currently being written, or null
304
// outside any member. A TypeSpec naming a captured type parameter
305
// has to be encoded in that member's terms: inside a frame method
306
// the parameter is one of the frame class's own, and encoding it
307
// at the declared method-level index of the function it was
308
// written in produces a reference to a method type parameter the
309
// frame method does not have.
310
current_emission_member: Semantic.Symbols.Symbol? public
311
312
add_type_specification(
313
type: Semantic.Types.Type
314
) -> System.Reflection.Metadata.TypeSpecificationHandle is
315
// Same mapping the member's own signature is written under
316
// (see SRM_SIGNATURE_ENCODER.field_signature and
317
// method_signature). A TypeSpec is built from wherever the
318
// instruction referencing it sits, so it needs the mapping
319
// opened here rather than inheriting one.
320
let mapping = SRM_SIGNATURE_ENCODER.frame_mapping_for_emission(current_emission_member)
321
322
if mapping? then
323
mapping.map_type_arguments()
324
fi
325
326
try
327
return _add_type_specification(type)
328
finally
329
if mapping? then
330
mapping.unmap_type_arguments()
331
fi
332
yrt
333
si
334
335
_add_type_specification(
336
type: Semantic.Types.Type
337
) -> System.Reflection.Metadata.TypeSpecificationHandle is
338
let signature = SRM_SIGNATURE_ENCODER(self).type_specification_signature(type)
339
340
let key = System.Convert.to_base64_string(signature)
341
342
if _type_specs.contains_key(key) then
343
return _type_specs[key]
344
fi
345
346
let handle = _metadata.add_type_specification(_metadata.get_or_add_blob(signature))
347
348
_type_specs[key] = handle
349
350
return handle
351
si
352
353
// A reference to a constructor on a type this assembly does not
354
// define. The owner is a handle rather than a symbol because the
355
// constructors that need this are named by a constructed type.
356
// A generic method is called through a MethodSpec naming the
357
// open method plus the arguments it was instantiated with. The
358
// open method keeps one reference row however many
359
// instantiations there are.
360
_method_specs: Collections.MAP[(method: int, signature: string), System.Reflection.Metadata.MethodSpecificationHandle]
361
362
// `key` is a human-readable description for diagnostics only;
363
// the cache is keyed on the open method plus the encoded
364
// arguments, for the same reason add_type_specification is.
365
add_method_specification(
366
method: EntityHandle,
367
key: string,
368
type_arguments: Collections.List[Semantic.Types.Type]
369
) -> System.Reflection.Metadata.MethodSpecificationHandle is
370
let builder = BlobBuilder(16)
371
372
let encoder =
373
System.Reflection.Metadata.Ecma335.BlobEncoder(builder)
374
.method_specification_signature(type_arguments.count)
375
376
let signatures = SRM_SIGNATURE_ENCODER(self)
377
378
for argument in type_arguments do
379
signatures.encode_type(encoder.add_argument(), argument)
380
od
381
382
let identity =
383
(
384
method = MetadataTokens.get_token(method),
385
signature = System.Convert.to_base64_string(builder.to_array())
386
)
387
388
if _method_specs.contains_key(identity) then
389
return _method_specs[identity]
390
fi
391
392
let handle =
393
_metadata.add_method_specification(method, _metadata.get_or_add_blob(builder.to_array()))
394
395
_method_specs[identity] = handle
396
397
return handle
398
si
399
400
add_constructor_reference(
401
owner: EntityHandle,
402
key: string,
403
argument_types: Collections.List[Semantic.Types.Type]
404
) -> MemberReferenceHandle =>
405
add_named_member_reference(
406
owner,
407
".ctor",
408
key,
409
SRM_SIGNATURE_ENCODER(self).constructor_signature(argument_types))
410
411
// A reference to a member of a type this assembly does not
412
// define, where the signature is built rather than read off a
413
// symbol. The owner is a handle so that a constructed generic's
414
// TypeSpec can own it.
415
//
416
// `key` is a human-readable description for diagnostics only.
417
// The cache is keyed on what actually identifies the row —
418
// owner, name and encoded signature — because a description
419
// can collide where those differ and differ where they match.
420
//
421
// Several callers have no symbol to key on: `Invoke` on a
422
// delegate type, `String::Concat`, a synthesised `.ctor`, a unit
423
// variant's interned instance. The row's own identity is what
424
// every caller does have, and it is what the CLR compares.
425
add_named_member_reference(
426
owner: EntityHandle,
427
name: string,
428
key: string,
429
signature: ubyte[]
430
) -> MemberReferenceHandle is
431
let identity =
432
(
433
owner = MetadataTokens.get_token(owner),
434
name = name,
435
signature = System.Convert.to_base64_string(signature)
436
)
437
438
if _named_member_refs.contains_key(identity) then
439
return _named_member_refs[identity]
440
fi
441
442
let handle = _metadata.add_member_reference(
443
owner,
444
_metadata.get_or_add_string(name),
445
_metadata.get_or_add_blob(signature))
446
447
_named_member_refs[identity] = handle
448
449
return handle
450
si
451
452
_named_member_refs: Collections.MAP[(owner: int, name: string, signature: string), MemberReferenceHandle]
453
454
455
// A method with locals needs a StandAloneSig naming their
456
// types, in slot order, for the body header to point at.
457
add_method_body(encoder: InstructionEncoder, body: SRM_METHOD_BODY_EMITTER) -> int is
458
let locals =
459
if body.has_locals then
460
add_local_variable_signature(body.local_types)
461
else
462
_[System.Reflection.Metadata.StandaloneSignatureHandle]
463
fi
464
465
// Locals are always initialized: a method that both has
466
// locals and contains a protected region is rejected
467
// outright by the runtime otherwise — an
468
// InvalidProgramException naming the method, with nothing
469
// in the body to point at.
470
return
471
_body_stream.add_method_body(
472
encoder,
473
body.max_stack,
474
locals,
475
System.Reflection.Metadata.Ecma335.MethodBodyAttributes.INIT_LOCALS)
476
si
477
478
add_local_variable_signature(
479
types: Collections.List[Semantic.Types.Type]
480
) -> System.Reflection.Metadata.StandaloneSignatureHandle is
481
// A body's locals are named in the terms of the member the
482
// body belongs to, the same as the TypeSpecs its instructions
483
// reference — see add_type_specification.
484
let mapping = SRM_SIGNATURE_ENCODER.frame_mapping_for_emission(current_emission_member)
485
486
if mapping? then
487
mapping.map_type_arguments()
488
fi
489
490
try
491
return _add_local_variable_signature(types)
492
finally
493
if mapping? then
494
mapping.unmap_type_arguments()
495
fi
496
yrt
497
si
498
499
_add_local_variable_signature(
500
types: Collections.List[Semantic.Types.Type]
501
) -> System.Reflection.Metadata.StandaloneSignatureHandle is
502
let builder = BlobBuilder(32)
503
504
let variables =
505
System.Reflection.Metadata.Ecma335.BlobEncoder(builder)
506
.local_variable_signature(types.count)
507
508
let signatures = SRM_SIGNATURE_ENCODER(self)
509
510
for type in types do
511
let referenced = SRM_SIGNATURE_ENCODER.pointee(type)
512
513
signatures.encode_type(
514
variables.add_variable().`type(referenced?, false), referenced ?? type)
515
od
516
517
return _metadata.add_standalone_signature(_metadata.get_or_add_blob(builder.to_array()))
518
si
519
520
// The source positions of the body at `offset`, recorded as the
521
// body is flushed and read back when its MethodDef row is
522
// written. Keyed on the offset because that is the only thing
523
// the two sides share: the body is encoded during the tree
524
// walk and the row is written afterwards, and every body
525
// occupies a distinct offset in the stream.
526
_sequence_points: Collections.MAP[int, Collections.List[SRM_SEQUENCE_POINT]]
527
528
// The modules P/Invoke methods call into, by name.
529
_module_references: Collections.MAP[string, System.Reflection.Metadata.ModuleReferenceHandle]
530
531
set_sequence_points(
532
body_offset: int,
533
points: Collections.List[SRM_SEQUENCE_POINT]
534
) is
535
_sequence_points[body_offset] = points
536
si
537
538
add_method_definition(
539
flags: MethodAttributes,
540
impl_flags: MethodImplAttributes,
541
name: StringHandle,
542
signature: BlobHandle,
543
body_offset: int,
544
parameter_list: System.Reflection.Metadata.ParameterHandle
545
) -> MethodDefinitionHandle is
546
let handle =
547
_metadata.add_method_definition(
548
flags, impl_flags, name, signature, body_offset, parameter_list)
549
550
// MethodDebugInformation is read positionally against
551
// MethodDef, so every row added here needs one there -
552
// including the ones with nothing to say. Doing it in the
553
// same call is what keeps the two in step; see
554
// SRM_PDB_BUILDER.
555
if let pdb = _pdb then
556
let points =
557
if _sequence_points.contains_key(body_offset) then
558
_sequence_points[body_offset]
559
else
560
null
561
fi
562
563
pdb.add_method_debug_information(points)
564
fi
565
566
return handle
567
si
568
569
// The module a P/Invoke calls into, one row per distinct name:
570
// ModuleRef is not a sorted side table, and a second row for a
571
// module already named would be a second module as far as a
572
// reader is concerned.
573
get_or_add_module_reference(name: string) -> System.Reflection.Metadata.ModuleReferenceHandle is
574
if _module_references.contains_key(name) then
575
return _module_references[name]
576
fi
577
578
let handle = _metadata.add_module_reference(get_or_add_string(name))
579
580
_module_references[name] = handle
581
582
return handle
583
si
584
585
// The ImplMap row that says what a P/Invoke method calls: the
586
// module, the name to look up in it, and how to marshal. SRM
587
// sorts this table, so the row can be added as the method is
588
// written.
589
add_method_import(
590
method: MethodDefinitionHandle,
591
attributes: System.Reflection.MethodImportAttributes,
592
name: string,
593
module: System.Reflection.Metadata.ModuleReferenceHandle
594
) is
595
_metadata.add_method_import(method, attributes, get_or_add_string(name), module)
596
si
597
598
add_parameter(
599
name: StringHandle,
600
sequence_number: int
601
) -> System.Reflection.Metadata.ParameterHandle =>
602
_metadata.add_parameter(cast System.Reflection.ParameterAttributes(0), name, sequence_number)
603
604
add_field_definition(
605
flags: System.Reflection.FieldAttributes,
606
name: StringHandle,
607
signature: BlobHandle
608
) -> System.Reflection.Metadata.FieldDefinitionHandle =>
609
_metadata.add_field_definition(flags, name, signature)
610
611
// The compile-time value of a literal field. The Constant table
612
// is one of the sorted side tables, so SRM orders the rows and
613
// they can be added as each field is written.
614
add_constant(
615
parent: EntityHandle,
616
value: object
617
) -> System.Reflection.Metadata.ConstantHandle =>
618
_metadata.add_constant(parent, value)
619
620
// A custom attribute on whatever `parent` names — a type, a
621
// method, a parameter, the assembly itself.
622
//
623
// CustomAttribute is sorted on its parent, but SRM sorts it
624
// rather than validating it, so rows can be added as the walk
625
// reaches them.
626
add_custom_attribute(
627
parent: EntityHandle,
628
constructor: EntityHandle,
629
value: ubyte[]
630
) is
631
_metadata.add_custom_attribute(parent, constructor, get_or_add_blob(value))
632
si
633
634
add_property(
635
name: StringHandle,
636
signature: ubyte[]
637
) -> System.Reflection.Metadata.PropertyDefinitionHandle =>
638
_metadata.add_property(
639
cast System.Reflection.PropertyAttributes(0),
640
name,
641
get_or_add_blob(signature))
642
643
// Points a type at the run of property rows it owns. PropertyMap
644
// is sorted on its parent, and the walk writes types in
645
// ascending row order, so adding one per type as the walk
646
// reaches it is already in order.
647
add_property_map(
648
parent: TypeDefinitionHandle,
649
first_property: System.Reflection.Metadata.PropertyDefinitionHandle
650
) is
651
_metadata.add_property_map(parent, first_property)
652
si
653
654
// Ties an accessor method to the property it reads or writes.
655
// MethodSemantics is a sorted side table that SRM orders itself,
656
// so these can be added as the walk reaches them.
657
add_property_accessor(
658
property: System.Reflection.Metadata.PropertyDefinitionHandle,
659
accessor: MethodDefinitionHandle,
660
is_getter: bool
661
) is
662
_metadata.add_method_semantics(
663
cast EntityHandle(property),
664
if is_getter then
665
System.Reflection.MethodSemanticsAttributes.GETTER
666
else
667
System.Reflection.MethodSemanticsAttributes.SETTER
668
fi,
669
accessor)
670
si
671
672
// An attribute the compiler applies itself rather than resolving
673
// from a pragma, named rather than reached through a symbol: the
674
// marker attributes carrying what metadata cannot express, the
675
// framework attributes on a return or parameter slot, and the
676
// assembly-level attributes the command line supplies.
677
//
678
// The type name is qualified, and split here rather than written
679
// as a namespace and a simple name at each call site: a
680
// reference built from the two halves out of step names a type
681
// that does not exist while still emitting cleanly.
682
add_named_attribute(
683
parent: EntityHandle,
684
assembly_name: string,
685
qualified_name: string,
686
argument_types: Collections.List[Semantic.Types.Type],
687
value: ubyte[]
688
) is
689
let dot = qualified_name.last_index_of('.')
690
691
let namespace_name =
692
if dot >= 0 then qualified_name.substring(0, dot) else "" fi
693
694
let simple_name =
695
if dot >= 0 then qualified_name.substring(dot + 1) else qualified_name fi
696
697
let attribute_type =
698
add_type_reference_by_name(assembly_name, namespace_name, simple_name)
699
700
add_custom_attribute(
701
parent,
702
cast EntityHandle(
703
add_constructor_reference(
704
cast EntityHandle(attribute_type),
705
"{qualified_name}::.ctor",
706
argument_types)),
707
value)
708
si
709
710
// The value blob of an attribute applied with no arguments: the
711
// two-byte prolog every attribute blob opens with, then a
712
// named-argument count of zero.
713
NO_ARGUMENT_ATTRIBUTE_VALUE: ubyte[] static => [1ub, 0ub, 0ub, 0ub]
714
715
add_type_definition(
716
flags: System.Reflection.TypeAttributes,
717
namespace_name: StringHandle,
718
simple_name: StringHandle,
719
base_type: EntityHandle,
720
field_list: System.Reflection.Metadata.FieldDefinitionHandle,
721
method_list: MethodDefinitionHandle
722
) -> System.Reflection.Metadata.TypeDefinitionHandle =>
723
_metadata.add_type_definition(
724
flags, namespace_name, simple_name, base_type, field_list, method_list)
725
726
// The packing and size a `StructLayout` gives a type, which the
727
// runtime reads from this row rather than from the attribute.
728
add_type_layout(
729
`type: System.Reflection.Metadata.TypeDefinitionHandle,
730
pack: int,
731
size: int
732
) is
733
_metadata.add_type_layout(`type, cast ushort(pack), cast uint(size))
734
si
735
736
// A field's offset within an explicitly laid out type.
737
add_field_layout(`field: System.Reflection.Metadata.FieldDefinitionHandle, offset: int) is
738
_metadata.add_field_layout(`field, offset)
739
si
740
741
// A type or method that declares type parameters needs a row per
742
// parameter. Without them the declaration is not generic, and
743
// every signature that names one by index - a field of type !0,
744
// an argument of type !!0 - is naming something the type does
745
// not have.
746
add_generic_parameter(
747
owner: EntityHandle,
748
index: int,
749
name: string,
750
attributes: System.Reflection.GenericParameterAttributes
751
) -> System.Reflection.Metadata.GenericParameterHandle =>
752
_metadata.add_generic_parameter(
753
owner,
754
attributes,
755
_metadata.get_or_add_string(name),
756
index)
757
758
// The type a parameter is bounded by (`[T: SomeBase]`). The CLR
759
// verifies shared generic code against the declared parameter
760
// rather than against each call site's substitution, so without
761
// this row the parameter is unbounded as far as the runtime is
762
// concerned: a body that relies on the bound fails verification,
763
// and passing the parameter on to a callee declaring the same
764
// bound is rejected as violating it.
765
add_generic_parameter_constraint(
766
parameter: System.Reflection.Metadata.GenericParameterHandle,
767
`type: EntityHandle
768
) is
769
_metadata.add_generic_parameter_constraint(parameter, `type)
770
si
771
772
// One row per interface a type declares. Without it the type
773
// still loads and its own methods still run, but nothing binds
774
// the interface's slots, so a call through the interface fails
775
// at dispatch rather than at load.
776
//
777
// InterfaceImpl is a sorted table, and SRM orders it on
778
// serialization, so rows go in as the walk reaches them.
779
//
780
// The returned handle is what the caller attaches a
781
// `NullableAttribute` to when the interface's own type
782
// arguments carry a reference-`?` position — see
783
// `SRM_STRUCTURE_WALK._interfaces`. `InterfaceImpl` is one of
784
// the few metadata rows .NET reflection has no `MemberInfo` for,
785
// so that attribute is the only way the optionality survives
786
// into another assembly's view of this type.
787
add_interface_implementation(
788
type: System.Reflection.Metadata.TypeDefinitionHandle,
789
`interface: EntityHandle
790
) -> InterfaceImplementationHandle is
791
return _metadata.add_interface_implementation(type, `interface)
792
si
793
794
// Binds a method this type defines to the interface slot it
795
// implements, for a member whose name cannot match the slot on
796
// its own — an explicit implementation, named for the interface
797
// it satisfies.
798
add_method_implementation(
799
type: System.Reflection.Metadata.TypeDefinitionHandle,
800
body: EntityHandle,
801
declaration: EntityHandle
802
) is
803
_metadata.add_method_implementation(type, body, declaration)
804
si
805
806
set_entry_point(method: MethodDefinitionHandle) is
807
_entry_point = method
808
si
809
810
// The identity a deterministic build gives its output: a hash of
811
// the content, rather than a fresh guid and the wall clock. Two
812
// builds of the same source then produce the same bytes, which
813
// is what lets the self-hosting check be a comparison of two
814
// assemblies rather than of two disassemblies.
815
_content_id_from_content(
816
content: Collections.Iterable[System.Reflection.Metadata.Blob]
817
) -> System.Reflection.Metadata.BlobContentId static is
818
let hasher =
819
System.Security.Cryptography.IncrementalHash.create_hash(
820
System.Security.Cryptography.HashAlgorithmName.sha256)
821
822
for blob in content do
823
let bytes = blob.get_bytes()
824
825
let array: ubyte[]? = bytes.array
826
827
hasher.append_data(array!, bytes.offset, bytes.count)
828
od
829
830
return
831
System.Reflection.Metadata.BlobContentId.from_hash(
832
System.Collections.Immutable.ImmutableArray.create[ubyte](
833
hasher.get_hash_and_reset()))
834
si
835
836
write_to(path: string) is
837
// The PDB is written first because the assembly has to name
838
// it: a debug directory entry carries the PDB's path and
839
// the identity a runtime checks the two match on, and that
840
// identity is not known until the PDB's bytes are.
841
let debug_directory =
842
if let pdb = _pdb then
843
let pdb_path = IO.Path.change_extension(path, ".pdb")!
844
845
let pdb_content_id =
846
pdb.write_to(
847
pdb_path,
848
_metadata.get_row_counts(),
849
_entry_point ?? _[MethodDefinitionHandle],
850
_content_id_from_content)
851
852
let builder =
853
System.Reflection.PortableExecutable.DebugDirectoryBuilder()
854
855
// The name is what the runtime looks for beside the
856
// assembly, so it is the file's own name rather than
857
// the path this compiler happened to write it to.
858
builder.add_code_view_entry(
859
IO.Path.get_file_name(pdb_path)!,
860
pdb_content_id,
861
_PORTABLE_PDB_VERSION)
862
863
builder
864
else
865
_[System.Reflection.PortableExecutable.DebugDirectoryBuilder?]
866
fi
867
868
let pe_header =
869
if _want_library then
870
PEHeaderBuilder.create_library_header()
871
else
872
PEHeaderBuilder.create_executable_header()
873
fi
874
875
// Every resource's bytes go into one blob as a four-byte
876
// little-endian length followed by the data, aligned to
877
// ManagedPEBuilder.ManagedResourcesDataAlignment (8) so the
878
// next resource's row offset lands where the format expects
879
// it. A nil `implementation` handle says the resource lives
880
// in this module rather than another file or assembly.
881
let managed_resources =
882
if _resources.count > 0 then
883
let blob = BlobBuilder(1024)
884
885
for r in _resources do
886
let offset = blob.count
887
888
blob.write_int32(r.bytes.count)
889
blob.write_bytes(r.bytes)
890
blob.align(8)
891
892
_metadata.add_manifest_resource(
893
System.Reflection.ManifestResourceAttributes.PUBLIC,
894
_metadata.get_or_add_string(r.name),
895
_[EntityHandle],
896
cast uint(offset))
897
od
898
899
blob
900
else
901
_[BlobBuilder?]
902
fi
903
904
let pe_builder = ManagedPEBuilder(
905
pe_header,
906
MetadataRootBuilder(_metadata, null, false),
907
_il_builder,
908
null,
909
managed_resources,
910
null,
911
debug_directory,
912
0,
913
_entry_point ?? _[MethodDefinitionHandle],
914
cast CorFlags(1), // ILOnly
915
_content_id_from_content)
916
917
let pe_blob = BlobBuilder(1024)
918
let content_id = pe_builder.serialize(pe_blob)
919
920
// Now that the content is fixed, the id derived from it can
921
// go into the space reserved for it above.
922
System.Reflection.Metadata.BlobWriter(_module_version_id).write_guid(content_id.guid)
923
924
let stream = IO.File.create(path)
925
pe_blob.write_content_to(stream)
926
stream.close()
927
si
928
si
929
si