Is it possible to extract a class from an assembly created with Reflection.Emit and save it physically to a directory?
I would like to use this manipulation to generate projects dynamically with specific content (classes, methods ...).
Is there a way to save dynamic classes with code without need for an external tool to decompile them?
Yes, as long as you pass in AssemblyBuilderAccess.RunAndSave or AssemblyBuilderAccess.Save when you call AssemblyBuilder.DefineDynamicAssembly. Then you can use the Save method to write it to disk - very useful for running it through Peverify to see what you've done wrong :)
Note that this saves the IL - not C# source code, so you would still need to decompile them. If you want C# source code without decompiling, then you would need to generate C# source code as your origin - presumably passing it through Roslyn or CSharpCodeProvider to get the IL.
Note: not all operations are valid when used in this way - if you are skipping accessibility checks, for example, to access non-public members of types outside of your control. This is allowed in some runtime-only scenarios, but is not reliable in assemblies loaded from disk. Similarly, a lot of things are possible in IL that have no direct C# equivalent.
Related
I'm basically know about metadata in c#.net and I recently heard about .net Obfuscating.
I want to know if I use any obfuscator to make my assemblies from being understood it will obfuscate the IL, but will it also change metadata? Then can I add it as a reference to my project and see the real name for classes and its members?
These days most obfuscators can basically rewrite your assembly for you. The majority of the features include:
Renaming (tool vendors often will provide an option to create a map so you can manually map a renamed member to the original member name with a tool like Reflector)
String encryption - this encrypts string constants in the code (stored in the string heap area of the meatadata) so if you open the file in Reflector it will usually show encrypted. The encrypted values still get decrypted right before using them.
IL obfuscation - control flow rewriting of the IL to make spaghetti code and difficult to follow
There are also other tools that go way beyond this but they all just raise the bar of what it takes to reverse something.
If you set a reference to an obfuscated dll/exe you'll see the obfuscated/renamed members, but if the vendor provides a map (most will) you can figure out which is which. You can also typically use interfaces that are not obfuscated if you need a readable api to use. An example would be Reflector - the addin apis are all interfaces that are not obfuscated but all implementations of the concrete classes are obfuscated.
Try using Confuser, as there's still no Deobfuscator for this one.
http://confuser.codeplex.com/
You won't see normal names of classes and methods as it hashes them and also many more. It is basically impossible to get anything out of code afterwards.
Recently I started to use Reflection, Reflection.Emit and Code Dom. The purpose of my coding is to load an assembly (e.g. "C:\Temp\MyAssembly.exe"), read its classes and methods. This has been done however I am interested to save a copy of "MyAssembly.exe" to "MyAssembly.dll". The reason is because I want to instrument the code and make some changes to the methods.
I am aware about how to create new assemblies and save them, but I am not sure if it is possible to "clone" an existing assembly (including all its classes and methods) with extension .exe to .dll.
I will appreciate any advice!
Thanks.
Peter
Simply saving a copy of "MyAssembly.exe" to "MyAssembly.dll" shouldn't be much of a problem (use File.Copy, for example) and doesn't require Reflection or Reflection.Emit.
But, as the comments reveal, the problem is more one of saving a modified copy of "MyAssembly.exe" to a different file name. It is not possible to modify an existing assembly using Reflection.Emit, but you have other options:
you could use a third-party tool such as Cecil or Microsoft CCI to load the assembly, modify it, and save it under a different name;
you could use the IL disassembler and IL assembler included with the .NET framework/SDK to disassemble, then modify, then reassemble your assembly;
in theory, you could probably load the assembly, analyze it via Reflection and emit a completely equivalent new assembly using Reflection.Emit; however, I'd not take that route, as it would be an enormous piece of work to get this right.
I'm trying to figure out if it's possible via reflection (or otherwise) to "audit" some code to enforce validation requirements -- such as checking whether or not code creates any threads (System.Threading.Thread) or uses other BCLs. The assumption is that the code is already compiled into a dll. Thanks!
Look at FxCop. It can load a compiled binary (dll or exe) and perform validation and compliance checking against that compiled IL, regardless of the .NET language used to write it.
You can write your own rules - which you would do in this case to catch cases of "= new Thread()" and the like.
You can do this with reflection if you are very well-versed in IL.
MethodBody mb = this.GetType().GetMethod( "Method", BindingFlags.Default ).GetMethodBody();
byte[] bytes = mb.GetILAsByteArray();
Probably way more trouble than it is worth; the resulting IL will need to be parsed.
An IL parser (but somewhat dated): http://www.codeproject.com/KB/cs/sdilreader.aspx which will generate a list of OpCodes for you (look for OpCodes.Newobj for instantiation of a Thread).
As others have said reflection won't help you as it only describes the metadata of tpyes.
However, the Mono.Cecil project is a runtime way of actually looking at the IL (Intermediate Language) of types within an assembly. Although a product of the Mono framework it is compatible with the Microsoft CLR.
Reflection does not allow inspection of the body of members, only their signatures. In other words, it won't tell you anything about what a particular method or property does, just what it looks like.
To do what you're after, you'll have to use something like ildasm.exe to turn the compiled .dll or .exe into IL, then go over the IL and see if it's doing anything to which you object.
Reflection will allow you to inspect the body of methods through MethodBase.GetMethodBody, which gives you a MethodBody to inspect.
However, at this level you are dealing with raw IL in a byte array, which you have to analyze start to end to find out calls to external methods and what they do etc.
So it won't be pretty or easy, but certainly it's possible.
Using System.Reflection, I can get all methods from a specific class
I need know what are the references to these methods. For example: in Visual Studio, if you want the references of specific object
right click on the object and select "Find All References"
Visual Studio show the references of this selected object
I want make the same, but from code with reflection or another way.
Can I do this?
This cannot be done with reflection. Reflection is a tool for inspecting metadata and assemblies. In order to find all references to a given method / type, you'd need to inspect the underlying IL of an assembly. Reflection only has very limited IL capabilities (simply returns it as a byte array). You'll need to custom inspect that byte stream in order to gather any context about what it's referencing.
That's not something that's directly accessible via runtime reflection on a specific class. You will have to introspect the entire source code tree or resulting IL to determine if any references to a particular method with the same name are the right overload and signature for the method you're trying to find references to.
Furthermore, without additional work, you're never going to find references to a specific method that are themselves invoked via reflection. (This is one reason why obfuscating that kind of code is challenging and error-prone.)
If you're just looking to find the references for informational purposes, Reflector has that feature.
http://www.red-gate.com/products/reflector/
Microsoft released the Common Compiler Infrastructure projects under an open source license. These projects aim to support many compiler-related features, including assembly analysis like you're referring to. The documentation is limited, so you'll need to have a thorough understanding of ECMA-335 (Common Language Infrastructure) to effectively use it for your purposes.
There are no magic code samples here. This is a large and quite complicated task where you'll be on your own most of the way.
I happened upon a brief discussion recently on another site about C# runtime compilation recently while searching for something else and thought the idea was interesting. Have you ever used this? I'm trying to determine how/when one might use this and what problem it solves. I'd be very interested in hearing how you've used it or in what context it makes sense.
Thanks much.
Typically, I see this used in cases where you are currently using Reflection and need to optimize for performance.
For example, instead of using reflection to call method X, you generate a Dynamic Method at runtime to do this for you.
You can use this to add scripting support to your application. For examples look here or here.
It is quite easily possible to publish parts of your internal object framework to the scripting part, so you could with relative ease add something to your application that has the same effect as for example VBA for Office.
I've seen this (runtime compilation / use of System.Reflection.Emit classes) in generating dynamic proxies ( Code project sample ) or other means of optimizing reflection calls (time-wise).
At least one case you might use it is when generating dynamic code. For example, the framework is using this internally to generate XML serializers on the fly. After looking into a class at runtime, it can generate the code to serialize / deserialize the class. It then compiles that code and users it as needed.
In the same way you can generate code to handle arbitrary DB tables etc. and then compile and load the generated assembly.
Well, all C# code is run-time compiled, since it's a JIT (just-in-time) compiler. I assume you are referring to Reflection.Emit to create classes etc. on the fly. Here's an example I have seen recently in the Xml-Rpc.Net library.
I create a C# interface that has the same signature as an XML-RPC service's method calls, e.g.
IMyProxy : IXmlRpcProxy
{
[XmlRpcMethod]
int Add(int a, int b);
}
Then in my code I call something like
IMyProxy proxy = (IMyProxy)XmlRcpFactory.Create(typeof(IMyProxy));
This uses run-time code generation to create a fully functional proxy for me, so I can use it like this:
int result = proxy.Add(1, 2);
This then handles the XML-RPC call for me. Pretty cool.
I used runtime compiler services from .NET in my diploma thesis. Basically, it was about visually creating some graphical component for a process visualization, which is generated as C# code, compiled into an assembly and can then be used on the target system without being interpreted, to make it faster and more compact. And, as a bonus, the generated images could be packaged into the very same assembly as resources.
The other use of that was in Java. I had an application that had to plot a potentially expensive function using some numerical algorithm (was back at university) the user could enter. I put the entered function into a class, compiled and loaded it and it was then available for relatively fast execution.
So, these are my two experiences where runtime code generation was a good thing.
something I used it for was for allowing C# and VB code to bu run by the user ad-hoc. They could type in a line of code (or a couple lines) and it would be compiled, loaded into an app domain, and executed, and then unloaded. This probably isnt the best example of its usage, but an example of it none-the-less