James, the contract for the registry functions is that the output handle might be set to an undefined value should RegOpenKey*/RegCreateKey* fail. (There is no documentation stating otherwise.) You cannot assume that a particular value is retained, nor that a particular sentinel value is returned on failure. In fact, there are cases where the code as you have written it will do the wrong thing in today’s implementation.
While it is less convenient, you cannot assume any particular value in the output parameter of these functions as neither the contract or the implementation guarantee it.
Additionally, NULL is the only contractually defined invalid registry key handle. It would be specific to today’s implementation to assume INVALID_HANDLE_VALUE is also outlawed (though this is admittedly a pedantic and likely academic point; the usage of the output key hande parameter as described above, is not).
-----Original Message-----
From: xxxxx@lists.osr.com [mailto:xxxxx@lists.osr.com] On Behalf Of James Harper
Sent: Saturday, October 23, 2010 1:58 AM
To: Windows System Software Devs Interest List
Subject: RE: RE:[ntdev] what is an invalid HKEY?
Actually, the registry key open/create functions do not guarantee that
the
output key handle will be initialized to any particular value on
failure. You
cannot rely on this as it’s not the case in all situations. (I went
ahead and
checked the code on this, if you’re wondering.)
I initialise the output key myself. I only need a guarantee that the handle will be untouched on error, and that the invalid value I use (whether it be NULL or INVALID_HANDLE_VALUE) will never be returned to me as a valid handle. The actual code is more like:
handle1 = INVALID_HANDLE_VALUE
handle2 = INVALID_HANDLE_VALUE
handle3 = INVALID_HANDLE_VALUE
hr = open(HKEY_LOCAL_MACHINE, “somekey”, &handle1) if (hr is failure)
goto cleanup
…
hr = open(handle1, “some other key”, &handle2) if (hr is failure)
goto cleanup
…
if (some error condition)
goto cleanup
…
hr = open(handle1, “yet another key”, &handle3) if (hr is failure)
goto cleanup
…
cleanup:
if (handle3 != INVALID_HANDLE_VALUE)
close(handle3)
if (handle2 != INVALID_HANDLE_VALUE)
close(handle2)
if (handle1 != INVALID_HANDLE_VALUE)
close(handle1)
it makes the cleanup routine easier to do it this way, rather than repeat the closing of opened resources every time I check for an error or create Boolean values to tell me if the handle needs closing or not.
thanks
James
NTDEV is sponsored by OSR
For our schedule of WDF, WDM, debugging and other seminars visit:
http://www.osr.com/seminars
To unsubscribe, visit the List Server section of OSR Online at http://www.osronline.com/page.cfm?name=ListServer