def SetValue(space, w_hkey, w_subkey, typ, value): """SetValue(key, sub_key, type, value) - Associates a value with a specified key. key is an already open key, or any one of the predefined HKEY_* constants. sub_key is a string that names the subkey with which the value is associated. type is an integer that specifies the type of the data. Currently this must be REG_SZ, meaning only strings are supported. value is a string that specifies the new value. If the key specified by the sub_key parameter does not exist, the SetValue function creates it. Value lengths are limited by available memory. Long values (more than 2048 bytes) should be stored as files with the filenames stored in the configuration registry. This helps the registry perform efficiently. The key identified by the key parameter must have been opened with KEY_SET_VALUE access.""" if typ != rwinreg.REG_SZ: raise oefmt(space.w_ValueError, "Type must be winreg.REG_SZ") hkey = hkey_w(w_hkey, space) with rffi.scoped_unicode2wcharp(space.unicode_w(w_subkey)) as subkey: c_subkey = rffi.cast(rffi.CCHARP, subkey) with rffi.scoped_unicode2wcharp(value) as dataptr: c_dataptr = rffi.cast(rffi.CCHARP, dataptr) ret = rwinreg.RegSetValueW(hkey, c_subkey, rwinreg.REG_SZ, c_dataptr, len(value)) if ret != 0: raiseWindowsError(space, ret, 'RegSetValue')
def test_encode_decimal(self, space, api): with rffi.scoped_unicode2wcharp(u' (12, 35 ABC)') as u: with rffi.scoped_alloc_buffer(20) as buf: res = api.PyUnicode_EncodeDecimal(u, 13, buf.raw, None) s = rffi.charp2str(buf.raw) assert res == 0 assert s == ' (12, 35 ABC)' with rffi.scoped_unicode2wcharp(u' (12, \u1234\u1235)') as u: with rffi.scoped_alloc_buffer(20) as buf: res = api.PyUnicode_EncodeDecimal(u, 9, buf.raw, None) assert res == -1 api.PyErr_Clear() with rffi.scoped_unicode2wcharp(u' (12, \u1234\u1235)') as u: with rffi.scoped_alloc_buffer(20) as buf: with rffi.scoped_str2charp("replace") as errors: res = api.PyUnicode_EncodeDecimal(u, 9, buf.raw, errors) s = rffi.charp2str(buf.raw) assert res == 0 assert s == " (12, ??)" with rffi.scoped_unicode2wcharp(u'12\u1234') as u: with rffi.scoped_alloc_buffer(20) as buf: with rffi.scoped_str2charp("xmlcharrefreplace") as errors: res = api.PyUnicode_EncodeDecimal(u, 3, buf.raw, errors) s = rffi.charp2str(buf.raw) assert res == 0 assert s == "12ሴ"
def LoadKey(space, w_hkey, subkey, filename): """LoadKey(key, sub_key, file_name) - Creates a subkey under the specified key and stores registration information from a specified file into that subkey. key is an already open key, or any one of the predefined HKEY_* constants. sub_key is a string that identifies the sub_key to load file_name is the name of the file to load registry data from. This file must have been created with the SaveKey() function. Under the file allocation table (FAT) file system, the filename may not have an extension. A call to LoadKey() fails if the calling process does not have the SE_RESTORE_PRIVILEGE privilege. If key is a handle returned by ConnectRegistry(), then the path specified in fileName is relative to the remote computer. The docs imply key must be in the HKEY_USER or HKEY_LOCAL_MACHINE tree""" # XXX should filename use space.fsencode_w? hkey = hkey_w(w_hkey, space) with rffi.scoped_unicode2wcharp(subkey) as wide_subkey: c_subkey = rffi.cast(rffi.CCHARP, wide_subkey) with rffi.scoped_unicode2wcharp(filename) as wide_filename: c_filename = rffi.cast(rffi.CCHARP, wide_filename) ret = rwinreg.RegLoadKeyW(hkey, c_subkey, c_filename) if ret != 0: raiseWindowsError(space, ret, 'RegLoadKey')
def test_encode_decimal(self, space): with rffi.scoped_unicode2wcharp(u' (12, 35 ABC)') as u: with rffi.scoped_alloc_buffer(20) as buf: res = PyUnicode_EncodeDecimal(space, u, 13, buf.raw, None) s = rffi.charp2str(buf.raw) assert res == 0 assert s == ' (12, 35 ABC)' with rffi.scoped_unicode2wcharp(u' (12, \u1234\u1235)') as u: with rffi.scoped_alloc_buffer(20) as buf: with pytest.raises(OperationError): PyUnicode_EncodeDecimal(space, u, 9, buf.raw, None) with rffi.scoped_unicode2wcharp(u' (12, \u1234\u1235)') as u: with rffi.scoped_alloc_buffer(20) as buf: with rffi.scoped_str2charp("replace") as errors: res = PyUnicode_EncodeDecimal(space, u, 9, buf.raw, errors) s = rffi.charp2str(buf.raw) assert res == 0 assert s == " (12, ??)" with rffi.scoped_unicode2wcharp(u'12\u1234') as u: with rffi.scoped_alloc_buffer(20) as buf: with rffi.scoped_str2charp("xmlcharrefreplace") as errors: res = PyUnicode_EncodeDecimal(space, u, 3, buf.raw, errors) s = rffi.charp2str(buf.raw) assert res == 0 assert s == "12ሴ"
def QueryValue(space, w_hkey, w_subkey): """ string = QueryValue(key, sub_key) - retrieves the unnamed value for a key. key is an already open key, or any one of the predefined HKEY_* constants. sub_key is a string that holds the name of the subkey with which the value is associated. If this parameter is None or empty, the function retrieves the value set by the SetValue() method for the key identified by key. Values in the registry have name, type, and data components. This method retrieves the data for a key's first value that has a NULL name. But the underlying API call doesn't return the type: Lame, DONT USE THIS!!!""" hkey = hkey_w(w_hkey, space) if space.is_w(w_subkey, space.w_None): subkey = None else: subkey = space.utf8_w(w_subkey).decode('utf8') with rffi.scoped_unicode2wcharp(subkey) as wide_subkey: c_subkey = rffi.cast(rffi.CWCHARP, wide_subkey) with lltype.scoped_alloc(rwin32.PLONG.TO, 1) as bufsize_p: bufsize_p[0] = 0 ret = rwinreg.RegQueryValueW(hkey, c_subkey, None, bufsize_p) if ret == 0 and intmask(bufsize_p[0]) == 0: return space.newtext('', 0) elif ret != 0 and ret != rwinreg.ERROR_MORE_DATA: raiseWindowsError(space, ret, 'RegQueryValue') # Add extra space for a NULL ending buf = ByteBuffer(intmask(bufsize_p[0]) * 2 + 2) bufP = rffi.cast(rwin32.LPWSTR, buf.get_raw_address()) ret = rwinreg.RegQueryValueW(hkey, c_subkey, bufP, bufsize_p) if ret != 0: raiseWindowsError(space, ret, 'RegQueryValue') utf8, lgt = wbuf_to_utf8(space, buf[0:intmask(bufsize_p[0])]) return space.newtext(utf8, lgt)
def DeleteValue(space, w_hkey, subkey): """DeleteValue(key, value) - Removes a named value from a registry key. key is an already open key, or any one of the predefined HKEY_* constants. value is a string that identifies the value to remove.""" hkey = hkey_w(w_hkey, space) with rffi.scoped_unicode2wcharp(subkey) as wide_subkey: c_subkey = rffi.cast(rffi.CCHARP, wide_subkey) ret = rwinreg.RegDeleteValueW(hkey, c_subkey) if ret != 0: raiseWindowsError(space, ret, 'RegDeleteValue')
def ExpandEnvironmentStrings(source): with rffi.scoped_unicode2wcharp(source) as src_buf: size = _ExpandEnvironmentStringsW(src_buf, lltype.nullptr(rffi.CWCHARP.TO), 0) if size == 0: raise rwin32.lastSavedWindowsError("ExpandEnvironmentStrings") size = intmask(size) with rffi.scoped_alloc_unicodebuffer(size) as dest_buf: if _ExpandEnvironmentStringsW(src_buf, dest_buf.raw, size) == 0: raise rwin32.lastSavedWindowsError("ExpandEnvironmentStrings") return dest_buf.str(size - 1) # remove trailing \0
def DeleteKey(space, w_hkey, subkey): """DeleteKey(key, subkey) - Deletes the specified key. key is an already open key, or any one of the predefined HKEY_* constants. sub_key is a string that must be a subkey of the key identified by the key parameter. This value must not be None, and the key may not have subkeys. This method can not delete keys with subkeys. If the method succeeds, the entire key, including all of its values, is removed. If the method fails, an EnvironmentError exception is raised.""" hkey = hkey_w(w_hkey, space) with rffi.scoped_unicode2wcharp(subkey) as wide_subkey: c_subkey = rffi.cast(rffi.CCHARP, wide_subkey) ret = rwinreg.RegDeleteKeyW(hkey, c_subkey) if ret != 0: raiseWindowsError(space, ret, 'RegDeleteKey')
def QueryValueEx(space, w_hkey, w_subkey): """ value,type_id = QueryValueEx(key, value_name) - Retrieves the type and data for a specified value name associated with an open registry key. key is an already open key, or any one of the predefined HKEY_* constants. value_name is a string indicating the value to query""" hkey = hkey_w(w_hkey, space) if space.is_w(w_subkey, space.w_None): subkey = None else: subkey = space.utf8_w(w_subkey).decode('utf8') null_dword = lltype.nullptr(rwin32.LPDWORD.TO) with rffi.scoped_unicode2wcharp(subkey) as wide_subkey: c_subkey = rffi.cast(rffi.CWCHARP, wide_subkey) with lltype.scoped_alloc(rwin32.LPDWORD.TO, 1) as dataSize: ret = rwinreg.RegQueryValueExW(hkey, c_subkey, null_dword, null_dword, None, dataSize) bufSize = intmask(dataSize[0]) if ret == rwinreg.ERROR_MORE_DATA: # Copy CPython behaviour, otherwise bufSize can be 0 bufSize = 256 elif ret != 0: raiseWindowsError(space, ret, 'RegQueryValue') while True: dataBuf = ByteBuffer(bufSize) dataBufP = rffi.cast(rffi.CWCHARP, dataBuf.get_raw_address()) with lltype.scoped_alloc(rwin32.LPDWORD.TO, 1) as retType: ret = rwinreg.RegQueryValueExW(hkey, c_subkey, null_dword, retType, dataBufP, dataSize) if ret == rwinreg.ERROR_MORE_DATA: # Resize and retry bufSize *= 2 dataSize[0] = rffi.cast(rwin32.DWORD, bufSize) continue if ret != 0: raiseWindowsError(space, ret, 'RegQueryValueEx') length = intmask(dataSize[0]) return space.newtuple([ convert_from_regdata(space, dataBuf, length, retType[0]), space.newint(intmask(retType[0])), ])
def SetValueEx(space, w_hkey, value_name, w_reserved, typ, w_value): """ SetValueEx(key, value_name, reserved, type, value) - Stores data in the value field of an open registry key. key is an already open key, or any one of the predefined HKEY_* constants. value_name is a string containing the name of the value to set, or None type is an integer that specifies the type of the data. This should be one of: REG_BINARY -- Binary data in any form. REG_DWORD -- A 32-bit number. REG_DWORD_LITTLE_ENDIAN -- A 32-bit number in little-endian format. REG_DWORD_BIG_ENDIAN -- A 32-bit number in big-endian format. REG_EXPAND_SZ -- A null-terminated string that contains unexpanded references to environment variables (for example, %PATH%). REG_LINK -- A Unicode symbolic link. REG_MULTI_SZ -- An sequence of null-terminated strings, terminated by two null characters. Note that Python handles this termination automatically. REG_NONE -- No defined value type. REG_RESOURCE_LIST -- A device-driver resource list. REG_SZ -- A null-terminated string. reserved can be anything - zero is always passed to the API. value is a string that specifies the new value. This method can also set additional value and type information for the specified key. The key identified by the key parameter must have been opened with KEY_SET_VALUE access. To open the key, use the CreateKeyEx() or OpenKeyEx() methods. Value lengths are limited by available memory. Long values (more than 2048 bytes) should be stored as files with the filenames stored in the configuration registry. This helps the registry perform efficiently.""" hkey = hkey_w(w_hkey, space) buf, buflen = convert_to_regdata(space, w_value, typ) try: with rffi.scoped_unicode2wcharp(value_name) as wide_vn: c_vn = rffi.cast(rffi.CWCHARP, wide_vn) ret = rwinreg.RegSetValueExW(hkey, c_vn, 0, typ, buf, buflen) finally: lltype.free(buf, flavor='raw') if ret != 0: raiseWindowsError(space, ret, 'RegSetValueEx')
def QueryValue(space, w_hkey, w_subkey): """string = QueryValue(key, sub_key) - retrieves the unnamed value for a key. key is an already open key, or any one of the predefined HKEY_* constants. sub_key is a string that holds the name of the subkey with which the value is associated. If this parameter is None or empty, the function retrieves the value set by the SetValue() method for the key identified by key. Values in the registry have name, type, and data components. This method retrieves the data for a key's first value that has a NULL name. But the underlying API call doesn't return the type, Lame Lame Lame, DONT USE THIS!!!""" hkey = hkey_w(w_hkey, space) if space.is_w(w_subkey, space.w_None): subkey = None else: subkey = space.unicode_w(w_subkey) with rffi.scoped_unicode2wcharp(subkey) as wide_subkey: c_subkey = rffi.cast(rffi.CCHARP, wide_subkey) with lltype.scoped_alloc(rwin32.PLONG.TO, 1) as bufsize_p: ret = rwinreg.RegQueryValueW(hkey, c_subkey, None, bufsize_p) bufSize = intmask(bufsize_p[0]) if ret == rwinreg.ERROR_MORE_DATA: bufSize = 256 elif ret != 0: raiseWindowsError(space, ret, 'RegQueryValue') while True: with lltype.scoped_alloc(rffi.CCHARP.TO, bufSize) as buf: ret = rwinreg.RegQueryValueW(hkey, c_subkey, buf, bufsize_p) if ret == rwinreg.ERROR_MORE_DATA: print 'bufSize was %d, too small' % bufSize # Resize and retry bufSize *= 2 bufsize_p[0] = bufSize continue if ret != 0: raiseWindowsError(space, ret, 'RegQueryValue') length = intmask(bufsize_p[0] - 1) / 2 wide_buf = rffi.cast(rffi.CWCHARP, buf) return space.newunicode( rffi.wcharp2unicoden(wide_buf, length))
def SaveKey(space, w_hkey, filename): """SaveKey(key, file_name) - Saves the specified key, and all its subkeys to the specified file. key is an already open key, or any one of the predefined HKEY_* constants. file_name is the name of the file to save registry data to. This file cannot already exist. If this filename includes an extension, it cannot be used on file allocation table (FAT) file systems by the LoadKey(), ReplaceKey() or RestoreKey() methods. If key represents a key on a remote computer, the path described by file_name is relative to the remote computer. The caller of this method must possess the SeBackupPrivilege security privilege. This function passes NULL for security_attributes to the API.""" hkey = hkey_w(w_hkey, space) with rffi.scoped_unicode2wcharp(filename) as wide_filename: c_filename = rffi.cast(rffi.CCHARP, wide_filename) ret = rwinreg.RegSaveKeyW(hkey, c_filename, None) if ret != 0: raiseWindowsError(space, ret, 'RegSaveKey')
def CreateKey(space, w_hkey, subkey): """key = CreateKey(key, sub_key) - Creates or opens the specified key. key is an already open key, or one of the predefined HKEY_* constants sub_key is a string that names the key this method opens or creates. If key is one of the predefined keys, sub_key may be None. In that case, the handle returned is the same key handle passed in to the function. If the key already exists, this function opens the existing key The return value is the handle of the opened key. If the function fails, an exception is raised.""" hkey = hkey_w(w_hkey, space) with rffi.scoped_unicode2wcharp(subkey) as wide_subkey: c_subkey = rffi.cast(rffi.CCHARP, wide_subkey) with lltype.scoped_alloc(rwinreg.PHKEY.TO, 1) as rethkey: ret = rwinreg.RegCreateKeyW(hkey, c_subkey, rethkey) if ret != 0: raiseWindowsError(space, ret, 'CreateKey') return W_HKEY(space, rethkey[0])
def OpenKey(space, w_key, sub_key, reserved=0, access=rwinreg.KEY_READ): """key = OpenKey(key, sub_key, res = 0, sam = KEY_READ) - Opens the specified key. key is an already open key, or any one of the predefined HKEY_* constants. sub_key is a string that identifies the sub_key to open res is a reserved integer, and must be zero. Default is zero. sam is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_READ The result is a new handle to the specified key If the function fails, an EnvironmentError exception is raised.""" hkey = hkey_w(w_key, space) with rffi.scoped_unicode2wcharp(sub_key) as wide_subkey: c_subkey = rffi.cast(rffi.CCHARP, wide_subkey) with lltype.scoped_alloc(rwinreg.PHKEY.TO, 1) as rethkey: ret = rwinreg.RegOpenKeyExW(hkey, c_subkey, reserved, access, rethkey) if ret != 0: raiseWindowsError(space, ret, 'RegOpenKeyEx') return W_HKEY(space, rethkey[0])
def dlopen_w(space, w_filename, flags): if WIN32 and space.isinstance_w(w_filename, space.w_unicode): fname = space.text_w(space.repr(w_filename)) unicode_name = space.unicode_w(w_filename) with rffi.scoped_unicode2wcharp(unicode_name) as ll_libname: try: handle = dlopenU(ll_libname, flags) except DLOpenError as e: raise wrap_dlopenerror(space, e, fname) else: if space.is_none(w_filename): fname = None else: fname = space.fsencode_w(w_filename) with rffi.scoped_str2charp(fname) as ll_libname: if fname is None: fname = "<None>" try: handle = dlopen(ll_libname, flags) except DLOpenError as e: raise wrap_dlopenerror(space, e, fname) return fname, handle
def SetEnvironmentVariableW(name, value): with rffi.scoped_unicode2wcharp(name) as nameWbuf: with rffi.scoped_unicode2wcharp(value) as valueWbuf: return _SetEnvironmentVariableW(nameWbuf, valueWbuf)
def convert_to_regdata(space, w_value, typ): ''' returns CCHARP, int ''' buf = None if typ == rwinreg.REG_DWORD: if space.is_none(w_value) or space.isinstance_w(w_value, space.w_int): if space.is_none(w_value): value = r_uint(0) else: value = space.c_uint_w(w_value) buflen = rffi.sizeof(rwin32.DWORD) buf1 = lltype.malloc(rffi.CArray(rwin32.DWORD), 1, flavor='raw') buf1[0] = value buf = rffi.cast(rffi.CCHARP, buf1) elif typ == rwinreg.REG_SZ or typ == rwinreg.REG_EXPAND_SZ: if space.is_w(w_value, space.w_None): buflen = 1 buf = lltype.malloc(rffi.CCHARP.TO, buflen, flavor='raw') buf[0] = '\0' else: buf = rffi.unicode2wcharp(space.unicode_w(w_value)) buf = rffi.cast(rffi.CCHARP, buf) buflen = (space.len_w(w_value) * 2) + 1 elif typ == rwinreg.REG_MULTI_SZ: if space.is_w(w_value, space.w_None): buflen = 1 buf = lltype.malloc(rffi.CCHARP.TO, buflen, flavor='raw') buf[0] = '\0' elif space.isinstance_w(w_value, space.w_list): strings = [] buflen = 0 # unwrap strings and compute total size w_iter = space.iter(w_value) while True: try: w_item = space.next(w_iter) item = space.unicode_w(w_item) strings.append(item) buflen += 2 * (len(item) + 1) except OperationError as e: if not e.match(space, space.w_StopIteration): raise # re-raise other app-level exceptions break buflen += 2 buf = lltype.malloc(rffi.CCHARP.TO, buflen, flavor='raw') # Now copy data buflen = 0 for string in strings: with rffi.scoped_unicode2wcharp(string) as wchr: c_str = rffi.cast(rffi.CCHARP, wchr) for i in range(len(string) * 2): buf[buflen + i] = c_str[i] buflen += (len(string) + 1) * 2 buf[buflen - 1] = '\0' buf[buflen - 2] = '\0' buflen += 2 buf[buflen - 1] = '\0' buf[buflen - 2] = '\0' else: # REG_BINARY and ALL unknown data types. if space.is_w(w_value, space.w_None): buflen = 0 buf = lltype.malloc(rffi.CCHARP.TO, 1, flavor='raw') buf[0] = '\0' else: try: value = w_value.buffer_w(space, space.BUF_SIMPLE) except BufferInterfaceNotFound: raise oefmt( space.w_TypeError, "Objects of type '%T' can not be used as binary " "registry values", w_value) else: value = value.as_str() buflen = len(value) buf = rffi.str2charp(value) if buf is not None: return rffi.cast(rffi.CCHARP, buf), buflen raise oefmt(space.w_ValueError, "Could not convert the data to the specified type")
def transform_decimal(s): with rffi.scoped_unicode2wcharp(s) as u: return space.unwrap( api.PyUnicode_TransformDecimalToASCII(u, len(s)))