Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/cpython
Path: blob/main/PC/winreg.c
12 views
1
/*
2
winreg.c
3
4
Windows Registry access module for Python.
5
6
* Simple registry access written by Mark Hammond in win32api
7
module circa 1995.
8
* Bill Tutt expanded the support significantly not long after.
9
* Numerous other people have submitted patches since then.
10
* Ripped from win32api module 03-Feb-2000 by Mark Hammond, and
11
basic Unicode support added.
12
13
*/
14
15
#include "Python.h"
16
#include "pycore_object.h" // _PyObject_Init()
17
#include "pycore_moduleobject.h"
18
#include "structmember.h" // PyMemberDef
19
#include <windows.h>
20
21
#if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM) || defined(MS_WINDOWS_GAMES)
22
23
typedef struct {
24
PyTypeObject *PyHKEY_Type;
25
} winreg_state;
26
27
/* Forward declares */
28
29
static BOOL PyHKEY_AsHKEY(winreg_state *st, PyObject *ob, HKEY *pRes, BOOL bNoneOK);
30
static BOOL clinic_HKEY_converter(winreg_state *st, PyObject *ob, void *p);
31
static PyObject *PyHKEY_FromHKEY(winreg_state *st, HKEY h);
32
static BOOL PyHKEY_Close(winreg_state *st, PyObject *obHandle);
33
34
static char errNotAHandle[] = "Object is not a handle";
35
36
/* The win32api module reports the function name that failed,
37
but this concept is not in the Python core.
38
Hopefully it will one day, and in the meantime I don't
39
want to lose this info...
40
*/
41
#define PyErr_SetFromWindowsErrWithFunction(rc, fnname) \
42
PyErr_SetFromWindowsErr(rc)
43
44
/* Doc strings */
45
PyDoc_STRVAR(module_doc,
46
"This module provides access to the Windows registry API.\n"
47
"\n"
48
"Functions:\n"
49
"\n"
50
"CloseKey() - Closes a registry key.\n"
51
"ConnectRegistry() - Establishes a connection to a predefined registry handle\n"
52
" on another computer.\n"
53
"CreateKey() - Creates the specified key, or opens it if it already exists.\n"
54
"DeleteKey() - Deletes the specified key.\n"
55
"DeleteValue() - Removes a named value from the specified registry key.\n"
56
"EnumKey() - Enumerates subkeys of the specified open registry key.\n"
57
"EnumValue() - Enumerates values of the specified open registry key.\n"
58
"ExpandEnvironmentStrings() - Expand the env strings in a REG_EXPAND_SZ\n"
59
" string.\n"
60
"FlushKey() - Writes all the attributes of the specified key to the registry.\n"
61
"LoadKey() - Creates a subkey under HKEY_USER or HKEY_LOCAL_MACHINE and\n"
62
" stores registration information from a specified file into that\n"
63
" subkey.\n"
64
"OpenKey() - Opens the specified key.\n"
65
"OpenKeyEx() - Alias of OpenKey().\n"
66
"QueryValue() - Retrieves the value associated with the unnamed value for a\n"
67
" specified key in the registry.\n"
68
"QueryValueEx() - Retrieves the type and data for a specified value name\n"
69
" associated with an open registry key.\n"
70
"QueryInfoKey() - Returns information about the specified key.\n"
71
"SaveKey() - Saves the specified key, and all its subkeys a file.\n"
72
"SetValue() - Associates a value with a specified key.\n"
73
"SetValueEx() - Stores data in the value field of an open registry key.\n"
74
"\n"
75
"Special objects:\n"
76
"\n"
77
"HKEYType -- type object for HKEY objects\n"
78
"error -- exception raised for Win32 errors\n"
79
"\n"
80
"Integer constants:\n"
81
"Many constants are defined - see the documentation for each function\n"
82
"to see what constants are used, and where.");
83
84
85
86
/* PyHKEY docstrings */
87
PyDoc_STRVAR(PyHKEY_doc,
88
"PyHKEY Object - A Python object, representing a win32 registry key.\n"
89
"\n"
90
"This object wraps a Windows HKEY object, automatically closing it when\n"
91
"the object is destroyed. To guarantee cleanup, you can call either\n"
92
"the Close() method on the PyHKEY, or the CloseKey() method.\n"
93
"\n"
94
"All functions which accept a handle object also accept an integer --\n"
95
"however, use of the handle object is encouraged.\n"
96
"\n"
97
"Functions:\n"
98
"Close() - Closes the underlying handle.\n"
99
"Detach() - Returns the integer Win32 handle, detaching it from the object\n"
100
"\n"
101
"Properties:\n"
102
"handle - The integer Win32 handle.\n"
103
"\n"
104
"Operations:\n"
105
"__bool__ - Handles with an open object return true, otherwise false.\n"
106
"__int__ - Converting a handle to an integer returns the Win32 handle.\n"
107
"rich comparison - Handle objects are compared using the handle value.");
108
109
110
111
/************************************************************************
112
113
The PyHKEY object definition
114
115
************************************************************************/
116
typedef struct {
117
PyObject_VAR_HEAD
118
HKEY hkey;
119
} PyHKEYObject;
120
121
#define PyHKEY_Check(st, op) Py_IS_TYPE(op, st->PyHKEY_Type)
122
123
static char *failMsg = "bad operand type";
124
125
static PyObject *
126
PyHKEY_unaryFailureFunc(PyObject *ob)
127
{
128
PyErr_SetString(PyExc_TypeError, failMsg);
129
return NULL;
130
}
131
static PyObject *
132
PyHKEY_binaryFailureFunc(PyObject *ob1, PyObject *ob2)
133
{
134
PyErr_SetString(PyExc_TypeError, failMsg);
135
return NULL;
136
}
137
static PyObject *
138
PyHKEY_ternaryFailureFunc(PyObject *ob1, PyObject *ob2, PyObject *ob3)
139
{
140
PyErr_SetString(PyExc_TypeError, failMsg);
141
return NULL;
142
}
143
144
static void
145
PyHKEY_deallocFunc(PyObject *ob)
146
{
147
/* Can not call PyHKEY_Close, as the ob->tp_type
148
has already been cleared, thus causing the type
149
check to fail!
150
*/
151
PyHKEYObject *obkey = (PyHKEYObject *)ob;
152
if (obkey->hkey)
153
RegCloseKey((HKEY)obkey->hkey);
154
155
PyTypeObject *tp = Py_TYPE(ob);
156
PyObject_GC_UnTrack(ob);
157
PyObject_GC_Del(ob);
158
Py_DECREF(tp);
159
}
160
161
static int
162
PyHKEY_traverseFunc(PyHKEYObject *self, visitproc visit, void *arg)
163
{
164
Py_VISIT(Py_TYPE(self));
165
return 0;
166
}
167
168
static int
169
PyHKEY_boolFunc(PyObject *ob)
170
{
171
return ((PyHKEYObject *)ob)->hkey != 0;
172
}
173
174
static PyObject *
175
PyHKEY_intFunc(PyObject *ob)
176
{
177
PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
178
return PyLong_FromVoidPtr(pyhkey->hkey);
179
}
180
181
static PyObject *
182
PyHKEY_strFunc(PyObject *ob)
183
{
184
PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
185
return PyUnicode_FromFormat("<PyHKEY:%p>", pyhkey->hkey);
186
}
187
188
static int
189
PyHKEY_compareFunc(PyObject *ob1, PyObject *ob2)
190
{
191
PyHKEYObject *pyhkey1 = (PyHKEYObject *)ob1;
192
PyHKEYObject *pyhkey2 = (PyHKEYObject *)ob2;
193
return pyhkey1 == pyhkey2 ? 0 :
194
(pyhkey1 < pyhkey2 ? -1 : 1);
195
}
196
197
static Py_hash_t
198
PyHKEY_hashFunc(PyObject *ob)
199
{
200
/* Just use the address.
201
XXX - should we use the handle value?
202
*/
203
return _Py_HashPointer(ob);
204
}
205
206
207
/*[clinic input]
208
module winreg
209
class winreg.HKEYType "PyHKEYObject *" "&PyHKEY_Type"
210
[clinic start generated code]*/
211
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=4c964eba3bf914d6]*/
212
213
/*[python input]
214
class REGSAM_converter(int_converter):
215
type = 'REGSAM'
216
217
class DWORD_converter(unsigned_long_converter):
218
type = 'DWORD'
219
220
class HKEY_converter(CConverter):
221
type = 'HKEY'
222
converter = 'clinic_HKEY_converter'
223
224
def parse_arg(self, argname, displayname):
225
return """
226
if (!{converter}(_PyModule_GetState(module), {argname}, &{paramname})) {{{{
227
goto exit;
228
}}}}
229
""".format(argname=argname, paramname=self.parser_name,
230
converter=self.converter)
231
232
class HKEY_return_converter(CReturnConverter):
233
type = 'HKEY'
234
235
def render(self, function, data):
236
self.declare(data)
237
self.err_occurred_if_null_pointer("_return_value", data)
238
data.return_conversion.append(
239
'return_value = PyHKEY_FromHKEY(_PyModule_GetState(module), _return_value);\n')
240
241
# HACK: this only works for PyHKEYObjects, nothing else.
242
# Should this be generalized and enshrined in clinic.py,
243
# destroy this converter with prejudice.
244
class self_return_converter(CReturnConverter):
245
type = 'PyHKEYObject *'
246
247
def render(self, function, data):
248
self.declare(data)
249
data.return_conversion.append(
250
'return_value = (PyObject *)_return_value;\n')
251
[python start generated code]*/
252
/*[python end generated code: output=da39a3ee5e6b4b0d input=17e645060c7b8ae1]*/
253
254
#include "clinic/winreg.c.h"
255
256
/************************************************************************
257
258
The PyHKEY object methods
259
260
************************************************************************/
261
/*[clinic input]
262
winreg.HKEYType.Close
263
264
Closes the underlying Windows handle.
265
266
If the handle is already closed, no error is raised.
267
[clinic start generated code]*/
268
269
static PyObject *
270
winreg_HKEYType_Close_impl(PyHKEYObject *self)
271
/*[clinic end generated code: output=fced3a624fb0c344 input=6786ac75f6b89de6]*/
272
{
273
winreg_state *st = _PyType_GetModuleState(Py_TYPE(self));
274
assert(st != NULL);
275
if (!PyHKEY_Close(st, (PyObject *)self)) {
276
return NULL;
277
}
278
Py_RETURN_NONE;
279
}
280
281
/*[clinic input]
282
winreg.HKEYType.Detach
283
284
Detaches the Windows handle from the handle object.
285
286
The result is the value of the handle before it is detached. If the
287
handle is already detached, this will return zero.
288
289
After calling this function, the handle is effectively invalidated,
290
but the handle is not closed. You would call this function when you
291
need the underlying win32 handle to exist beyond the lifetime of the
292
handle object.
293
[clinic start generated code]*/
294
295
static PyObject *
296
winreg_HKEYType_Detach_impl(PyHKEYObject *self)
297
/*[clinic end generated code: output=dda5a9e1a01ae78f input=dd2cc09e6c6ba833]*/
298
{
299
void* ret;
300
if (PySys_Audit("winreg.PyHKEY.Detach", "n", (Py_ssize_t)self->hkey) < 0) {
301
return NULL;
302
}
303
ret = (void*)self->hkey;
304
self->hkey = 0;
305
return PyLong_FromVoidPtr(ret);
306
}
307
308
/*[clinic input]
309
winreg.HKEYType.__enter__ -> self
310
[clinic start generated code]*/
311
312
static PyHKEYObject *
313
winreg_HKEYType___enter___impl(PyHKEYObject *self)
314
/*[clinic end generated code: output=52c34986dab28990 input=c40fab1f0690a8e2]*/
315
{
316
return (PyHKEYObject*)Py_XNewRef(self);
317
}
318
319
320
/*[clinic input]
321
winreg.HKEYType.__exit__
322
323
exc_type: object
324
exc_value: object
325
traceback: object
326
[clinic start generated code]*/
327
328
static PyObject *
329
winreg_HKEYType___exit___impl(PyHKEYObject *self, PyObject *exc_type,
330
PyObject *exc_value, PyObject *traceback)
331
/*[clinic end generated code: output=923ebe7389e6a263 input=fb32489ee92403c7]*/
332
{
333
winreg_state *st = _PyType_GetModuleState(Py_TYPE(self));
334
assert(st != NULL);
335
if (!PyHKEY_Close(st, (PyObject *)self)) {
336
return NULL;
337
}
338
Py_RETURN_NONE;
339
}
340
341
/*[clinic input]
342
[clinic start generated code]*/
343
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=da39a3ee5e6b4b0d]*/
344
345
static struct PyMethodDef PyHKEY_methods[] = {
346
WINREG_HKEYTYPE_CLOSE_METHODDEF
347
WINREG_HKEYTYPE_DETACH_METHODDEF
348
WINREG_HKEYTYPE___ENTER___METHODDEF
349
WINREG_HKEYTYPE___EXIT___METHODDEF
350
{NULL}
351
};
352
353
#define OFF(e) offsetof(PyHKEYObject, e)
354
static PyMemberDef PyHKEY_memberlist[] = {
355
{"handle", T_INT, OFF(hkey), READONLY},
356
{NULL} /* Sentinel */
357
};
358
359
static PyType_Slot pyhkey_type_slots[] = {
360
{Py_tp_dealloc, PyHKEY_deallocFunc},
361
{Py_tp_members, PyHKEY_memberlist},
362
{Py_tp_methods, PyHKEY_methods},
363
{Py_tp_doc, (char *)PyHKEY_doc},
364
{Py_tp_traverse, PyHKEY_traverseFunc},
365
{Py_tp_hash, PyHKEY_hashFunc},
366
{Py_tp_str, PyHKEY_strFunc},
367
368
// Number protocol
369
{Py_nb_add, PyHKEY_binaryFailureFunc},
370
{Py_nb_subtract, PyHKEY_binaryFailureFunc},
371
{Py_nb_multiply, PyHKEY_binaryFailureFunc},
372
{Py_nb_remainder, PyHKEY_binaryFailureFunc},
373
{Py_nb_divmod, PyHKEY_binaryFailureFunc},
374
{Py_nb_power, PyHKEY_ternaryFailureFunc},
375
{Py_nb_negative, PyHKEY_unaryFailureFunc},
376
{Py_nb_positive, PyHKEY_unaryFailureFunc},
377
{Py_nb_absolute, PyHKEY_unaryFailureFunc},
378
{Py_nb_bool, PyHKEY_boolFunc},
379
{Py_nb_invert, PyHKEY_unaryFailureFunc},
380
{Py_nb_lshift, PyHKEY_binaryFailureFunc},
381
{Py_nb_rshift, PyHKEY_binaryFailureFunc},
382
{Py_nb_and, PyHKEY_binaryFailureFunc},
383
{Py_nb_xor, PyHKEY_binaryFailureFunc},
384
{Py_nb_or, PyHKEY_binaryFailureFunc},
385
{Py_nb_int, PyHKEY_intFunc},
386
{Py_nb_float, PyHKEY_unaryFailureFunc},
387
{0, NULL},
388
};
389
390
static PyType_Spec pyhkey_type_spec = {
391
.name = "winreg.PyHKEY",
392
.basicsize = sizeof(PyHKEYObject),
393
.flags = (Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE |
394
Py_TPFLAGS_DISALLOW_INSTANTIATION),
395
.slots = pyhkey_type_slots,
396
};
397
398
/************************************************************************
399
The public PyHKEY API (well, not public yet :-)
400
************************************************************************/
401
PyObject *
402
PyHKEY_New(PyObject *m, HKEY hInit)
403
{
404
winreg_state *st = _PyModule_GetState(m);
405
PyHKEYObject *key = PyObject_GC_New(PyHKEYObject, st->PyHKEY_Type);
406
if (key == NULL) {
407
return NULL;
408
}
409
key->hkey = hInit;
410
PyObject_GC_Track(key);
411
return (PyObject *)key;
412
}
413
414
BOOL
415
PyHKEY_Close(winreg_state *st, PyObject *ob_handle)
416
{
417
LONG rc;
418
HKEY key;
419
420
if (!PyHKEY_AsHKEY(st, ob_handle, &key, TRUE)) {
421
return FALSE;
422
}
423
if (PyHKEY_Check(st, ob_handle)) {
424
((PyHKEYObject*)ob_handle)->hkey = 0;
425
}
426
rc = key ? RegCloseKey(key) : ERROR_SUCCESS;
427
if (rc != ERROR_SUCCESS)
428
PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
429
return rc == ERROR_SUCCESS;
430
}
431
432
BOOL
433
PyHKEY_AsHKEY(winreg_state *st, PyObject *ob, HKEY *pHANDLE, BOOL bNoneOK)
434
{
435
if (ob == Py_None) {
436
if (!bNoneOK) {
437
PyErr_SetString(
438
PyExc_TypeError,
439
"None is not a valid HKEY in this context");
440
return FALSE;
441
}
442
*pHANDLE = (HKEY)0;
443
}
444
else if (PyHKEY_Check(st ,ob)) {
445
PyHKEYObject *pH = (PyHKEYObject *)ob;
446
*pHANDLE = pH->hkey;
447
}
448
else if (PyLong_Check(ob)) {
449
/* We also support integers */
450
PyErr_Clear();
451
*pHANDLE = (HKEY)PyLong_AsVoidPtr(ob);
452
if (PyErr_Occurred())
453
return FALSE;
454
}
455
else {
456
PyErr_SetString(
457
PyExc_TypeError,
458
"The object is not a PyHKEY object");
459
return FALSE;
460
}
461
return TRUE;
462
}
463
464
BOOL
465
clinic_HKEY_converter(winreg_state *st, PyObject *ob, void *p)
466
{
467
if (!PyHKEY_AsHKEY(st, ob, (HKEY *)p, FALSE)) {
468
return FALSE;
469
}
470
return TRUE;
471
}
472
473
PyObject *
474
PyHKEY_FromHKEY(winreg_state *st, HKEY h)
475
{
476
PyHKEYObject *op = (PyHKEYObject *)PyObject_GC_New(PyHKEYObject,
477
st->PyHKEY_Type);
478
if (op == NULL) {
479
return NULL;
480
}
481
op->hkey = h;
482
PyObject_GC_Track(op);
483
return (PyObject *)op;
484
}
485
486
487
/************************************************************************
488
The module methods
489
************************************************************************/
490
BOOL
491
PyWinObject_CloseHKEY(winreg_state *st, PyObject *obHandle)
492
{
493
BOOL ok;
494
if (PyHKEY_Check(st, obHandle)) {
495
ok = PyHKEY_Close(st, obHandle);
496
}
497
#if SIZEOF_LONG >= SIZEOF_HKEY
498
else if (PyLong_Check(obHandle)) {
499
long rc = RegCloseKey((HKEY)PyLong_AsLong(obHandle));
500
ok = (rc == ERROR_SUCCESS);
501
if (!ok)
502
PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
503
}
504
#else
505
else if (PyLong_Check(obHandle)) {
506
long rc = RegCloseKey((HKEY)PyLong_AsVoidPtr(obHandle));
507
ok = (rc == ERROR_SUCCESS);
508
if (!ok)
509
PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
510
}
511
#endif
512
else {
513
PyErr_SetString(
514
PyExc_TypeError,
515
"A handle must be a HKEY object or an integer");
516
return FALSE;
517
}
518
return ok;
519
}
520
521
522
/*
523
Private Helper functions for the registry interfaces
524
525
** Note that fixupMultiSZ and countString have both had changes
526
** made to support "incorrect strings". The registry specification
527
** calls for strings to be terminated with 2 null bytes. It seems
528
** some commercial packages install strings which don't conform,
529
** causing this code to fail - however, "regedit" etc still work
530
** with these strings (ie only we don't!).
531
*/
532
static void
533
fixupMultiSZ(wchar_t **str, wchar_t *data, int len)
534
{
535
wchar_t *P;
536
int i;
537
wchar_t *Q;
538
539
if (len > 0 && data[len - 1] == '\0') {
540
Q = data + len - 1;
541
}
542
else {
543
Q = data + len;
544
}
545
546
for (P = data, i = 0; P < Q; P++, i++) {
547
str[i] = P;
548
for (; P < Q && *P != '\0'; P++) {
549
;
550
}
551
}
552
}
553
554
static int
555
countStrings(wchar_t *data, int len)
556
{
557
int strings;
558
wchar_t *P, *Q;
559
560
if (len > 0 && data[len - 1] == '\0') {
561
Q = data + len - 1;
562
}
563
else {
564
Q = data + len;
565
}
566
567
for (P = data, strings = 0; P < Q; P++, strings++) {
568
for (; P < Q && *P != '\0'; P++) {
569
;
570
}
571
}
572
return strings;
573
}
574
575
/* Convert PyObject into Registry data.
576
Allocates space as needed. */
577
static BOOL
578
Py2Reg(PyObject *value, DWORD typ, BYTE **retDataBuf, DWORD *retDataSize)
579
{
580
Py_ssize_t i,j;
581
switch (typ) {
582
case REG_DWORD:
583
{
584
if (value != Py_None && !PyLong_Check(value)) {
585
return FALSE;
586
}
587
DWORD d;
588
if (value == Py_None) {
589
d = 0;
590
}
591
else if (PyLong_Check(value)) {
592
d = PyLong_AsUnsignedLong(value);
593
if (d == (DWORD)(-1) && PyErr_Occurred()) {
594
return FALSE;
595
}
596
}
597
*retDataBuf = (BYTE *)PyMem_NEW(DWORD, 1);
598
if (*retDataBuf == NULL) {
599
PyErr_NoMemory();
600
return FALSE;
601
}
602
memcpy(*retDataBuf, &d, sizeof(DWORD));
603
*retDataSize = sizeof(DWORD);
604
break;
605
}
606
case REG_QWORD:
607
{
608
if (value != Py_None && !PyLong_Check(value)) {
609
return FALSE;
610
}
611
DWORD64 d;
612
if (value == Py_None) {
613
d = 0;
614
}
615
else if (PyLong_Check(value)) {
616
d = PyLong_AsUnsignedLongLong(value);
617
if (d == (DWORD64)(-1) && PyErr_Occurred()) {
618
return FALSE;
619
}
620
}
621
*retDataBuf = (BYTE *)PyMem_NEW(DWORD64, 1);
622
if (*retDataBuf == NULL) {
623
PyErr_NoMemory();
624
return FALSE;
625
}
626
memcpy(*retDataBuf, &d, sizeof(DWORD64));
627
*retDataSize = sizeof(DWORD64);
628
break;
629
}
630
case REG_SZ:
631
case REG_EXPAND_SZ:
632
{
633
if (value != Py_None) {
634
Py_ssize_t len;
635
if (!PyUnicode_Check(value))
636
return FALSE;
637
*retDataBuf = (BYTE*)PyUnicode_AsWideCharString(value, &len);
638
if (*retDataBuf == NULL)
639
return FALSE;
640
*retDataSize = Py_SAFE_DOWNCAST(
641
(len + 1) * sizeof(wchar_t),
642
Py_ssize_t, DWORD);
643
}
644
else {
645
*retDataBuf = (BYTE *)PyMem_NEW(wchar_t, 1);
646
if (*retDataBuf == NULL) {
647
PyErr_NoMemory();
648
return FALSE;
649
}
650
((wchar_t *)*retDataBuf)[0] = L'\0';
651
*retDataSize = 1 * sizeof(wchar_t);
652
}
653
break;
654
}
655
case REG_MULTI_SZ:
656
{
657
DWORD size = 0;
658
wchar_t *P;
659
660
if (value == Py_None)
661
i = 0;
662
else {
663
if (!PyList_Check(value))
664
return FALSE;
665
i = PyList_Size(value);
666
}
667
for (j = 0; j < i; j++)
668
{
669
PyObject *t;
670
Py_ssize_t len;
671
672
t = PyList_GET_ITEM(value, j);
673
if (!PyUnicode_Check(t))
674
return FALSE;
675
len = PyUnicode_AsWideChar(t, NULL, 0);
676
if (len < 0)
677
return FALSE;
678
size += Py_SAFE_DOWNCAST(len * sizeof(wchar_t),
679
size_t, DWORD);
680
}
681
682
*retDataSize = size + 2;
683
*retDataBuf = (BYTE *)PyMem_NEW(char,
684
*retDataSize);
685
if (*retDataBuf == NULL){
686
PyErr_NoMemory();
687
return FALSE;
688
}
689
P = (wchar_t *)*retDataBuf;
690
691
for (j = 0; j < i; j++)
692
{
693
PyObject *t;
694
Py_ssize_t len;
695
696
t = PyList_GET_ITEM(value, j);
697
assert(size > 0);
698
len = PyUnicode_AsWideChar(t, P, size);
699
assert(len >= 0);
700
assert((unsigned)len < size);
701
size -= (DWORD)len + 1;
702
P += len + 1;
703
}
704
/* And doubly-terminate the list... */
705
*P = L'\0';
706
break;
707
}
708
case REG_BINARY:
709
/* ALSO handle ALL unknown data types here. Even if we can't
710
support it natively, we should handle the bits. */
711
default:
712
if (value == Py_None) {
713
*retDataSize = 0;
714
*retDataBuf = NULL;
715
}
716
else {
717
Py_buffer view;
718
719
if (!PyObject_CheckBuffer(value)) {
720
PyErr_Format(PyExc_TypeError,
721
"Objects of type '%s' can not "
722
"be used as binary registry values",
723
Py_TYPE(value)->tp_name);
724
return FALSE;
725
}
726
727
if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0)
728
return FALSE;
729
730
*retDataBuf = (BYTE *)PyMem_NEW(char, view.len);
731
if (*retDataBuf == NULL){
732
PyBuffer_Release(&view);
733
PyErr_NoMemory();
734
return FALSE;
735
}
736
*retDataSize = Py_SAFE_DOWNCAST(view.len, Py_ssize_t, DWORD);
737
memcpy(*retDataBuf, view.buf, view.len);
738
PyBuffer_Release(&view);
739
}
740
break;
741
}
742
return TRUE;
743
}
744
745
/* Convert Registry data into PyObject*/
746
static PyObject *
747
Reg2Py(BYTE *retDataBuf, DWORD retDataSize, DWORD typ)
748
{
749
PyObject *obData;
750
751
switch (typ) {
752
case REG_DWORD:
753
if (retDataSize == 0)
754
obData = PyLong_FromUnsignedLong(0);
755
else
756
obData = PyLong_FromUnsignedLong(*(DWORD *)retDataBuf);
757
break;
758
case REG_QWORD:
759
if (retDataSize == 0)
760
obData = PyLong_FromUnsignedLongLong(0);
761
else
762
obData = PyLong_FromUnsignedLongLong(*(DWORD64 *)retDataBuf);
763
break;
764
case REG_SZ:
765
case REG_EXPAND_SZ:
766
{
767
/* REG_SZ should be a NUL terminated string, but only by
768
* convention. The buffer may have been saved without a NUL
769
* or with embedded NULs. To be consistent with reg.exe and
770
* regedit.exe, consume only up to the first NUL. */
771
wchar_t *data = (wchar_t *)retDataBuf;
772
size_t len = wcsnlen(data, retDataSize / sizeof(wchar_t));
773
obData = PyUnicode_FromWideChar(data, len);
774
break;
775
}
776
case REG_MULTI_SZ:
777
if (retDataSize == 0)
778
obData = PyList_New(0);
779
else
780
{
781
int index = 0;
782
wchar_t *data = (wchar_t *)retDataBuf;
783
int len = retDataSize / 2;
784
int s = countStrings(data, len);
785
wchar_t **str = PyMem_New(wchar_t *, s);
786
if (str == NULL)
787
return PyErr_NoMemory();
788
789
fixupMultiSZ(str, data, len);
790
obData = PyList_New(s);
791
if (obData == NULL) {
792
PyMem_Free(str);
793
return NULL;
794
}
795
for (index = 0; index < s; index++)
796
{
797
size_t slen = wcsnlen(str[index], len);
798
PyObject *uni = PyUnicode_FromWideChar(str[index], slen);
799
if (uni == NULL) {
800
Py_DECREF(obData);
801
PyMem_Free(str);
802
return NULL;
803
}
804
PyList_SET_ITEM(obData, index, uni);
805
len -= Py_SAFE_DOWNCAST(slen + 1, size_t, int);
806
}
807
PyMem_Free(str);
808
809
break;
810
}
811
case REG_BINARY:
812
/* ALSO handle ALL unknown data types here. Even if we can't
813
support it natively, we should handle the bits. */
814
default:
815
if (retDataSize == 0) {
816
obData = Py_NewRef(Py_None);
817
}
818
else
819
obData = PyBytes_FromStringAndSize(
820
(char *)retDataBuf, retDataSize);
821
break;
822
}
823
return obData;
824
}
825
826
/* The Python methods */
827
828
/*[clinic input]
829
winreg.CloseKey
830
831
hkey: object
832
A previously opened key.
833
/
834
835
Closes a previously opened registry key.
836
837
Note that if the key is not closed using this method, it will be
838
closed when the hkey object is destroyed by Python.
839
[clinic start generated code]*/
840
841
static PyObject *
842
winreg_CloseKey(PyObject *module, PyObject *hkey)
843
/*[clinic end generated code: output=a4fa537019a80d15 input=5b1aac65ba5127ad]*/
844
{
845
if (!PyHKEY_Close(_PyModule_GetState(module), hkey)) {
846
return NULL;
847
}
848
Py_RETURN_NONE;
849
}
850
851
#if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
852
853
/*[clinic input]
854
winreg.ConnectRegistry -> HKEY
855
856
computer_name: Py_UNICODE(accept={str, NoneType})
857
The name of the remote computer, of the form r"\\computername". If
858
None, the local computer is used.
859
key: HKEY
860
The predefined key to connect to.
861
/
862
863
Establishes a connection to the registry on another computer.
864
865
The return value is the handle of the opened key.
866
If the function fails, an OSError exception is raised.
867
[clinic start generated code]*/
868
869
static HKEY
870
winreg_ConnectRegistry_impl(PyObject *module, const wchar_t *computer_name,
871
HKEY key)
872
/*[clinic end generated code: output=c77d12428f4bfe29 input=5f98a891a347e68e]*/
873
{
874
HKEY retKey;
875
long rc;
876
if (PySys_Audit("winreg.ConnectRegistry", "un",
877
computer_name, (Py_ssize_t)key) < 0) {
878
return NULL;
879
}
880
Py_BEGIN_ALLOW_THREADS
881
rc = RegConnectRegistryW(computer_name, key, &retKey);
882
Py_END_ALLOW_THREADS
883
if (rc != ERROR_SUCCESS) {
884
PyErr_SetFromWindowsErrWithFunction(rc, "ConnectRegistry");
885
return NULL;
886
}
887
return retKey;
888
}
889
890
#endif /* MS_WINDOWS_DESKTOP || MS_WINDOWS_SYSTEM */
891
892
/*[clinic input]
893
winreg.CreateKey -> HKEY
894
895
key: HKEY
896
An already open key, or one of the predefined HKEY_* constants.
897
sub_key: Py_UNICODE(accept={str, NoneType})
898
The name of the key this method opens or creates.
899
/
900
901
Creates or opens the specified key.
902
903
If key is one of the predefined keys, sub_key may be None. In that case,
904
the handle returned is the same key handle passed in to the function.
905
906
If the key already exists, this function opens the existing key.
907
908
The return value is the handle of the opened key.
909
If the function fails, an OSError exception is raised.
910
[clinic start generated code]*/
911
912
static HKEY
913
winreg_CreateKey_impl(PyObject *module, HKEY key, const wchar_t *sub_key)
914
/*[clinic end generated code: output=58d3eb2ed428a84d input=3cdd1622488acea2]*/
915
{
916
HKEY retKey;
917
long rc;
918
919
if (PySys_Audit("winreg.CreateKey", "nun",
920
(Py_ssize_t)key, sub_key,
921
(Py_ssize_t)KEY_WRITE) < 0) {
922
return NULL;
923
}
924
rc = RegCreateKeyW(key, sub_key, &retKey);
925
if (rc != ERROR_SUCCESS) {
926
PyErr_SetFromWindowsErrWithFunction(rc, "CreateKey");
927
return NULL;
928
}
929
if (PySys_Audit("winreg.OpenKey/result", "n",
930
(Py_ssize_t)retKey) < 0) {
931
return NULL;
932
}
933
return retKey;
934
}
935
936
/*[clinic input]
937
winreg.CreateKeyEx -> HKEY
938
939
key: HKEY
940
An already open key, or one of the predefined HKEY_* constants.
941
sub_key: Py_UNICODE(accept={str, NoneType})
942
The name of the key this method opens or creates.
943
reserved: int = 0
944
A reserved integer, and must be zero. Default is zero.
945
access: REGSAM(c_default='KEY_WRITE') = winreg.KEY_WRITE
946
An integer that specifies an access mask that describes the
947
desired security access for the key. Default is KEY_WRITE.
948
949
Creates or opens the specified key.
950
951
If key is one of the predefined keys, sub_key may be None. In that case,
952
the handle returned is the same key handle passed in to the function.
953
954
If the key already exists, this function opens the existing key
955
956
The return value is the handle of the opened key.
957
If the function fails, an OSError exception is raised.
958
[clinic start generated code]*/
959
960
static HKEY
961
winreg_CreateKeyEx_impl(PyObject *module, HKEY key, const wchar_t *sub_key,
962
int reserved, REGSAM access)
963
/*[clinic end generated code: output=51b53e38d5e00d4b input=42c2b03f98406b66]*/
964
{
965
HKEY retKey;
966
long rc;
967
968
if (PySys_Audit("winreg.CreateKey", "nun",
969
(Py_ssize_t)key, sub_key,
970
(Py_ssize_t)access) < 0) {
971
return NULL;
972
}
973
rc = RegCreateKeyExW(key, sub_key, reserved, NULL, 0,
974
access, NULL, &retKey, NULL);
975
if (rc != ERROR_SUCCESS) {
976
PyErr_SetFromWindowsErrWithFunction(rc, "CreateKeyEx");
977
return NULL;
978
}
979
if (PySys_Audit("winreg.OpenKey/result", "n",
980
(Py_ssize_t)retKey) < 0) {
981
return NULL;
982
}
983
return retKey;
984
}
985
986
/*[clinic input]
987
winreg.DeleteKey
988
key: HKEY
989
An already open key, or any one of the predefined HKEY_* constants.
990
sub_key: Py_UNICODE
991
A string that must be the name of a subkey of the key identified by
992
the key parameter. This value must not be None, and the key may not
993
have subkeys.
994
/
995
996
Deletes the specified key.
997
998
This method can not delete keys with subkeys.
999
1000
If the function succeeds, the entire key, including all of its values,
1001
is removed. If the function fails, an OSError exception is raised.
1002
[clinic start generated code]*/
1003
1004
static PyObject *
1005
winreg_DeleteKey_impl(PyObject *module, HKEY key, const wchar_t *sub_key)
1006
/*[clinic end generated code: output=2e9f7c09eb7701b8 input=b31d225b935e4211]*/
1007
{
1008
long rc;
1009
if (PySys_Audit("winreg.DeleteKey", "nun",
1010
(Py_ssize_t)key, sub_key,
1011
(Py_ssize_t)0) < 0) {
1012
return NULL;
1013
}
1014
Py_BEGIN_ALLOW_THREADS
1015
rc = RegDeleteKeyW(key, sub_key);
1016
Py_END_ALLOW_THREADS
1017
if (rc != ERROR_SUCCESS)
1018
return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKey");
1019
Py_RETURN_NONE;
1020
}
1021
1022
/*[clinic input]
1023
winreg.DeleteKeyEx
1024
1025
key: HKEY
1026
An already open key, or any one of the predefined HKEY_* constants.
1027
sub_key: Py_UNICODE
1028
A string that must be the name of a subkey of the key identified by
1029
the key parameter. This value must not be None, and the key may not
1030
have subkeys.
1031
access: REGSAM(c_default='KEY_WOW64_64KEY') = winreg.KEY_WOW64_64KEY
1032
An integer that specifies an access mask that describes the
1033
desired security access for the key. Default is KEY_WOW64_64KEY.
1034
reserved: int = 0
1035
A reserved integer, and must be zero. Default is zero.
1036
1037
Deletes the specified key (intended for 64-bit OS).
1038
1039
While this function is intended to be used for 64-bit OS, it is also
1040
available on 32-bit systems.
1041
1042
This method can not delete keys with subkeys.
1043
1044
If the function succeeds, the entire key, including all of its values,
1045
is removed. If the function fails, an OSError exception is raised.
1046
On unsupported Windows versions, NotImplementedError is raised.
1047
[clinic start generated code]*/
1048
1049
static PyObject *
1050
winreg_DeleteKeyEx_impl(PyObject *module, HKEY key, const wchar_t *sub_key,
1051
REGSAM access, int reserved)
1052
/*[clinic end generated code: output=3bf4865c783fe7b2 input=a3186db079b3bf85]*/
1053
{
1054
long rc;
1055
if (PySys_Audit("winreg.DeleteKey", "nun",
1056
(Py_ssize_t)key, sub_key,
1057
(Py_ssize_t)access) < 0) {
1058
return NULL;
1059
}
1060
Py_BEGIN_ALLOW_THREADS
1061
rc = RegDeleteKeyExW(key, sub_key, access, reserved);
1062
Py_END_ALLOW_THREADS
1063
if (rc != ERROR_SUCCESS)
1064
return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKeyEx");
1065
Py_RETURN_NONE;
1066
}
1067
1068
/*[clinic input]
1069
winreg.DeleteValue
1070
1071
key: HKEY
1072
An already open key, or any one of the predefined HKEY_* constants.
1073
value: Py_UNICODE(accept={str, NoneType})
1074
A string that identifies the value to remove.
1075
/
1076
1077
Removes a named value from a registry key.
1078
[clinic start generated code]*/
1079
1080
static PyObject *
1081
winreg_DeleteValue_impl(PyObject *module, HKEY key, const wchar_t *value)
1082
/*[clinic end generated code: output=ed24b297aab137a5 input=a78d3407a4197b21]*/
1083
{
1084
long rc;
1085
if (PySys_Audit("winreg.DeleteValue", "nu",
1086
(Py_ssize_t)key, value) < 0) {
1087
return NULL;
1088
}
1089
Py_BEGIN_ALLOW_THREADS
1090
rc = RegDeleteValueW(key, value);
1091
Py_END_ALLOW_THREADS
1092
if (rc !=ERROR_SUCCESS)
1093
return PyErr_SetFromWindowsErrWithFunction(rc,
1094
"RegDeleteValue");
1095
Py_RETURN_NONE;
1096
}
1097
1098
/*[clinic input]
1099
winreg.EnumKey
1100
1101
key: HKEY
1102
An already open key, or any one of the predefined HKEY_* constants.
1103
index: int
1104
An integer that identifies the index of the key to retrieve.
1105
/
1106
1107
Enumerates subkeys of an open registry key.
1108
1109
The function retrieves the name of one subkey each time it is called.
1110
It is typically called repeatedly until an OSError exception is
1111
raised, indicating no more values are available.
1112
[clinic start generated code]*/
1113
1114
static PyObject *
1115
winreg_EnumKey_impl(PyObject *module, HKEY key, int index)
1116
/*[clinic end generated code: output=25a6ec52cd147bc4 input=fad9a7c00ab0e04b]*/
1117
{
1118
long rc;
1119
PyObject *retStr;
1120
1121
if (PySys_Audit("winreg.EnumKey", "ni",
1122
(Py_ssize_t)key, index) < 0) {
1123
return NULL;
1124
}
1125
/* The Windows docs claim that the max key name length is 255
1126
* characters, plus a terminating nul character. However,
1127
* empirical testing demonstrates that it is possible to
1128
* create a 256 character key that is missing the terminating
1129
* nul. RegEnumKeyEx requires a 257 character buffer to
1130
* retrieve such a key name. */
1131
wchar_t tmpbuf[257];
1132
DWORD len = sizeof(tmpbuf)/sizeof(wchar_t); /* includes NULL terminator */
1133
1134
Py_BEGIN_ALLOW_THREADS
1135
rc = RegEnumKeyExW(key, index, tmpbuf, &len, NULL, NULL, NULL, NULL);
1136
Py_END_ALLOW_THREADS
1137
if (rc != ERROR_SUCCESS)
1138
return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnumKeyEx");
1139
1140
retStr = PyUnicode_FromWideChar(tmpbuf, len);
1141
return retStr; /* can be NULL */
1142
}
1143
1144
/*[clinic input]
1145
winreg.EnumValue
1146
1147
key: HKEY
1148
An already open key, or any one of the predefined HKEY_* constants.
1149
index: int
1150
An integer that identifies the index of the value to retrieve.
1151
/
1152
1153
Enumerates values of an open registry key.
1154
1155
The function retrieves the name of one subkey each time it is called.
1156
It is typically called repeatedly, until an OSError exception
1157
is raised, indicating no more values.
1158
1159
The result is a tuple of 3 items:
1160
value_name
1161
A string that identifies the value.
1162
value_data
1163
An object that holds the value data, and whose type depends
1164
on the underlying registry type.
1165
data_type
1166
An integer that identifies the type of the value data.
1167
[clinic start generated code]*/
1168
1169
static PyObject *
1170
winreg_EnumValue_impl(PyObject *module, HKEY key, int index)
1171
/*[clinic end generated code: output=d363b5a06f8789ac input=4414f47a6fb238b5]*/
1172
{
1173
long rc;
1174
wchar_t *retValueBuf;
1175
BYTE *tmpBuf;
1176
BYTE *retDataBuf;
1177
DWORD retValueSize, bufValueSize;
1178
DWORD retDataSize, bufDataSize;
1179
DWORD typ;
1180
PyObject *obData;
1181
PyObject *retVal;
1182
1183
if (PySys_Audit("winreg.EnumValue", "ni",
1184
(Py_ssize_t)key, index) < 0) {
1185
return NULL;
1186
}
1187
if ((rc = RegQueryInfoKeyW(key, NULL, NULL, NULL, NULL, NULL, NULL,
1188
NULL,
1189
&retValueSize, &retDataSize, NULL, NULL))
1190
!= ERROR_SUCCESS)
1191
return PyErr_SetFromWindowsErrWithFunction(rc,
1192
"RegQueryInfoKey");
1193
++retValueSize; /* include null terminators */
1194
++retDataSize;
1195
bufDataSize = retDataSize;
1196
bufValueSize = retValueSize;
1197
retValueBuf = PyMem_New(wchar_t, retValueSize);
1198
if (retValueBuf == NULL)
1199
return PyErr_NoMemory();
1200
retDataBuf = (BYTE *)PyMem_Malloc(retDataSize);
1201
if (retDataBuf == NULL) {
1202
PyMem_Free(retValueBuf);
1203
return PyErr_NoMemory();
1204
}
1205
1206
while (1) {
1207
Py_BEGIN_ALLOW_THREADS
1208
rc = RegEnumValueW(key,
1209
index,
1210
retValueBuf,
1211
&retValueSize,
1212
NULL,
1213
&typ,
1214
(BYTE *)retDataBuf,
1215
&retDataSize);
1216
Py_END_ALLOW_THREADS
1217
1218
if (rc != ERROR_MORE_DATA)
1219
break;
1220
1221
bufDataSize *= 2;
1222
tmpBuf = (BYTE *)PyMem_Realloc(retDataBuf, bufDataSize);
1223
if (tmpBuf == NULL) {
1224
PyErr_NoMemory();
1225
retVal = NULL;
1226
goto fail;
1227
}
1228
retDataBuf = tmpBuf;
1229
retDataSize = bufDataSize;
1230
retValueSize = bufValueSize;
1231
}
1232
1233
if (rc != ERROR_SUCCESS) {
1234
retVal = PyErr_SetFromWindowsErrWithFunction(rc,
1235
"PyRegEnumValue");
1236
goto fail;
1237
}
1238
obData = Reg2Py(retDataBuf, retDataSize, typ);
1239
if (obData == NULL) {
1240
retVal = NULL;
1241
goto fail;
1242
}
1243
retVal = Py_BuildValue("uOi", retValueBuf, obData, typ);
1244
Py_DECREF(obData);
1245
fail:
1246
PyMem_Free(retValueBuf);
1247
PyMem_Free(retDataBuf);
1248
return retVal;
1249
}
1250
1251
/*[clinic input]
1252
winreg.ExpandEnvironmentStrings
1253
1254
string: Py_UNICODE
1255
/
1256
1257
Expand environment vars.
1258
[clinic start generated code]*/
1259
1260
static PyObject *
1261
winreg_ExpandEnvironmentStrings_impl(PyObject *module, const wchar_t *string)
1262
/*[clinic end generated code: output=53f120bbe788fa6f input=b2a9714d2b751aa6]*/
1263
{
1264
wchar_t *retValue = NULL;
1265
DWORD retValueSize;
1266
DWORD rc;
1267
PyObject *o;
1268
1269
if (PySys_Audit("winreg.ExpandEnvironmentStrings", "u",
1270
string) < 0) {
1271
return NULL;
1272
}
1273
1274
retValueSize = ExpandEnvironmentStringsW(string, retValue, 0);
1275
if (retValueSize == 0) {
1276
return PyErr_SetFromWindowsErrWithFunction(retValueSize,
1277
"ExpandEnvironmentStrings");
1278
}
1279
retValue = PyMem_New(wchar_t, retValueSize);
1280
if (retValue == NULL) {
1281
return PyErr_NoMemory();
1282
}
1283
1284
rc = ExpandEnvironmentStringsW(string, retValue, retValueSize);
1285
if (rc == 0) {
1286
PyMem_Free(retValue);
1287
return PyErr_SetFromWindowsErrWithFunction(retValueSize,
1288
"ExpandEnvironmentStrings");
1289
}
1290
o = PyUnicode_FromWideChar(retValue, wcslen(retValue));
1291
PyMem_Free(retValue);
1292
return o;
1293
}
1294
1295
#if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
1296
1297
/*[clinic input]
1298
winreg.FlushKey
1299
1300
key: HKEY
1301
An already open key, or any one of the predefined HKEY_* constants.
1302
/
1303
1304
Writes all the attributes of a key to the registry.
1305
1306
It is not necessary to call FlushKey to change a key. Registry changes
1307
are flushed to disk by the registry using its lazy flusher. Registry
1308
changes are also flushed to disk at system shutdown. Unlike
1309
CloseKey(), the FlushKey() method returns only when all the data has
1310
been written to the registry.
1311
1312
An application should only call FlushKey() if it requires absolute
1313
certainty that registry changes are on disk. If you don't know whether
1314
a FlushKey() call is required, it probably isn't.
1315
[clinic start generated code]*/
1316
1317
static PyObject *
1318
winreg_FlushKey_impl(PyObject *module, HKEY key)
1319
/*[clinic end generated code: output=e6fc230d4c5dc049 input=f57457c12297d82f]*/
1320
{
1321
long rc;
1322
Py_BEGIN_ALLOW_THREADS
1323
rc = RegFlushKey(key);
1324
Py_END_ALLOW_THREADS
1325
if (rc != ERROR_SUCCESS)
1326
return PyErr_SetFromWindowsErrWithFunction(rc, "RegFlushKey");
1327
Py_RETURN_NONE;
1328
}
1329
1330
#endif /* MS_WINDOWS_DESKTOP || MS_WINDOWS_SYSTEM */
1331
1332
#if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
1333
1334
/*[clinic input]
1335
winreg.LoadKey
1336
1337
key: HKEY
1338
An already open key, or any one of the predefined HKEY_* constants.
1339
sub_key: Py_UNICODE
1340
A string that identifies the sub-key to load.
1341
file_name: Py_UNICODE
1342
The name of the file to load registry data from. This file must
1343
have been created with the SaveKey() function. Under the file
1344
allocation table (FAT) file system, the filename may not have an
1345
extension.
1346
/
1347
1348
Insert data into the registry from a file.
1349
1350
Creates a subkey under the specified key and stores registration
1351
information from a specified file into that subkey.
1352
1353
A call to LoadKey() fails if the calling process does not have the
1354
SE_RESTORE_PRIVILEGE privilege.
1355
1356
If key is a handle returned by ConnectRegistry(), then the path
1357
specified in fileName is relative to the remote computer.
1358
1359
The MSDN docs imply key must be in the HKEY_USER or HKEY_LOCAL_MACHINE
1360
tree.
1361
[clinic start generated code]*/
1362
1363
static PyObject *
1364
winreg_LoadKey_impl(PyObject *module, HKEY key, const wchar_t *sub_key,
1365
const wchar_t *file_name)
1366
/*[clinic end generated code: output=5561b0216e5ab263 input=e3b5b45ade311582]*/
1367
{
1368
long rc;
1369
1370
if (PySys_Audit("winreg.LoadKey", "nuu",
1371
(Py_ssize_t)key, sub_key, file_name) < 0) {
1372
return NULL;
1373
}
1374
Py_BEGIN_ALLOW_THREADS
1375
rc = RegLoadKeyW(key, sub_key, file_name );
1376
Py_END_ALLOW_THREADS
1377
if (rc != ERROR_SUCCESS)
1378
return PyErr_SetFromWindowsErrWithFunction(rc, "RegLoadKey");
1379
Py_RETURN_NONE;
1380
}
1381
1382
#endif /* MS_WINDOWS_DESKTOP || MS_WINDOWS_SYSTEM */
1383
1384
/*[clinic input]
1385
winreg.OpenKey -> HKEY
1386
1387
key: HKEY
1388
An already open key, or any one of the predefined HKEY_* constants.
1389
sub_key: Py_UNICODE(accept={str, NoneType})
1390
A string that identifies the sub_key to open.
1391
reserved: int = 0
1392
A reserved integer that must be zero. Default is zero.
1393
access: REGSAM(c_default='KEY_READ') = winreg.KEY_READ
1394
An integer that specifies an access mask that describes the desired
1395
security access for the key. Default is KEY_READ.
1396
1397
Opens the specified key.
1398
1399
The result is a new handle to the specified key.
1400
If the function fails, an OSError exception is raised.
1401
[clinic start generated code]*/
1402
1403
static HKEY
1404
winreg_OpenKey_impl(PyObject *module, HKEY key, const wchar_t *sub_key,
1405
int reserved, REGSAM access)
1406
/*[clinic end generated code: output=5efbad23b3ffe2e7 input=098505ac36a9ae28]*/
1407
{
1408
HKEY retKey;
1409
long rc;
1410
1411
if (PySys_Audit("winreg.OpenKey", "nun",
1412
(Py_ssize_t)key, sub_key,
1413
(Py_ssize_t)access) < 0) {
1414
return NULL;
1415
}
1416
Py_BEGIN_ALLOW_THREADS
1417
rc = RegOpenKeyExW(key, sub_key, reserved, access, &retKey);
1418
Py_END_ALLOW_THREADS
1419
if (rc != ERROR_SUCCESS) {
1420
PyErr_SetFromWindowsErrWithFunction(rc, "RegOpenKeyEx");
1421
return NULL;
1422
}
1423
if (PySys_Audit("winreg.OpenKey/result", "n",
1424
(Py_ssize_t)retKey) < 0) {
1425
return NULL;
1426
}
1427
return retKey;
1428
}
1429
1430
/*[clinic input]
1431
winreg.OpenKeyEx = winreg.OpenKey
1432
1433
Opens the specified key.
1434
1435
The result is a new handle to the specified key.
1436
If the function fails, an OSError exception is raised.
1437
[clinic start generated code]*/
1438
1439
static HKEY
1440
winreg_OpenKeyEx_impl(PyObject *module, HKEY key, const wchar_t *sub_key,
1441
int reserved, REGSAM access)
1442
/*[clinic end generated code: output=435e675800fa78c2 input=c6c4972af8622959]*/
1443
{
1444
return winreg_OpenKey_impl(module, key, sub_key, reserved, access);
1445
}
1446
1447
/*[clinic input]
1448
winreg.QueryInfoKey
1449
1450
key: HKEY
1451
An already open key, or any one of the predefined HKEY_* constants.
1452
/
1453
1454
Returns information about a key.
1455
1456
The result is a tuple of 3 items:
1457
An integer that identifies the number of sub keys this key has.
1458
An integer that identifies the number of values this key has.
1459
An integer that identifies when the key was last modified (if available)
1460
as 100's of nanoseconds since Jan 1, 1600.
1461
[clinic start generated code]*/
1462
1463
static PyObject *
1464
winreg_QueryInfoKey_impl(PyObject *module, HKEY key)
1465
/*[clinic end generated code: output=dc657b8356a4f438 input=c3593802390cde1f]*/
1466
{
1467
long rc;
1468
DWORD nSubKeys, nValues;
1469
FILETIME ft;
1470
LARGE_INTEGER li;
1471
PyObject *l;
1472
PyObject *ret;
1473
1474
if (PySys_Audit("winreg.QueryInfoKey", "n", (Py_ssize_t)key) < 0) {
1475
return NULL;
1476
}
1477
if ((rc = RegQueryInfoKeyW(key, NULL, NULL, 0, &nSubKeys, NULL, NULL,
1478
&nValues, NULL, NULL, NULL, &ft))
1479
!= ERROR_SUCCESS) {
1480
return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryInfoKey");
1481
}
1482
li.LowPart = ft.dwLowDateTime;
1483
li.HighPart = ft.dwHighDateTime;
1484
l = PyLong_FromLongLong(li.QuadPart);
1485
if (l == NULL) {
1486
return NULL;
1487
}
1488
ret = Py_BuildValue("iiO", nSubKeys, nValues, l);
1489
Py_DECREF(l);
1490
return ret;
1491
}
1492
1493
1494
/*[clinic input]
1495
winreg.QueryValue
1496
1497
key: HKEY
1498
An already open key, or any one of the predefined HKEY_* constants.
1499
sub_key: Py_UNICODE(accept={str, NoneType})
1500
A string that holds the name of the subkey with which the value
1501
is associated. If this parameter is None or empty, the function
1502
retrieves the value set by the SetValue() method for the key
1503
identified by key.
1504
/
1505
1506
Retrieves the unnamed value for a key.
1507
1508
Values in the registry have name, type, and data components. This method
1509
retrieves the data for a key's first value that has a NULL name.
1510
But since the underlying API call doesn't return the type, you'll
1511
probably be happier using QueryValueEx; this function is just here for
1512
completeness.
1513
[clinic start generated code]*/
1514
1515
static PyObject *
1516
winreg_QueryValue_impl(PyObject *module, HKEY key, const wchar_t *sub_key)
1517
/*[clinic end generated code: output=b665ce9ae391fda9 input=41cafbbf423b21d6]*/
1518
{
1519
LONG rc;
1520
HKEY childKey = key;
1521
WCHAR buf[256], *pbuf = buf;
1522
DWORD size = sizeof(buf);
1523
DWORD type;
1524
Py_ssize_t length;
1525
PyObject *result = NULL;
1526
1527
if (PySys_Audit("winreg.QueryValue", "nuu",
1528
(Py_ssize_t)key, sub_key, NULL) < 0)
1529
{
1530
return NULL;
1531
}
1532
1533
if (key == HKEY_PERFORMANCE_DATA) {
1534
return PyErr_SetFromWindowsErrWithFunction(ERROR_INVALID_HANDLE,
1535
"RegQueryValue");
1536
}
1537
1538
if (sub_key && sub_key[0]) {
1539
Py_BEGIN_ALLOW_THREADS
1540
rc = RegOpenKeyExW(key, sub_key, 0, KEY_QUERY_VALUE, &childKey);
1541
Py_END_ALLOW_THREADS
1542
if (rc != ERROR_SUCCESS) {
1543
return PyErr_SetFromWindowsErrWithFunction(rc, "RegOpenKeyEx");
1544
}
1545
}
1546
1547
while (1) {
1548
Py_BEGIN_ALLOW_THREADS
1549
rc = RegQueryValueExW(childKey, NULL, NULL, &type, (LPBYTE)pbuf,
1550
&size);
1551
Py_END_ALLOW_THREADS
1552
if (rc != ERROR_MORE_DATA) {
1553
break;
1554
}
1555
void *tmp = PyMem_Realloc(pbuf != buf ? pbuf : NULL, size);
1556
if (tmp == NULL) {
1557
PyErr_NoMemory();
1558
goto exit;
1559
}
1560
pbuf = tmp;
1561
}
1562
1563
if (rc == ERROR_SUCCESS) {
1564
if (type != REG_SZ) {
1565
PyErr_SetFromWindowsErrWithFunction(ERROR_INVALID_DATA,
1566
"RegQueryValue");
1567
goto exit;
1568
}
1569
length = wcsnlen(pbuf, size / sizeof(WCHAR));
1570
}
1571
else if (rc == ERROR_FILE_NOT_FOUND) {
1572
// Return an empty string if there's no default value.
1573
length = 0;
1574
}
1575
else {
1576
PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValueEx");
1577
goto exit;
1578
}
1579
1580
result = PyUnicode_FromWideChar(pbuf, length);
1581
1582
exit:
1583
if (pbuf != buf) {
1584
PyMem_Free(pbuf);
1585
}
1586
if (childKey != key) {
1587
RegCloseKey(childKey);
1588
}
1589
return result;
1590
}
1591
1592
1593
/*[clinic input]
1594
winreg.QueryValueEx
1595
1596
key: HKEY
1597
An already open key, or any one of the predefined HKEY_* constants.
1598
name: Py_UNICODE(accept={str, NoneType})
1599
A string indicating the value to query.
1600
/
1601
1602
Retrieves the type and value of a specified sub-key.
1603
1604
Behaves mostly like QueryValue(), but also returns the type of the
1605
specified value name associated with the given open registry key.
1606
1607
The return value is a tuple of the value and the type_id.
1608
[clinic start generated code]*/
1609
1610
static PyObject *
1611
winreg_QueryValueEx_impl(PyObject *module, HKEY key, const wchar_t *name)
1612
/*[clinic end generated code: output=2cdecaa44c8c333e input=cf366cada4836891]*/
1613
{
1614
long rc;
1615
BYTE *retBuf, *tmp;
1616
DWORD bufSize = 0, retSize;
1617
DWORD typ;
1618
PyObject *obData;
1619
PyObject *result;
1620
1621
if (PySys_Audit("winreg.QueryValue", "nuu",
1622
(Py_ssize_t)key, NULL, name) < 0) {
1623
return NULL;
1624
}
1625
rc = RegQueryValueExW(key, name, NULL, NULL, NULL, &bufSize);
1626
if (rc == ERROR_MORE_DATA)
1627
bufSize = 256;
1628
else if (rc != ERROR_SUCCESS)
1629
return PyErr_SetFromWindowsErrWithFunction(rc,
1630
"RegQueryValueEx");
1631
retBuf = (BYTE *)PyMem_Malloc(bufSize);
1632
if (retBuf == NULL)
1633
return PyErr_NoMemory();
1634
1635
while (1) {
1636
retSize = bufSize;
1637
rc = RegQueryValueExW(key, name, NULL, &typ,
1638
(BYTE *)retBuf, &retSize);
1639
if (rc != ERROR_MORE_DATA)
1640
break;
1641
1642
bufSize *= 2;
1643
tmp = (char *) PyMem_Realloc(retBuf, bufSize);
1644
if (tmp == NULL) {
1645
PyMem_Free(retBuf);
1646
return PyErr_NoMemory();
1647
}
1648
retBuf = tmp;
1649
}
1650
1651
if (rc != ERROR_SUCCESS) {
1652
PyMem_Free(retBuf);
1653
return PyErr_SetFromWindowsErrWithFunction(rc,
1654
"RegQueryValueEx");
1655
}
1656
obData = Reg2Py(retBuf, bufSize, typ);
1657
PyMem_Free(retBuf);
1658
if (obData == NULL)
1659
return NULL;
1660
result = Py_BuildValue("Oi", obData, typ);
1661
Py_DECREF(obData);
1662
return result;
1663
}
1664
1665
#if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
1666
1667
/*[clinic input]
1668
winreg.SaveKey
1669
1670
key: HKEY
1671
An already open key, or any one of the predefined HKEY_* constants.
1672
file_name: Py_UNICODE
1673
The name of the file to save registry data to. This file cannot
1674
already exist. If this filename includes an extension, it cannot be
1675
used on file allocation table (FAT) file systems by the LoadKey(),
1676
ReplaceKey() or RestoreKey() methods.
1677
/
1678
1679
Saves the specified key, and all its subkeys to the specified file.
1680
1681
If key represents a key on a remote computer, the path described by
1682
file_name is relative to the remote computer.
1683
1684
The caller of this method must possess the SeBackupPrivilege
1685
security privilege. This function passes NULL for security_attributes
1686
to the API.
1687
[clinic start generated code]*/
1688
1689
static PyObject *
1690
winreg_SaveKey_impl(PyObject *module, HKEY key, const wchar_t *file_name)
1691
/*[clinic end generated code: output=249b1b58b9598eef input=da735241f91ac7a2]*/
1692
{
1693
LPSECURITY_ATTRIBUTES pSA = NULL;
1694
1695
long rc;
1696
/* One day we may get security into the core?
1697
if (!PyWinObject_AsSECURITY_ATTRIBUTES(obSA, &pSA, TRUE))
1698
return NULL;
1699
*/
1700
if (PySys_Audit("winreg.SaveKey", "nu",
1701
(Py_ssize_t)key, file_name) < 0) {
1702
return NULL;
1703
}
1704
Py_BEGIN_ALLOW_THREADS
1705
rc = RegSaveKeyW(key, file_name, pSA );
1706
Py_END_ALLOW_THREADS
1707
if (rc != ERROR_SUCCESS)
1708
return PyErr_SetFromWindowsErrWithFunction(rc, "RegSaveKey");
1709
Py_RETURN_NONE;
1710
}
1711
1712
#endif /* MS_WINDOWS_DESKTOP || MS_WINDOWS_SYSTEM */
1713
1714
/*[clinic input]
1715
winreg.SetValue
1716
1717
key: HKEY
1718
An already open key, or any one of the predefined HKEY_* constants.
1719
sub_key: Py_UNICODE(accept={str, NoneType})
1720
A string that names the subkey with which the value is associated.
1721
type: DWORD
1722
An integer that specifies the type of the data. Currently this must
1723
be REG_SZ, meaning only strings are supported.
1724
value as value_obj: unicode
1725
A string that specifies the new value.
1726
/
1727
1728
Associates a value with a specified key.
1729
1730
If the key specified by the sub_key parameter does not exist, the
1731
SetValue function creates it.
1732
1733
Value lengths are limited by available memory. Long values (more than
1734
2048 bytes) should be stored as files with the filenames stored in
1735
the configuration registry to help the registry perform efficiently.
1736
1737
The key identified by the key parameter must have been opened with
1738
KEY_SET_VALUE access.
1739
[clinic start generated code]*/
1740
1741
static PyObject *
1742
winreg_SetValue_impl(PyObject *module, HKEY key, const wchar_t *sub_key,
1743
DWORD type, PyObject *value_obj)
1744
/*[clinic end generated code: output=de590747df47d2c7 input=bf088494ae2d24fd]*/
1745
{
1746
LONG rc;
1747
HKEY childKey = key;
1748
LPWSTR value;
1749
Py_ssize_t size;
1750
Py_ssize_t length;
1751
PyObject *result = NULL;
1752
1753
if (type != REG_SZ) {
1754
PyErr_SetString(PyExc_TypeError, "type must be winreg.REG_SZ");
1755
return NULL;
1756
}
1757
1758
value = PyUnicode_AsWideCharString(value_obj, &length);
1759
if (value == NULL) {
1760
return NULL;
1761
}
1762
1763
size = (length + 1) * sizeof(WCHAR);
1764
if ((Py_ssize_t)(DWORD)size != size) {
1765
PyErr_SetString(PyExc_OverflowError, "value is too long");
1766
goto exit;
1767
}
1768
1769
if (PySys_Audit("winreg.SetValue", "nunu#",
1770
(Py_ssize_t)key, sub_key, (Py_ssize_t)type,
1771
value, length) < 0)
1772
{
1773
goto exit;
1774
}
1775
1776
if (key == HKEY_PERFORMANCE_DATA) {
1777
PyErr_SetFromWindowsErrWithFunction(ERROR_INVALID_HANDLE,
1778
"RegSetValue");
1779
goto exit;
1780
}
1781
1782
if (sub_key && sub_key[0]) {
1783
Py_BEGIN_ALLOW_THREADS
1784
rc = RegCreateKeyExW(key, sub_key, 0, NULL, 0, KEY_SET_VALUE, NULL,
1785
&childKey, NULL);
1786
Py_END_ALLOW_THREADS
1787
if (rc != ERROR_SUCCESS) {
1788
PyErr_SetFromWindowsErrWithFunction(rc, "RegCreateKeyEx");
1789
goto exit;
1790
}
1791
}
1792
1793
Py_BEGIN_ALLOW_THREADS
1794
rc = RegSetValueExW(childKey, NULL, 0, REG_SZ, (LPBYTE)value, (DWORD)size);
1795
Py_END_ALLOW_THREADS
1796
if (rc == ERROR_SUCCESS) {
1797
result = Py_NewRef(Py_None);
1798
}
1799
else {
1800
PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValueEx");
1801
}
1802
1803
exit:
1804
PyMem_Free(value);
1805
if (childKey != key) {
1806
RegCloseKey(childKey);
1807
}
1808
return result;
1809
}
1810
1811
1812
/*[clinic input]
1813
winreg.SetValueEx
1814
1815
key: HKEY
1816
An already open key, or any one of the predefined HKEY_* constants.
1817
value_name: Py_UNICODE(accept={str, NoneType})
1818
A string containing the name of the value to set, or None.
1819
reserved: object
1820
Can be anything - zero is always passed to the API.
1821
type: DWORD
1822
An integer that specifies the type of the data, one of:
1823
REG_BINARY -- Binary data in any form.
1824
REG_DWORD -- A 32-bit number.
1825
REG_DWORD_LITTLE_ENDIAN -- A 32-bit number in little-endian format. Equivalent to REG_DWORD
1826
REG_DWORD_BIG_ENDIAN -- A 32-bit number in big-endian format.
1827
REG_EXPAND_SZ -- A null-terminated string that contains unexpanded
1828
references to environment variables (for example,
1829
%PATH%).
1830
REG_LINK -- A Unicode symbolic link.
1831
REG_MULTI_SZ -- A sequence of null-terminated strings, terminated
1832
by two null characters. Note that Python handles
1833
this termination automatically.
1834
REG_NONE -- No defined value type.
1835
REG_QWORD -- A 64-bit number.
1836
REG_QWORD_LITTLE_ENDIAN -- A 64-bit number in little-endian format. Equivalent to REG_QWORD.
1837
REG_RESOURCE_LIST -- A device-driver resource list.
1838
REG_SZ -- A null-terminated string.
1839
value: object
1840
A string that specifies the new value.
1841
/
1842
1843
Stores data in the value field of an open registry key.
1844
1845
This method can also set additional value and type information for the
1846
specified key. The key identified by the key parameter must have been
1847
opened with KEY_SET_VALUE access.
1848
1849
To open the key, use the CreateKeyEx() or OpenKeyEx() methods.
1850
1851
Value lengths are limited by available memory. Long values (more than
1852
2048 bytes) should be stored as files with the filenames stored in
1853
the configuration registry to help the registry perform efficiently.
1854
[clinic start generated code]*/
1855
1856
static PyObject *
1857
winreg_SetValueEx_impl(PyObject *module, HKEY key, const wchar_t *value_name,
1858
PyObject *reserved, DWORD type, PyObject *value)
1859
/*[clinic end generated code: output=295db04deb456d9e input=900a9e3990bfb196]*/
1860
{
1861
LONG rc;
1862
BYTE *data = NULL;
1863
DWORD size;
1864
PyObject *result = NULL;
1865
1866
if (!Py2Reg(value, type, &data, &size))
1867
{
1868
if (!PyErr_Occurred()) {
1869
PyErr_SetString(PyExc_ValueError,
1870
"Could not convert the data to the specified type.");
1871
}
1872
return NULL;
1873
}
1874
if (PySys_Audit("winreg.SetValue", "nunO",
1875
(Py_ssize_t)key, value_name, (Py_ssize_t)type,
1876
value) < 0)
1877
{
1878
goto exit;
1879
}
1880
1881
Py_BEGIN_ALLOW_THREADS
1882
rc = RegSetValueExW(key, value_name, 0, type, data, size);
1883
Py_END_ALLOW_THREADS
1884
if (rc == ERROR_SUCCESS) {
1885
result = Py_NewRef(Py_None);
1886
}
1887
else {
1888
PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValueEx");
1889
}
1890
1891
exit:
1892
PyMem_Free(data);
1893
return result;
1894
}
1895
1896
#if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
1897
1898
/*[clinic input]
1899
winreg.DisableReflectionKey
1900
1901
key: HKEY
1902
An already open key, or any one of the predefined HKEY_* constants.
1903
/
1904
1905
Disables registry reflection for 32bit processes running on a 64bit OS.
1906
1907
Will generally raise NotImplementedError if executed on a 32bit OS.
1908
1909
If the key is not on the reflection list, the function succeeds but has
1910
no effect. Disabling reflection for a key does not affect reflection
1911
of any subkeys.
1912
[clinic start generated code]*/
1913
1914
static PyObject *
1915
winreg_DisableReflectionKey_impl(PyObject *module, HKEY key)
1916
/*[clinic end generated code: output=830cce504cc764b4 input=70bece2dee02e073]*/
1917
{
1918
HMODULE hMod;
1919
typedef LONG (WINAPI *RDRKFunc)(HKEY);
1920
RDRKFunc pfn = NULL;
1921
LONG rc;
1922
1923
if (PySys_Audit("winreg.DisableReflectionKey", "n", (Py_ssize_t)key) < 0) {
1924
return NULL;
1925
}
1926
1927
/* Only available on 64bit platforms, so we must load it
1928
dynamically.*/
1929
Py_BEGIN_ALLOW_THREADS
1930
hMod = GetModuleHandleW(L"advapi32.dll");
1931
if (hMod)
1932
pfn = (RDRKFunc)GetProcAddress(hMod,
1933
"RegDisableReflectionKey");
1934
Py_END_ALLOW_THREADS
1935
if (!pfn) {
1936
PyErr_SetString(PyExc_NotImplementedError,
1937
"not implemented on this platform");
1938
return NULL;
1939
}
1940
Py_BEGIN_ALLOW_THREADS
1941
rc = (*pfn)(key);
1942
Py_END_ALLOW_THREADS
1943
if (rc != ERROR_SUCCESS)
1944
return PyErr_SetFromWindowsErrWithFunction(rc,
1945
"RegDisableReflectionKey");
1946
Py_RETURN_NONE;
1947
}
1948
1949
/*[clinic input]
1950
winreg.EnableReflectionKey
1951
1952
key: HKEY
1953
An already open key, or any one of the predefined HKEY_* constants.
1954
/
1955
1956
Restores registry reflection for the specified disabled key.
1957
1958
Will generally raise NotImplementedError if executed on a 32bit OS.
1959
Restoring reflection for a key does not affect reflection of any
1960
subkeys.
1961
[clinic start generated code]*/
1962
1963
static PyObject *
1964
winreg_EnableReflectionKey_impl(PyObject *module, HKEY key)
1965
/*[clinic end generated code: output=86fa1385fdd9ce57 input=eeae770c6eb9f559]*/
1966
{
1967
HMODULE hMod;
1968
typedef LONG (WINAPI *RERKFunc)(HKEY);
1969
RERKFunc pfn = NULL;
1970
LONG rc;
1971
1972
if (PySys_Audit("winreg.EnableReflectionKey", "n", (Py_ssize_t)key) < 0) {
1973
return NULL;
1974
}
1975
1976
/* Only available on 64bit platforms, so we must load it
1977
dynamically.*/
1978
Py_BEGIN_ALLOW_THREADS
1979
hMod = GetModuleHandleW(L"advapi32.dll");
1980
if (hMod)
1981
pfn = (RERKFunc)GetProcAddress(hMod,
1982
"RegEnableReflectionKey");
1983
Py_END_ALLOW_THREADS
1984
if (!pfn) {
1985
PyErr_SetString(PyExc_NotImplementedError,
1986
"not implemented on this platform");
1987
return NULL;
1988
}
1989
Py_BEGIN_ALLOW_THREADS
1990
rc = (*pfn)(key);
1991
Py_END_ALLOW_THREADS
1992
if (rc != ERROR_SUCCESS)
1993
return PyErr_SetFromWindowsErrWithFunction(rc,
1994
"RegEnableReflectionKey");
1995
Py_RETURN_NONE;
1996
}
1997
1998
/*[clinic input]
1999
winreg.QueryReflectionKey
2000
2001
key: HKEY
2002
An already open key, or any one of the predefined HKEY_* constants.
2003
/
2004
2005
Returns the reflection state for the specified key as a bool.
2006
2007
Will generally raise NotImplementedError if executed on a 32bit OS.
2008
[clinic start generated code]*/
2009
2010
static PyObject *
2011
winreg_QueryReflectionKey_impl(PyObject *module, HKEY key)
2012
/*[clinic end generated code: output=4e774af288c3ebb9 input=a98fa51d55ade186]*/
2013
{
2014
HMODULE hMod;
2015
typedef LONG (WINAPI *RQRKFunc)(HKEY, BOOL *);
2016
RQRKFunc pfn = NULL;
2017
BOOL result;
2018
LONG rc;
2019
2020
if (PySys_Audit("winreg.QueryReflectionKey", "n", (Py_ssize_t)key) < 0) {
2021
return NULL;
2022
}
2023
2024
/* Only available on 64bit platforms, so we must load it
2025
dynamically.*/
2026
Py_BEGIN_ALLOW_THREADS
2027
hMod = GetModuleHandleW(L"advapi32.dll");
2028
if (hMod)
2029
pfn = (RQRKFunc)GetProcAddress(hMod,
2030
"RegQueryReflectionKey");
2031
Py_END_ALLOW_THREADS
2032
if (!pfn) {
2033
PyErr_SetString(PyExc_NotImplementedError,
2034
"not implemented on this platform");
2035
return NULL;
2036
}
2037
Py_BEGIN_ALLOW_THREADS
2038
rc = (*pfn)(key, &result);
2039
Py_END_ALLOW_THREADS
2040
if (rc != ERROR_SUCCESS)
2041
return PyErr_SetFromWindowsErrWithFunction(rc,
2042
"RegQueryReflectionKey");
2043
return PyBool_FromLong(result);
2044
}
2045
2046
#endif /* MS_WINDOWS_DESKTOP || MS_WINDOWS_SYSTEM */
2047
2048
static struct PyMethodDef winreg_methods[] = {
2049
WINREG_CLOSEKEY_METHODDEF
2050
WINREG_CONNECTREGISTRY_METHODDEF
2051
WINREG_CREATEKEY_METHODDEF
2052
WINREG_CREATEKEYEX_METHODDEF
2053
WINREG_DELETEKEY_METHODDEF
2054
WINREG_DELETEKEYEX_METHODDEF
2055
WINREG_DELETEVALUE_METHODDEF
2056
WINREG_DISABLEREFLECTIONKEY_METHODDEF
2057
WINREG_ENABLEREFLECTIONKEY_METHODDEF
2058
WINREG_ENUMKEY_METHODDEF
2059
WINREG_ENUMVALUE_METHODDEF
2060
WINREG_EXPANDENVIRONMENTSTRINGS_METHODDEF
2061
WINREG_FLUSHKEY_METHODDEF
2062
WINREG_LOADKEY_METHODDEF
2063
WINREG_OPENKEY_METHODDEF
2064
WINREG_OPENKEYEX_METHODDEF
2065
WINREG_QUERYVALUE_METHODDEF
2066
WINREG_QUERYVALUEEX_METHODDEF
2067
WINREG_QUERYINFOKEY_METHODDEF
2068
WINREG_QUERYREFLECTIONKEY_METHODDEF
2069
WINREG_SAVEKEY_METHODDEF
2070
WINREG_SETVALUE_METHODDEF
2071
WINREG_SETVALUEEX_METHODDEF
2072
NULL,
2073
};
2074
2075
#define ADD_INT(VAL) do { \
2076
if (PyModule_AddIntConstant(m, #VAL, VAL) < 0) { \
2077
return -1; \
2078
} \
2079
} while (0)
2080
2081
static int
2082
inskey(PyObject *mod, char *name, HKEY key)
2083
{
2084
PyObject *v = PyLong_FromVoidPtr(key);
2085
if (v == NULL) {
2086
return -1;
2087
}
2088
int rc = PyModule_AddObjectRef(mod, name, v);
2089
Py_DECREF(v);
2090
return rc;
2091
}
2092
2093
#define ADD_KEY(VAL) do { \
2094
if (inskey(m, #VAL, VAL) < 0) { \
2095
return -1; \
2096
} \
2097
} while (0)
2098
2099
static int
2100
exec_module(PyObject *m)
2101
{
2102
winreg_state *st = (winreg_state *)_PyModule_GetState(m);
2103
2104
st->PyHKEY_Type = (PyTypeObject *)
2105
PyType_FromModuleAndSpec(m, &pyhkey_type_spec, NULL);
2106
if (st->PyHKEY_Type == NULL) {
2107
return -1;
2108
}
2109
if (PyModule_AddObjectRef(m, "HKEYType", (PyObject *)st->PyHKEY_Type) < 0) {
2110
return -1;
2111
}
2112
if (PyModule_AddObjectRef(m, "error", PyExc_OSError) < 0) {
2113
return -1;
2114
}
2115
2116
/* Add the relevant constants */
2117
ADD_KEY(HKEY_CLASSES_ROOT);
2118
ADD_KEY(HKEY_CURRENT_USER);
2119
ADD_KEY(HKEY_LOCAL_MACHINE);
2120
ADD_KEY(HKEY_USERS);
2121
ADD_KEY(HKEY_PERFORMANCE_DATA);
2122
#ifdef HKEY_CURRENT_CONFIG
2123
ADD_KEY(HKEY_CURRENT_CONFIG);
2124
#endif
2125
#ifdef HKEY_DYN_DATA
2126
ADD_KEY(HKEY_DYN_DATA);
2127
#endif
2128
ADD_INT(KEY_QUERY_VALUE);
2129
ADD_INT(KEY_SET_VALUE);
2130
ADD_INT(KEY_CREATE_SUB_KEY);
2131
ADD_INT(KEY_ENUMERATE_SUB_KEYS);
2132
ADD_INT(KEY_NOTIFY);
2133
ADD_INT(KEY_CREATE_LINK);
2134
ADD_INT(KEY_READ);
2135
ADD_INT(KEY_WRITE);
2136
ADD_INT(KEY_EXECUTE);
2137
ADD_INT(KEY_ALL_ACCESS);
2138
#ifdef KEY_WOW64_64KEY
2139
ADD_INT(KEY_WOW64_64KEY);
2140
#endif
2141
#ifdef KEY_WOW64_32KEY
2142
ADD_INT(KEY_WOW64_32KEY);
2143
#endif
2144
ADD_INT(REG_OPTION_RESERVED);
2145
ADD_INT(REG_OPTION_NON_VOLATILE);
2146
ADD_INT(REG_OPTION_VOLATILE);
2147
ADD_INT(REG_OPTION_CREATE_LINK);
2148
ADD_INT(REG_OPTION_BACKUP_RESTORE);
2149
ADD_INT(REG_OPTION_OPEN_LINK);
2150
ADD_INT(REG_LEGAL_OPTION);
2151
ADD_INT(REG_CREATED_NEW_KEY);
2152
ADD_INT(REG_OPENED_EXISTING_KEY);
2153
ADD_INT(REG_WHOLE_HIVE_VOLATILE);
2154
ADD_INT(REG_REFRESH_HIVE);
2155
ADD_INT(REG_NO_LAZY_FLUSH);
2156
ADD_INT(REG_NOTIFY_CHANGE_NAME);
2157
ADD_INT(REG_NOTIFY_CHANGE_ATTRIBUTES);
2158
ADD_INT(REG_NOTIFY_CHANGE_LAST_SET);
2159
ADD_INT(REG_NOTIFY_CHANGE_SECURITY);
2160
ADD_INT(REG_LEGAL_CHANGE_FILTER);
2161
ADD_INT(REG_NONE);
2162
ADD_INT(REG_SZ);
2163
ADD_INT(REG_EXPAND_SZ);
2164
ADD_INT(REG_BINARY);
2165
ADD_INT(REG_DWORD);
2166
ADD_INT(REG_DWORD_LITTLE_ENDIAN);
2167
ADD_INT(REG_DWORD_BIG_ENDIAN);
2168
ADD_INT(REG_QWORD);
2169
ADD_INT(REG_QWORD_LITTLE_ENDIAN);
2170
ADD_INT(REG_LINK);
2171
ADD_INT(REG_MULTI_SZ);
2172
ADD_INT(REG_RESOURCE_LIST);
2173
ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR);
2174
ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST);
2175
2176
#undef ADD_INT
2177
return 0;
2178
}
2179
2180
static PyModuleDef_Slot winreg_slots[] = {
2181
{Py_mod_exec, exec_module},
2182
{Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
2183
{0, NULL}
2184
};
2185
2186
static int
2187
winreg_traverse(PyObject *module, visitproc visit, void *arg)
2188
{
2189
winreg_state *state = _PyModule_GetState(module);
2190
Py_VISIT(state->PyHKEY_Type);
2191
return 0;
2192
}
2193
2194
static int
2195
winreg_clear(PyObject *module)
2196
{
2197
winreg_state *state = _PyModule_GetState(module);
2198
Py_CLEAR(state->PyHKEY_Type);
2199
return 0;
2200
}
2201
2202
static struct PyModuleDef winregmodule = {
2203
.m_base = PyModuleDef_HEAD_INIT,
2204
.m_name = "winreg",
2205
.m_doc = module_doc,
2206
.m_size = sizeof(winreg_state),
2207
.m_methods = winreg_methods,
2208
.m_slots = winreg_slots,
2209
.m_traverse = winreg_traverse,
2210
.m_clear = winreg_clear,
2211
};
2212
2213
PyMODINIT_FUNC PyInit_winreg(void)
2214
{
2215
return PyModuleDef_Init(&winregmodule);
2216
}
2217
2218
#endif /* MS_WINDOWS_DESKTOP || MS_WINDOWS_SYSTEM || MS_WINDOWS_GAMES */
2219
2220