Skip to content

Commit 1c0ce30

Browse files
authored
Fix field offset not being set for 0-offset (#105894)
PersistedAssemblyBuilder didn't write field offset correctly when field offset was 0. This fixes that, and adds a test to ensure the behaviour is working. Fixes #105795
1 parent 9390b99 commit 1c0ce30

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -638,7 +638,7 @@ private void WriteFields(TypeBuilderImpl typeBuilder, BlobBuilder fieldDataBuild
638638
Debug.Assert(field._handle == handle);
639639
WriteCustomAttributes(field._customAttributes, handle);
640640

641-
if (field._offset > 0 && (typeBuilder.Attributes & TypeAttributes.ExplicitLayout) != 0)
641+
if (field._offset >= 0 && (typeBuilder.Attributes & TypeAttributes.ExplicitLayout) != 0)
642642
{
643643
AddFieldLayout(handle, field._offset);
644644
}

src/libraries/System.Reflection.Emit/tests/PersistedAssemblyBuilder/AssemblySaveILGeneratorTests.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2740,5 +2740,22 @@ public void ValueTypeParentTest()
27402740
Assert.Equal(1, result);
27412741
}
27422742
}
2743+
2744+
[Fact]
2745+
public void ExplicitFieldOffsetSavesAndLoads()
2746+
{
2747+
PersistedAssemblyBuilder ab = new PersistedAssemblyBuilder(new AssemblyName("MyAssemblyForExplicitLayout"), typeof(object).Assembly);
2748+
ModuleBuilder mob = ab.DefineDynamicModule("MyModule");
2749+
TypeBuilder tb = mob.DefineType("ExplicitLayoutType", TypeAttributes.ExplicitLayout);
2750+
FieldBuilder f1 = tb.DefineField("field1", typeof(int), 0);
2751+
f1.SetOffset(0);
2752+
tb.CreateType();
2753+
2754+
using var stream = new MemoryStream();
2755+
ab.Save(stream);
2756+
stream.Seek(0, SeekOrigin.Begin);
2757+
var assembly = AssemblyLoadContext.Default.LoadFromStream(stream);
2758+
var method = assembly.GetType("ExplicitLayoutType")!;
2759+
}
27432760
}
27442761
}

0 commit comments

Comments
 (0)