def __str__(self): buf = wintypes.LPWSTR() if not _CovertSidToStringSid(self.pointer, buf): raise ctypes.WinError() string_sid = buf.value _LocalFree(buf) return string_sid
def format_system_message(errno): """ Call FormatMessage with a system error number to retrieve the descriptive error message. """ # first some flags used by FormatMessageW ALLOCATE_BUFFER = 0x100 FROM_SYSTEM = 0x1000 # Let FormatMessageW allocate the buffer (we'll free it below) # Also, let it know we want a system error message. flags = ALLOCATE_BUFFER | FROM_SYSTEM source = None message_id = errno language_id = 0 result_buffer = wintypes.LPWSTR() buffer_size = 0 arguments = None bytes = windll.kernel32.FormatMessageW( flags, source, message_id, language_id, byref(result_buffer), buffer_size, arguments, ) # note the following will cause an infinite loop if GetLastError # repeatedly returns an error that cannot be formatted, although # this should not happen. handle_nonzero_success(bytes) message = result_buffer.value windll.kernel32.LocalFree(result_buffer) return message
def _formatMessage(errorCode): """A nice wrapper for FormatMessageW(). TODO Microsoft Documentation: https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-formatmessagew Additional information: https://stackoverflow.com/questions/18905702/python-ctypes-and-mutable-buffers https://stackoverflow.com/questions/455434/how-should-i-use-formatmessage-properly-in-c """ lpBuffer = wintypes.LPWSTR() ctypes.windll.kernel32.FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorCode, 0, # dwLanguageId ctypes.cast(ctypes.byref(lpBuffer), wintypes.LPWSTR), 0, # nSize NULL) msg = lpBuffer.value.rstrip() ctypes.windll.kernel32.LocalFree( lpBuffer) # Free the memory allocated for the error message's buffer. return msg
def CryptUnprotectData(data, optional_entropy=None, prompt_struct=None, flags=0): """ Returns a tuple of (description, data) where description is the the description that was passed to the CryptProtectData call and data is the decrypted result. """ data_in = DATA_BLOB(data) entropy = DATA_BLOB(optional_entropy) if optional_entropy else None data_out = DATA_BLOB() ptr_description = wintypes.LPWSTR() res = _CryptUnprotectData( data_in, ctypes.byref(ptr_description), entropy, None, # reserved prompt_struct, flags | CRYPTPROTECT_UI_FORBIDDEN, data_out, ) handle_nonzero_success(res) description = ptr_description.value if ptr_description.value is not None: ctypes.windll.kernel32.LocalFree(ptr_description) res = data_out.get_data() data_out.free() return description, res
def get_known_folder_path(folder_id, htoken=None): pszPath = wintypes.LPWSTR() _shell32.SHGetKnownFolderPath(ctypes.byref(folder_id), 0, htoken, ctypes.byref(pszPath)) folder_path = pszPath.value _ole32.CoTaskMemFree(pszPath) return folder_path
def __str__(self): if not self: raise ValueError('NULL pointer access') sid = wintypes.LPWSTR() advapi32.ConvertSidToStringSidW(self, ctypes.byref(sid)) try: return sid.value finally: if sid: kernel32.LocalFree(sid)
def __str__(self): if not self: raise ValueError('NULL pointer access') security_identifier = wintypes.LPWSTR() advapi32.ConvertSidToStringSidW(self, ctypes.byref(security_identifier)) try: return security_identifier.value finally: if security_identifier: kernel32.LocalFree(security_identifier)
def __str_to_winustr__(self, in_str_u): """ In: Python unicode string Out: UNICODE_STRING """ in_ustr = UNICODE_STRING() in_ustr.Length = len(in_str_u) in_ustr.MaximumLength = len(in_str_u) + 2 in_ustr.Buffer = wintypes.LPWSTR(in_str_u) return in_ustr
def setup_windows_icon(): # reference: https://stackoverflow.com/questions/1551605 import ctypes from ctypes import wintypes lpBuffer = wintypes.LPWSTR() AppUserModelID = ctypes.windll.shell32.GetCurrentProcessExplicitAppUserModelID AppUserModelID(ctypes.cast(ctypes.byref(lpBuffer), wintypes.LPWSTR)) appid = lpBuffer.value ctypes.windll.kernel32.LocalFree(lpBuffer) if appid is None: appid = 'aps.xpcs_viewer.viewer.0.20' ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(appid)
def _format_message(error_code): lp_buffer = wintypes.LPWSTR() ctypes.windll.kernel32.FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error_code, 0, ctypes.cast(ctypes.byref(lp_buffer), wintypes.LPWSTR), 0, NULL ) msg = lp_buffer.value.rstrip() ctypes.windll.kernel32.LocalFree(lp_buffer) return msg
def get_app_uid(): import ctypes from ctypes import wintypes lpBuffer = wintypes.LPWSTR() try: AppUserModelID = ctypes.windll.shell32.GetCurrentProcessExplicitAppUserModelID except Exception: # Vista has no app uids return AppUserModelID.argtypes = [wintypes.LPWSTR] AppUserModelID.restype = wintypes.HRESULT try: AppUserModelID(ctypes.cast(ctypes.byref(lpBuffer), wintypes.LPWSTR)) except Exception: return appid = lpBuffer.value ctypes.windll.ole32.CoTaskMemFree(lpBuffer) return appid
def open_file_nonblocking(filename, access): # Removes the b for binary access. internal_access = access.replace("b", "") access_mode = ACCESS_MODES[internal_access] open_mode = OPEN_MODES[internal_access] handle = wintypes.HANDLE( ctypes.windll.kernel32.CreateFileW( wintypes.LPWSTR(filename), wintypes.DWORD(access_mode), wintypes.DWORD(2 | 1), # File share read and write ctypes.c_void_p(0), wintypes.DWORD(open_mode), wintypes.DWORD(0), wintypes.HANDLE(0))) try: fd = msvcrt.open_osfhandle(handle.value, 0) except OverflowError as exc: # Python 3.X raise OSError("Failed to open file.") from None # Python 2 # raise OSError("Failed to open file.") return os.fdopen(fd, access)
def _onerror(self, errorcode=None): errid = windll.kernel32.GetLastError() if errid == 0: LANG_NEUTRAL = 0x0 SUBLANG_NEUTRAL = 0x0 LANG_ENGLISH = 0x9 SUBLANG_ENGLISH_US = 0x1 # SYS_FLAG is a combination of: # FORMAT_MESSAGE_ALLOCATE_BUFFER, # FORMAT_MESSAGE_IGNORE_INSERTS and # FORMAT_MESSAGE_FROM_SYSTEM SYS_FLAG = 0x1300 bufptr = wintypes.LPWSTR() # Format as english chars = windll.kernel32.FormatMessageW( SYS_FLAG, None, errid, (LANG_ENGLISH & 0xff) | (SUBLANG_ENGLISH_US & 0xff) << 16, ctypes.byref(bufptr), 0, None) # If that fails, format in system neutral language if chars == 0: chars = windll.kernel32.FormatMessageW( SYS_FLAG, None, errid, (LANG_NEUTRAL & 0xff) | (SUBLANG_NEUTRAL & 0xff) << 16, ctypes.byref(bufptr), 0, None) # Free the message buffer msg = bufptr.value[:chars] windll.kernel32.LocalFree(bufptr) if errorcode is None: raise OSError(msg) else: raise OSError(errorcode, msg)
def _unpackSimpleType(self, record, info, event_property): """ This method handles dumping all simple types of data (i.e., non-struct types). :param record: The EventRecord structure for the event we are parsing :param info: The TraceEventInfo structure for the event we are parsing :param event_property: The EVENT_PROPERTY_INFO structure for the TopLevelProperty of the event we are parsing :return: Returns a key-value pair as a dictionary. If we fail, the dictionary is {} """ # Get the EVENT_MAP_INFO, if it is present. map_info, success = self._getMapInfo(record, info, event_property) if not success: return {} # Get the length of the value of the property we are dealing with. property_length = self._getPropertyLength(record, info, event_property) if property_length is None: return {} # The version of the Python interpreter may be different than the system architecture. if record.contents.EventHeader.Flags & ec.EVENT_HEADER_FLAG_32_BIT_HEADER: ptr_size = 4 else: ptr_size = 8 name_field = rel_ptr_to_str(info, event_property.NameOffset) if property_length == 0 and self.vfield_length is not None: if self.vfield_length == 0: self.vfield_length = None return {name_field: None} # If vfield_length isn't 0, we should be able to parse the property. property_length = self.vfield_length # After calling the TdhFormatProperty function, use the UserDataConsumed parameter value to set the new values # of the UserData and UserDataLength parameters (Subtract UserDataConsumed from UserDataLength and use # UserDataLength to increment the UserData pointer). # All of the variables needed to actually use TdhFormatProperty retrieve the value user_data = record.contents.UserData + self.index user_data_remaining = record.contents.UserDataLength - self.index # if there is no data remaining then return if user_data_remaining <= 0: return {} in_type = event_property.epi_u1.nonStructType.InType out_type = event_property.epi_u1.nonStructType.OutType formatted_data_size = wt.DWORD() formatted_data = wt.LPWSTR() user_data_consumed = ct.c_ushort() status = tdh.TdhFormatProperty( info, map_info, ptr_size, in_type, out_type, ct.c_ushort(property_length), user_data_remaining, ct.cast(user_data, ct.POINTER(ct.c_byte)), ct.byref(formatted_data_size), None, ct.byref(user_data_consumed)) if status == tdh.ERROR_INSUFFICIENT_BUFFER: formatted_data = ct.cast((ct.c_char * formatted_data_size.value)(), wt.LPWSTR) status = tdh.TdhFormatProperty( info, map_info, ptr_size, in_type, out_type, ct.c_ushort(property_length), user_data_remaining, ct.cast(user_data, ct.POINTER(ct.c_byte)), ct.byref(formatted_data_size), formatted_data, ct.byref(user_data_consumed)) if status != tdh.ERROR_SUCCESS: if status != tdh.ERROR_EVT_INVALID_EVENT_DATA: raise ct.WinError(status) # We can handle this error and still capture the data. user_data_consumed, formatted_data = self._handleEvtInvalidEvtData( user_data, user_data_remaining) # Increment where we are in the user data segment that we are parsing. self.index += user_data_consumed.value if name_field.lower().endswith('length'): try: self.vfield_length = int(formatted_data.value, 10) except ValueError: logger.warning('Setting vfield_length to None') self.vfield_length = None data = formatted_data.value # Convert the formatted data if necessary if out_type in tdh.TDH_CONVERTER_LOOKUP: data = tdh.TDH_CONVERTER_LOOKUP[out_type](data) return {name_field: data}
QMainWindow.__init__(self) # It is imperative to call self.setupUi (self) for the interface to initialize. # This is defined in design.py file automatically self.setupUi(self) self.setWindowTitle("Design of Experiments - by Vincent STRAGIER") if __name__ == "__main__": # For Windows set AppID to add an Icon in the taskbar # https://stackoverflow.com/questions/1551605/how-to-set-applications-taskbar-icon-in-windows-7 if sys.platform == 'win32': import ctypes from ctypes import wintypes appid = u'vincent_stragier.umons.doe.v1.0.0' # arbitrary string ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(appid) lpBuffer = wintypes.LPWSTR() AppUserModelID = ctypes.windll.shell32.GetCurrentProcessExplicitAppUserModelID AppUserModelID(ctypes.cast(ctypes.byref(lpBuffer), wintypes.LPWSTR)) appid = lpBuffer.value ctypes.windll.kernel32.LocalFree(lpBuffer) app = QApplication(sys.argv) # Launch the main app. MyApplication = MainApp() MyApplication.show() # Show the form icon_path = os.path.join(os.path.dirname(sys.argv[0]), 'ico', 'fpms.svg') app.setWindowIcon(QIcon(icon_path)) MyApplication.setWindowIcon(QIcon(icon_path)) sys.exit(app.exec_()) # Execute the app
def GetVolumeInformation_handle(self, *argus): # print("GetVolumeInformation_handle") sss = wintypes.LPWSTR(self.volume_name) memmove(argus[0], sss, len(sss.value) * 2) return ntstatus.STATUS_SUCCESS