forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
winreg.c
1956 lines (1692 loc) · 59.7 KB
/
winreg.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
winreg.c
Windows Registry access module for Python.
* Simple registry access written by Mark Hammond in win32api
module circa 1995.
* Bill Tutt expanded the support significantly not long after.
* Numerous other people have submitted patches since then.
* Ripped from win32api module 03-Feb-2000 by Mark Hammond, and
basic Unicode support added.
*/
#include "Python.h"
#include "structmember.h"
#include "windows.h"
static BOOL PyHKEY_AsHKEY(PyObject *ob, HKEY *pRes, BOOL bNoneOK);
static BOOL clinic_HKEY_converter(PyObject *ob, void *p);
static PyObject *PyHKEY_FromHKEY(HKEY h);
static BOOL PyHKEY_Close(PyObject *obHandle);
static char errNotAHandle[] = "Object is not a handle";
/* The win32api module reports the function name that failed,
but this concept is not in the Python core.
Hopefully it will one day, and in the meantime I dont
want to lose this info...
*/
#define PyErr_SetFromWindowsErrWithFunction(rc, fnname) \
PyErr_SetFromWindowsErr(rc)
/* Forward declares */
/* Doc strings */
PyDoc_STRVAR(module_doc,
"This module provides access to the Windows registry API.\n"
"\n"
"Functions:\n"
"\n"
"CloseKey() - Closes a registry key.\n"
"ConnectRegistry() - Establishes a connection to a predefined registry handle\n"
" on another computer.\n"
"CreateKey() - Creates the specified key, or opens it if it already exists.\n"
"DeleteKey() - Deletes the specified key.\n"
"DeleteValue() - Removes a named value from the specified registry key.\n"
"EnumKey() - Enumerates subkeys of the specified open registry key.\n"
"EnumValue() - Enumerates values of the specified open registry key.\n"
"ExpandEnvironmentStrings() - Expand the env strings in a REG_EXPAND_SZ\n"
" string.\n"
"FlushKey() - Writes all the attributes of the specified key to the registry.\n"
"LoadKey() - Creates a subkey under HKEY_USER or HKEY_LOCAL_MACHINE and\n"
" stores registration information from a specified file into that\n"
" subkey.\n"
"OpenKey() - Opens the specified key.\n"
"OpenKeyEx() - Alias of OpenKey().\n"
"QueryValue() - Retrieves the value associated with the unnamed value for a\n"
" specified key in the registry.\n"
"QueryValueEx() - Retrieves the type and data for a specified value name\n"
" associated with an open registry key.\n"
"QueryInfoKey() - Returns information about the specified key.\n"
"SaveKey() - Saves the specified key, and all its subkeys a file.\n"
"SetValue() - Associates a value with a specified key.\n"
"SetValueEx() - Stores data in the value field of an open registry key.\n"
"\n"
"Special objects:\n"
"\n"
"HKEYType -- type object for HKEY objects\n"
"error -- exception raised for Win32 errors\n"
"\n"
"Integer constants:\n"
"Many constants are defined - see the documentation for each function\n"
"to see what constants are used, and where.");
/* PyHKEY docstrings */
PyDoc_STRVAR(PyHKEY_doc,
"PyHKEY Object - A Python object, representing a win32 registry key.\n"
"\n"
"This object wraps a Windows HKEY object, automatically closing it when\n"
"the object is destroyed. To guarantee cleanup, you can call either\n"
"the Close() method on the PyHKEY, or the CloseKey() method.\n"
"\n"
"All functions which accept a handle object also accept an integer - \n"
"however, use of the handle object is encouraged.\n"
"\n"
"Functions:\n"
"Close() - Closes the underlying handle.\n"
"Detach() - Returns the integer Win32 handle, detaching it from the object\n"
"\n"
"Properties:\n"
"handle - The integer Win32 handle.\n"
"\n"
"Operations:\n"
"__bool__ - Handles with an open object return true, otherwise false.\n"
"__int__ - Converting a handle to an integer returns the Win32 handle.\n"
"rich comparison - Handle objects are compared using the handle value.");
/************************************************************************
The PyHKEY object definition
************************************************************************/
typedef struct {
PyObject_VAR_HEAD
HKEY hkey;
} PyHKEYObject;
#define PyHKEY_Check(op) ((op)->ob_type == &PyHKEY_Type)
static char *failMsg = "bad operand type";
static PyObject *
PyHKEY_unaryFailureFunc(PyObject *ob)
{
PyErr_SetString(PyExc_TypeError, failMsg);
return NULL;
}
static PyObject *
PyHKEY_binaryFailureFunc(PyObject *ob1, PyObject *ob2)
{
PyErr_SetString(PyExc_TypeError, failMsg);
return NULL;
}
static PyObject *
PyHKEY_ternaryFailureFunc(PyObject *ob1, PyObject *ob2, PyObject *ob3)
{
PyErr_SetString(PyExc_TypeError, failMsg);
return NULL;
}
static void
PyHKEY_deallocFunc(PyObject *ob)
{
/* Can not call PyHKEY_Close, as the ob->tp_type
has already been cleared, thus causing the type
check to fail!
*/
PyHKEYObject *obkey = (PyHKEYObject *)ob;
if (obkey->hkey)
RegCloseKey((HKEY)obkey->hkey);
PyObject_DEL(ob);
}
static int
PyHKEY_boolFunc(PyObject *ob)
{
return ((PyHKEYObject *)ob)->hkey != 0;
}
static PyObject *
PyHKEY_intFunc(PyObject *ob)
{
PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
return PyLong_FromVoidPtr(pyhkey->hkey);
}
static PyObject *
PyHKEY_strFunc(PyObject *ob)
{
PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
return PyUnicode_FromFormat("<PyHKEY:%p>", pyhkey->hkey);
}
static int
PyHKEY_compareFunc(PyObject *ob1, PyObject *ob2)
{
PyHKEYObject *pyhkey1 = (PyHKEYObject *)ob1;
PyHKEYObject *pyhkey2 = (PyHKEYObject *)ob2;
return pyhkey1 == pyhkey2 ? 0 :
(pyhkey1 < pyhkey2 ? -1 : 1);
}
static Py_hash_t
PyHKEY_hashFunc(PyObject *ob)
{
/* Just use the address.
XXX - should we use the handle value?
*/
return _Py_HashPointer(ob);
}
static PyNumberMethods PyHKEY_NumberMethods =
{
PyHKEY_binaryFailureFunc, /* nb_add */
PyHKEY_binaryFailureFunc, /* nb_subtract */
PyHKEY_binaryFailureFunc, /* nb_multiply */
PyHKEY_binaryFailureFunc, /* nb_remainder */
PyHKEY_binaryFailureFunc, /* nb_divmod */
PyHKEY_ternaryFailureFunc, /* nb_power */
PyHKEY_unaryFailureFunc, /* nb_negative */
PyHKEY_unaryFailureFunc, /* nb_positive */
PyHKEY_unaryFailureFunc, /* nb_absolute */
PyHKEY_boolFunc, /* nb_bool */
PyHKEY_unaryFailureFunc, /* nb_invert */
PyHKEY_binaryFailureFunc, /* nb_lshift */
PyHKEY_binaryFailureFunc, /* nb_rshift */
PyHKEY_binaryFailureFunc, /* nb_and */
PyHKEY_binaryFailureFunc, /* nb_xor */
PyHKEY_binaryFailureFunc, /* nb_or */
PyHKEY_intFunc, /* nb_int */
0, /* nb_reserved */
PyHKEY_unaryFailureFunc, /* nb_float */
};
/*[clinic input]
module winreg
class winreg.HKEYType "PyHKEYObject *" "&PyHKEY_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=4c964eba3bf914d6]*/
/*[python input]
class REGSAM_converter(CConverter):
type = 'REGSAM'
format_unit = 'i'
class DWORD_converter(CConverter):
type = 'DWORD'
format_unit = 'k'
class HKEY_converter(CConverter):
type = 'HKEY'
converter = 'clinic_HKEY_converter'
class HKEY_return_converter(CReturnConverter):
type = 'HKEY'
def render(self, function, data):
self.declare(data)
self.err_occurred_if_null_pointer("_return_value", data)
data.return_conversion.append(
'return_value = PyHKEY_FromHKEY(_return_value);\n')
# HACK: this only works for PyHKEYObjects, nothing else.
# Should this be generalized and enshrined in clinic.py,
# destroy this converter with prejudice.
class self_return_converter(CReturnConverter):
type = 'PyHKEYObject *'
def render(self, function, data):
self.declare(data)
data.return_conversion.append(
'return_value = (PyObject *)_return_value;\n')
[python start generated code]*/
/*[python end generated code: output=da39a3ee5e6b4b0d input=22f7aedc6d68e80e]*/
#include "clinic/winreg.c.h"
/************************************************************************
The PyHKEY object methods
************************************************************************/
/*[clinic input]
winreg.HKEYType.Close
Closes the underlying Windows handle.
If the handle is already closed, no error is raised.
[clinic start generated code]*/
static PyObject *
winreg_HKEYType_Close_impl(PyHKEYObject *self)
/*[clinic end generated code: output=fced3a624fb0c344 input=6786ac75f6b89de6]*/
{
if (!PyHKEY_Close((PyObject *)self))
return NULL;
Py_RETURN_NONE;
}
/*[clinic input]
winreg.HKEYType.Detach
Detaches the Windows handle from the handle object.
The result is the value of the handle before it is detached. If the
handle is already detached, this will return zero.
After calling this function, the handle is effectively invalidated,
but the handle is not closed. You would call this function when you
need the underlying win32 handle to exist beyond the lifetime of the
handle object.
[clinic start generated code]*/
static PyObject *
winreg_HKEYType_Detach_impl(PyHKEYObject *self)
/*[clinic end generated code: output=dda5a9e1a01ae78f input=dd2cc09e6c6ba833]*/
{
void* ret;
ret = (void*)self->hkey;
self->hkey = 0;
return PyLong_FromVoidPtr(ret);
}
/*[clinic input]
winreg.HKEYType.__enter__ -> self
[clinic start generated code]*/
static PyHKEYObject *
winreg_HKEYType___enter___impl(PyHKEYObject *self)
/*[clinic end generated code: output=52c34986dab28990 input=c40fab1f0690a8e2]*/
{
Py_XINCREF(self);
return self;
}
/*[clinic input]
winreg.HKEYType.__exit__
exc_type: object
exc_value: object
traceback: object
[clinic start generated code]*/
static PyObject *
winreg_HKEYType___exit___impl(PyHKEYObject *self, PyObject *exc_type,
PyObject *exc_value, PyObject *traceback)
/*[clinic end generated code: output=923ebe7389e6a263 input=fb32489ee92403c7]*/
{
if (!PyHKEY_Close((PyObject *)self))
return NULL;
Py_RETURN_NONE;
}
/*[clinic input]
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=da39a3ee5e6b4b0d]*/
static struct PyMethodDef PyHKEY_methods[] = {
WINREG_HKEYTYPE_CLOSE_METHODDEF
WINREG_HKEYTYPE_DETACH_METHODDEF
WINREG_HKEYTYPE___ENTER___METHODDEF
WINREG_HKEYTYPE___EXIT___METHODDEF
{NULL}
};
#define OFF(e) offsetof(PyHKEYObject, e)
static PyMemberDef PyHKEY_memberlist[] = {
{"handle", T_INT, OFF(hkey), READONLY},
{NULL} /* Sentinel */
};
/* The type itself */
PyTypeObject PyHKEY_Type =
{
PyVarObject_HEAD_INIT(0, 0) /* fill in type at module init */
"PyHKEY",
sizeof(PyHKEYObject),
0,
PyHKEY_deallocFunc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
&PyHKEY_NumberMethods, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
PyHKEY_hashFunc, /* tp_hash */
0, /* tp_call */
PyHKEY_strFunc, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
0, /* tp_flags */
PyHKEY_doc, /* tp_doc */
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
PyHKEY_methods, /*tp_methods*/
PyHKEY_memberlist, /*tp_members*/
};
/************************************************************************
The public PyHKEY API (well, not public yet :-)
************************************************************************/
PyObject *
PyHKEY_New(HKEY hInit)
{
PyHKEYObject *key = PyObject_NEW(PyHKEYObject, &PyHKEY_Type);
if (key)
key->hkey = hInit;
return (PyObject *)key;
}
BOOL
PyHKEY_Close(PyObject *ob_handle)
{
LONG rc;
PyHKEYObject *key;
if (!PyHKEY_Check(ob_handle)) {
PyErr_SetString(PyExc_TypeError, "bad operand type");
return FALSE;
}
key = (PyHKEYObject *)ob_handle;
rc = key->hkey ? RegCloseKey((HKEY)key->hkey) : ERROR_SUCCESS;
key->hkey = 0;
if (rc != ERROR_SUCCESS)
PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
return rc == ERROR_SUCCESS;
}
BOOL
PyHKEY_AsHKEY(PyObject *ob, HKEY *pHANDLE, BOOL bNoneOK)
{
if (ob == Py_None) {
if (!bNoneOK) {
PyErr_SetString(
PyExc_TypeError,
"None is not a valid HKEY in this context");
return FALSE;
}
*pHANDLE = (HKEY)0;
}
else if (PyHKEY_Check(ob)) {
PyHKEYObject *pH = (PyHKEYObject *)ob;
*pHANDLE = pH->hkey;
}
else if (PyLong_Check(ob)) {
/* We also support integers */
PyErr_Clear();
*pHANDLE = (HKEY)PyLong_AsVoidPtr(ob);
if (PyErr_Occurred())
return FALSE;
}
else {
PyErr_SetString(
PyExc_TypeError,
"The object is not a PyHKEY object");
return FALSE;
}
return TRUE;
}
BOOL
clinic_HKEY_converter(PyObject *ob, void *p)
{
if (!PyHKEY_AsHKEY(ob, (HKEY *)p, FALSE))
return FALSE;
return TRUE;
}
PyObject *
PyHKEY_FromHKEY(HKEY h)
{
PyHKEYObject *op;
/* Inline PyObject_New */
op = (PyHKEYObject *) PyObject_MALLOC(sizeof(PyHKEYObject));
if (op == NULL)
return PyErr_NoMemory();
PyObject_INIT(op, &PyHKEY_Type);
op->hkey = h;
return (PyObject *)op;
}
/************************************************************************
The module methods
************************************************************************/
BOOL
PyWinObject_CloseHKEY(PyObject *obHandle)
{
BOOL ok;
if (PyHKEY_Check(obHandle)) {
ok = PyHKEY_Close(obHandle);
}
#if SIZEOF_LONG >= SIZEOF_HKEY
else if (PyLong_Check(obHandle)) {
long rc = RegCloseKey((HKEY)PyLong_AsLong(obHandle));
ok = (rc == ERROR_SUCCESS);
if (!ok)
PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
}
#else
else if (PyLong_Check(obHandle)) {
long rc = RegCloseKey((HKEY)PyLong_AsVoidPtr(obHandle));
ok = (rc == ERROR_SUCCESS);
if (!ok)
PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
}
#endif
else {
PyErr_SetString(
PyExc_TypeError,
"A handle must be a HKEY object or an integer");
return FALSE;
}
return ok;
}
/*
Private Helper functions for the registry interfaces
** Note that fixupMultiSZ and countString have both had changes
** made to support "incorrect strings". The registry specification
** calls for strings to be terminated with 2 null bytes. It seems
** some commercial packages install strings which dont conform,
** causing this code to fail - however, "regedit" etc still work
** with these strings (ie only we dont!).
*/
static void
fixupMultiSZ(wchar_t **str, wchar_t *data, int len)
{
wchar_t *P;
int i;
wchar_t *Q;
Q = data + len;
for (P = data, i = 0; P < Q && *P != '\0'; P++, i++) {
str[i] = P;
for(; *P != '\0'; P++)
;
}
}
static int
countStrings(wchar_t *data, int len)
{
int strings;
wchar_t *P;
wchar_t *Q = data + len;
for (P = data, strings = 0; P < Q && *P != '\0'; P++, strings++)
for (; P < Q && *P != '\0'; P++)
;
return strings;
}
/* Convert PyObject into Registry data.
Allocates space as needed. */
static BOOL
Py2Reg(PyObject *value, DWORD typ, BYTE **retDataBuf, DWORD *retDataSize)
{
Py_ssize_t i,j;
switch (typ) {
case REG_DWORD:
if (value != Py_None && !PyLong_Check(value))
return FALSE;
*retDataBuf = (BYTE *)PyMem_NEW(DWORD, 1);
if (*retDataBuf == NULL){
PyErr_NoMemory();
return FALSE;
}
*retDataSize = sizeof(DWORD);
if (value == Py_None) {
DWORD zero = 0;
memcpy(*retDataBuf, &zero, sizeof(DWORD));
}
else {
DWORD d = PyLong_AsUnsignedLong(value);
memcpy(*retDataBuf, &d, sizeof(DWORD));
}
break;
case REG_QWORD:
if (value != Py_None && !PyLong_Check(value))
return FALSE;
*retDataBuf = (BYTE *)PyMem_NEW(DWORD64, 1);
if (*retDataBuf == NULL){
PyErr_NoMemory();
return FALSE;
}
*retDataSize = sizeof(DWORD64);
if (value == Py_None) {
DWORD64 zero = 0;
memcpy(*retDataBuf, &zero, sizeof(DWORD64));
}
else {
DWORD64 d = PyLong_AsUnsignedLongLong(value);
memcpy(*retDataBuf, &d, sizeof(DWORD64));
}
break;
case REG_SZ:
case REG_EXPAND_SZ:
{
if (value != Py_None) {
Py_ssize_t len;
if (!PyUnicode_Check(value))
return FALSE;
*retDataBuf = (BYTE*)PyUnicode_AsWideCharString(value, &len);
if (*retDataBuf == NULL)
return FALSE;
*retDataSize = Py_SAFE_DOWNCAST(
(len + 1) * sizeof(wchar_t),
Py_ssize_t, DWORD);
}
else {
*retDataBuf = (BYTE *)PyMem_NEW(wchar_t, 1);
if (*retDataBuf == NULL) {
PyErr_NoMemory();
return FALSE;
}
((wchar_t *)*retDataBuf)[0] = L'\0';
*retDataSize = 1 * sizeof(wchar_t);
}
break;
}
case REG_MULTI_SZ:
{
DWORD size = 0;
wchar_t *P;
if (value == Py_None)
i = 0;
else {
if (!PyList_Check(value))
return FALSE;
i = PyList_Size(value);
}
for (j = 0; j < i; j++)
{
PyObject *t;
wchar_t *wstr;
Py_ssize_t len;
t = PyList_GET_ITEM(value, j);
if (!PyUnicode_Check(t))
return FALSE;
wstr = PyUnicode_AsUnicodeAndSize(t, &len);
if (wstr == NULL)
return FALSE;
size += Py_SAFE_DOWNCAST((len + 1) * sizeof(wchar_t),
size_t, DWORD);
}
*retDataSize = size + 2;
*retDataBuf = (BYTE *)PyMem_NEW(char,
*retDataSize);
if (*retDataBuf == NULL){
PyErr_NoMemory();
return FALSE;
}
P = (wchar_t *)*retDataBuf;
for (j = 0; j < i; j++)
{
PyObject *t;
wchar_t *wstr;
Py_ssize_t len;
t = PyList_GET_ITEM(value, j);
wstr = PyUnicode_AsUnicodeAndSize(t, &len);
if (wstr == NULL)
return FALSE;
wcscpy(P, wstr);
P += (len + 1);
}
/* And doubly-terminate the list... */
*P = '\0';
break;
}
case REG_BINARY:
/* ALSO handle ALL unknown data types here. Even if we can't
support it natively, we should handle the bits. */
default:
if (value == Py_None) {
*retDataSize = 0;
*retDataBuf = NULL;
}
else {
Py_buffer view;
if (!PyObject_CheckBuffer(value)) {
PyErr_Format(PyExc_TypeError,
"Objects of type '%s' can not "
"be used as binary registry values",
value->ob_type->tp_name);
return FALSE;
}
if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0)
return FALSE;
*retDataBuf = (BYTE *)PyMem_NEW(char, view.len);
if (*retDataBuf == NULL){
PyBuffer_Release(&view);
PyErr_NoMemory();
return FALSE;
}
*retDataSize = Py_SAFE_DOWNCAST(view.len, Py_ssize_t, DWORD);
memcpy(*retDataBuf, view.buf, view.len);
PyBuffer_Release(&view);
}
break;
}
return TRUE;
}
/* Convert Registry data into PyObject*/
static PyObject *
Reg2Py(BYTE *retDataBuf, DWORD retDataSize, DWORD typ)
{
PyObject *obData;
switch (typ) {
case REG_DWORD:
if (retDataSize == 0)
obData = PyLong_FromUnsignedLong(0);
else
obData = PyLong_FromUnsignedLong(*(DWORD *)retDataBuf);
break;
case REG_QWORD:
if (retDataSize == 0)
obData = PyLong_FromUnsignedLongLong(0);
else
obData = PyLong_FromUnsignedLongLong(*(DWORD64 *)retDataBuf);
break;
case REG_SZ:
case REG_EXPAND_SZ:
{
/* REG_SZ should be a NUL terminated string, but only by
* convention. The buffer may have been saved without a NUL
* or with embedded NULs. To be consistent with reg.exe and
* regedit.exe, consume only up to the first NUL. */
wchar_t *data = (wchar_t *)retDataBuf;
size_t len = wcsnlen(data, retDataSize / sizeof(wchar_t));
obData = PyUnicode_FromWideChar(data, len);
break;
}
case REG_MULTI_SZ:
if (retDataSize == 0)
obData = PyList_New(0);
else
{
int index = 0;
wchar_t *data = (wchar_t *)retDataBuf;
int len = retDataSize / 2;
int s = countStrings(data, len);
wchar_t **str = PyMem_New(wchar_t *, s);
if (str == NULL)
return PyErr_NoMemory();
fixupMultiSZ(str, data, len);
obData = PyList_New(s);
if (obData == NULL) {
PyMem_Free(str);
return NULL;
}
for (index = 0; index < s; index++)
{
size_t len = wcslen(str[index]);
if (len > INT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"registry string is too long for a Python string");
Py_DECREF(obData);
PyMem_Free(str);
return NULL;
}
PyList_SetItem(obData,
index,
PyUnicode_FromWideChar(str[index], len));
}
PyMem_Free(str);
break;
}
case REG_BINARY:
/* ALSO handle ALL unknown data types here. Even if we can't
support it natively, we should handle the bits. */
default:
if (retDataSize == 0) {
Py_INCREF(Py_None);
obData = Py_None;
}
else
obData = PyBytes_FromStringAndSize(
(char *)retDataBuf, retDataSize);
break;
}
return obData;
}
/* The Python methods */
/*[clinic input]
winreg.CloseKey
hkey: object
A previously opened key.
/
Closes a previously opened registry key.
Note that if the key is not closed using this method, it will be
closed when the hkey object is destroyed by Python.
[clinic start generated code]*/
static PyObject *
winreg_CloseKey(PyObject *module, PyObject *hkey)
/*[clinic end generated code: output=a4fa537019a80d15 input=5b1aac65ba5127ad]*/
{
if (!PyHKEY_Close(hkey))
return NULL;
Py_RETURN_NONE;
}
/*[clinic input]
winreg.ConnectRegistry -> HKEY
computer_name: Py_UNICODE(accept={str, NoneType})
The name of the remote computer, of the form r"\\computername". If
None, the local computer is used.
key: HKEY
The predefined key to connect to.
/
Establishes a connection to the registry on another computer.
The return value is the handle of the opened key.
If the function fails, an OSError exception is raised.
[clinic start generated code]*/
static HKEY
winreg_ConnectRegistry_impl(PyObject *module, Py_UNICODE *computer_name,
HKEY key)
/*[clinic end generated code: output=5ab79d02aa3167b4 input=5f98a891a347e68e]*/
{
HKEY retKey;
long rc;
Py_BEGIN_ALLOW_THREADS
rc = RegConnectRegistryW(computer_name, key, &retKey);
Py_END_ALLOW_THREADS
if (rc != ERROR_SUCCESS) {
PyErr_SetFromWindowsErrWithFunction(rc, "ConnectRegistry");
return NULL;
}
return retKey;
}
/*[clinic input]
winreg.CreateKey -> HKEY
key: HKEY
An already open key, or one of the predefined HKEY_* constants.
sub_key: Py_UNICODE(accept={str, NoneType})
The name of the key this method opens or creates.
/
Creates or opens the specified key.
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, an OSError exception is raised.
[clinic start generated code]*/
static HKEY
winreg_CreateKey_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key)
/*[clinic end generated code: output=9c81d4095527c927 input=3cdd1622488acea2]*/
{
HKEY retKey;
long rc;
rc = RegCreateKeyW(key, sub_key, &retKey);
if (rc != ERROR_SUCCESS) {
PyErr_SetFromWindowsErrWithFunction(rc, "CreateKey");
return NULL;
}
return retKey;
}
/*[clinic input]
winreg.CreateKeyEx -> HKEY
key: HKEY
An already open key, or one of the predefined HKEY_* constants.
sub_key: Py_UNICODE(accept={str, NoneType})
The name of the key this method opens or creates.
reserved: int = 0
A reserved integer, and must be zero. Default is zero.
access: REGSAM(c_default='KEY_WRITE') = winreg.KEY_WRITE
An integer that specifies an access mask that describes the
desired security access for the key. Default is KEY_WRITE.
Creates or opens the specified key.
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, an OSError exception is raised.
[clinic start generated code]*/
static HKEY
winreg_CreateKeyEx_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key,
int reserved, REGSAM access)
/*[clinic end generated code: output=b9fce6dc5c4e39b1 input=42c2b03f98406b66]*/
{
HKEY retKey;
long rc;
rc = RegCreateKeyExW(key, sub_key, reserved, NULL, (DWORD)NULL,
access, NULL, &retKey, NULL);
if (rc != ERROR_SUCCESS) {
PyErr_SetFromWindowsErrWithFunction(rc, "CreateKeyEx");
return NULL;
}
return retKey;
}
/*[clinic input]
winreg.DeleteKey
key: HKEY
An already open key, or any one of the predefined HKEY_* constants.
sub_key: Py_UNICODE
A string that must be the name of a subkey of the key identified by
the key parameter. This value must not be None, and the key may not
have subkeys.
/
Deletes the specified key.
This method can not delete keys with subkeys.
If the function succeeds, the entire key, including all of its values,
is removed. If the function fails, an OSError exception is raised.
[clinic start generated code]*/
static PyObject *
winreg_DeleteKey_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key)
/*[clinic end generated code: output=7734b1e431991ae4 input=b31d225b935e4211]*/
{
long rc;
rc = RegDeleteKeyW(key, sub_key );
if (rc != ERROR_SUCCESS)
return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKey");
Py_RETURN_NONE;
}
/*[clinic input]
winreg.DeleteKeyEx
key: HKEY
An already open key, or any one of the predefined HKEY_* constants.
sub_key: Py_UNICODE
A string that must be the name of a subkey of the key identified by
the key parameter. This value must not be None, and the key may not
have subkeys.
access: REGSAM(c_default='KEY_WOW64_64KEY') = winreg.KEY_WOW64_64KEY
An integer that specifies an access mask that describes the
desired security access for the key. Default is KEY_WOW64_64KEY.
reserved: int = 0
A reserved integer, and must be zero. Default is zero.
Deletes the specified key (64-bit OS only).
This method can not delete keys with subkeys.
If the function succeeds, the entire key, including all of its values,
is removed. If the function fails, an OSError exception is raised.
On unsupported Windows versions, NotImplementedError is raised.
[clinic start generated code]*/
static PyObject *
winreg_DeleteKeyEx_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key,
REGSAM access, int reserved)
/*[clinic end generated code: output=01378d86ad3eb936 input=711d9d89e7ecbed7]*/
{
HMODULE hMod;
typedef LONG (WINAPI *RDKEFunc)(HKEY, const wchar_t*, REGSAM, int);
RDKEFunc pfn = NULL;
long rc;
/* Only available on 64bit platforms, so we must load it
dynamically. */
hMod = GetModuleHandleW(L"advapi32.dll");
if (hMod)
pfn = (RDKEFunc)GetProcAddress(hMod,
"RegDeleteKeyExW");
if (!pfn) {
PyErr_SetString(PyExc_NotImplementedError,
"not implemented on this platform");
return NULL;
}
Py_BEGIN_ALLOW_THREADS
rc = (*pfn)(key, sub_key, access, reserved);
Py_END_ALLOW_THREADS
if (rc != ERROR_SUCCESS)
return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKeyEx");
Py_RETURN_NONE;
}
/*[clinic input]