Skip to content

Commit

Permalink
[mono] ILStrip sorts custom attribute table (#87923)
Browse files Browse the repository at this point in the history
This prevents custom attribute table corruption by sorting it as the last step when stripping an assembly. Addresses #85414.

The PR will have to be backported to net7.0.
  • Loading branch information
jandupej committed Jun 22, 2023
1 parent fad3d54 commit 1df51a3
Showing 1 changed file with 25 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,16 @@

namespace AssemblyStripper
{
class CustomAttrRowComparer : IComparer
{
public int Compare(object left, object right)
{
CustomAttributeRow row_left = (CustomAttributeRow)left;
CustomAttributeRow row_right = (CustomAttributeRow)right;
return row_left.Parent.RID.CompareTo(row_right.Parent.RID);
}
}

public class AssemblyStripper
{
AssemblyDefinition assembly;
Expand Down Expand Up @@ -40,6 +50,7 @@ void Strip()
PatchMethods();
PatchFields();
PatchResources();
SortCustomAttributes();
Write();
}

Expand Down Expand Up @@ -192,6 +203,20 @@ void PatchResources()
}
}

// Types that are trimmed away also have their respective rows removed from the
// custom attribute table. This introduces holes in their places, causing the table
// to no longer be sorted by Parent, corrupting the assembly. Runtimes assume ordering
// and may fail to locate the attributes set for a particular type. This step sorts
// the custom attribute table again.
void SortCustomAttributes()
{
CustomAttributeTable table = (CustomAttributeTable)stripped_tables[CustomAttributeTable.RId];
if (table == null)
return;

table.Rows.Sort(new CustomAttrRowComparer());
}

void Write()
{
stripped.MetadataRoot.Accept(metadata_writer);
Expand All @@ -209,7 +234,6 @@ public static void StripAssembly(string assemblyFile, string outputPath)
{
AssemblyDefinition assembly = AssemblyFactory.GetAssembly(assemblyFile);
AssemblyStripper.StripAssembly(assembly, outputPath);

}
}
}

0 comments on commit 1df51a3

Please sign in to comment.