Skip to content

Commit fbf109b

Browse files
authored
Add EventBuilder implementation (#95936)
* Add EventBuilder implementation
1 parent a6f8607 commit fbf109b

File tree

7 files changed

+253
-3
lines changed

7 files changed

+253
-3
lines changed

src/libraries/System.Reflection.Emit/src/System.Reflection.Emit.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
<Compile Include="System\Reflection\Emit\CustomAttributeWrapper.cs" />
1515
<Compile Include="System\Reflection\Emit\AssemblyBuilderImpl.cs" />
1616
<Compile Include="System\Reflection\Emit\EnumBuilderImpl.cs" />
17+
<Compile Include="System\Reflection\Emit\EventBuilderImpl.cs" />
1718
<Compile Include="System\Reflection\Emit\FieldBuilderImpl.cs" />
1819
<Compile Include="System\Reflection\Emit\GenericTypeParameterBuilderImpl.cs" />
1920
<Compile Include="System\Reflection\Emit\ILGeneratorImpl.cs" />
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System.Collections.Generic;
5+
using System.Reflection.Metadata;
6+
7+
namespace System.Reflection.Emit
8+
{
9+
internal sealed class EventBuilderImpl : EventBuilder
10+
{
11+
private readonly string _name;
12+
private EventAttributes _attributes;
13+
private readonly TypeBuilderImpl _typeBuilder;
14+
private readonly Type _eventType;
15+
16+
internal EventDefinitionHandle _handle;
17+
internal MethodBuilder? _addOnMethod;
18+
internal MethodBuilder? _raiseMethod;
19+
internal MethodBuilder? _removeMethod;
20+
internal HashSet<MethodBuilder>? _otherMethods;
21+
internal List<CustomAttributeWrapper>? _customAttributes;
22+
23+
public EventBuilderImpl(string name, EventAttributes attributes, Type eventType, TypeBuilderImpl typeBuilder)
24+
{
25+
_name = name;
26+
_attributes = attributes;
27+
_typeBuilder = typeBuilder;
28+
_eventType = eventType;
29+
}
30+
31+
internal EventAttributes Attributes => _attributes;
32+
internal string Name => _name;
33+
internal Type EventType => _eventType;
34+
35+
protected override void AddOtherMethodCore(MethodBuilder mdBuilder)
36+
{
37+
ArgumentNullException.ThrowIfNull(mdBuilder);
38+
_typeBuilder.ThrowIfCreated();
39+
40+
_otherMethods ??= new HashSet<MethodBuilder>();
41+
_otherMethods.Add(mdBuilder);
42+
}
43+
44+
protected override void SetAddOnMethodCore(MethodBuilder mdBuilder)
45+
{
46+
ArgumentNullException.ThrowIfNull(mdBuilder);
47+
_typeBuilder.ThrowIfCreated();
48+
49+
_addOnMethod = mdBuilder;
50+
}
51+
52+
protected override void SetCustomAttributeCore(ConstructorInfo con, ReadOnlySpan<byte> binaryAttribute)
53+
{
54+
_typeBuilder.ThrowIfCreated();
55+
56+
if (con.ReflectedType!.FullName == "System.Runtime.CompilerServices.SpecialNameAttribute")
57+
{
58+
_attributes |= EventAttributes.SpecialName;
59+
return;
60+
}
61+
62+
_customAttributes ??= new List<CustomAttributeWrapper>();
63+
_customAttributes.Add(new CustomAttributeWrapper(con, binaryAttribute));
64+
}
65+
66+
protected override void SetRaiseMethodCore(MethodBuilder mdBuilder)
67+
{
68+
ArgumentNullException.ThrowIfNull(mdBuilder);
69+
_typeBuilder.ThrowIfCreated();
70+
71+
_raiseMethod = mdBuilder;
72+
}
73+
74+
protected override void SetRemoveOnMethodCore(MethodBuilder mdBuilder)
75+
{
76+
ArgumentNullException.ThrowIfNull(mdBuilder);
77+
_typeBuilder.ThrowIfCreated();
78+
79+
_removeMethod = mdBuilder;
80+
}
81+
}
82+
}

src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/ModuleBuilderImpl.cs

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ internal sealed class ModuleBuilderImpl : ModuleBuilder
2828
private int _nextFieldDefRowId = 1;
2929
private int _nextParameterRowId = 1;
3030
private int _nextPropertyRowId = 1;
31+
private int _nextEventRowId = 1;
3132
private bool _coreTypesFullyPopulated;
3233
private Type?[]? _coreTypes;
3334
private static readonly Type[] s_coreTypes = { typeof(void), typeof(object), typeof(bool), typeof(char), typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int),
@@ -173,6 +174,7 @@ internal void AppendMetadata(MethodBodyStreamEncoder methodBodyEncoder)
173174
WriteProperties(typeBuilder);
174175
WriteFields(typeBuilder);
175176
WriteMethods(typeBuilder._methodDefinitions, genericParams, methodBodyEncoder);
177+
WriteEvents(typeBuilder);
176178
}
177179

178180
// Now write all generic parameters in order
@@ -190,6 +192,44 @@ internal void AppendMetadata(MethodBodyStreamEncoder methodBodyEncoder)
190192
}
191193
}
192194

195+
private void WriteEvents(TypeBuilderImpl typeBuilder)
196+
{
197+
if (typeBuilder._eventDefinitions.Count == 0)
198+
{
199+
return;
200+
}
201+
202+
AddEventMap(typeBuilder._handle, typeBuilder._firstEventToken);
203+
foreach (EventBuilderImpl eventBuilder in typeBuilder._eventDefinitions)
204+
{
205+
EventDefinitionHandle eventHandle = AddEventDefinition(eventBuilder, GetTypeHandle(eventBuilder.EventType));
206+
WriteCustomAttributes(eventBuilder._customAttributes, eventHandle);
207+
208+
if (eventBuilder._addOnMethod is MethodBuilderImpl aMb)
209+
{
210+
AddMethodSemantics(eventHandle, MethodSemanticsAttributes.Adder, aMb._handle);
211+
}
212+
213+
if (eventBuilder._raiseMethod is MethodBuilderImpl rMb)
214+
{
215+
AddMethodSemantics(eventHandle, MethodSemanticsAttributes.Raiser, rMb._handle);
216+
}
217+
218+
if (eventBuilder._removeMethod is MethodBuilderImpl remMb)
219+
{
220+
AddMethodSemantics(eventHandle, MethodSemanticsAttributes.Remover, remMb._handle);
221+
}
222+
223+
if (eventBuilder._otherMethods != null)
224+
{
225+
foreach (MethodBuilderImpl method in eventBuilder._otherMethods)
226+
{
227+
AddMethodSemantics(eventHandle, MethodSemanticsAttributes.Other, method._handle);
228+
}
229+
}
230+
}
231+
}
232+
193233
private void WriteProperties(TypeBuilderImpl typeBuilder)
194234
{
195235
if (typeBuilder._propertyDefinitions.Count == 0)
@@ -252,15 +292,25 @@ private void PopulatePropertyDefinitionHandles(List<PropertyBuilderImpl> propert
252292
}
253293
}
254294

295+
private void PopulateEventDefinitionHandles(List<EventBuilderImpl> eventDefinitions)
296+
{
297+
foreach (EventBuilderImpl eventBuilder in eventDefinitions)
298+
{
299+
eventBuilder._handle = MetadataTokens.EventDefinitionHandle(_nextEventRowId++);
300+
}
301+
}
302+
255303
internal void PopulateTypeAndItsMembersTokens(TypeBuilderImpl typeBuilder)
256304
{
257305
typeBuilder._handle = MetadataTokens.TypeDefinitionHandle(++_nextTypeDefRowId);
258306
typeBuilder._firstMethodToken = _nextMethodDefRowId;
259307
typeBuilder._firstFieldToken = _nextFieldDefRowId;
260308
typeBuilder._firstPropertyToken = _nextPropertyRowId;
309+
typeBuilder._firstEventToken = _nextEventRowId;
261310
PopulateMethodDefinitionHandles(typeBuilder._methodDefinitions);
262311
PopulateFieldDefinitionHandles(typeBuilder._fieldDefinitions);
263312
PopulatePropertyDefinitionHandles(typeBuilder._propertyDefinitions);
313+
PopulateEventDefinitionHandles(typeBuilder._eventDefinitions);
264314
}
265315

266316
private void WriteMethods(List<MethodBuilderImpl> methods, List<GenericTypeParameterBuilderImpl> genericParams, MethodBodyStreamEncoder methodBodyEncoder)
@@ -528,6 +578,17 @@ private PropertyDefinitionHandle AddPropertyDefinition(PropertyBuilderImpl prope
528578
name: _metadataBuilder.GetOrAddString(property.Name),
529579
signature: _metadataBuilder.GetOrAddBlob(signature));
530580

581+
private EventDefinitionHandle AddEventDefinition(EventBuilderImpl eventBuilder, EntityHandle eventType) =>
582+
_metadataBuilder.AddEvent(
583+
attributes: eventBuilder.Attributes,
584+
name: _metadataBuilder.GetOrAddString(eventBuilder.Name),
585+
type: eventType);
586+
587+
private void AddEventMap(TypeDefinitionHandle typeHandle, int firstEventToken) =>
588+
_metadataBuilder.AddEventMap(
589+
declaringType: typeHandle,
590+
eventList: MetadataTokens.EventDefinitionHandle(firstEventToken));
591+
531592
private void AddPropertyMap(TypeDefinitionHandle typeHandle, int firstPropertyToken) =>
532593
_metadataBuilder.AddPropertyMap(
533594
declaringType: typeHandle,

src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/PropertyBuilderImpl.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ internal sealed class PropertyBuilderImpl : PropertyBuilder
1717
private PropertyAttributes _attributes;
1818
private MethodInfo? _getMethod;
1919
private MethodInfo? _setMethod;
20-
internal List<MethodInfo>? _otherMethods;
20+
internal HashSet<MethodInfo>? _otherMethods;
2121

2222
internal PropertyDefinitionHandle _handle;
2323
internal List<CustomAttributeWrapper>? _customAttributes;
@@ -43,7 +43,7 @@ protected override void AddOtherMethodCore(MethodBuilder mdBuilder)
4343
ArgumentNullException.ThrowIfNull(mdBuilder);
4444
_containingType.ThrowIfCreated();
4545

46-
_otherMethods ??= new List<MethodInfo>();
46+
_otherMethods ??= new HashSet<MethodInfo>();
4747
_otherMethods.Add(mdBuilder);
4848
}
4949

src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/TypeBuilderImpl.cs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,13 @@ internal sealed class TypeBuilderImpl : TypeBuilder
3030
internal int _firstFieldToken;
3131
internal int _firstMethodToken;
3232
internal int _firstPropertyToken;
33+
internal int _firstEventToken;
3334
internal readonly List<MethodBuilderImpl> _methodDefinitions = new();
3435
internal readonly List<FieldBuilderImpl> _fieldDefinitions = new();
3536
internal readonly List<ConstructorBuilderImpl> _constructorDefinitions = new();
3637
internal List<Type>? _interfaces;
3738
internal readonly List<PropertyBuilderImpl> _propertyDefinitions = new();
39+
internal readonly List<EventBuilderImpl> _eventDefinitions = new();
3840
internal List<CustomAttributeWrapper>? _customAttributes;
3941

4042
internal TypeBuilderImpl(string fullName, TypeAttributes typeAttributes,
@@ -181,7 +183,15 @@ private ConstructorBuilderImpl DefineDefaultConstructorInternal(MethodAttributes
181183
return constBuilder;
182184
}
183185

184-
protected override EventBuilder DefineEventCore(string name, EventAttributes attributes, Type eventtype) => throw new NotImplementedException();
186+
protected override EventBuilder DefineEventCore(string name, EventAttributes attributes, Type eventtype)
187+
{
188+
ArgumentNullException.ThrowIfNull(eventtype);
189+
ThrowIfCreated();
190+
191+
EventBuilderImpl eventBuilder = new EventBuilderImpl(name, attributes, eventtype, this);
192+
_eventDefinitions.Add(eventBuilder);
193+
return eventBuilder;
194+
}
185195

186196
protected override FieldBuilder DefineFieldCore(string fieldName, Type type, Type[]? requiredCustomModifiers, Type[]? optionalCustomModifiers, FieldAttributes attributes)
187197
{
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System.Collections.Generic;
5+
using System.IO;
6+
using System.Linq;
7+
using Xunit;
8+
9+
namespace System.Reflection.Emit.Tests
10+
{
11+
[ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))]
12+
public class AssemblySaveEventBuilderTests
13+
{
14+
[Fact]
15+
public void DefineEventAndItsAccessors()
16+
{
17+
using (TempFile file = TempFile.Create())
18+
{
19+
AssemblyBuilder ab = AssemblySaveTools.PopulateAssemblyBuilderTypeBuilderAndSaveMethod(out TypeBuilder type, out MethodInfo saveMethod);
20+
EventBuilder eventType = type.DefineEvent("TestEvent", EventAttributes.SpecialName, typeof(int));
21+
MethodBuilder addMethod = type.DefineMethod("AddMethod", MethodAttributes.Public | MethodAttributes.SpecialName);
22+
MethodBuilder addMethod2 = type.DefineMethod("AddMethod2", MethodAttributes.Public | MethodAttributes.HideBySig, typeof(int), Type.EmptyTypes);
23+
MethodBuilder raiseMethod = type.DefineMethod("RaiseMethod", MethodAttributes.Assembly | MethodAttributes.SpecialName, typeof(int), Type.EmptyTypes);
24+
MethodBuilder removeMethod = type.DefineMethod("RemoveMethod", MethodAttributes.Public, typeof(void), Type.EmptyTypes);
25+
MethodBuilder otherMethod = type.DefineMethod("OtherMethod", MethodAttributes.Family, typeof(int), [typeof(int)]);
26+
CustomAttributeBuilder customAttrBuilder = new CustomAttributeBuilder(typeof(IntPropertyAttribute).GetConstructor([typeof(int)]), [9]);
27+
eventType.SetCustomAttribute(customAttrBuilder);
28+
addMethod.GetILGenerator().Emit(OpCodes.Ret);
29+
ILGenerator adderIL = addMethod2.GetILGenerator();
30+
adderIL.Emit(OpCodes.Ldc_I4_1);
31+
adderIL.Emit(OpCodes.Ret);
32+
eventType.SetAddOnMethod(addMethod);
33+
eventType.SetAddOnMethod(addMethod2); // last set wins
34+
ILGenerator raiseIL = raiseMethod.GetILGenerator();
35+
raiseIL.Emit(OpCodes.Ldc_I4_2);
36+
raiseIL.Emit(OpCodes.Ret);
37+
eventType.SetRaiseMethod(raiseMethod);
38+
removeMethod.GetILGenerator().Emit(OpCodes.Ret);
39+
eventType.SetRemoveOnMethod(removeMethod);
40+
ILGenerator otherILGenerator = otherMethod.GetILGenerator();
41+
otherILGenerator.Emit(OpCodes.Ldarg_1);
42+
otherILGenerator.Emit(OpCodes.Ret);
43+
eventType.AddOtherMethod(otherMethod);
44+
type.CreateType();
45+
saveMethod.Invoke(ab, new[] { file.Path });
46+
47+
Assembly assemblyFromDisk = AssemblySaveTools.LoadAssemblyFromPath(file.Path);
48+
Type typeFromDisk = assemblyFromDisk.Modules.First().GetType("MyType");
49+
EventInfo eventFromDisk = typeFromDisk.GetEvent("TestEvent");
50+
Assert.Equal(addMethod2.Name, eventFromDisk.AddMethod.Name);
51+
Assert.Equal(raiseMethod.Name, eventFromDisk.RaiseMethod.Name);
52+
Assert.Equal(removeMethod.Name, eventFromDisk.RemoveMethod.Name);
53+
Assert.Equal(typeof(int).FullName, eventFromDisk.EventHandlerType.FullName);
54+
Assert.NotNull(typeFromDisk.GetMethod("OtherMethod", BindingFlags.NonPublic | BindingFlags.Instance));
55+
Assert.Equal(EventAttributes.SpecialName, eventFromDisk.Attributes);
56+
IList<CustomAttributeData> caData = eventFromDisk.GetCustomAttributesData();
57+
Assert.Equal(1, caData.Count);
58+
Assert.Equal(typeof(IntPropertyAttribute).FullName, caData[0].AttributeType.FullName);
59+
Assert.Equal(1, caData[0].ConstructorArguments.Count);
60+
Assert.Equal(9, caData[0].ConstructorArguments[0].Value);
61+
}
62+
}
63+
64+
[Fact]
65+
public void Set_NullValue_ThrowsArgumentNullException()
66+
{
67+
AssemblySaveTools.PopulateAssemblyBuilderTypeBuilderAndSaveMethod(out TypeBuilder type, out MethodInfo _);
68+
EventBuilder eventBuilder = type.DefineEvent("TestEvent", EventAttributes.None, typeof(string));
69+
70+
AssertExtensions.Throws<ArgumentNullException>("eventtype", () => type.DefineEvent("EventTypeNull", EventAttributes.None, null));
71+
AssertExtensions.Throws<ArgumentNullException>("mdBuilder", () => eventBuilder.SetRaiseMethod(null));
72+
AssertExtensions.Throws<ArgumentNullException>("mdBuilder", () => eventBuilder.SetRemoveOnMethod(null));
73+
AssertExtensions.Throws<ArgumentNullException>("mdBuilder", () => eventBuilder.SetAddOnMethod(null));
74+
AssertExtensions.Throws<ArgumentNullException>("mdBuilder", () => eventBuilder.AddOtherMethod(null));
75+
AssertExtensions.Throws<ArgumentNullException>("customBuilder", () => eventBuilder.SetCustomAttribute(null));
76+
}
77+
78+
[Fact]
79+
public void Set_WhenTypeAlreadyCreated_ThrowsInvalidOperationException()
80+
{
81+
AssemblySaveTools.PopulateAssemblyBuilderTypeBuilderAndSaveMethod(out TypeBuilder type, out MethodInfo _);
82+
EventBuilder eventBuilder = type.DefineEvent("TestEvent", EventAttributes.None, typeof(int));
83+
84+
MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.SpecialName, typeof(int), null);
85+
CustomAttributeBuilder customAttrBuilder = new CustomAttributeBuilder(typeof(IntPropertyAttribute).GetConstructor([typeof(int)]), [10]);
86+
type.CreateType();
87+
88+
Assert.Throws<InvalidOperationException>(() => eventBuilder.SetAddOnMethod(method));
89+
Assert.Throws<InvalidOperationException>(() => eventBuilder.SetRaiseMethod(method));
90+
Assert.Throws<InvalidOperationException>(() => eventBuilder.SetRemoveOnMethod(method));
91+
Assert.Throws<InvalidOperationException>(() => eventBuilder.AddOtherMethod(method));
92+
Assert.Throws<InvalidOperationException>(() => eventBuilder.SetCustomAttribute(customAttrBuilder));
93+
}
94+
}
95+
}

src/libraries/System.Reflection.Emit/tests/System.Reflection.Emit.Tests.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@
6565
<Compile Include="PersistableAssemblyBuilder\AssemblySaveCustomAttributeTests.cs" />
6666
<Compile Include="PersistableAssemblyBuilder\AssemblySaveConstructorBuilderTests.cs" />
6767
<Compile Include="PersistableAssemblyBuilder\AssemblySaveEnumBuilderTests.cs" />
68+
<Compile Include="PersistableAssemblyBuilder\AssemblySaveEventBuilderTests.cs" />
6869
<Compile Include="PersistableAssemblyBuilder\AssemblySaveILGeneratorTests.cs" />
6970
<Compile Include="PersistableAssemblyBuilder\AssemblySavePropertyBuilderTests.cs" />
7071
<Compile Include="PersistableAssemblyBuilder\AssemblySaveTools.cs" />

0 commit comments

Comments
 (0)