Skip to content

Commit 40fa266

Browse files
committed
Issue python#25778: winreg does not truncase string correctly (Patch by Eryk Sun)
1 parent ce042af commit 40fa266

3 files changed

Lines changed: 21 additions & 8 deletions

File tree

Lib/test/test_winreg.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def setUp(self):
5757

5858
def delete_tree(self, root, subkey):
5959
try:
60-
hkey = OpenKey(root, subkey, KEY_ALL_ACCESS)
60+
hkey = OpenKey(root, subkey, 0, KEY_ALL_ACCESS)
6161
except OSError:
6262
# subkey does not exist
6363
return
@@ -368,6 +368,18 @@ def test_setvalueex_crash_with_none_arg(self):
368368
finally:
369369
DeleteKey(HKEY_CURRENT_USER, test_key_name)
370370

371+
def test_read_string_containing_null(self):
372+
# Test for issue 25778: REG_SZ should not contain null characters
373+
try:
374+
with CreateKey(HKEY_CURRENT_USER, test_key_name) as ck:
375+
self.assertNotEqual(ck.handle, 0)
376+
test_val = "A string\x00 with a null"
377+
SetValueEx(ck, "test_name", 0, REG_SZ, test_val)
378+
ret_val, ret_type = QueryValueEx(ck, "test_name")
379+
self.assertEqual(ret_type, REG_SZ)
380+
self.assertEqual(ret_val, "A string")
381+
finally:
382+
DeleteKey(HKEY_CURRENT_USER, test_key_name)
371383

372384

373385
@unittest.skipUnless(REMOTE_NAME, "Skipping remote registry tests")

Misc/NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ Library
4949
Windows
5050
-------
5151

52+
- Issue #25778: winreg does not truncase string correctly (Patch by Eryk Sun)
53+
5254
- Issue #28896: Deprecate WindowsRegistryFinder and disable it by default.
5355

5456
Tests

PC/winreg.c

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -719,14 +719,13 @@ Reg2Py(BYTE *retDataBuf, DWORD retDataSize, DWORD typ)
719719
case REG_SZ:
720720
case REG_EXPAND_SZ:
721721
{
722-
/* the buffer may or may not have a trailing NULL */
722+
/* REG_SZ should be a NUL terminated string, but only by
723+
* convention. The buffer may have been saved without a NUL
724+
* or with embedded NULs. To be consistent with reg.exe and
725+
* regedit.exe, consume only up to the first NUL. */
723726
wchar_t *data = (wchar_t *)retDataBuf;
724-
int len = retDataSize / 2;
725-
if (retDataSize && data[len-1] == '\0')
726-
retDataSize -= 2;
727-
if (retDataSize <= 0)
728-
data = L"";
729-
obData = PyUnicode_FromWideChar(data, retDataSize/2);
727+
size_t len = wcsnlen(data, retDataSize / sizeof(wchar_t));
728+
obData = PyUnicode_FromWideChar(data, len);
730729
break;
731730
}
732731
case REG_MULTI_SZ:

0 commit comments

Comments
 (0)