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