简体   繁体   中英

Disable "Constant Literals Pruning" in Eazfuscator.NET

I would like to disable "Constant Literals Pruning" in Eazfuscator.NET (assembly level). How is this possible?

Background: We use enums in a custom attribute constructor. The type of constructor parameter is object, because the attribute class is in an assembly that doesn't reference the assembly containing the enum.

Before obfuscation:

[MyAttribute(MyEnum.Value3)]
public class MyClass
{

}

After obfuscation (decompiled):

[MyAttribute(2)]
public class MyAttribute : Attribute
{

}

In the constructor of the attribute I cast the value to Enum. This generates an exception in the obfuscated assembly, but not in the unobfuscated variant:

public class MyAttribute : Attribute
{
    public MyAttribute(object value)
    {
       var x = (Enum) value;    // this throws an InvalidCastException after obfuscation
    }
}

I'm a colleague of Frans, and we thought of the following solution. To be able to cast the integer back to its enum-value, you have to pass the type of the enum.

Any thoughts?

[myAttribute("description", param1: MyOwnEnum.MyParticularEnumValue, param2: MyOwnEnum.MyParticularEnumValue2, passedType: typeof(MyOwnEnum)]

internal class myAttribute : Attribute {

public myAttribute(string description, object param1, object param2, Type passedType)
{
    this.myAttributeDescription = description;
    this.SomePropertyWhichIsAnEnum = (Enum)Enum.ToObject(passedType, param1));
    this.SomeOtherPropertyWhichIsAnEnum = (Enum)Enum.ToObject(passedType, param2)
}

}

You cannot cast an integer to the Enum base class.

You might, however, not need to disable “Constant Literals Pruning”. You can cast an integer to a specific enum type instead of casting to the the Enum base type. This also works when the enum doesn't have a value representing the integer value.

[MyAttribute(MyEnum.Value3)]
public class MyClass1
{
    //...
}

[MyAttribute(2)]
public class MyClass2
{
    //...
}

[MyAttribute(123456)]
public class MyClass4
{
    // MyEnum does not have a value with 123456
    // but it still works
}


public class MyAttribute : Attribute
{
    public MyAttribute(object value)
    {
       var x1 = (MyEnum)value; // works with enum and number
       var x2 = (Enum)(MyEnum)value; // works (but why would you?)
       var x3 = (Enum) value; // this throws an InvalidCastException after obfuscation
    }
}

This is how you can disable stripping/pruning of the enum literals with Eazfuscator.NET:

[Obfuscation(Feature = "enum values pruning", Exclude = true)]
enum SampleEnum
{
    None,
    Digit1,
    Digit2
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM