Skip to content

Commit 07b1cdb

Browse files
youknowdotcodex
andauthored
Update Windows registry behavior and canonical 3.15 tests (#9420)
* Update Windows registry behavior and canonical 3.15 tests Add DeleteTree with nullable wide paths, audit emission, native errors, and thread release; compare HKEY handles as CPython does while retaining upstream identity hashing. Migrate canonical winreg and winapi tests from CPython d220409a13b77de7a6c30abe16ea90db01528edc. Assisted-by: OpenAI Codex: model version unavailable * Accept nullable subkeys in winreg OpenKey Keep sub_key required while accepting None, matching CPython and the canonical HKEY comparison test prerequisite. Forward a null path to RegOpenKeyExW, retain owned wide strings across thread release, and emit the input and result audit events without leaking the returned handle on an audit error. Assisted-by: OpenAI Codex: model version unavailable --------- Co-authored-by: Codex <[email protected]>
1 parent 648b3b8 commit 07b1cdb

4 files changed

Lines changed: 172 additions & 17 deletions

File tree

‎Lib/test/test_winapi.py‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# Test the Windows-only _winapi module
22

3+
import errno
34
import os
45
import pathlib
56
import re
@@ -11,9 +12,16 @@
1112
MAXIMUM_WAIT_OBJECTS = 64
1213
MAXIMUM_BATCHED_WAIT_OBJECTS = (MAXIMUM_WAIT_OBJECTS - 1) ** 2
1314

15+
16+
def close_events(events):
17+
for handle in events:
18+
_winapi.CloseHandle(handle)
19+
20+
1421
class WinAPIBatchedWaitForMultipleObjectsTests(unittest.TestCase):
1522
def _events_waitall_test(self, n):
1623
evts = [_winapi.CreateEventW(0, False, False, None) for _ in range(n)]
24+
self.addCleanup(close_events, evts)
1725

1826
with self.assertRaises(TimeoutError):
1927
_winapi.BatchedWaitForMultipleObjects(evts, True, 100)
@@ -41,6 +49,7 @@ def _events_waitall_test(self, n):
4149

4250
def _events_waitany_test(self, n):
4351
evts = [_winapi.CreateEventW(0, False, False, None) for _ in range(n)]
52+
self.addCleanup(close_events, evts)
4453

4554
with self.assertRaises(TimeoutError):
4655
_winapi.BatchedWaitForMultipleObjects(evts, False, 100)
@@ -156,3 +165,38 @@ def test_namedpipe(self):
156165
pipe2.write(b'testdata')
157166
pipe2.flush()
158167
self.assertEqual((b'testdata', 8), _winapi.PeekNamedPipe(pipe, 8)[:2])
168+
169+
def test_event_source_registration(self):
170+
source_name = "PythonTestEventSource"
171+
172+
handle = _winapi.RegisterEventSource(None, source_name)
173+
self.addCleanup(_winapi.DeregisterEventSource, handle)
174+
self.assertNotEqual(handle, _winapi.INVALID_HANDLE_VALUE)
175+
176+
with self.assertRaises(OSError) as cm:
177+
_winapi.RegisterEventSource(None, "")
178+
self.assertEqual(cm.exception.errno, errno.EINVAL)
179+
180+
with self.assertRaises(OSError) as cm:
181+
_winapi.DeregisterEventSource(_winapi.INVALID_HANDLE_VALUE)
182+
self.assertEqual(cm.exception.errno, errno.EBADF)
183+
184+
def test_report_event(self):
185+
source_name = "PythonTestEventSource"
186+
187+
handle = _winapi.RegisterEventSource(None, source_name)
188+
self.assertNotEqual(handle, _winapi.INVALID_HANDLE_VALUE)
189+
self.addCleanup(_winapi.DeregisterEventSource, handle)
190+
191+
_winapi.ReportEvent(handle, _winapi.EVENTLOG_SUCCESS, 1, 1002,
192+
"Test message 1")
193+
194+
with self.assertRaises(TypeError):
195+
_winapi.ReportEvent(handle, _winapi.EVENTLOG_SUCCESS, 1, 1002, 42)
196+
197+
with self.assertRaises(TypeError):
198+
_winapi.ReportEvent(handle, _winapi.EVENTLOG_SUCCESS, 1, 1002, None)
199+
200+
with self.assertRaises(ValueError):
201+
_winapi.ReportEvent(handle, _winapi.EVENTLOG_SUCCESS, 1, 1002,
202+
"Test message \0 with embedded null character")

‎Lib/test/test_winreg.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,33 @@ def _test_named_args(self, key, sub_key):
210210
access=KEY_ALL_ACCESS) as okey:
211211
self.assertTrue(okey.handle != 0)
212212

213+
def test_hkey_comparison(self):
214+
"""Test HKEY comparison by handle value rather than object identity."""
215+
key1 = OpenKey(HKEY_CURRENT_USER, None)
216+
key2 = OpenKey(HKEY_CURRENT_USER, None)
217+
key3 = OpenKey(HKEY_LOCAL_MACHINE, None)
218+
219+
self.addCleanup(CloseKey, key1)
220+
self.addCleanup(CloseKey, key2)
221+
self.addCleanup(CloseKey, key3)
222+
223+
self.assertEqual(key1.handle, key2.handle)
224+
self.assertTrue(key1 == key2)
225+
self.assertFalse(key1 != key2)
226+
227+
self.assertTrue(key1 != key3)
228+
self.assertFalse(key1 == key3)
229+
230+
# Closed keys should be equal (all have handle=0)
231+
CloseKey(key1)
232+
CloseKey(key2)
233+
CloseKey(key3)
234+
235+
self.assertEqual(key1.handle, 0)
236+
self.assertEqual(key2.handle, 0)
237+
self.assertEqual(key3.handle, 0)
238+
self.assertEqual(key2, key3)
239+
213240

214241
class LocalWinregTests(BaseWinregTests):
215242

@@ -549,6 +576,21 @@ def test_exception_numbers(self):
549576
with self.assertRaises(FileNotFoundError) as ctx:
550577
QueryValue(HKEY_CLASSES_ROOT, 'some_value_that_does_not_exist')
551578

579+
def test_delete_tree(self):
580+
with CreateKey(HKEY_CURRENT_USER, test_key_name) as main_key:
581+
with CreateKey(main_key, "subkey1") as subkey1:
582+
SetValueEx(subkey1, "value1", 0, REG_SZ, "test_value1")
583+
with CreateKey(subkey1, "subsubkey1") as subsubkey1:
584+
SetValueEx(subsubkey1, "value2", 0, REG_DWORD, 42)
585+
586+
with CreateKey(main_key, "subkey2") as subkey2:
587+
SetValueEx(subkey2, "value3", 0, REG_SZ, "test_value3")
588+
589+
DeleteTree(HKEY_CURRENT_USER, test_key_name)
590+
591+
with self.assertRaises(OSError):
592+
OpenKey(HKEY_CURRENT_USER, test_key_name)
593+
552594

553595
if __name__ == "__main__":
554596
if not REMOTE_NAME:

‎crates/host_env/src/winreg.rs‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,11 @@ pub unsafe fn delete_value(key: Registry::HKEY, value_name: Option<&widestring::
161161
unsafe { Registry::RegDeleteValueW(key, name_ptr) }
162162
}
163163

164+
pub unsafe fn delete_tree(key: Registry::HKEY, sub_key: Option<&widestring::WideCStr>) -> u32 {
165+
let name_ptr = sub_key.map_or(core::ptr::null(), |n| n.as_ptr());
166+
unsafe { Registry::RegDeleteTreeW(key, name_ptr) }
167+
}
168+
164169
pub unsafe fn enum_key_ex(
165170
key: Registry::HKEY,
166171
index: u32,
@@ -280,12 +285,13 @@ pub unsafe fn load_key(
280285

281286
pub unsafe fn open_key_ex(
282287
key: Registry::HKEY,
283-
sub_key: &widestring::WideCStr,
288+
sub_key: Option<&widestring::WideCStr>,
284289
options: u32,
285290
sam: u32,
286291
out_key: *mut Registry::HKEY,
287292
) -> u32 {
288-
unsafe { Registry::RegOpenKeyExW(key, sub_key.as_ptr(), options, sam, out_key) }
293+
let name_ptr = sub_key.map_or(core::ptr::null(), |n| n.as_ptr());
294+
unsafe { Registry::RegOpenKeyExW(key, name_ptr, options, sam, out_key) }
289295
}
290296

291297
pub unsafe fn query_value_ex(
@@ -351,7 +357,15 @@ pub fn query_default_value(
351357
) -> Result<String, QueryStringError> {
352358
let child_key = if let Some(sub_key) = sub_key.filter(|s| !s.is_empty()) {
353359
let mut out_key = core::ptr::null_mut();
354-
let res = unsafe { open_key_ex(hkey, sub_key, 0, Registry::KEY_QUERY_VALUE, &mut out_key) };
360+
let res = unsafe {
361+
open_key_ex(
362+
hkey,
363+
Some(sub_key),
364+
0,
365+
Registry::KEY_QUERY_VALUE,
366+
&mut out_key,
367+
)
368+
};
355369
if res != 0 {
356370
return Err(QueryStringError::Code(res));
357371
}

‎crates/vm/src/stdlib/winreg.rs‎

Lines changed: 69 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,11 @@ mod winreg {
99
use crate::common::hash::PyHash;
1010
use crate::convert::{ToPyException, TryFromObject};
1111
use crate::exceptions::nul_char_error;
12-
use crate::function::FuncArgs;
12+
use crate::function::{FuncArgs, OptionalOption, PyComparisonValue};
1313
use crate::object::AsObject;
1414
use crate::protocol::PyNumberMethods;
15-
use crate::types::{AsNumber, Hashable};
16-
use crate::{Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine};
15+
use crate::types::{AsNumber, Comparable, Hashable, PyComparisonOp};
16+
use crate::{Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine};
1717
use core::ptr;
1818
use crossbeam_utils::atomic::AtomicCell;
1919
use malachite_bigint::Sign;
@@ -153,7 +153,7 @@ mod winreg {
153153
}
154154
}
155155

156-
#[pyclass(with(AsNumber, Hashable))]
156+
#[pyclass(with(AsNumber, Comparable, Hashable))]
157157
impl Py<PyHkey> {
158158
#[pygetset]
159159
fn handle(&self) -> usize {
@@ -208,6 +208,26 @@ mod winreg {
208208
}
209209
}
210210

211+
impl Comparable for PyHkey {
212+
fn cmp(
213+
zelf: &Py<Self>,
214+
other: &PyObject,
215+
op: PyComparisonOp,
216+
_vm: &VirtualMachine,
217+
) -> PyResult<PyComparisonValue> {
218+
op.eq_only(|| {
219+
if other.class().is(zelf.class())
220+
&& let Some(other) = other.downcast_ref::<Self>()
221+
{
222+
return Ok(PyComparisonValue::Implemented(
223+
zelf.hkey.load() == other.hkey.load(),
224+
));
225+
}
226+
Ok(PyComparisonValue::NotImplemented)
227+
})
228+
}
229+
}
230+
211231
impl Hashable for PyHkey {
212232
// CPython uses PyObject_GenericHash which hashes the object's address
213233
fn hash(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<PyHash> {
@@ -343,6 +363,28 @@ mod winreg {
343363
}
344364
}
345365

366+
#[pyfunction]
367+
fn DeleteTree(
368+
key: HKEYArg,
369+
sub_key: OptionalOption<PyRef<PyStr>>,
370+
vm: &VirtualMachine,
371+
) -> PyResult<()> {
372+
let sub_key = sub_key.flatten();
373+
let wide_sub_key = sub_key
374+
.as_ref()
375+
.map(|s| WideCString::from_vec(s.as_wtf8().encode_wide().collect::<Vec<_>>()))
376+
.transpose()
377+
.map_err(|_| nul_char_error(vm))?;
378+
vm.audit("winreg.DeleteTree", || (key.0 as isize, sub_key))?;
379+
let res = vm
380+
.allow_threads(|| unsafe { host_winreg::delete_tree(key.0, wide_sub_key.as_deref()) });
381+
if res == 0 {
382+
Ok(())
383+
} else {
384+
Err(os_error_from_windows_code(vm, res as i32))
385+
}
386+
}
387+
346388
#[pyfunction]
347389
fn DeleteValue(key: PyRef<PyHkey>, value: Option<String>, vm: &VirtualMachine) -> PyResult<()> {
348390
let wide_value = value
@@ -527,7 +569,7 @@ mod winreg {
527569
#[pyarg(any)]
528570
key: PyRef<PyHkey>,
529571
#[pyarg(any)]
530-
sub_key: String,
572+
sub_key: Option<PyRef<PyStr>>,
531573
#[pyarg(any, default)]
532574
reserved: u32,
533575
#[pyarg(any, default = host_winreg::KEY_READ, py_default = "winreg.KEY_READ")]
@@ -537,17 +579,30 @@ mod winreg {
537579
#[pyfunction]
538580
#[pyfunction(name = "OpenKeyEx")]
539581
fn OpenKey(args: OpenKeyArgs, vm: &VirtualMachine) -> PyResult<PyHkey> {
540-
let sub_key = WideCString::from_str(args.sub_key).map_err(|e| e.to_pyexception(vm))?;
582+
let sub_key = args
583+
.sub_key
584+
.as_ref()
585+
.map(|s| WideCString::from_vec(s.as_wtf8().encode_wide().collect::<Vec<_>>()))
586+
.transpose()
587+
.map_err(|_| nul_char_error(vm))?;
588+
let key = args.key.hkey.load();
589+
vm.audit("winreg.OpenKey", || {
590+
(key as isize, args.sub_key, args.access as isize)
591+
})?;
541592
let mut res: host_winreg::HKEY = core::ptr::null_mut();
542-
let err = unsafe {
543-
let key = args.key.hkey.load();
544-
host_winreg::open_key_ex(key, &sub_key, args.reserved, args.access, &mut res)
545-
};
593+
let err = vm.allow_threads(|| unsafe {
594+
host_winreg::open_key_ex(
595+
key,
596+
sub_key.as_deref(),
597+
args.reserved,
598+
args.access,
599+
&mut res,
600+
)
601+
});
546602
if err == 0 {
547-
Ok(PyHkey {
548-
#[allow(clippy::arc_with_non_send_sync)]
549-
hkey: AtomicHKEY::new(res),
550-
})
603+
let result = PyHkey::new(res);
604+
vm.audit("winreg.OpenKey/result", || (res as isize,))?;
605+
Ok(result)
551606
} else {
552607
Err(os_error_from_windows_code(vm, err as i32))
553608
}

0 commit comments

Comments
 (0)