PageRenderTime 2722ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/module/_winreg/interp_winreg.py

https://bitbucket.org/pypy/pypy/
Python | 740 lines | 717 code | 12 blank | 11 comment | 0 complexity | 0dca3dd597d92e2f692d15b8f55fc041 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. from __future__ import with_statement
  2. from pypy.interpreter.baseobjspace import W_Root, BufferInterfaceNotFound
  3. from pypy.interpreter.gateway import interp2app, unwrap_spec
  4. from pypy.interpreter.typedef import TypeDef, GetSetProperty
  5. from pypy.interpreter.error import OperationError, oefmt, wrap_windowserror
  6. from rpython.rtyper.lltypesystem import rffi, lltype
  7. from rpython.rlib import rwinreg, rwin32
  8. from rpython.rlib.rarithmetic import r_uint, intmask
  9. def raiseWindowsError(space, errcode, context):
  10. message = rwin32.FormatError(errcode)
  11. raise OperationError(space.w_WindowsError,
  12. space.newtuple([space.wrap(errcode),
  13. space.wrap(message)]))
  14. class W_HKEY(W_Root):
  15. def __init__(self, space, hkey):
  16. self.hkey = hkey
  17. self.space = space
  18. self.register_finalizer(space)
  19. def _finalize_(self):
  20. self.Close(self.space)
  21. def as_int(self):
  22. return rffi.cast(rffi.SIZE_T, self.hkey)
  23. def descr_nonzero(self, space):
  24. return space.wrap(self.as_int() != 0)
  25. def descr_handle_get(self, space):
  26. return space.wrap(self.as_int())
  27. def descr_repr(self, space):
  28. return space.wrap("<PyHKEY:0x%x>" % (self.as_int(),))
  29. def descr_int(self, space):
  30. return space.wrap(self.as_int())
  31. def descr__enter__(self, space):
  32. return self
  33. def descr__exit__(self, space, __args__):
  34. CloseKey(space, self)
  35. def Close(self, space):
  36. """key.Close() - Closes the underlying Windows handle.
  37. If the handle is already closed, no error is raised."""
  38. CloseKey(space, self)
  39. def Detach(self, space):
  40. """int = key.Detach() - Detaches the Windows handle from the handle object.
  41. The result is the value of the handle before it is detached. If the
  42. handle is already detached, this will return zero.
  43. After calling this function, the handle is effectively invalidated,
  44. but the handle is not closed. You would call this function when you
  45. need the underlying win32 handle to exist beyond the lifetime of the
  46. handle object.
  47. On 64 bit windows, the result of this function is a long integer"""
  48. key = self.as_int()
  49. self.hkey = rwin32.NULL_HANDLE
  50. return space.wrap(key)
  51. @unwrap_spec(key=int)
  52. def new_HKEY(space, w_subtype, key):
  53. hkey = rffi.cast(rwinreg.HKEY, key)
  54. return space.wrap(W_HKEY(space, hkey))
  55. descr_HKEY_new = interp2app(new_HKEY)
  56. W_HKEY.typedef = TypeDef(
  57. "_winreg.HKEYType",
  58. __doc__ = """\
  59. PyHKEY Object - A Python object, representing a win32 registry key.
  60. This object wraps a Windows HKEY object, automatically closing it when
  61. the object is destroyed. To guarantee cleanup, you can call either
  62. the Close() method on the PyHKEY, or the CloseKey() method.
  63. All functions which accept a handle object also accept an integer -
  64. however, use of the handle object is encouraged.
  65. Functions:
  66. Close() - Closes the underlying handle.
  67. Detach() - Returns the integer Win32 handle, detaching it from the object
  68. Properties:
  69. handle - The integer Win32 handle.
  70. Operations:
  71. __nonzero__ - Handles with an open object return true, otherwise false.
  72. __int__ - Converting a handle to an integer returns the Win32 handle.
  73. __cmp__ - Handle objects are compared using the handle value.""",
  74. __new__ = descr_HKEY_new,
  75. __repr__ = interp2app(W_HKEY.descr_repr),
  76. __int__ = interp2app(W_HKEY.descr_int),
  77. __nonzero__ = interp2app(W_HKEY.descr_nonzero),
  78. __enter__ = interp2app(W_HKEY.descr__enter__),
  79. __exit__ = interp2app(W_HKEY.descr__exit__),
  80. handle = GetSetProperty(W_HKEY.descr_handle_get),
  81. Close = interp2app(W_HKEY.Close),
  82. Detach = interp2app(W_HKEY.Detach),
  83. )
  84. def hkey_w(w_hkey, space):
  85. if space.is_w(w_hkey, space.w_None):
  86. raise oefmt(space.w_TypeError,
  87. "None is not a valid HKEY in this context")
  88. elif isinstance(w_hkey, W_HKEY):
  89. return w_hkey.hkey
  90. elif space.isinstance_w(w_hkey, space.w_int):
  91. return rffi.cast(rwinreg.HKEY, space.int_w(w_hkey))
  92. elif space.isinstance_w(w_hkey, space.w_long):
  93. return rffi.cast(rwinreg.HKEY, space.uint_w(w_hkey))
  94. else:
  95. raise oefmt(space.w_TypeError, "The object is not a PyHKEY object")
  96. def CloseKey(space, w_hkey):
  97. """CloseKey(hkey) - Closes a previously opened registry key.
  98. The hkey argument specifies a previously opened key.
  99. Note that if the key is not closed using this method, it will be
  100. closed when the hkey object is destroyed by Python."""
  101. hkey = hkey_w(w_hkey, space)
  102. if hkey:
  103. ret = rwinreg.RegCloseKey(hkey)
  104. if ret != 0:
  105. raiseWindowsError(space, ret, 'RegCloseKey')
  106. if isinstance(w_hkey, W_HKEY):
  107. space.interp_w(W_HKEY, w_hkey).hkey = rwin32.NULL_HANDLE
  108. def FlushKey(space, w_hkey):
  109. """FlushKey(key) - Writes all the attributes of a key to the registry.
  110. key is an already open key, or any one of the predefined HKEY_* constants.
  111. It is not necessary to call RegFlushKey to change a key.
  112. Registry changes are flushed to disk by the registry using its lazy flusher.
  113. Registry changes are also flushed to disk at system shutdown.
  114. Unlike CloseKey(), the FlushKey() method returns only when all the data has
  115. been written to the registry.
  116. An application should only call FlushKey() if it requires absolute certainty that registry changes are on disk.
  117. If you don't know whether a FlushKey() call is required, it probably isn't."""
  118. hkey = hkey_w(w_hkey, space)
  119. if hkey:
  120. ret = rwinreg.RegFlushKey(hkey)
  121. if ret != 0:
  122. raiseWindowsError(space, ret, 'RegFlushKey')
  123. @unwrap_spec(subkey=str, filename=str)
  124. def LoadKey(space, w_hkey, subkey, filename):
  125. """LoadKey(key, sub_key, file_name) - Creates a subkey under the specified key
  126. and stores registration information from a specified file into that subkey.
  127. key is an already open key, or any one of the predefined HKEY_* constants.
  128. sub_key is a string that identifies the sub_key to load
  129. file_name is the name of the file to load registry data from.
  130. This file must have been created with the SaveKey() function.
  131. Under the file allocation table (FAT) file system, the filename may not
  132. have an extension.
  133. A call to LoadKey() fails if the calling process does not have the
  134. SE_RESTORE_PRIVILEGE privilege.
  135. If key is a handle returned by ConnectRegistry(), then the path specified
  136. in fileName is relative to the remote computer.
  137. The docs imply key must be in the HKEY_USER or HKEY_LOCAL_MACHINE tree"""
  138. hkey = hkey_w(w_hkey, space)
  139. ret = rwinreg.RegLoadKey(hkey, subkey, filename)
  140. if ret != 0:
  141. raiseWindowsError(space, ret, 'RegLoadKey')
  142. @unwrap_spec(filename=str)
  143. def SaveKey(space, w_hkey, filename):
  144. """SaveKey(key, file_name) - Saves the specified key, and all its subkeys to the specified file.
  145. key is an already open key, or any one of the predefined HKEY_* constants.
  146. file_name is the name of the file to save registry data to.
  147. This file cannot already exist. If this filename includes an extension,
  148. it cannot be used on file allocation table (FAT) file systems by the
  149. LoadKey(), ReplaceKey() or RestoreKey() methods.
  150. If key represents a key on a remote computer, the path described by
  151. file_name is relative to the remote computer.
  152. The caller of this method must possess the SeBackupPrivilege security privilege.
  153. This function passes NULL for security_attributes to the API."""
  154. hkey = hkey_w(w_hkey, space)
  155. ret = rwinreg.RegSaveKey(hkey, filename, None)
  156. if ret != 0:
  157. raiseWindowsError(space, ret, 'RegSaveKey')
  158. @unwrap_spec(typ=int, value=str)
  159. def SetValue(space, w_hkey, w_subkey, typ, value):
  160. """SetValue(key, sub_key, type, value) - Associates a value with a specified key.
  161. key is an already open key, or any one of the predefined HKEY_* constants.
  162. sub_key is a string that names the subkey with which the value is associated.
  163. type is an integer that specifies the type of the data. Currently this
  164. must be REG_SZ, meaning only strings are supported.
  165. value is a string that specifies the new value.
  166. If the key specified by the sub_key parameter does not exist, the SetValue
  167. function creates it.
  168. Value lengths are limited by available memory. Long values (more than
  169. 2048 bytes) should be stored as files with the filenames stored in
  170. the configuration registry. This helps the registry perform efficiently.
  171. The key identified by the key parameter must have been opened with
  172. KEY_SET_VALUE access."""
  173. if typ != rwinreg.REG_SZ:
  174. raise oefmt(space.w_ValueError, "Type must be _winreg.REG_SZ")
  175. hkey = hkey_w(w_hkey, space)
  176. if space.is_w(w_subkey, space.w_None):
  177. subkey = None
  178. else:
  179. subkey = space.str_w(w_subkey)
  180. with rffi.scoped_str2charp(value) as dataptr:
  181. ret = rwinreg.RegSetValue(hkey, subkey, rwinreg.REG_SZ, dataptr, len(value))
  182. if ret != 0:
  183. raiseWindowsError(space, ret, 'RegSetValue')
  184. def QueryValue(space, w_hkey, w_subkey):
  185. """string = QueryValue(key, sub_key) - retrieves the unnamed value for a key.
  186. key is an already open key, or any one of the predefined HKEY_* constants.
  187. sub_key is a string that holds the name of the subkey with which the value
  188. is associated. If this parameter is None or empty, the function retrieves
  189. the value set by the SetValue() method for the key identified by key.
  190. Values in the registry have name, type, and data components. This method
  191. retrieves the data for a key's first value that has a NULL name.
  192. But the underlying API call doesn't return the type, Lame Lame Lame, DONT USE THIS!!!"""
  193. hkey = hkey_w(w_hkey, space)
  194. if space.is_w(w_subkey, space.w_None):
  195. subkey = None
  196. else:
  197. subkey = space.str_w(w_subkey)
  198. with lltype.scoped_alloc(rwin32.PLONG.TO, 1) as bufsize_p:
  199. ret = rwinreg.RegQueryValue(hkey, subkey, None, bufsize_p)
  200. bufSize = intmask(bufsize_p[0])
  201. if ret == rwinreg.ERROR_MORE_DATA:
  202. bufSize = 256
  203. elif ret != 0:
  204. raiseWindowsError(space, ret, 'RegQueryValue')
  205. while True:
  206. with lltype.scoped_alloc(rffi.CCHARP.TO, bufSize) as buf:
  207. ret = rwinreg.RegQueryValue(hkey, subkey, buf, bufsize_p)
  208. if ret == rwinreg.ERROR_MORE_DATA:
  209. # Resize and retry
  210. bufSize *= 2
  211. bufsize_p[0] = bufSize
  212. continue
  213. if ret != 0:
  214. raiseWindowsError(space, ret, 'RegQueryValue')
  215. length = intmask(bufsize_p[0] - 1)
  216. return space.wrap(rffi.charp2strn(buf, length))
  217. def convert_to_regdata(space, w_value, typ):
  218. buf = None
  219. if typ == rwinreg.REG_DWORD:
  220. if space.is_none(w_value) or (
  221. space.isinstance_w(w_value, space.w_int) or
  222. space.isinstance_w(w_value, space.w_long)):
  223. if space.is_none(w_value):
  224. value = r_uint(0)
  225. else:
  226. value = space.c_uint_w(w_value)
  227. buflen = rffi.sizeof(rwin32.DWORD)
  228. buf1 = lltype.malloc(rffi.CArray(rwin32.DWORD), 1, flavor='raw')
  229. buf1[0] = value
  230. buf = rffi.cast(rffi.CCHARP, buf1)
  231. elif typ == rwinreg.REG_SZ or typ == rwinreg.REG_EXPAND_SZ:
  232. if space.is_w(w_value, space.w_None):
  233. buflen = 1
  234. buf = lltype.malloc(rffi.CCHARP.TO, buflen, flavor='raw')
  235. buf[0] = '\0'
  236. else:
  237. if space.isinstance_w(w_value, space.w_unicode):
  238. w_value = space.call_method(w_value, 'encode',
  239. space.wrap('mbcs'))
  240. buf = rffi.str2charp(space.str_w(w_value))
  241. buflen = space.len_w(w_value) + 1
  242. elif typ == rwinreg.REG_MULTI_SZ:
  243. if space.is_w(w_value, space.w_None):
  244. buflen = 1
  245. buf = lltype.malloc(rffi.CCHARP.TO, buflen, flavor='raw')
  246. buf[0] = '\0'
  247. elif space.isinstance_w(w_value, space.w_list):
  248. strings = []
  249. buflen = 0
  250. # unwrap strings and compute total size
  251. w_iter = space.iter(w_value)
  252. while True:
  253. try:
  254. w_item = space.next(w_iter)
  255. if space.isinstance_w(w_item, space.w_unicode):
  256. w_item = space.call_method(w_item, 'encode',
  257. space.wrap('mbcs'))
  258. item = space.str_w(w_item)
  259. strings.append(item)
  260. buflen += len(item) + 1
  261. except OperationError as e:
  262. if not e.match(space, space.w_StopIteration):
  263. raise # re-raise other app-level exceptions
  264. break
  265. buflen += 1
  266. buf = lltype.malloc(rffi.CCHARP.TO, buflen, flavor='raw')
  267. # Now copy data
  268. buflen = 0
  269. for string in strings:
  270. for i in range(len(string)):
  271. buf[buflen + i] = string[i]
  272. buflen += len(string) + 1
  273. buf[buflen - 1] = '\0'
  274. buflen += 1
  275. buf[buflen - 1] = '\0'
  276. else: # REG_BINARY and ALL unknown data types.
  277. if space.is_w(w_value, space.w_None):
  278. buflen = 0
  279. buf = lltype.malloc(rffi.CCHARP.TO, 1, flavor='raw')
  280. buf[0] = '\0'
  281. else:
  282. try:
  283. value = w_value.readbuf_w(space)
  284. except BufferInterfaceNotFound:
  285. raise oefmt(space.w_TypeError,
  286. "Objects of type '%T' can not be used as binary "
  287. "registry values", w_value)
  288. else:
  289. value = value.as_str()
  290. buflen = len(value)
  291. buf = rffi.str2charp(value)
  292. if buf is not None:
  293. return rffi.cast(rffi.CCHARP, buf), buflen
  294. raise oefmt(space.w_ValueError,
  295. "Could not convert the data to the specified type")
  296. def convert_from_regdata(space, buf, buflen, typ):
  297. if typ == rwinreg.REG_DWORD:
  298. if not buflen:
  299. return space.wrap(0)
  300. d = rffi.cast(rwin32.LPDWORD, buf)[0]
  301. return space.wrap(d)
  302. elif typ == rwinreg.REG_SZ or typ == rwinreg.REG_EXPAND_SZ:
  303. if not buflen:
  304. return space.wrap("")
  305. s = rffi.charp2strn(rffi.cast(rffi.CCHARP, buf), buflen)
  306. return space.wrap(s)
  307. elif typ == rwinreg.REG_MULTI_SZ:
  308. if not buflen:
  309. return space.newlist([])
  310. i = 0
  311. l = []
  312. while i < buflen and buf[i]:
  313. s = []
  314. while i < buflen and buf[i] != '\0':
  315. s.append(buf[i])
  316. i += 1
  317. if len(s) == 0:
  318. break
  319. s = ''.join(s)
  320. l.append(space.wrap(s))
  321. i += 1
  322. return space.newlist(l)
  323. else: # REG_BINARY and all other types
  324. return space.newbytes(rffi.charpsize2str(buf, buflen))
  325. @unwrap_spec(value_name=str, typ=int)
  326. def SetValueEx(space, w_hkey, value_name, w_reserved, typ, w_value):
  327. """SetValueEx(key, value_name, reserved, type, value) - Stores data in the value field of an open registry key.
  328. key is an already open key, or any one of the predefined HKEY_* constants.
  329. value_name is a string containing the name of the value to set, or None
  330. type is an integer that specifies the type of the data. This should be one of:
  331. REG_BINARY -- Binary data in any form.
  332. REG_DWORD -- A 32-bit number.
  333. REG_DWORD_LITTLE_ENDIAN -- A 32-bit number in little-endian format.
  334. REG_DWORD_BIG_ENDIAN -- A 32-bit number in big-endian format.
  335. REG_EXPAND_SZ -- A null-terminated string that contains unexpanded references
  336. to environment variables (for example, %PATH%).
  337. REG_LINK -- A Unicode symbolic link.
  338. REG_MULTI_SZ -- An sequence of null-terminated strings, terminated by
  339. two null characters. Note that Python handles this
  340. termination automatically.
  341. REG_NONE -- No defined value type.
  342. REG_RESOURCE_LIST -- A device-driver resource list.
  343. REG_SZ -- A null-terminated string.
  344. reserved can be anything - zero is always passed to the API.
  345. value is a string that specifies the new value.
  346. This method can also set additional value and type information for the
  347. specified key. The key identified by the key parameter must have been
  348. opened with KEY_SET_VALUE access.
  349. To open the key, use the CreateKeyEx() or OpenKeyEx() methods.
  350. Value lengths are limited by available memory. Long values (more than
  351. 2048 bytes) should be stored as files with the filenames stored in
  352. the configuration registry. This helps the registry perform efficiently."""
  353. hkey = hkey_w(w_hkey, space)
  354. buf, buflen = convert_to_regdata(space, w_value, typ)
  355. try:
  356. ret = rwinreg.RegSetValueEx(hkey, value_name, 0, typ, buf, buflen)
  357. finally:
  358. lltype.free(buf, flavor='raw')
  359. if ret != 0:
  360. raiseWindowsError(space, ret, 'RegSetValueEx')
  361. def QueryValueEx(space, w_hkey, w_subkey):
  362. """value,type_id = QueryValueEx(key, value_name) - Retrieves the type and data for a specified value name associated with an open registry key.
  363. key is an already open key, or any one of the predefined HKEY_* constants.
  364. value_name is a string indicating the value to query"""
  365. hkey = hkey_w(w_hkey, space)
  366. if space.is_w(w_subkey, space.w_None):
  367. subkey = None
  368. else:
  369. subkey = space.str_w(w_subkey)
  370. null_dword = lltype.nullptr(rwin32.LPDWORD.TO)
  371. with lltype.scoped_alloc(rwin32.LPDWORD.TO, 1) as retDataSize:
  372. ret = rwinreg.RegQueryValueEx(hkey, subkey, null_dword, null_dword,
  373. None, retDataSize)
  374. bufSize = intmask(retDataSize[0])
  375. if ret == rwinreg.ERROR_MORE_DATA:
  376. bufSize = 256
  377. elif ret != 0:
  378. raiseWindowsError(space, ret, 'RegQueryValueEx')
  379. while True:
  380. with lltype.scoped_alloc(rffi.CCHARP.TO, bufSize) as databuf:
  381. with lltype.scoped_alloc(rwin32.LPDWORD.TO, 1) as retType:
  382. ret = rwinreg.RegQueryValueEx(hkey, subkey, null_dword,
  383. retType, databuf, retDataSize)
  384. if ret == rwinreg.ERROR_MORE_DATA:
  385. # Resize and retry
  386. bufSize *= 2
  387. retDataSize[0] = rffi.cast(rwin32.DWORD, bufSize)
  388. continue
  389. if ret != 0:
  390. raiseWindowsError(space, ret, 'RegQueryValueEx')
  391. length = intmask(retDataSize[0])
  392. return space.newtuple([
  393. convert_from_regdata(space, databuf,
  394. length, retType[0]),
  395. space.wrap(retType[0]),
  396. ])
  397. @unwrap_spec(subkey=str)
  398. def CreateKey(space, w_hkey, subkey):
  399. """key = CreateKey(key, sub_key) - Creates or opens the specified key.
  400. key is an already open key, or one of the predefined HKEY_* constants
  401. sub_key is a string that names the key this method opens or creates.
  402. If key is one of the predefined keys, sub_key may be None. In that case,
  403. the handle returned is the same key handle passed in to the function.
  404. If the key already exists, this function opens the existing key
  405. The return value is the handle of the opened key.
  406. If the function fails, an exception is raised."""
  407. hkey = hkey_w(w_hkey, space)
  408. with lltype.scoped_alloc(rwinreg.PHKEY.TO, 1) as rethkey:
  409. ret = rwinreg.RegCreateKey(hkey, subkey, rethkey)
  410. if ret != 0:
  411. raiseWindowsError(space, ret, 'CreateKey')
  412. return space.wrap(W_HKEY(space, rethkey[0]))
  413. @unwrap_spec(subkey=str, res=int, sam=rffi.r_uint)
  414. def CreateKeyEx(space, w_hkey, subkey, res=0, sam=rwinreg.KEY_WRITE):
  415. """key = CreateKey(key, sub_key) - Creates or opens the specified key.
  416. key is an already open key, or one of the predefined HKEY_* constants
  417. sub_key is a string that names the key this method opens or creates.
  418. If key is one of the predefined keys, sub_key may be None. In that case,
  419. the handle returned is the same key handle passed in to the function.
  420. If the key already exists, this function opens the existing key
  421. The return value is the handle of the opened key.
  422. If the function fails, an exception is raised."""
  423. hkey = hkey_w(w_hkey, space)
  424. with lltype.scoped_alloc(rwinreg.PHKEY.TO, 1) as rethkey:
  425. ret = rwinreg.RegCreateKeyEx(hkey, subkey, res, None, 0,
  426. sam, None, rethkey,
  427. lltype.nullptr(rwin32.LPDWORD.TO))
  428. if ret != 0:
  429. raiseWindowsError(space, ret, 'CreateKeyEx')
  430. return space.wrap(W_HKEY(space, rethkey[0]))
  431. @unwrap_spec(subkey=str)
  432. def DeleteKey(space, w_hkey, subkey):
  433. """DeleteKey(key, sub_key) - Deletes the specified key.
  434. key is an already open key, or any one of the predefined HKEY_* constants.
  435. sub_key is a string that must be a subkey of the key identified by the key parameter.
  436. This value must not be None, and the key may not have subkeys.
  437. This method can not delete keys with subkeys.
  438. If the method succeeds, the entire key, including all of its values,
  439. is removed. If the method fails, an EnvironmentError exception is raised."""
  440. hkey = hkey_w(w_hkey, space)
  441. ret = rwinreg.RegDeleteKey(hkey, subkey)
  442. if ret != 0:
  443. raiseWindowsError(space, ret, 'RegDeleteKey')
  444. @unwrap_spec(subkey=str)
  445. def DeleteValue(space, w_hkey, subkey):
  446. """DeleteValue(key, value) - Removes a named value from a registry key.
  447. key is an already open key, or any one of the predefined HKEY_* constants.
  448. value is a string that identifies the value to remove."""
  449. hkey = hkey_w(w_hkey, space)
  450. ret = rwinreg.RegDeleteValue(hkey, subkey)
  451. if ret != 0:
  452. raiseWindowsError(space, ret, 'RegDeleteValue')
  453. @unwrap_spec(subkey=str, res=int, sam=rffi.r_uint)
  454. def OpenKey(space, w_hkey, subkey, res=0, sam=rwinreg.KEY_READ):
  455. """key = OpenKey(key, sub_key, res = 0, sam = KEY_READ) - Opens the specified key.
  456. key is an already open key, or any one of the predefined HKEY_* constants.
  457. sub_key is a string that identifies the sub_key to open
  458. res is a reserved integer, and must be zero. Default is zero.
  459. sam is an integer that specifies an access mask that describes the desired
  460. security access for the key. Default is KEY_READ
  461. The result is a new handle to the specified key
  462. If the function fails, an EnvironmentError exception is raised."""
  463. hkey = hkey_w(w_hkey, space)
  464. with lltype.scoped_alloc(rwinreg.PHKEY.TO, 1) as rethkey:
  465. ret = rwinreg.RegOpenKeyEx(hkey, subkey, res, sam, rethkey)
  466. if ret != 0:
  467. raiseWindowsError(space, ret, 'RegOpenKeyEx')
  468. return space.wrap(W_HKEY(space, rethkey[0]))
  469. @unwrap_spec(index=int)
  470. def EnumValue(space, w_hkey, index):
  471. """tuple = EnumValue(key, index) - Enumerates values of an open registry key.
  472. key is an already open key, or any one of the predefined HKEY_* constants.
  473. index is an integer that identifies the index of the value to retrieve.
  474. The function retrieves the name of one subkey each time it is called.
  475. It is typically called repeatedly, until an EnvironmentError exception
  476. is raised, indicating no more values.
  477. The result is a tuple of 3 items:
  478. value_name is a string that identifies the value.
  479. value_data is an object that holds the value data, and whose type depends
  480. on the underlying registry type.
  481. data_type is an integer that identifies the type of the value data."""
  482. hkey = hkey_w(w_hkey, space)
  483. null_dword = lltype.nullptr(rwin32.LPDWORD.TO)
  484. with lltype.scoped_alloc(rwin32.LPDWORD.TO, 1) as retValueSize:
  485. with lltype.scoped_alloc(rwin32.LPDWORD.TO, 1) as retDataSize:
  486. ret = rwinreg.RegQueryInfoKey(
  487. hkey, None, null_dword, null_dword,
  488. null_dword, null_dword, null_dword,
  489. null_dword, retValueSize, retDataSize,
  490. null_dword, lltype.nullptr(rwin32.PFILETIME.TO))
  491. if ret != 0:
  492. raiseWindowsError(space, ret, 'RegQueryInfoKey')
  493. # include null terminators
  494. retValueSize[0] += 1
  495. retDataSize[0] += 1
  496. bufDataSize = intmask(retDataSize[0])
  497. bufValueSize = intmask(retValueSize[0])
  498. with lltype.scoped_alloc(rffi.CCHARP.TO,
  499. intmask(retValueSize[0])) as valuebuf:
  500. while True:
  501. with lltype.scoped_alloc(rffi.CCHARP.TO,
  502. bufDataSize) as databuf:
  503. with lltype.scoped_alloc(rwin32.LPDWORD.TO,
  504. 1) as retType:
  505. ret = rwinreg.RegEnumValue(
  506. hkey, index, valuebuf, retValueSize,
  507. null_dword, retType, databuf, retDataSize)
  508. if ret == rwinreg.ERROR_MORE_DATA:
  509. # Resize and retry
  510. bufDataSize *= 2
  511. retDataSize[0] = rffi.cast(rwin32.DWORD,
  512. bufDataSize)
  513. retValueSize[0] = rffi.cast(rwin32.DWORD,
  514. bufValueSize)
  515. continue
  516. if ret != 0:
  517. raiseWindowsError(space, ret, 'RegEnumValue')
  518. length = intmask(retDataSize[0])
  519. return space.newtuple([
  520. space.wrap(rffi.charp2str(valuebuf)),
  521. convert_from_regdata(space, databuf,
  522. length, retType[0]),
  523. space.wrap(retType[0]),
  524. ])
  525. @unwrap_spec(index=int)
  526. def EnumKey(space, w_hkey, index):
  527. """string = EnumKey(key, index) - Enumerates subkeys of an open registry key.
  528. key is an already open key, or any one of the predefined HKEY_* constants.
  529. index is an integer that identifies the index of the key to retrieve.
  530. The function retrieves the name of one subkey each time it is called.
  531. It is typically called repeatedly until an EnvironmentError exception is
  532. raised, indicating no more values are available."""
  533. hkey = hkey_w(w_hkey, space)
  534. null_dword = lltype.nullptr(rwin32.LPDWORD.TO)
  535. # The Windows docs claim that the max key name length is 255
  536. # characters, plus a terminating nul character. However,
  537. # empirical testing demonstrates that it is possible to
  538. # create a 256 character key that is missing the terminating
  539. # nul. RegEnumKeyEx requires a 257 character buffer to
  540. # retrieve such a key name.
  541. with lltype.scoped_alloc(rffi.CCHARP.TO, 257) as buf:
  542. with lltype.scoped_alloc(rwin32.LPDWORD.TO, 1) as retValueSize:
  543. retValueSize[0] = r_uint(257) # includes NULL terminator
  544. ret = rwinreg.RegEnumKeyEx(hkey, index, buf, retValueSize,
  545. null_dword, None, null_dword,
  546. lltype.nullptr(rwin32.PFILETIME.TO))
  547. if ret != 0:
  548. raiseWindowsError(space, ret, 'RegEnumKeyEx')
  549. return space.wrap(rffi.charp2str(buf))
  550. def QueryInfoKey(space, w_hkey):
  551. """tuple = QueryInfoKey(key) - Returns information about a key.
  552. key is an already open key, or any one of the predefined HKEY_* constants.
  553. The result is a tuple of 3 items:
  554. An integer that identifies the number of sub keys this key has.
  555. An integer that identifies the number of values this key has.
  556. A long integer that identifies when the key was last modified (if available)
  557. as 100's of nanoseconds since Jan 1, 1600."""
  558. hkey = hkey_w(w_hkey, space)
  559. with lltype.scoped_alloc(rwin32.LPDWORD.TO, 1) as nSubKeys:
  560. with lltype.scoped_alloc(rwin32.LPDWORD.TO, 1) as nValues:
  561. with lltype.scoped_alloc(rwin32.PFILETIME.TO, 1) as ft:
  562. null_dword = lltype.nullptr(rwin32.LPDWORD.TO)
  563. ret = rwinreg.RegQueryInfoKey(
  564. hkey, None, null_dword, null_dword,
  565. nSubKeys, null_dword, null_dword,
  566. nValues, null_dword, null_dword,
  567. null_dword, ft)
  568. if ret != 0:
  569. raiseWindowsError(space, ret, 'RegQueryInfoKey')
  570. l = ((lltype.r_longlong(ft[0].c_dwHighDateTime) << 32) +
  571. lltype.r_longlong(ft[0].c_dwLowDateTime))
  572. return space.newtuple([space.wrap(nSubKeys[0]),
  573. space.wrap(nValues[0]),
  574. space.wrap(l)])
  575. def ConnectRegistry(space, w_machine, w_hkey):
  576. """key = ConnectRegistry(computer_name, key)
  577. Establishes a connection to a predefined registry handle on another computer.
  578. computer_name is the name of the remote computer, of the form \\\\computername.
  579. If None, the local computer is used.
  580. key is the predefined handle to connect to.
  581. The return value is the handle of the opened key.
  582. If the function fails, an EnvironmentError exception is raised."""
  583. machine = space.str_or_None_w(w_machine)
  584. hkey = hkey_w(w_hkey, space)
  585. with lltype.scoped_alloc(rwinreg.PHKEY.TO, 1) as rethkey:
  586. ret = rwinreg.RegConnectRegistry(machine, hkey, rethkey)
  587. if ret != 0:
  588. raiseWindowsError(space, ret, 'RegConnectRegistry')
  589. return space.wrap(W_HKEY(space, rethkey[0]))
  590. @unwrap_spec(source=unicode)
  591. def ExpandEnvironmentStrings(space, source):
  592. "string = ExpandEnvironmentStrings(string) - Expand environment vars."
  593. try:
  594. return space.wrap(rwinreg.ExpandEnvironmentStrings(source))
  595. except WindowsError as e:
  596. raise wrap_windowserror(space, e)
  597. def DisableReflectionKey(space, w_key):
  598. """Disables registry reflection for 32-bit processes running on a 64-bit
  599. Operating System. Will generally raise NotImplemented if executed on
  600. a 32-bit Operating System.
  601. If the key is not on the reflection list, the function succeeds but has no effect.
  602. Disabling reflection for a key does not affect reflection of any subkeys."""
  603. raise oefmt(space.w_NotImplementedError,
  604. "not implemented on this platform")
  605. def EnableReflectionKey(space, w_key):
  606. """Restores registry reflection for the specified disabled key.
  607. Will generally raise NotImplemented if executed on a 32-bit Operating System.
  608. Restoring reflection for a key does not affect reflection of any subkeys."""
  609. raise oefmt(space.w_NotImplementedError,
  610. "not implemented on this platform")
  611. def QueryReflectionKey(space, w_key):
  612. """bool = QueryReflectionKey(hkey) - Determines the reflection state for the specified key.
  613. Will generally raise NotImplemented if executed on a 32-bit Operating System."""
  614. raise oefmt(space.w_NotImplementedError,
  615. "not implemented on this platform")
  616. @unwrap_spec(subkey=str)
  617. def DeleteKeyEx(space, w_key, subkey):
  618. """DeleteKeyEx(key, sub_key, sam, res) - Deletes the specified key.
  619. key is an already open key, or any one of the predefined HKEY_* constants.
  620. sub_key is a string that must be a subkey of the key identified by the key parameter.
  621. res is a reserved integer, and must be zero. Default is zero.
  622. sam is an integer that specifies an access mask that describes the desired
  623. This value must not be None, and the key may not have subkeys.
  624. This method can not delete keys with subkeys.
  625. If the method succeeds, the entire key, including all of its values,
  626. is removed. If the method fails, a WindowsError exception is raised.
  627. On unsupported Windows versions, NotImplementedError is raised."""
  628. raise oefmt(space.w_NotImplementedError,
  629. "not implemented on this platform")