Can I call a Win32 API from the Visual Studio Immediate Window? - c++

I'm debugging a C++ Win32 application and I'd like to call an arbitrary Win32 API from the context of that process, as though the program had run this line of code:
DestroyWindow(0x00021c0e);
But entering that into the Immediate Window gives:
CXX0017: Error: symbol "DestroyWindow" not found
Edit: Using the full name of the function, {,,user32.dll}_NtUserDestroyWindow#4, I can get the Immediate Window to understand which function I mean and display the function's address:
{,,user32.dll}_NtUserDestroyWindow#4
0x76600454 _NtUserDestroyWindow#4
but when I try to call it, this happens:
{,,user32.dll}_NtUserDestroyWindow#4(0x00021c0e);
CXX0004: Error: syntax error
Is it even possible to call a C function from the Immediate Window like this, or am I barking up the wrong tree?

Once you have the function address (as you've done in the updated question), you can try casting it to a function pointer and calling it:
(*(BOOL (*)(HWND))0x76600454)((HWND)0x00021c0e)
The first part of that casts the address to BOOL (*)(HWND), which is a pointer to a function taking an HWND parameter and returning BOOL. Then, the function pointer is dereferenced and called. Make sure to get the parameters correct, otherwise bad things will happen. On 64-bit systems, and HWND might be 64 bits, so you might not be able to get away with passing the parameter as an int.
Edit: See the comments for the full story.

I believe the problem is that the C++ EE is having problems resolving the context of DestroyWindow. Try the following
{,,user32}DestroyWindow(0x00021c0e);
I'm not sure if the method invocation syntax supports this style of qualification (only used it for casting in the past). But it's worth a shot.
EDIT You may or may not need to add a ! after the closing }. It's been awhile since I've used this syntax and I often confuse it with the equivalent windbg one.

I figured out a workaround, but I'd still prefer to get the Immediate Window to work.
The workaround is:
get the address of the function, as shown in the question
use the Disassembly window to go to that address, and put a breakpoint there
do something to the application to make it call DestroyWindow
step back up the call stack to the caller of DestroyWindow, which looks like this:
6D096A9D push ecx
6D096A9E call dword ptr ds:[6D0BB4B8h]
put a breakpoint on the push ecx instruction, and clear the one on DestroyWindow
hit Continue, and again do something to the application to make it call that code
note down the value of ecx
change the value of ecx in the debugger to the desired value and step over the push/call
restore the value of ecx and use Set Next Statement to go back to the push, then Continue
It's longwinded, but it works. It assumes you can make the application call the appropriate API at will.

Related

Why does `RtlGetFullPathName_U` look different in ntdll.dll and reactos' docs?

I'm hooking an udocumented Windows API function RtlGetFullPathName_U (residing in ntdll.dll), to detect process injections in my game. However, the function type looks different when looking at the function in IDA, and when looking at the function through the only info I could find about the function (from ReactOS's docs).
When looking in IDA:
The file analyzed above is ntdll.dll found through x32dbg:
When looking in ReactOS' docs, I see RtlGetFullPathName_U looks like this:
ULONG
NTAPI
RtlGetFullPathName_U(
IN PCWSTR FileName,
IN ULONG Size,
IN PWSTR Buffer,
OUT PWSTR *ShortName
);
Using ReactOS' version of RtlGetFullPathName_U works when I hook, but I notice a difference in amount of parameters, why is that? I mean my approach would normally be to see the exported functions through IDA, not through ReactOS' documentation.
A last question; are there other relevant functions I could hook to detect process injections? Besides LoadLibraryA/W/Ex?
As you can see in the disassembly, the function uses push ecx early on, followed by saving the address of the just-pushed value in eax. The address in eax is then pushed onto the stack as an argument for the next function.
So what you read in the decompiler output is not technically wrong: it stores the value of ecx in a local variable and then passes the address of that local variable to RtlGetFullPathName_UEx.
To capture this, IDA assumes that the value passed to the function in ecx might matter and marks it as a parameter.
However, most likely, the real purpose of the push ecx instruction here is not to save the value of ecx, but simply to reserve four bytes on the stack for a local variable (a more common idiom for which would be sub esp, 4). Using push is an optimization.
To confirm this definitively, you would have to analyze the called function, RtlGetFullPathName_UEx, and see whether it ever reads the contents of the memory pointed to by its last parameter. If, as I strongly suspect, it does not, and this parameter is only used for output, then the value in the caller can simply be considered uninitialized.
After you've confirmed this (or if for some other reason, e.g. trusting ReactOS's declaration, you believe this is the case), you can modify the function prototype to use __stdcall and remove the void *this parameter in IDA, and it will show it as what it (probably) is: passing a pointer to an uninitialized local variable.

Filter out breaks based on stack trace

I want to break in a function, but only if it was NOT called from a specific other function. That's because there's one or two functions that amount for most of the calls, but I'm not interested in debugging them.
I noticed that breakpoints have a Filter option:
Is that something that could be used to filter stack trace and break based on it's contents?
I don't think you can use the filters for that, based on this: Use breakpoints in the Visual Studio debugger Specifically, the breakpoint filters are meant for concurrent programs, and you can filter on:
MachineName, ProcessId, ProcessName, ThreadId, or ThreadName.
One suggestion I would make to get something like what you want, is to add an extra parameter with a default value to the function you want to break in. Then set the value to something different in the places you don't want to monitor, and use a "Conditional Expression" in the breakpoint to make it only break on the default value.
Of course, this requires you to make debugging-only changes to your code (and then revert them when done), so it is a pretty ugly approach.
If you know the address of the code location where the function is called from, you could make the breakpoint condition depend on the return address stored on the call stack.
Therefore, you should be able to set the breakpoint as a condition of the value *(DWORD*)ESP (32-bit code) or *(QWORD*)RSP (64-bit code). I haven't tested it though.
However, my above example will only work if the breakpoint is set at the very start of the function, before the called function pushes any values on the stack or modifies the stack pointer. I'm not sure where Visual Studio sets the breakpoint if you place it on the first instruction of a function. Therefore, you may have to either set the breakpoint in the disassembly window to the first assembler instruction of the function or you might have to compensate for the function having modified the stack pointer in the function prolog.
Alternatively, if a proper stack frame has been set up using the EBP register (or RBP for 64-bit), then you could use that instead.
Please note that not the address of the CALL instructon will be placed on the stack, but rather the return address, which is the address of the next assembler-level instruction of the calling function.
I suggest you first set an unconditional breakpoint where you want it and then inspect the stack using the memory viewer in the debugger, specifically to see where the values of ESP/RSP and EBP/RBP are pointing and where the return address is stored on the stack.

C++ Function Hook (memory address only)

I have a memory address, its the memory address of a function in another program (one of its dlls). I am already loaded into the program via DLL injection. I already have the bass address, and the actual location of the function each time the program loads. So, this is not an issue.
I want to just simply hook that location, and grab the variables. I know the function's pseudocode. So this is not an issue. OR another approach that would be great is doing a break point at that memory location and grab the debug registers.
I can not find any clear-cut examples of this. I also do not have the "name" of the function, I just have the memory address. Is there any way to work with just a memory address? Most, if not all the examples have you use the name of the function, which I do not have.
If anyone could point me into the right direction so I can accomplish this task, I would greatly appreciate it. It also might help a lot of other people who may have the same question.
Edit: I should also mention that Id rather not overload my program with someone else code, I really just want the barebones, much like a basic car with roll-up windows. No luxury packages for me please.
You missed the most important part, is this for 32 or 64 bit code? In any case, the code project has a good run-down and lib here that covers both.
If you want to do this "old-school", then it can be done quite simply:
firstly, you need to find the virtual address of the function you want to hook (due to ASLR, you should never rely on it being in the same place), this is generally done with RVA + module base load address for function that are not exported, for exported functions, you can use GetProcAddress.
From there, the type hook depends on what you want to accomplish, in your case, there are two methods:
patch a jump/call out to your function in the target function' prologue
patch all call sites to the function you want to hook, redirecting to your function
the first is simpler, but messy as it generally involves some inline assembly (unless you are hooking a /HOTPATCH binary or you just want to stub it), the second is much cleaner, but requires a bit of work with a debugger.
The function you'll jump out to should have the same parameters and calling convention (ABI) as the function you are hooking, this function is where you can capture the passed parameters, manipulate them, filter calls or whatever you are after.
for both, you need a way to write some assembly to do the patching, under windows, WriteProcessMemory is your first port of call (note: you require RWX permissions to do this, hence the calls to VirtualProtect), this is a little utility function that creates a 32bit relative call or jump (depending on the opcode passed as eType)
#pragma pack(1)
struct patch_t
{
BYTE nPatchType;
DWORD dwAddress;
};
#pragma pack()
BOOL ApplyPatch(BYTE eType, DWORD dwAddress, const void* pTarget)
{
DWORD dwOldValue, dwTemp;
patch_t pWrite =
{
eType,
(DWORD)pTarget - (dwAddress + sizeof(DWORD) + sizeof(BYTE))
};
VirtualProtect((LPVOID)dwAddress,sizeof(DWORD),PAGE_EXECUTE_READWRITE,&dwOldValue);
BOOL bSuccess = WriteProcessMemory(GetCurrentProcess(),(LPVOID)dwAddress,&pWrite,sizeof(pWrite),NULL);
VirtualProtect((LPVOID)dwAddress,sizeof(DWORD),dwOldValue,&dwTemp);
return bSuccess;
}
This function works great for method 2, but for method 1, you'll need to jump to an intermediary assembly trampoline to restore any code that the patch overwrote before returning to the original function, this gets very tedious, which is why its better to just use an existing and tested library.
From the sounds of it, using method 1 and patching a jump over the prologue of your target function will do what you need, as it seems you don't care about executing the function you patched.
(there is a third method using HW breakpoints, but this is very brittle, and can become problematic, as you are limited to 4 HW breakpoints).
Your "sample" is here:
http://www.codeproject.com/Articles/4610/Three-Ways-to-Inject-Your-Code-into-Another-Proces#section_1
Normally when you "hook" into the DLL, you actually put your function in front of the one in the DLL that gets called, so your function gets called instead. You then capture whatever you want, call the other function, capture its return values and whatever else, then return to the original caller.

Why does using the wrong calling convention sometimes work?

I used "StartServiceCtrlDispatcher" function to register a callback function (called ServiceMain) in windows, but the callback function I declared got compiled with the wrong calling convention.
The thing is that on some computers, when the application returned from the callback function, the application crashed, but on other computers the application did not crash.
Now, once I found the bug everything worked, but I just don't understand why on some computers it worked correctly without crashing ?
Thanks! :-)
This is all very Windows-specific, we're not talking standard C++ here.
Checking out the documentation of StartServiceDispatcher it has only one argument, and is declared as WINAPI which in turn means __stcall calling convention.
For freestanding functions, __stdcall is one of two main calling conventions. The other one is __cdecl. The machine code level difference is simply who restores the stack pointer: with __stdcall it is the function itself, while with __cdecl it is the calling code.
When the function actually is __stdcall but is invoked as if it was __cdecl, the situation is that there are two attempts to restore the stack pointer: one at the exit from the function, and one in the calling code. The one in the function will succeed. Depending on how the attempt in the calling code is done, it can mess things up thoroughly (e.g. if just adding the required offset, treating the stack pointer as relative), or it may have no harmful effect. But it's very likely to create a mess, since the assumption about the stack pointer value on return from the function, is incorrect.
When the function actually is __cdecl it will not itself restore the stack pointer, since that is the calling code's responsibility. And if the calling code is treating it as __stdcall then the calling code won't restore it either, since from the calling code's view the function is doing that. The result, if you don't get an early crash (because of broken assumptions), should then be that repeated calls, say in a loop, will eat stack space.
It's all very much Undefined Behavior.
And one property of Undefined Behavior is that it can do anything, including apparently working…
Cheers & hth.,
Calling conventions differ in the details, like which registers are preserved. If you happened to not store anything you still needed in those registers, then it didn't matter that they were erased when they didn't have to be. Similarly, if your calling convention differs about how it deals with return values, if you don't return anything, then it doesn't matter.
Fortunately, x64 only has one calling convention and this whole mess will be in the past.
The computers where the application crashed might have been using .NET Framework version 4.
Have a look at the following article:
http://msdn.microsoft.com/en-us/library/ee941656.aspx
It states the following under Interoperability - Platform Invoke:
"To improve performance in interoperability with unmanaged code, incorrect calling conventions in a platform invoke now cause the application to fail. In previous versions, the marshaling layer resolved these errors up the stack."
This is all related to what is current in the memory. Let's assume you have two functions like this:
void stdcall f1(...) { ... }
void cdecl f2(...) { ... }
stdcall is Windows calling convention, while cdecl is used by most compilers. The difference between them is who owns the responsibility to clear the stack after the call. In stdcall, the callee (f1, or f2) does, in cdecl, the caller does.
The stack, after all, is filled with unknown values. Therefore, when it gets cleaned up (wrongly), the next value that you access in the stack is undetermined. It could very well be an acceptable value, or it could be a very bad one. This is, in principle, how stack overflow (the bug, not the site) works.

Pointer mysteriously resetting to NULL

I'm working on a game and I'm currently working on the part that handles input. Three classes are involved here, there's the ProjectInstance class which starts the level and stuff, there's a GameController which will handle the input, and a PlayerEntity which will be influenced by the controls as determined by the GameController. Upon starting the level the ProjectInstance creates the GameController, and it will call its EvaluateControls method in the Step method, which is called inside the game loop. The EvaluateControls method looks a bit like this:
void CGameController::EvaluateControls(CInputBindings *pib) {
// if no player yet
if (gc_ppePlayer == NULL) {
// create it
Handle<CPlayerEntityProperties> hep = memNew(CPlayerEntityProperties);
gc_ppePlayer = (CPlayerEntity *)hep->SpawnEntity();
memDelete((CPlayerEntityProperties *)hep);
ASSERT(gc_ppePlayer != NULL);
return;
}
// handles controls here
}
This function is called correctly and the assert never triggers. However, every time this function is called, gc_ppePlayer is set to NULL. As you can see it's not a local variable going out of scope. The only place gc_ppePlayer can be set to NULL is in the constructor or possibly in the destructor, neither of which are being called in between the calls to EvaluateControls. When debugging, gc_ppePlayer receives a correct and expected value before the return. When I press F10 one more time and the cursor is at the closing brace, the value changes to 0xffffffff. I'm at a loss here, how can this happen? Anyone?
set a watch point on gc_ppePlayer == NULL when the value of that expression changes (to NULL or from NULL) the debugger will point you to exactly where it happened.
Try that and see what happens. Look for unterminated strings or mempcy copying into memory that is too small etc ... usually that is the cause of the problem of global/stack variables being overwritten randomly.
To add a watchpoint in VS2005 (instructions by brone)
Go to Breakpoints window
Click New,
Click Data breakpoint. Enter
&gc_ppePlayer in Address box, leave
other values alone.
Then run.
When gc_ppePlayer changes,
breakpoint
will be hit. – brone
Are you debugging a Release or Debug configuration? In release build configuration, what you see in the debugger isn't always true. Optimisations are made, and this can make the watch window show quirky values like you are seeing.
Are you actually seeing the ASSERT triggering? ASSERTs are normally compiled out of Release builds, so I'm guessing you are debugging a release build which is why the ASSERT isn't causing the application to terminate.
I would recommend build a Debug version of the software, and then seeing if gc_ppePlayer is really NULL. If it really is, maybe you are seeing memory heap corruption of some sort where this pointer is being overridden. But if it was memory corruption, it would generally be much less deterministic than you are describing.
As an aside, using global pointer values like this is generally considered bad practice. See if you can replace this with a singleton class if it is truly a single object and needs to be globally accessible.
My first thought is to say that SpawnEntity() is returning a pointer to an internal member that is getting "cleared" when memDelete() is called. It's not clear to me when the pointer is set to 0xffffffff, but if it occurs during the call to memDelete(), then this explains why your ASSERT is not firing - 0xffffffff is not the same as NULL.
How long has it been since you've rebuilt the entire code base? I've seen memory problems like this every now and again that are cleared up by simply rebuilding the entire solution.
Have you tried doing a step into (F11) instead of the step over (F10) at the end of the function? Although your example doesn't show any local variables, perhaps you left some out for the sake of simplicity. If so, F11 will (hopefully) step into the destructors for any of those variables, allowing you to see if one of them is causing the problem.
You have a "fandango on core."
The dynamic initialization is overwriting assorted bits (sic) of memory.
Either directly, or indirectly, the global is being overwritten.
where is the global in memory relative to the heap?
binary chop the dynamically initialized portion until the problem goes away.
(comment out half at a time, recursively)
Depending on what platform you are on there are tools (free or paid) that can quickly figure out this sort of memory issue.
Off the top of my head:
Valgrind
Rational Purify