hooking via hotpatching... non exported class method in dll - reverse-engineering

I have been studying this method of API hooking using the mechanisms for hotpatching in windows dlls.
http://www.codeproject.com/KB/winsdk/0xF9EB_Hooking.aspx
I was wondering if anyone would know of a way to extend that to hooking non exported functions such as a C++ constructor for an internal class inside of a DLL. I have already know the address via dis-assembly... the problem I am having is how to set up the right calling conventions so that I can call the original function inside of my hook function.
I'm already to the point to where my hook function gets called... the program crashes because I can't return the results of calling the original function.
Lets assume we are talking about hooking an internal class constructor with a prototype something like this:
public __thiscall <class_name>::<class_name>(<single pointer arg to another object>)

depending on how your module is loaded, you can generally just overwrite the relative or absolute addresses at their respective call sites, else you need to make a trampolining function, for which its easier to use something like MS Detours.
In terms of the correct prototype for __thiscall based class member functions, you need some trickery, as you can't generally use __thiscall outside classes. The fastest and easiest way is to use __fastcall and ignore the second parameter. So your first definition becomes void __fastcall myctor(myobj* pObj).

Define it as a typical __stdcall function except that you'll have this pointer in ecx register. If you need this pointer, then use the __asm keyword to get the value:
void __stdcall HookedConstructor( SomeObject *pObject){
HookedClass *pClass;
__asm mov pClass, ecx;
...
}
Note that you'll have to do this at the beginning of the call. Otherwise, the value of ecx register may be overwritten.

Related

How to write C++ constructor of cython extension type?

How do I modify the C++ class constructor that cython will generate from a Cython extension type that I've defined in a .pyx file wo that I don't incur the penalty of using def __cinit__(self)? Assume I am compiling to C++, not C.
What I would like to do is set the default values as I would in an initialization list in C++, and maybe run some code in the constructor without interacting with Python. It looks like the __cinit__ method runs after the C++ class members are initialized and the C++ constructor finishes running.
In this example, it says
Cython initializes C++ class attributes of a cdef class using the nullary constructor.
I assume this refers to the default constructor since the C++ constructor is a nullary constructor. I also assumes this happens with or without a __cinit__ method.
If the class you’re wrapping does not have a nullary constructor, you must store a pointer to the wrapped class and manually allocate and deallocate it. A convenient and safe place to do so is in the cinit and dealloc methods which are guaranteed to be called exactly once upon creation and deletion of the Python instance.
I have an existing class where I call Py_XDECREF on a member object in a loop inside of __dealloc__. This object holds pointers to Python objects. When I convert to C++ code, the annotated HTML shows no highlighted yellow text in the lines where the __dealloc__ method is defined. This is interesting because __dealloc__ is also defined using def.
When I try to initialize a member that is an instance of a Cython Extension that I defined (and did not create from wrapping C++ code), however, the __cinit__ method is highlighted in yellow.
def __cinit__(self):
self._member = MyCyExt()
I'm wondering if it's because I can't initialize a Cython Extension Type in pure C++. I don't know why that would be the case since Cython calls the nullary constructor by default.
This answer solves the problem, but it incurs the overhead I am trying to avoid. Is there a way to do this without incurring that overhead and actually writing the constructor itself in a .pyx file?

Why things are so different in a driver class ("static void main") and a class definition?

I know some of the terms I use are confusing. To clarify, a driver class is basically one built on a class definition (starting with public class...) but is a method itself with the header public static void main (String args[]).
The point of this post is to resolve my serious confusion. (I am a beginner in programming)
to me, since a driver class is a method, all it does is to implement itself. But things kinda turn out to be the opposite . For example:
to implement a constructor in a driver class, you simply put down the constructor heading, like public Rectangle(), with its name being the same as that of the class. but in a class definition, to creat a object/ implement a constructor, you also have to write down happen inside that constructor, so you use the expression "type name = new type name ()".
PS: I might have used some terms wrongly, correct me thanks. Or some concept
I'll try to answer this the best way that I can.
Let's look at each of the keywords in a "driver class method" and determine the meaning.
public - this method is publicly callable by a class outside of it
static - this method is callable WITHOUT an instance of the class. In Java, look at the Math class. You don't need to instantiate an instance of the Math class to use the sqrt function (Math m = New Math(); m.sqrt(25);), you can just use Math.sqrt(25).
void - this method returns nothing
main - name of the method
Now that we have that cleared up, let's ask ourselves why these things have to be here for a "driver class"
The Virtual Machine (the program that runs your custom programs) is hard coded to look for a method named main that is public and can also be called WITHOUT CREATING AN INSTANCE OF YOUR CLASS.
So this means that when your program first runs, there is no instance of it.
To counter this, you can either create all of your methods and properties as static (generally considered bad practice) OR you can create an instance of your own class inside of it's own entry method, and begin to call the non-static methods and properties that belong to the instance.
I hope this makes sense.

How do I define 'out' parameters a in C++CX Windows Runtime Component?

By the looks of Google it seems like this might not be possible, but:
How do I define an 'out' parameter in a C++/CX 'ref class'?
If your answer is that this isn't possible, please provide a reference.
Any parameter which is of type T* (where T is a ABI-legal type) will be treated by the compiler as an out parameter, and decorated in metadata as such. The following code:
namespace TestMakePublic {
public ref class Class1 sealed
{
public:
void foo(int* out1, Object^* out2){}
};
}
Produces a function in metadata which looks like this (ildasm output):
.method public hidebysig newslot virtual final
instance void foo([out] int32& out1,
[out] object& out2) runtime managed
{
.override TestMakePublic.__IClass1PublicNonVirtuals::foo
} // end of method Class1::foo
Note that WinRT does not support "in/out" parameters, so the value of out1 and out2 are only valid for returning from the function, and cannot be trusted as inputs to foo.
It is a C# specific keyword, COM has it too in the IDL syntax. The equivalent in MSVC++ is the [out] attribute.
But no, the compiler is going to reject that with C3115 if you try to use it. Keep in mind that you use the C++/CX language extension to write code that's used by other languages. Which in general support to notion of [out] very poorly. Neither C++, Javascript or .NET languages like vb.net support it. You can see this as well in the .h files in C:\Program Files (x86)\Windows Kits\8.0\Include\WinRT, generated from the .idl files in that same directory that does have the [out] attribute. It was stripped in the .h file by midl.
It doesn't matter anyway since your code will be used in-process so there's no benefit at all from [out] being able to optimize the marshaling of the argument value. Just a plain pointer gets the job done. Having to initialize the argument value in C# code is however inevitable lossage.
You can use:
_Out_opt_
_Out_
But these are available only for private, internal, and protected members AFAIK.

What are callback methods?

I'm a programming noob and didn't quite understand the concept behind callback methods. Tried reading about it in wiki and it went over my head. Can somebody please explain this in simple terms?
The callback is something that you pass to a function, which tells it what it should call at some point in its operation. The code in the function decides when to call the function (and what arguments to pass). Typically, the way you do this is to pass the function itself as the 'callback', in languages where functions are objects. In other languages, you might have to pass some kind of special thing called a "function pointer" (or similar); or you might have to pass the name of the function (which then gets looked up at runtime).
A trivial example, in Python:
void call_something_three_times(what_to_call, what_to_pass_it):
for i in xrange(3): what_to_call(what_to_pass_it)
# Write "Hi mom" three times, using a callback.
call_something_three_times(sys.stdout.write, "Hi mom\n")
This example let us separate the task of repeating a function call, from the task of actually calling the function. That's not very useful, but it demonstrates the concept.
In the real world, callbacks are used a lot for things like threading libraries, where you call some thread-creation function with a callback that describes the work that the thread will do. The thread-creation function does the necessary work to set up a thread, and then arranges for the callback function to be called by the new thread.
Wiki says:
In computer programming, a callback is
a reference to executable code, or a
piece of executable code, that is
passed as an argument to other code.
This allows a lower-level software
layer to call a subroutine (or
function) defined in a higher-level
layer.
In common terms it is the mechanism to notify a piece of code i.e. a method, which piece of code to execute, i.e. another method, when it is needed.
Callback is related to the fact that the client of the calling function specifies a function that belongs to the client code's responsibility to the calling function to execute and this is passed as an argument.
An example is in GUIs. You pass as argument the function to be called once an event occurs (e.g. button pressed) and once the event
occurs this function is called.
This function is usually implemented by the object that originally registered for the event
Callback function is a function that is called through a function pointer. If you pass the pointer (address) of a function as an argument to another, when that pointer is used to call the function it points to it is said that a call back is made.
Why Should You Use Callback Functions?
A callback can be used for notifications. For instance, you need to set a timer in your application. Each time the timer expires, your application must be notified. But, the implementer of the time'rs mechanism doesn't know anything about your application. It only wants a pointer to a function with a given prototype, and in using that pointer it makes a callback, notifying your application about the event that has occurred. Indeed, the SetTimer() WinAPI uses a callback function to notify that the timer has expired (and, in case there is no callback function provided, it posts a message to the application's queue).
In general you supply a function as a parameter which gets called when something occurs.
In C code you will pass something that looks like this:
int (callback *)(void *, long );
meaning a function that takes two parameters, void * and long and returns an int.
With object-orientated languages the syntax is sometimes simpler. For example you might be able to construct a callback mechanism that allows the user to pass in an object that looks like a function or has an abstract method (thus wrapping a function) and context data too.
Modern languages use the term "delegate" to refer to a function "pattern". These can be used as callbacks. Some languages also use the term lambda which is essentially a function with no name, often created "on the fly" in a block of code and passed as a callback.
C++11 has introduced these into its standard.
The advantage of using a callback is that you can separate out, i.e. reduce / decouple an API from what is calling it, and to some extent vice versa, i.e. although in one place you know you are calling into the API, at the point of the "handler" it does not need to know from where it was called.
For example, you can have an API that generates objects and then "calls-back" as they get generated.
Call back means that you pass the code as a parameter. For example, imagine a button, that much show a dialog when pressed:
Button testBtn;
testBtn.setOnClickListener(new OnClickListener() {
#Override
public void onCLick() {
JOptionPane.showDialog(testBtn, "Test button pressed");
}
}
Here we tell the button what to execute, when it will be click. So, the framework will execute the passed code, when it detecs the click. Inside the framework there are some code like:
void processEvent(Event e) {
if (e.type == Event.CLICK) {
e.getComponent().getOnClickListener().onClick();
}
}
So, some basic code calls back the listener when the appropriate event happens.
PS: Pseudocode here, just do describe the idea.
A callback method is a method that gets called when an event occurs
In simple word, actually, a Callback is a reference to a function or method, which you can pass as a parameter to another function for calling it back later.
From the above figure, B_reference() is the callback method.
Source code sample:
>>> def A(A_msg,B_reference):
... # After printing message, method B is called.
... print(A_msg)
... B_reference()
...
>>> def B():
... print("Message from B")
...
>>>
>>> A("Message from A",B)
Message from A
Message from B
>>>
If you still don't understand what it is, you can check this video:

Whats the difference between C# delegates, Dynamic Proxy, Closures and function pointers?

What are useful definitions for the common methods of passing a method or function as data, such as:
Delegates
Closures
Function pointers
Invocation by dynamic proxy and
First class methods?
Function pointers lets you pass functions around like variables. Function pointer is basically legacy method to pass function around in languages that don't support first-class methods, such as C/C++.
First class methods Basically means you can pass functions around like variables. Methods (loosely) mean functions. So this basically means first class functions. In simplest terms, it means functions are treated as "first class citizens", like variables. In the old days (C/C++), because we can't directly pass a function around, and we had to resort to workarounds like function pointers, we said functions weren't first-class citizens.
Delegates is C#'s answer to first-class methods. Delegates are somewhat more powerful because it involves closures, consider the following code snippet:
void foo( int a )
{
void bar() { writefln( a ); }
call( &bar );
}
void call( void delegate() dg ) { dg(); }
int main( char[][] args ) {
foo( 100 );
}
Notice that bar can reference the local variable a because delegates can use closures.
Closures can be very confusing at first. But the lazy-man's definition can be really simple. It basically means a variable can be available in the human-expected way. Put in other words, a variable can be referenced in places where they look like they would be present, by reading the structure of the source code. For example, looking at the code fragment above. If we didn't have closure, bar would not be able to reference a because a was only local to foo, but not bar, which is another function.
Dynamic Proxy is the odd one out. It doesn't belong to these items. Explaining it requires some very long text. It stems from the famous Proxy Pattern. The problem with Proxy Pattern was that the Proxy class needs to be implementing the same interface as the Subject. Dynamic Proxy basically means using reflective approach to discover the Subject's method so that the ProxyPattern can be freed from being tied to the Subject's interface.
just the ones i know about:
Function pointers: just that, a pointer to a piece of code. you jump to it, it executes. typed languages can enforce some parameter passing convention (i.e. C declarations)
Closures: a function with some state paired. most naturally written in lexically scoped languages (i.e. Scheme, JavaScript, Lua). several closures can share the same state (or part of it), making it an easy way to implement OOP.
First class methods: a closure created from an object instance and a method. some languages with both closures and a native OOP (Python, JavaScript) can create closures automatically.
Closure is a programming language concept. Delegate is its realization in MS.NET.
A Delegate in MS.NET is a strongly typed pointer to an object's method (a delegate instance points to both - an object and its method). There is also a way to combine several void delegate instances into one.