How to disassemble .NET code right? [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to disassemble my C# code and then debug it on assembly language level.
Let's say we have a simple C# method:
var a = 1235;
var b = ++a;
var c = ++b;
Console.WriteLine("test");
Console.ReadKey();
I've found two different ways how to get an assembly code.
The first one is to start C# code debugging in VS and then open Disassembly window. Here we have the following code.
Everything is OK and assembly code is pretty much simple and short but the problem is that the logic of this assembly code differs from the logic of the IL code generated by ildasm.
So here is the second way. We can compile C# code, use ildasm to get the IL code from PE file and then use ilasm to generate PE file back. Now we have the following assembly code.
As you can see this assembly code is more like the IL code but it contains much more instructions and it is more complicated.
AFAIK C# compiles to CIL code and then to an assembly code in both cases. But it seems to be that in the first way it just compiles to an assembly code.
So the question is why the assembly code of the first method differs from the IL code? And why the assembly code of the first method differs from the assembly code of the second method?

The JIT is able to re-order and merge machine instructions as an optomisation, but will try to avoid moving the effects across sequence points provided by the pdb. The compiler generally generates one sequence point per line of code, since you generally step through it one line at a time.
While C# will often generate multiple IL instructions per line of code, ilasm is given each instruction explicitly and so generates more sequence points, leaving less room for JIT optimizations.

Related

How to prevent MSIL runtime injection? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
As seen here Programmatic MSIL injection or here http://www.codeproject.com/Articles/463508/NET-CLR-Injection-Modify-IL-Code-during-Run-time you can modify IL code at runtime using some tricky injections.
My question is : how to prevent that? For instance, if someone use that to bypass a security feature, how can i avoid that security hole?
how to prevent that?
You can't, as far as I understand. But you can do make it not easy.
In the simple case, you don't even need to inject IL. You can do IL weaving to modify the assembly. For example, you can find the login method ant delete the original IL code and simply return true, or you can jump to your own login method.
public bool Login(string userName)
{
// original method did security checks
// and return true if the user is authorized
// your implementation can return true or jump to other method
}
For this you must to do it when the application is not running, you modifying the assembly itself. You can do it with mono.cecil and you can look on StaticProxy.Fody for example.
The other case is inject code to running assembly. and this is divide to two cases:
When the code isn't jitted\ngen'd
When the code is jitted\ngen'd
For the first case is more easy, You still have the IL of each method and you inject your own IL instructions.
The second case is more complex because the Jitter redirect the IL pointer to the machine code.
For two of them you can see a bunch of articles\libraris to make the inject work.
Codecope
Article 1
Article 2
But even if you however make it impossible to inject, you still not protected. Because you can modify the bytes itself. See this article for details.
For all above method, there is cases when it more complex to do the work. For example, Generics, DynamicMethods, prevent load assemblies to your process (which is needed in some cases).
To summarize, you can do it very hardly to inject your code but not prevent it.

Is it possible to make a program that reads its own source code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
The community reviewed whether to reopen this question 3 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
What I mean is, could one possibly make a program that does the equivalent of
public class PrintOwnSourceCode
{
public static void Main ( )
{
System.Console.WriteLine([something]);
// prints "public class PrintOwnSourceCode { public static void Main ( ) { ... } }"
}
}
???
And would that be an example of reflection?
Somewhat.
Decompilers can do something similar to this:
I just decompiled a decompiler so I could use it to decompile itself
.NET Decompilers, like [.NET Reflector] (http://www.red-gate.com/products/dotnet-development/reflector/) and dotPeek are capable of reflecting upon a .NET assembly and generating files that resemble the source code. It will not look exactly like the source code because compiling and decompiling is kind of like translating English to French and then back to English--the results are not always guaranteed to be 1:1 as Google Translate can demonstrate. Information, like whitespace, that are for easy reading but not required by the compiler will be lost in the decompilation process. So, your application could decompile itself or invoke an external decompiler to print itself.
Aside
In compiled languages, the compiled code does not have direct access to the source code. (Companies don't typically ship the source code with the compiled code to customers. They only ship the compiled executable.) When it comes to parsed languages, like JavaScript, it's a whole different story. Because the source must be available to the runtime so that it can be parsed and run, the code can always find it's own source file, open it, and print it out.
This was answered here.
The short answer is that you cannot print it via reflection.
If you want to print out the file, then you will need to load in the source file itself (and have the file available).

Using a class in two projects [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a class ProductKeyLib that is part of project MyProgram-Web, which itself is a part of solution MyProgram. As of now, this lib only checks whether the key is valid, but does not generate one.
The interface for key generation will be in project MyProgram-KeyGen, which also is part of solution MyProgram.
Now, the tricky part:
I would like to have both functions (generation and check) in one class, because, as you may guess, 100% compatibility between key generation and key check is better achieved when everything is in one file, and also my unit tests will be easier then.
But: both programs should include that part in their program, I don't want to have a special dll. Furthermore, MyProgram-Web should only include the checking part, not the key generation.
Can I do that in VisualStudio? If so, how?
Well, it's probably not a good idea, but you can use a combination of compiler defines and linked source files.
So you'd have a single cs file containing all the code linked to both projects (no common library - just the single code file). In it, you'd have all your code:
#if KeyGen
public string GenerateKey(...)
{
...
}
#endif
public bool CheckKey(...)
{
...
}
Then, in your keygen project, you'd put a compiler define named KeyGen, and the generation code will only be compiled in the keygen part, and not the client application.
However, this still reeks of "security by obscurity". If the key generation and checking is actually important, this would be insufficient. For example, just through knowing how the key is checked, you can in many cases easily find ways to construct the keys (and even brute-force algorithms are very reliable nowadays, even without utilizing the GPU).

Emitting IronPython code in C# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Basically I have two questions:
1) How to emit or generate a IronPython code (tools, libs) in a C# application. The result of this process should be string consisting of real IronPython code not IL code.
2) How beneficial is the approach above over generating a IronPython code on your own (simply by using StringBuilder)?
I am looking for some code generator library similar to this IMAGINARY pseudo code generator:
IronPythonCodeGenerator generator = new IronPythonCodeGenerator();
Parameter param = new Parameter("str");
ParameterValue value=new ParameterValue(param,"This piece is printed by the generated code!!!");
Function function = IronPythonCodeGenerator.CreateFunction("PrintExtended",param);
function.AppendStatement("print",param);
function.AppendStatement(Statements.Return);
FunctionCall functionCall = new FunctionCall(function,value);
generator.MainBody.Append(function);
generator.MainBody.Append(functionCall);
Console.WriteLine(generator.MainBody.ToString());
, which outputs the IronPython code:
def PrintExtended( str ):
print str;
return;
PrintExtended("This piece is printed by the generated code!!!");
Reflection.Emit is for generating IL code, not for generating high-level language code. So if your target language is IronPython, building it up in a StringBuilder is probably your best bet.
It of course depends on your needs. If all you want to do is just generate code without wanting to change the order of methods, or modify methods after they've been defined etc., just constructing code in a StringBuilder and then compiling it would be the easiest way.

Converting a VB.NET Project to a C# Project [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm looking for a tool (paid or OSS) to convert a mid-sized VB.NET project to a C# project. I've searched StackOverflow and have found a few questions/answers, but most suggest .NET Reflector or online copy/paste single file tools. Reflector doesn't seem to fit the bill as it will convert an assembly, but we're looking for a whole-sale project converter which will maintain the project including file names, comments, etc.
We're fully willing to manually address items that cannot be automatically converted, but would like to start off with a fairly comprehensive converted project.
One recommendation we found is Elegance Technologies' CSharpener for VB.NET - http://www.elegancetech.com/csvb/csvb.aspx. Based on their site, it hasn't been revved since pre-VS 2008.
Recommendations will be appreciated.
SharpDevelop is an open source IDE and it allows you to covert between VB and C#.
Do be aware that there are some things which can be done nicely in VB.net that cannot be done nicely, if at all in C# (and vice versa). Two of note:
In vb.net, declaration-initializations (e.g. "Dim Foo As Bar = Whatever") in a derived class occur after the base constructor has run, and can make reference to the object being constructed. In C#, such declaration-initializations occur before the base constructor is run, and cannot reference the object under construction. One could probably move all such initialization to the constructor, but if there are multiple constructors that may require the creation of redundant code.
In vb.net, a Catch statement may include a condition (e.g. Catch Ex As FancyException When Ex.SomeProperty = 9). In C#, the only way to a achieve a somewhat similar result is to catch an exception and then decide if it meets the necessary criteria, rethrowing if not; this will yield different semantics in a number of ways. Among other things, at the time the When clause is evaluated, Finally statements which will be tripped by the exception will not yet have run, so allowing the state of the system to be captured. Further, if break-on-unhandled-exception is set, and no "When" condition is satisfied, the debugger will break at the location where the original exception occurred. If the exception had been caught and rethrown, the debugger would break at the re-throw.
I would think an IL-to-C# translator might do an okay job of moving initializations to an object's constructors, though that lead to some annoying repetition. I don't think there's any way for C# code to match the semantics of VB.net's exception handling, though.
Two words: A programmer.
If you want it to be the most bug free and just work hire a programmer.
A quick google turns up http://www.freelancer.com where you can hire a one time programmer.
If you're not satisfied with SharpDevelop, TangibleSolutions will provide support with their converters to ensure your happiness.
SharpDevelop is quite good, but at my company we've found VBConversions to provide a much more complete conversion. It's a commerical app though, but for the time saved over SharpDevelop it was a no-brainer for us.
As a specific example, one thing we found that SharpDevelop didn't convert correctly was VB indexes, which use curvy brackets. It seemed unable to distinguish between indexes and method calls so didn't convert the indexes to square brackets. VBConversions converted them fine. This one thing made it worth its purchase for us.

Categories