Skip to content

Commit

Permalink
Fix field offset not being set for 0-offset (#105894)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
TrueLunacy committed Aug 3, 2024
1 parent 9390b99 commit 1c0ce30
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,7 @@ private void WriteFields(TypeBuilderImpl typeBuilder, BlobBuilder fieldDataBuild
Debug.Assert(field._handle == handle);
WriteCustomAttributes(field._customAttributes, handle);

if (field._offset > 0 && (typeBuilder.Attributes & TypeAttributes.ExplicitLayout) != 0)
if (field._offset >= 0 && (typeBuilder.Attributes & TypeAttributes.ExplicitLayout) != 0)
{
AddFieldLayout(handle, field._offset);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2740,5 +2740,22 @@ public void ValueTypeParentTest()
Assert.Equal(1, result);
}
}

[Fact]
public void ExplicitFieldOffsetSavesAndLoads()
{
PersistedAssemblyBuilder ab = new PersistedAssemblyBuilder(new AssemblyName("MyAssemblyForExplicitLayout"), typeof(object).Assembly);
ModuleBuilder mob = ab.DefineDynamicModule("MyModule");
TypeBuilder tb = mob.DefineType("ExplicitLayoutType", TypeAttributes.ExplicitLayout);
FieldBuilder f1 = tb.DefineField("field1", typeof(int), 0);
f1.SetOffset(0);
tb.CreateType();

using var stream = new MemoryStream();
ab.Save(stream);
stream.Seek(0, SeekOrigin.Begin);
var assembly = AssemblyLoadContext.Default.LoadFromStream(stream);
var method = assembly.GetType("ExplicitLayoutType")!;
}
}
}

0 comments on commit 1c0ce30

Please sign in to comment.