Index: Doc/library/_winreg.rst =================================================================== --- Doc/library/_winreg.rst (revision 76432) +++ Doc/library/_winreg.rst (working copy) @@ -68,6 +68,29 @@ :exc:`WindowsError` exception is raised. +.. function:: CreateKeyEx(key, sub_key[, res=0][, sam=KEY_ALL_ACCESS]) + + Creates or opens the specified key, returning a :dfn:`handle object` + + *key* is an already open key, or one of the predefined :const:`HKEY_\*` + constants. + + *sub_key* is a string that names the key this method opens or creates. + + *res* is a reserved integer, and must be zero. The default is zero. + + *sam* is an integer that specifies an access mask that describes the desired + security access for the key. Default is :const:`KEY_ALL_ACCESS` + + If *key* is one of the predefined keys, *sub_key* may be ``None``. In that + case, the handle returned is the same key handle passed in to the function. + + If the key already exists, this function opens the existing key. + + The return value is the handle of the opened key. If the function fails, a + :exc:`WindowsError` exception is raised. + + .. function:: DeleteKey(key, sub_key) Deletes the specified key. @@ -84,6 +107,34 @@ If the method fails, a :exc:`WindowsError` exception is raised. +.. function:: DeleteKeyEx(key, sub_key[, sam=KEY_WOW64_64KEY][, res=0]) + + Deletes the specified key. + + .. note:: + The :func:`DeleteKeyEx` function is implemented with the RegDeleteKeyEx + Windows API function, which is specific to 64-bit versions of Windows. + See http://msdn.microsoft.com/en-us/library/ms724847%28VS.85%29.aspx + + *key* is an already open key, or any one of the predefined :const:`HKEY_\*` + constants. + + *sub_key* is a string that must be a subkey of the key identified by the *key* + parameter. This value must not be ``None``, and the key may not have subkeys. + + *res* is a reserved integer, and must be zero. The default is zero. + + *sam* is an integer that specifies an access mask that describes the desired + security access for the key. Default is :const:`KEY_WOW64_64KEY` + + *This method can not delete keys with subkeys.* + + If the method succeeds, the entire key, including all of its values, is removed. + If the method fails, a :exc:`WindowsError` exception is raised. + + On unsupported Windows versions, :exc:`NotImplementedError` is raised. + + .. function:: DeleteValue(key, value) Removes a named value from a registry key. @@ -381,8 +432,50 @@ Value lengths are limited by available memory. Long values (more than 2048 bytes) should be stored as files with the filenames stored in the configuration registry. This helps the registry perform efficiently. + + +.. function:: DisableReflectionKey(key) + + Disables registry reflection for 32-bit processes running on a 64-bit + Operating System. + + *key* is an already open key, or one of the predefined :const:`HKEY_\*` + constants. + + Will generally raise :exc:`NotImplemented` if executed on a 32-bit + Operating System. + If the key is not on the reflection list, the function succeeds but has no + effect. Disabling reflection for a key does not affect reflection of any + subkeys. + +.. function:: EnableReflectionKey(key) + + Restores registry reflection for the specified disabled key. + + *key* is an already open key, or one of the predefined :const:`HKEY_\*` + constants. + + Will generally raise :exc:`NotImplemented` if executed on a 32-bit + Operating System. + + Restoring reflection for a key does not affect reflection of any subkeys. + + +.. function:: QueryReflectionKey(key) + + Determines the reflection state for the specified key. + + *key* is an already open key, or one of the predefined :const:`HKEY_\*` + constants. + + Returns ``True`` if reflection is disabled. + + Will generally raise :exc:`NotImplemented` if executed on a 32-bit + Operating System. + + .. _handle-object: Registry Handle Objects Index: Lib/test/delete_regkey.vbs =================================================================== --- Lib/test/delete_regkey.vbs (revision 0) +++ Lib/test/delete_regkey.vbs (revision 0) @@ -0,0 +1,12 @@ +const HKEY_LOCAL_MACHINE = &H80000002 + +host = "." +Set objReg = GetObject("winmgmts:\\" & host & "\root\default:StdRegProv") +key_path = "SOFTWARE\Python Registry Test Key - Delete Me" + +Return = objReg.DeleteKey(HKEY_LOCAL_MACHINE, key_path) +if Return = 0 Then + wscript.Quit 0 +else + wscript.Quit 1 +end if \ No newline at end of file Index: Lib/test/test_winreg.py =================================================================== --- Lib/test/test_winreg.py (revision 76432) +++ Lib/test/test_winreg.py (working copy) @@ -4,13 +4,35 @@ import os, sys import unittest from test import test_support +from subprocess import Popen, PIPE # Do this first so test will be skipped if module doesn't exist test_support.import_module('_winreg') # Now import everything from _winreg import * +try: + REMOTE_NAME = sys.argv[sys.argv.index("--remote")+1] +except (IndexError, ValueError): + REMOTE_NAME = None + +WIN64_SYSTEM = False +WINXP_SYSTEM = False +try: + # Read the systeminfo command to see if we are on x64 + p = Popen("systeminfo", stdout=PIPE, stderr=PIPE) + output = p.stdout.read() + if output.find("x64") is not -1: + WIN64_SYSTEM = True + if output.find("Windows XP") is not -1: + WINXP_SYSTEM = True +except: + pass + +WIN64_PYTHON = True if sys.version.find("64 bit") is not -1 else False + test_key_name = "SOFTWARE\\Python Registry Test Key - Delete Me" +test_reflected_key_name = "SOFTWARE\\Wow6432Node\\Python Registry Test Key - Delete Me" test_data = [ ("Int Value", 45, REG_DWORD), @@ -32,8 +54,7 @@ "values"], REG_MULTI_SZ), ] -class WinregTests(unittest.TestCase): - remote_name = None +class BaseWinregTests(unittest.TestCase): def setUp(self): # Make sure that the test key is absent when the test @@ -56,7 +77,7 @@ CloseKey(hkey) DeleteKey(root, subkey) - def WriteTestData(self, root_key): + def _write_test_data(self, root_key, CreateKey=CreateKey): # Set the default value for this key. SetValue(root_key, test_key_name, REG_SZ, "Default value") key = CreateKey(root_key, test_key_name) @@ -96,7 +117,7 @@ except EnvironmentError: pass - def ReadTestData(self, root_key): + def _read_test_data(self, root_key, OpenKey=OpenKey): # Check we can get default value for this key. val = QueryValue(root_key, test_key_name) self.assertEquals(val, "Default value", @@ -136,7 +157,7 @@ key.Close() - def DeleteTestData(self, root_key): + def _delete_test_data(self, root_key): key = OpenKey(root_key, test_key_name, 0, KEY_ALL_ACCESS) sub_key = OpenKey(key, "sub_key", 0, KEY_ALL_ACCESS) # It is not necessary to delete the values before deleting @@ -166,38 +187,205 @@ except WindowsError: # Use this error name this time pass - def TestAll(self, root_key): - self.WriteTestData(root_key) - self.ReadTestData(root_key) - self.DeleteTestData(root_key) + def _test_all(self, root_key): + self._write_test_data(root_key) + self._read_test_data(root_key) + self._delete_test_data(root_key) + +class LocalWinregTests(BaseWinregTests): - def testLocalMachineRegistryWorks(self): - self.TestAll(HKEY_CURRENT_USER) + def test_registry_works(self): + self._test_all(HKEY_CURRENT_USER) + + def test_registry_works_with_extended_functions(self): + self._write_test_data(HKEY_CURRENT_USER, CreateKeyEx) + self._read_test_data(HKEY_CURRENT_USER, OpenKeyEx) + self._delete_test_data(HKEY_CURRENT_USER) - def testConnectRegistryToLocalMachineWorks(self): + def test_connect_registry_to_local_machine_works(self): # perform minimal ConnectRegistry test which just invokes it h = ConnectRegistry(None, HKEY_LOCAL_MACHINE) + self.assertNotEqual(h.handle, 0) h.Close() + self.assertEqual(h.handle, 0) + + def test_inexistant_remote_registry(self): + connect = lambda: ConnectRegistry("abcdefghijkl", HKEY_CURRENT_USER) + self.assertRaises(WindowsError, connect) - def testRemoteMachineRegistryWorks(self): - if not self.remote_name: - return # remote machine name not specified - remote_key = ConnectRegistry(self.remote_name, HKEY_CURRENT_USER) - self.TestAll(remote_key) - - def testExpandEnvironmentStrings(self): + def test_expand_environment_strings(self): r = ExpandEnvironmentStrings(u"%windir%\\test") self.assertEqual(type(r), unicode) self.assertEqual(r, os.environ["windir"] + "\\test") + + def test_context_manager(self): + # ensure that the handle is closed if an exception occurs + try: + with ConnectRegistry(None, HKEY_LOCAL_MACHINE) as h: + self.assertNotEqual(h.handle, 0) + raise WindowsError + except WindowsError: + self.assertEqual(h.handle, 0) + @unittest.skipIf(not WINXP_SYSTEM, "XP specific") + @unittest.skipIf(WIN64_SYSTEM, "32-bit specific") + def test_reflection_specifics(self): + # The following calls should only work on the following operating + # systems: Vista, XP x64, Server 2008, Server 2003 SP1, or greater. + # Therefore, on XP 32-bit and Windows 2000 the calls should raise + # NotImplementedError. We can find out that a machine is XP 32-bit + # from the 'systeminfo' command, but that is not available on W2k. + try: + created = CreateKey(HKEY_CURRENT_USER, test_key_name) + self.assertNotEqual(created.handle, 0) + created.Close() + + key = OpenKey(HKEY_CURRENT_USER, test_key_name) + self.assertNotEqual(key.handle, 0) + + disable = lambda: DisableReflectionKey(key) + self.assertRaises(NotImplementedError, disable) + + enable = lambda: EnableReflectionKey(key) + self.assertRaises(NotImplementedError, enable) + + query = lambda: QueryReflectionKey(key) + self.assertRaises(NotImplementedError, query) + + delete = lambda: DeleteKeyEx(HKEY_CURRENT_USER, test_key_name) + self.assertRaises(NotImplementedError, delete) + except WindowsError, err: + self.fail(err) + finally: + DeleteKey(HKEY_CURRENT_USER, test_key_name) + + +@unittest.skipIf(not REMOTE_NAME, "Skipping remote registry tests") +class RemoteWinregTests(BaseWinregTests): + + def test_remote_registry_works(self): + try: + remote_key = ConnectRegistry(REMOTE_NAME, HKEY_CURRENT_USER) + self._test_all(remote_key) + except WindowsError, err: + self.fail(err) + + +@unittest.skipIf(not WIN64_SYSTEM, "x64 specific registry tests") +class Win64WinregTests(BaseWinregTests): + """Tests specific to the x64 versions of Windows""" + + @unittest.skipIf(not WIN64_PYTHON, "32-bit compiled Python") + def test_registry_works_64bit(self): + # 64-bit Python on a 64-bit Windows should work untouched here + self._test_all(HKEY_CURRENT_USER) + + @unittest.skipIf(not WIN64_PYTHON, "32-bit compiled Python") + def test_create_open_delete_for_32bit(self): + # Test that we can create, open, and delete keys in the 32-bit + # redirection area from a 64-bit Python. This requires the use of + # the KEY_WOW64_32KEY flag. + try: + created_key = CreateKeyEx(HKEY_LOCAL_MACHINE, test_key_name, 0, + KEY_ALL_ACCESS | KEY_WOW64_32KEY) + self.assertNotEqual(created_key.handle, 0) + + # The key should be available in the regular location when we + # tell OpenKey to look there with the KEY_WOW64_64KEY flag + with OpenKey(HKEY_LOCAL_MACHINE, test_key_name, 0, + KEY_READ | KEY_WOW64_32KEY) as key: + self.assertNotEqual(key.handle, 0) + except WindowsError, err: + self.fail(err) + finally: + DeleteKeyEx(HKEY_LOCAL_MACHINE, test_key_name, KEY_WOW64_32KEY, 0) + + @unittest.skipIf(WIN64_PYTHON, "64-bit compiled Python") + def test_registry_works_32bit(self): + # 32-bit Python on 64-bit Windows uses redirection + global test_key_name + saved_key = test_key_name + test_key_name = test_reflected_key_name + try: + # test write, read, delete from the reflected area + self._test_all(HKEY_CURRENT_USER) + finally: + test_key_name = saved_key + + @unittest.skipIf(WIN64_PYTHON, "64-bit compiled Python") + def test_reflection(self): + # This should only be run on 32-bit compiled Python on a 64-bit OS + try: + with CreateKey(HKEY_CURRENT_USER, test_key_name) as created_key: + key = OpenKey(HKEY_CURRENT_USER, test_key_name) + self.assertNotEqual(key.handle, 0) + + disabled = QueryReflectionKey(key) + self.assertEqual(type(disabled), bool) + + try: + if not disabled: + DisableReflectionKey(key) + self.assertEqual(True, QueryReflectionKey(key)) + except WindowsError, err: + self.fail(err) + except WindowsError, err: + self.fail(err) + finally: + DeleteKey(HKEY_CURRENT_USER, test_key_name) + + @unittest.skipIf(WIN64_PYTHON, "64-bit compiled Python") + def test_avoid_redirection_32bit(self): + # Even though we can create keys in the 64-bit space via the + # KEY_WOW64_64KEY flag to CreateKeyEx, we cannot delete 64-bit + # keys from a 32-bit compiled Python. 64-bit compiled Python can + # offer DeleteKeyEx, which is the only way to delete 64-bit keys. + try: + created_key = CreateKeyEx(HKEY_LOCAL_MACHINE, test_key_name, 0, + KEY_ALL_ACCESS | KEY_WOW64_64KEY) + self.assertNotEqual(created_key.handle, 0) + + # The key should not be available in the Wow6432Node, + # which is where where OpenKey will look due to redirection + open_fail = lambda: OpenKey(HKEY_LOCAL_MACHINE, test_key_name) + self.assertRaises(WindowsError, open_fail) + + # The key should be available in the regular location when we + # tell OpenKey to look there with the KEY_WOW64_64KEY flag + with OpenKey(HKEY_LOCAL_MACHINE, test_key_name, 0, + KEY_READ | KEY_WOW64_64KEY) as key: + self.assertNotEqual(key.handle, 0) + except WindowsError, err: + self.fail(err) + finally: + # Run a VBScript script to handle the cleanup, since DeleteKey can't + try: + cscript_path = self._get_cscript_path() + if cscript_path is None: + raise ValueError("cscript path is None") + script = os.path.join(os.path.dirname(__file__), + "delete_regkey.vbs") + p = Popen([cscript_path, script], stdout=PIPE) + rv = not p.wait() + self.assertEqual(rv, 0, + "Error running delete_regkey.vbs") + except Exception, err: + self.fail(err) + + def _get_cscript_path(self): + """Return the full path to cscript.exe or None.""" + for dir in os.environ.get("PATH", "").split(os.pathsep): + cscript_path = os.path.join(dir, "cscript.exe") + if os.path.exists(cscript_path): + return cscript_path + + def test_main(): - test_support.run_unittest(WinregTests) + test_support.run_unittest(LocalWinregTests, RemoteWinregTests, + Win64WinregTests) if __name__ == "__main__": - try: - WinregTests.remote_name = sys.argv[sys.argv.index("--remote")+1] - except (IndexError, ValueError): + if not REMOTE_NAME: print "Remote registry calls can be tested using", print "'test_winreg.py --remote \\\\machine_name'" - WinregTests.remote_name = None test_main() Index: PC/_winreg.c =================================================================== --- PC/_winreg.c (revision 76432) +++ PC/_winreg.c (working copy) @@ -89,7 +89,7 @@ "key is the predefined handle to connect to.\n" "\n" "The return value is the handle of the opened key.\n" -"If the function fails, an EnvironmentError exception is raised."); +"If the function fails, an WindowsError exception is raised."); PyDoc_STRVAR(CreateKey_doc, "key = CreateKey(key, sub_key) - Creates or opens the specified key.\n" @@ -104,6 +104,21 @@ "The return value is the handle of the opened key.\n" "If the function fails, an exception is raised."); +PyDoc_STRVAR(CreateKeyEx_doc, +"key = CreateKeyEx(key, sub_key, res, sam) - Creates or opens the specified key.\n" +"\n" +"key is an already open key, or one of the predefined HKEY_* constants\n" +"sub_key is a string that names the key this method opens or creates.\n" +"res is a reserved integer, and must be zero. Default is zero.\n" +"sam is an integer that specifies an access mask that describes the desired\n" +" If key is one of the predefined keys, sub_key may be None. In that case,\n" +" the handle returned is the same key handle passed in to the function.\n" +"\n" +"If the key already exists, this function opens the existing key\n" +"\n" +"The return value is the handle of the opened key.\n" +"If the function fails, an exception is raised."); + PyDoc_STRVAR(DeleteKey_doc, "DeleteKey(key, sub_key) - Deletes the specified key.\n" "\n" @@ -114,8 +129,23 @@ "This method can not delete keys with subkeys.\n" "\n" "If the method succeeds, the entire key, including all of its values,\n" -"is removed. If the method fails, an EnvironmentError exception is raised."); +"is removed. If the method fails, an WindowsError exception is raised."); +PyDoc_STRVAR(DeleteKeyEx_doc, +"DeleteKeyEx(key, sub_key, sam, res) - Deletes the specified key.\n" +"\n" +"key is an already open key, or any one of the predefined HKEY_* constants.\n" +"sub_key is a string that must be a subkey of the key identified by the key parameter.\n" +"res is a reserved integer, and must be zero. Default is zero.\n" +"sam is an integer that specifies an access mask that describes the desired\n" +" This value must not be None, and the key may not have subkeys.\n" +"\n" +"This method can not delete keys with subkeys.\n" +"\n" +"If the method succeeds, the entire key, including all of its values,\n" +"is removed. If the method fails, an WindowsError exception is raised.\n" +"On unsupported Windows versions, NotImplementedError is raised."); + PyDoc_STRVAR(DeleteValue_doc, "DeleteValue(key, value) - Removes a named value from a registry key.\n" "\n" @@ -129,7 +159,7 @@ "index is an integer that identifies the index of the key to retrieve.\n" "\n" "The function retrieves the name of one subkey each time it is called.\n" -"It is typically called repeatedly until an EnvironmentError exception is\n" +"It is typically called repeatedly until an WindowsError exception is\n" "raised, indicating no more values are available."); PyDoc_STRVAR(EnumValue_doc, @@ -138,7 +168,7 @@ "index is an integer that identifies the index of the value to retrieve.\n" "\n" "The function retrieves the name of one subkey each time it is called.\n" -"It is typically called repeatedly, until an EnvironmentError exception\n" +"It is typically called repeatedly, until an WindowsError exception\n" "is raised, indicating no more values.\n" "\n" "The result is a tuple of 3 items:\n" @@ -192,7 +222,7 @@ " security access for the key. Default is KEY_READ\n" "\n" "The result is a new handle to the specified key\n" -"If the function fails, an EnvironmentError exception is raised."); +"If the function fails, an WindowsError exception is raised."); PyDoc_STRVAR(OpenKeyEx_doc, "See OpenKey()"); @@ -1014,6 +1044,29 @@ } static PyObject * +PyCreateKeyEx(PyObject *self, PyObject *args) +{ + HKEY hKey; + PyObject *obKey; + char *subKey; + HKEY retKey; + int res = 0; + REGSAM sam = KEY_ALL_ACCESS; + long rc; + if (!PyArg_ParseTuple(args, "Oz|ii:CreateKeyEx", &obKey, &subKey, + &res, &sam)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + rc = RegCreateKeyEx(hKey, subKey, res, NULL, (DWORD)NULL, + sam, NULL, &retKey, NULL); + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKeyEx"); + return PyHKEY_FromHKEY(retKey); +} + +static PyObject * PyDeleteKey(PyObject *self, PyObject *args) { HKEY hKey; @@ -1032,6 +1085,45 @@ } static PyObject * +PyDeleteKeyEx(PyObject *self, PyObject *args) +{ + HKEY hKey; + HMODULE hMod; + typedef LONG (WINAPI *RDKFunc)(HKEY, char*, REGSAM, int); + RDKFunc pfn = NULL; + PyObject *obKey; + char *subKey; + long rc; + int res = 0; + REGSAM sam = KEY_WOW64_64KEY; + if (!PyArg_ParseTuple(args, "Os|ii:DeleteKeyEx", + &obKey, &subKey, &sam, &res)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + // Only available on 64bit platforms, so we must load it + // dynamically. + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RDKFunc)GetProcAddress(hMod, + "RegDeleteKeyEx"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey, subKey, sam, res); + Py_END_ALLOW_THREADS + + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKeyEx"); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * PyDeleteValue(PyObject *self, PyObject *args) { HKEY hKey; @@ -1569,14 +1661,16 @@ if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryReflectionKey"); - return PyBool_FromLong(rc); + return PyBool_FromLong(result); } static struct PyMethodDef winreg_methods[] = { {"CloseKey", PyCloseKey, METH_VARARGS, CloseKey_doc}, {"ConnectRegistry", PyConnectRegistry, METH_VARARGS, ConnectRegistry_doc}, {"CreateKey", PyCreateKey, METH_VARARGS, CreateKey_doc}, + {"CreateKeyEx", PyCreateKeyEx, METH_VARARGS, CreateKeyEx_doc}, {"DeleteKey", PyDeleteKey, METH_VARARGS, DeleteKey_doc}, + {"DeleteKeyEx", PyDeleteKeyEx, METH_VARARGS, DeleteKeyEx_doc}, {"DeleteValue", PyDeleteValue, METH_VARARGS, DeleteValue_doc}, {"DisableReflectionKey", PyDisableReflectionKey, METH_VARARGS, DisableReflectionKey_doc}, {"EnableReflectionKey", PyEnableReflectionKey, METH_VARARGS, EnableReflectionKey_doc},