Click here to Skip to main content
15,890,741 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello ! I am coding an obfuscator using C# and dnlib. At some point i need to inject unsafe code in the executable but this should end up in an app crash, if you don't "declare" it . Is there a way to declare(with or without dnlib) that a selected module will contain unsafe code ?
Thanks!!

What I have tried:

Tried to find how to declare that a module will contain unsafe code using dnlib. I couldn't find anything in the docs.
Posted
Updated 22-Jun-17 1:11am

I can't speak for dnlib but the standard compiler marks unsafe modules with the [System.Security.UnverifiableCodeAttribute()]

The simplest detection would be something like
private void SafeOrUnsafe(Assembly asm) {
  foreach (Module m in asm.GetModules(true)) {
    Debug.Print("{0} Unsafe : {1}", m.Name, m.IsDefined(typeof(System.Security.UnverifiableCodeAttribute), true));
  }
}

Alan.
 
Share this answer
 
After some more digging, i found out that you can mark a module as unsafe with dnlib with the following code:
C#
ModuleDefMD module = ModuleDefMD.Load("theModuleYouWantToMarkAsUnsafe.exe");

module.CustomAttributes.Add(new CustomAttribute(new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), module.CorLibTypes.GetTypeRef("System.Security", "UnverifiableCodeAttribute"))));


I thank very much @Alan for pointing out what attribute is needed for the job !
 
Share this answer
 
v5
Comments
Graeme_Grant 28-Aug-17 20:28pm    
Please do not post solutions to your own problems, then flag as answered. This is considered reputation farming and can get you kicked.

Instead, include this update in the Question by clicking on the "Improved question" widget above. Once done, please delete this solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900