WinAPI OpenFile function returns HFILE, and GetFileTime for instance needs HANDLE. When I feed it with (HANDLE)some_hFile it seems to work fine. Is there any difference in this types, or one of these is simply rudimental?
OpenFile is a 16-bit Windows backward-compatibility function. CreateFile is the function to open files.
If the function succeeds then HFILE is a file HANDLE. If not, then it is an HFILE_ERROR constant (presumably -1). The point is that it can't be a HANDLE on error so they return something that can be either a HANDLE or an error value.
See #Barry's suggestion as well.
To answer your question, HANDLE is just an unsigned 32bit number defined as PVOID. It is a generic handle. HFILE is a specialized handle, although defined as signed 32bit number to be able to get value -1.
There are other specialized handles, like HACCEL, HBITMAP, HINSTANCE, etc., all defined as a dependence to HANDLE.
Years ago, HANDLES were 16-bit ints. All handles everywhere in Windows were HANDLES. Then someone realized that a file HANDLE wasn't quite the same thing as a window HANDLE, and if they were defined differently, say as HFILE and HWND, then maybe developers wouldn't accidentally interchange them as much. (However they were both typedef'ed to int).
Later still, someone realized that if they were defined completely defferently...say as:
typedef struct _hfile {} * HFILE;
typedef struct _hwnd {} * HWND;
then the compiler itself would complain if you used one in place of the other, even if, in reality, each was just a plain old 16-bit (eventually 32-bit) int value.
The OpenFile returns a File Handle if succed or a HFILE_ERROR if it fails.
Related
I was wondering if I had to close the handle if for example I were to call GetModuleHandle this way
GetProcAddress(GetModuleHandle("modulename"), "nameoftheexportedfunction")
what would be the proper way to close the handle? Do I need to do
HMODULE hModule = GetModuleHandle("modulename");
GetProcAddress(hModule, "nameoftheexportedfunction")
CloseHandle(hModule);
Or does it get deleted automatically if the value returned by GetModuleHandle isn't stored into a variable?
GetModuleHandle returns an HMODULE (aka HINSTANCE - see What is the difference between HINSTANCE and HMODULE?). This data type cannot be passed to CloseHandle.
The HMODULE could be passed to FreeLibrary but that is not required either, since GetModuleHandle doesn't increase the reference count on the module. In fact, calling FreeLibrary might cause the module to get unmapped prematurely, leading to a spectacular crash.
In short: GetModuleHandle returns a read-only value, that doesn't need to be disposed off in any way. The first line of code in your question is fine.
The Windows API can be very confusing in this respect, as there are multiple things called a handle, and they all have different rules.
In this case, CloseHandle closes kernel handles, which typically refer to files or other kernel resources such as synchronization objects that are created with a name—which all are identified by being returned as a HANDLE.
GetModuleHandle returns an HMODULE—actually the base address of a loaded EXE or DLL—and, as it is not a HANDLE, does not need to be, and must not be, released with CloseHandle.
As #David Heffernan points out, this does not mean other handle types never have their own destroy/release/un-acquire semantics, and it also does not mean that every HANDLE you get from an API must be passed to CloseHandle either. There is just no substitute for knowing the specific API you are dealing with and its particular handle management requirements.
I'm trying to use function SetForegroundWindow(HWND hWnD). I have some handles but it's not working as parameter of above function. My handle is a thread and I want to run it in foreground.
What are the differences between a HWND and a HANDLE?
They are just abstract data types.
According to MSDN, HANDLE and HWND are defined as:
HANDLE is a handle to an object.
HWND is a handle to a window.
So, a HWND is a HANDLE, but not all HANDLEs are HWND. In fact:
typedef void *PVOID;
typedef PVOID HANDLE;
typedef HANDLE HWND;
Example
You should only pass HWND to SetForegroundWindow unless you know what you are doing.
HWND hWnd = FindWindow(NULL, "Calculator");
SetForegroundWindow(hWnd);
This first gets the handle to a window titled "Calculator" with FindWindow and then brings that window to foreground.
A "handle" is the general term used to refer to a token that identifies a resource on the system (a menu, a DLL module, a block of memory, etc). Often referred to as a "magic cookie", it's normally returned when you first create the resource. You then pass that handle to other functions in the API responsible for processing the resource. You normally need not know what the handle is however. Sometimes it may be a pointer, other times a number, perhaps a structure, or whatever. That's why they hide it using names like HWND which is simply the handle used to identify a window (returned by the API function "CreateWindow()"). You therefore don't convert a "handle" to an HWND and back again since an HWND is already a "handle" (one that merely identifies windows you create).
Found here http://forums.codeguru.com/showthread.php?135438-Handle-and-HWND
You can use FindWindow to get the hwnd from an application http://msdn.microsoft.com/en-us/library/windows/desktop/ms633499(v=vs.85).aspx
This should allow you to get the HWND provided you have the handle to what you're looking for C++ Handle as HWND?
The HWND is also a HANDLE, but a global one.
I.e. a HWND valid in the context of one process is also valid in the context of another process.
Some undocumented info at https://winterdom.com/dev/ui/wnd/.
How can I increment refcount of the HMODULE returned by the GetModuleHandle? Can I DuplicateHandle, or I need to go through hops, retrieve module's path and then LoarLibrary on that path? In short, I want to emulate GetModuleHandleEx without using this function (which is XP+).
You cannot use DuplicateHandle() on a HMODULE. The MSDN Library article lists the kind of handles that DH will accept in the Remarks section, a module handle is not one of them.
One reason for this is that a HMODULE is not actually a handle at all, it is a pseudo handle. There's history behind this, back in the 16-bit versions of Windows they actually were handles. But that disappeared in the 32-bit version, they are now simply the address of the module where it is loaded in memory. One pretty standard trick to convert a code address to a module handle is to use VirtualQuery() and cast the returned MEMORY_BASIC_INFORMATION.BaseAddress to (HMODULE). Very handy sometimes.
Yes, the only other way to increment the reference count is to use LoadLibrary().
Is there a simple way to hook registry access of a process that my code executes? I know about SetWindowsHookEx and friends, but its just too complex... I still have hopes that there is a way as simple as LD_PRELOAD on Unix...
Read up on the theory of DLL Injection here: http://en.wikipedia.org/wiki/DLL_injection
However, I will supply you with a DLL Injection snippet here: http://www.dreamincode.net/code/snippet407.htm
It's pretty easy to do these types of things once you're in the memory of an external application, upon injection, you might as well be a part of the process.
There's something called detouring, which I believe is what you're looking for, it simply hooks a function, and when that process calls it, it executes your own function instead. (To ensure that it doesn't crash, call the function at the end of your function)
So if you were wanting to write your own function over CreateRegKeyEx
(http://msdn.microsoft.com/en-us/library/ms724844%28v=vs.85%29.aspx)
It might look something like this:
LONG WINAPI myRegCreateKeyEx(HKEY hKey, LPCTSTR lpSubKey, DWORD Reserved, LPTSTR lpClass, DWORD dwOptions, REGSAM samDesired, LPSECURITY_ATTRIBUTES lpSecurityAttributes, PHKEY phkResult, LPDWORD lpdwDisposition)
{
//check for suspicious keys being made via the parameters
RegCreateKeyEx(hKey, lpSubKey, Reserved, lpClass, dwOptions, samDesired, lpSecurityAttributes, phkResult, lpdwDisposition);
}
You can get a very well written detour library called DetourXS here: http://www.gamedeception.net/threads/10649-DetourXS
Here is his example code of how to establish a detour using it:
#include <detourxs.h>
typedef DWORD (WINAPI* tGetTickCount)(void);
tGetTickCount oGetTickCount;
DWORD WINAPI hGetTickCount(void)
{
printf("GetTickCount hooked!");
return oGetTickCount();
}
// To create the detour
oGetTickCount = (tGetTickCount) DetourCreate("kernel32.dll", "GetTickCount", hGetTickCount, DETOUR_TYPE_JMP);
// ...Or an address
oGetTickCount = (tGetTickCount) DetourCreate(0x00000000, hGetTickCount, DETOUR_TYPE_JMP);
// ...You can also specify the detour len
oGetTickCount = (tGetTickCount) DetourCreate(0x00000000, hGetTickCount, DETOUR_TYPE_JMP, 5);
// To remove the detour
DetourRemove(oGetTickCount);
And if you can't tell, that snippet is hooking GetTickCount() and whenever the function is called, he writes "GetTickCount hooked!" -- then he executes the function GetTickCount is it was intended.
Sorry for being so scattered with info, but I hope this helps. :)
-- I realize this is an old question. --
Most winapi calls generate symbol table entries for inter modular calls, this makes it pretty simple to hook them, all you need to do is overwrite the IAT addresses. Using something such as MSDetours, it can be done safely in a few lines of code. MSDetours also provides the tools to inject a custom dll into the target process so you can do the hooking
SetWindowsHookEx won't help at all - it provides different functionality.
Check if https://web.archive.org/web/20080212040635/http://www.codeproject.com/KB/system/RegMon.aspx helps. SysInternals' RegMon uses a kernel-mode driver which is very complicated way.
Update: Our company offers CallbackRegistry product, that lets you track registry operations without hassle. And BTW we offer free non-commercial licenses upon request (subject to approval on case by case basis).
On success, ShellExecute returns a handle.
Do we need to close this handle, and if so, how ?
According to examples published my Microsoft, we need not close this handle. But the doc of ShellExecute itself is mute on the subject. Can you confirm we indeed do not need to close this handle ?
But then, how can a handle be valid and in no need of being closed ??? Which of the following statements is/are true:
the handle is invalid and we can't do anything with it;
the handle is never freed and there is a (Microsoft-sponsored) memory leak (until the caller program ends);
the handle is automatically freed by the system at some time and never reused afterwards (-> another kind of resource leak). Only on trying to use it can we know whether it still points to something.
what else ?
That hinstance is a 16 bit thing, in win32, it is just a number > 32 on success and can't be used for anything other than as an error code when the function fails. On the other hand, if you pass SEE_MASK_NOCLOSEPROCESS to the Ex version, you have a handle you need to close.
Taken from: http://msdn.microsoft.com/en-us/library/bb762153%28VS.85%29.aspx
If the function succeeds, it returns a
value greater than 32. If the function
fails, it returns an error value that
indicates the cause of the failure.
The return value is cast as an
HINSTANCE for backward compatibility
with 16-bit Windows applications. It
is not a true HINSTANCE, however. It
can be cast only to an int and
compared to either 32 or the following
error codes below.
I clear a little what is HINSTANCE and HMODULE. This are not a HANDLE, but much more as a memory address (pointer). You can understand this if you just cast a hInstance to (IMAGE_DOS_HEADER *) and look inside of the loaded module. You can use VirtualQueryEx (GetCurrentProcess(),...) to receive more information (a size for example) from a memory address.
Look at http://blogs.msdn.com/oldnewthing/archive/2004/10/25/247180.aspx and http://www.apriorit.com/our-experience/articles/9-sd-articles/74-hmodule-hinstance-handle-from-static-library-in-c and you will be see how you can receive a HINSTANCE from a memory address (__ImageBase).
So if you LoadLibrary for example you receive a HMODULE (it's the same as HINSTANCE). You should use FreeLibrary not to "close handle", but to unload module from memory. If you use GetModuleHandle for example, you receive also the same address (you receive address casted as HMODULE), but you should NOT call FreeLibrary to "close the handle".
If you understand what is HINSTANCE and HMODULE and how they should be used, you will be know how to use HINSTANCE returned from ShellExecute.