Package winappdbg :: Package win32 :: Module kernel32
[hide private]
[frames] | no frames]

Source Code for Module winappdbg.win32.kernel32

   1  # Copyright (c) 2009, Mario Vilas 
   2  # All rights reserved. 
   3  # 
   4  # Redistribution and use in source and binary forms, with or without 
   5  # modification, are permitted provided that the following conditions are met: 
   6  # 
   7  #     * Redistributions of source code must retain the above copyright notice, 
   8  #       this list of conditions and the following disclaimer. 
   9  #     * Redistributions in binary form must reproduce the above copyright 
  10  #       notice,this list of conditions and the following disclaimer in the 
  11  #       documentation and/or other materials provided with the distribution. 
  12  #     * Neither the name of the copyright holder nor the names of its 
  13  #       contributors may be used to endorse or promote products derived from 
  14  #       this software without specific prior written permission. 
  15  # 
  16  # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
  17  # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
  18  # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
  19  # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
  20  # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
  21  # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
  22  # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
  23  # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
  24  # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
  25  # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
  26  # POSSIBILITY OF SUCH DAMAGE. 
  27   
  28  """ 
  29  Debugging API wrappers in ctypes. 
  30   
  31  @see: U{http://apps.sourceforge.net/trac/winappdbg/wiki/Win32APIWrappers} 
  32  """ 
  33   
  34  __revision__ = "$Id: kernel32.py 550 2009-12-13 23:52:46Z qvasimodo $" 
  35   
  36  from defines import * 
  37  from version import * 
  38   
  39  #--- CONTEXT structure and constants ------------------------------------------ 
  40   
  41  import context_i386 
  42  import context_amd64 
  43  import context_ia64 
  44   
  45  from context_i386  import CONTEXT_i386, CONTEXT_i486 
  46  from context_amd64 import CONTEXT_AMD64 
  47  from context_ia64  import CONTEXT_IA64 
  48   
  49  ContextArchMask = context_i386.CONTEXT_i386 
  50  ##ContextArchMask = ContextArchMask | context_amd64.CONTEXT_i486 
  51  ContextArchMask = ContextArchMask | context_amd64.CONTEXT_AMD64 
  52  ContextArchMask = ContextArchMask | context_ia64.CONTEXT_IA64 
  53   
  54  if   arch == 'i386': 
  55      from context_i386 import * 
  56  elif arch == 'amd64': 
  57      if sizeof(SIZE_T) == sizeof(DWORD64): 
  58          from context_amd64 import * 
  59      else: 
  60          from context_i386 import * 
  61  elif arch == 'ia64': 
  62      if sizeof(SIZE_T) == sizeof(DWORD64): 
  63          from context_ia64 import * 
  64      else: 
  65          from context_i386 import * 
  66  else: 
  67      print "Warning, unknown or unsupported architecture" 
  68   
  69  #--- Constants ---------------------------------------------------------------- 
  70   
  71  STILL_ACTIVE = 259 
  72   
  73  WAIT_TIMEOUT        = 0x102 
  74  WAIT_FAILED         = -1 
  75  WAIT_OBJECT_0       = 0 
  76   
  77  EXCEPTION_NONCONTINUABLE        = 0x1       # Noncontinuable exception 
  78  EXCEPTION_MAXIMUM_PARAMETERS    = 15        # maximum number of exception parameters 
  79  MAXIMUM_WAIT_OBJECTS            = 64        # Maximum number of wait objects 
  80  MAXIMUM_SUSPEND_COUNT           = 0x7f      # Maximum times thread can be suspended 
  81   
  82  FORMAT_MESSAGE_ALLOCATE_BUFFER  = 0x00000100 
  83  FORMAT_MESSAGE_FROM_SYSTEM      = 0x00001000 
  84   
  85  GR_GDIOBJECTS  = 0 
  86  GR_USEROBJECTS = 1 
  87   
  88  PROCESS_NAME_NATIVE = 1 
  89   
  90  # LoadLibraryEx constants 
  91  DONT_RESOLVE_DLL_REFERENCES         = 0x00000001 
  92  LOAD_LIBRARY_AS_DATAFILE            = 0x00000002 
  93  LOAD_WITH_ALTERED_SEARCH_PATH       = 0x00000008 
  94  LOAD_IGNORE_CODE_AUTHZ_LEVEL        = 0x00000010 
  95  LOAD_LIBRARY_AS_IMAGE_RESOURCE      = 0x00000020 
  96  LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE  = 0x00000040 
  97   
  98  # SetSearchPathMode flags 
  99  # TODO I couldn't find these constants :( 
 100  ##BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE     = ??? 
 101  ##BASE_SEARCH_PATH_DISABLE_SAFE_SEARCHMODE    = ??? 
 102  ##BASE_SEARCH_PATH_PERMANENT                  = ??? 
 103   
 104  # Console control events 
 105  CTRL_C_EVENT        = 0 
 106  CTRL_BREAK_EVENT    = 1 
 107  CTRL_CLOSE_EVENT    = 2 
 108  CTRL_LOGOFF_EVENT   = 5 
 109  CTRL_SHUTDOWN_EVENT = 6 
 110   
 111  # Heap flags 
 112  HEAP_NO_SERIALIZE           = 0x00000001 
 113  HEAP_GENERATE_EXCEPTIONS    = 0x00000004 
 114  HEAP_ZERO_MEMORY            = 0x00000008 
 115  HEAP_CREATE_ENABLE_EXECUTE  = 0x00040000 
 116   
 117  # Standard access rights 
 118  DELETE                      = (0x00010000L) 
 119  READ_CONTROL                = (0x00020000L) 
 120  WRITE_DAC                   = (0x00040000L) 
 121  WRITE_OWNER                 = (0x00080000L) 
 122  SYNCHRONIZE                 = (0x00100000L) 
 123  STANDARD_RIGHTS_REQUIRED    = (0x000F0000L) 
 124  STANDARD_RIGHTS_READ        = (READ_CONTROL) 
 125  STANDARD_RIGHTS_WRITE       = (READ_CONTROL) 
 126  STANDARD_RIGHTS_EXECUTE     = (READ_CONTROL) 
 127  STANDARD_RIGHTS_ALL         = (0x001F0000L) 
 128  SPECIFIC_RIGHTS_ALL         = (0x0000FFFFL) 
 129   
 130  # Process access rights for OpenProcess 
 131  PROCESS_TERMINATE         = (0x0001) 
 132  PROCESS_CREATE_THREAD     = (0x0002) 
 133  PROCESS_SET_SESSIONID     = (0x0004) 
 134  PROCESS_VM_OPERATION      = (0x0008) 
 135  PROCESS_VM_READ           = (0x0010) 
 136  PROCESS_VM_WRITE          = (0x0020) 
 137  PROCESS_DUP_HANDLE        = (0x0040) 
 138  PROCESS_CREATE_PROCESS    = (0x0080) 
 139  PROCESS_SET_QUOTA         = (0x0100) 
 140  PROCESS_SET_INFORMATION   = (0x0200) 
 141  PROCESS_QUERY_INFORMATION = (0x0400) 
 142  PROCESS_SUSPEND_RESUME    = (0x0800) 
 143  PROCESS_ALL_ACCESS        = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFF) 
 144   
 145  # Process priority classes 
 146   
 147  IDLE_PRIORITY_CLASS         = 0x00000040 
 148  BELOW_NORMAL_PRIORITY_CLASS = 0x00004000 
 149  NORMAL_PRIORITY_CLASS       = 0x00000020 
 150  ABOVE_NORMAL_PRIORITY_CLASS = 0x00008000 
 151  HIGH_PRIORITY_CLASS         = 0x00000080 
 152  REALTIME_PRIORITY_CLASS     = 0x00000100 
 153   
 154  PROCESS_MODE_BACKGROUND_BEGIN   = 0x00100000 
 155  PROCESS_MODE_BACKGROUND_END     = 0x00200000 
 156   
 157  # dwCreationFlag values 
 158   
 159  DEBUG_PROCESS                     = 0x00000001 
 160  DEBUG_ONLY_THIS_PROCESS           = 0x00000002 
 161  CREATE_SUSPENDED                  = 0x00000004    # Threads and processes 
 162  DETACHED_PROCESS                  = 0x00000008 
 163  CREATE_NEW_CONSOLE                = 0x00000010 
 164  NORMAL_PRIORITY_CLASS             = 0x00000020 
 165  IDLE_PRIORITY_CLASS               = 0x00000040 
 166  HIGH_PRIORITY_CLASS               = 0x00000080 
 167  REALTIME_PRIORITY_CLASS           = 0x00000100 
 168  CREATE_NEW_PROCESS_GROUP          = 0x00000200 
 169  CREATE_UNICODE_ENVIRONMENT        = 0x00000400 
 170  CREATE_SEPARATE_WOW_VDM           = 0x00000800 
 171  CREATE_SHARED_WOW_VDM             = 0x00001000 
 172  CREATE_FORCEDOS                   = 0x00002000 
 173  BELOW_NORMAL_PRIORITY_CLASS       = 0x00004000 
 174  ABOVE_NORMAL_PRIORITY_CLASS       = 0x00008000 
 175  INHERIT_PARENT_AFFINITY           = 0x00010000 
 176  STACK_SIZE_PARAM_IS_A_RESERVATION = 0x00010000    # Threads only 
 177  INHERIT_CALLER_PRIORITY           = 0x00020000    # Deprecated 
 178  CREATE_PROTECTED_PROCESS          = 0x00040000 
 179  EXTENDED_STARTUPINFO_PRESENT      = 0x00080000 
 180  PROCESS_MODE_BACKGROUND_BEGIN     = 0x00100000 
 181  PROCESS_MODE_BACKGROUND_END       = 0x00200000 
 182  CREATE_BREAKAWAY_FROM_JOB         = 0x01000000 
 183  CREATE_PRESERVE_CODE_AUTHZ_LEVEL  = 0x02000000 
 184  CREATE_DEFAULT_ERROR_MODE         = 0x04000000 
 185  CREATE_NO_WINDOW                  = 0x08000000 
 186  PROFILE_USER                      = 0x10000000 
 187  PROFILE_KERNEL                    = 0x20000000 
 188  PROFILE_SERVER                    = 0x40000000 
 189  CREATE_IGNORE_SYSTEM_DEFAULT      = 0x80000000 
 190   
 191  # Thread priority values 
 192   
 193  THREAD_BASE_PRIORITY_LOWRT  = 15    # value that gets a thread to LowRealtime-1 
 194  THREAD_BASE_PRIORITY_MAX    = 2     # maximum thread base priority boost 
 195  THREAD_BASE_PRIORITY_MIN    = (-2)  # minimum thread base priority boost 
 196  THREAD_BASE_PRIORITY_IDLE   = (-15) # value that gets a thread to idle 
 197   
 198  THREAD_PRIORITY_LOWEST          = THREAD_BASE_PRIORITY_MIN 
 199  THREAD_PRIORITY_BELOW_NORMAL    = (THREAD_PRIORITY_LOWEST+1) 
 200  THREAD_PRIORITY_NORMAL          = 0 
 201  THREAD_PRIORITY_HIGHEST         = THREAD_BASE_PRIORITY_MAX 
 202  THREAD_PRIORITY_ABOVE_NORMAL    = (THREAD_PRIORITY_HIGHEST-1) 
 203  THREAD_PRIORITY_ERROR_RETURN    = (0xFFFFFFFFL) 
 204   
 205  THREAD_PRIORITY_TIME_CRITICAL   = THREAD_BASE_PRIORITY_LOWRT 
 206  THREAD_PRIORITY_IDLE            = THREAD_BASE_PRIORITY_IDLE 
 207   
 208  # Memory access 
 209  SECTION_QUERY                = 0x0001 
 210  SECTION_MAP_WRITE            = 0x0002 
 211  SECTION_MAP_READ             = 0x0004 
 212  SECTION_MAP_EXECUTE          = 0x0008 
 213  SECTION_EXTEND_SIZE          = 0x0010 
 214  SECTION_MAP_EXECUTE_EXPLICIT = 0x0020 # not included in SECTION_ALL_ACCESS 
 215   
 216  SECTION_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED|SECTION_QUERY|\ 
 217                               SECTION_MAP_WRITE |      \ 
 218                               SECTION_MAP_READ |       \ 
 219                               SECTION_MAP_EXECUTE |    \ 
 220                               SECTION_EXTEND_SIZE) 
 221  PAGE_NOACCESS          = 0x01 
 222  PAGE_READONLY          = 0x02 
 223  PAGE_READWRITE         = 0x04 
 224  PAGE_WRITECOPY         = 0x08 
 225  PAGE_EXECUTE           = 0x10 
 226  PAGE_EXECUTE_READ      = 0x20 
 227  PAGE_EXECUTE_READWRITE = 0x40 
 228  PAGE_EXECUTE_WRITECOPY = 0x80 
 229  PAGE_GUARD            = 0x100 
 230  PAGE_NOCACHE          = 0x200 
 231  PAGE_WRITECOMBINE     = 0x400 
 232  MEM_COMMIT           = 0x1000 
 233  MEM_RESERVE          = 0x2000 
 234  MEM_DECOMMIT         = 0x4000 
 235  MEM_RELEASE          = 0x8000 
 236  MEM_FREE            = 0x10000 
 237  MEM_PRIVATE         = 0x20000 
 238  MEM_MAPPED          = 0x40000 
 239  MEM_RESET           = 0x80000 
 240  MEM_TOP_DOWN       = 0x100000 
 241  MEM_WRITE_WATCH    = 0x200000 
 242  MEM_PHYSICAL       = 0x400000 
 243  MEM_LARGE_PAGES  = 0x20000000 
 244  MEM_4MB_PAGES    = 0x80000000 
 245  SEC_FILE           = 0x800000 
 246  SEC_IMAGE         = 0x1000000 
 247  SEC_RESERVE       = 0x4000000 
 248  SEC_COMMIT        = 0x8000000 
 249  SEC_NOCACHE      = 0x10000000 
 250  SEC_LARGE_PAGES  = 0x80000000 
 251  MEM_IMAGE         = SEC_IMAGE 
 252  WRITE_WATCH_FLAG_RESET = 0x01 
 253  FILE_MAP_ALL_ACCESS = 0xF001F 
 254   
 255  SECTION_QUERY                   = 0x0001 
 256  SECTION_MAP_WRITE               = 0x0002 
 257  SECTION_MAP_READ                = 0x0004 
 258  SECTION_MAP_EXECUTE             = 0x0008 
 259  SECTION_EXTEND_SIZE             = 0x0010 
 260  SECTION_MAP_EXECUTE_EXPLICIT    = 0x0020 # not included in SECTION_ALL_ACCESS 
 261   
 262  SECTION_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED|SECTION_QUERY|\ 
 263                   SECTION_MAP_WRITE |      \ 
 264                   SECTION_MAP_READ |       \ 
 265                   SECTION_MAP_EXECUTE |    \ 
 266                   SECTION_EXTEND_SIZE) 
 267   
 268  FILE_MAP_COPY       = SECTION_QUERY 
 269  FILE_MAP_WRITE      = SECTION_MAP_WRITE 
 270  FILE_MAP_READ       = SECTION_MAP_READ 
 271  FILE_MAP_ALL_ACCESS = SECTION_ALL_ACCESS 
 272  FILE_MAP_EXECUTE    = SECTION_MAP_EXECUTE_EXPLICIT  # not included in FILE_MAP_ALL_ACCESS 
 273   
 274  GENERIC_READ                     = 0x80000000 
 275  GENERIC_WRITE                    = 0x40000000 
 276  GENERIC_EXECUTE                  = 0x20000000 
 277  GENERIC_ALL                      = 0x10000000 
 278   
 279  FILE_SHARE_READ                  = 0x00000001 
 280  FILE_SHARE_WRITE                 = 0x00000002 
 281  FILE_SHARE_DELETE                = 0x00000004 
 282   
 283  CREATE_NEW                       = 1 
 284  CREATE_ALWAYS                    = 2 
 285  OPEN_EXISTING                    = 3 
 286  OPEN_ALWAYS                      = 4 
 287  TRUNCATE_EXISTING                = 5 
 288   
 289  FILE_ATTRIBUTE_READONLY          = 0x00000001 
 290  FILE_ATTRIBUTE_NORMAL            = 0x00000080 
 291  FILE_ATTRIBUTE_TEMPORARY         = 0x00000100 
 292   
 293  FILE_FLAG_WRITE_THROUGH          = 0x80000000 
 294  FILE_FLAG_NO_BUFFERING           = 0x20000000 
 295  FILE_FLAG_RANDOM_ACCESS          = 0x10000000 
 296  FILE_FLAG_SEQUENTIAL_SCAN        = 0x08000000 
 297  FILE_FLAG_DELETE_ON_CLOSE        = 0x04000000 
 298  FILE_FLAG_OVERLAPPED             = 0x40000000 
 299   
 300  FILE_ATTRIBUTE_READONLY          = 0x00000001 
 301  FILE_ATTRIBUTE_HIDDEN            = 0x00000002 
 302  FILE_ATTRIBUTE_SYSTEM            = 0x00000004 
 303  FILE_ATTRIBUTE_DIRECTORY         = 0x00000010 
 304  FILE_ATTRIBUTE_ARCHIVE           = 0x00000020 
 305  FILE_ATTRIBUTE_DEVICE            = 0x00000040 
 306  FILE_ATTRIBUTE_NORMAL            = 0x00000080 
 307  FILE_ATTRIBUTE_TEMPORARY         = 0x00000100 
 308   
 309  # Debug events 
 310  EXCEPTION_DEBUG_EVENT       = 1 
 311  CREATE_THREAD_DEBUG_EVENT   = 2 
 312  CREATE_PROCESS_DEBUG_EVENT  = 3 
 313  EXIT_THREAD_DEBUG_EVENT     = 4 
 314  EXIT_PROCESS_DEBUG_EVENT    = 5 
 315  LOAD_DLL_DEBUG_EVENT        = 6 
 316  UNLOAD_DLL_DEBUG_EVENT      = 7 
 317  OUTPUT_DEBUG_STRING_EVENT   = 8 
 318  RIP_EVENT                   = 9 
 319   
 320  # Debug status codes 
 321  DBG_CONTINUE                    = 0x00010002L 
 322  DBG_EXCEPTION_HANDLED           = 0x00010001L 
 323  DBG_EXCEPTION_NOT_HANDLED       = 0x80010001L 
 324  DBG_TERMINATE_THREAD            = 0x40010003L 
 325  DBG_TERMINATE_PROCESS           = 0x40010004L 
 326  DBG_CONTROL_C                   = 0x40010005L 
 327  DBG_CONTROL_BREAK               = 0x40010008L 
 328  DBG_COMMAND_EXCEPTION           = 0x40010009L 
 329   
 330  # Status codes 
 331  STATUS_WAIT_0                   = 0x00000000L 
 332  STATUS_ABANDONED_WAIT_0         = 0x00000080L 
 333  STATUS_USER_APC                 = 0x000000C0L 
 334  STATUS_TIMEOUT                  = 0x00000102L 
 335  STATUS_PENDING                  = 0x00000103L 
 336  STATUS_SEGMENT_NOTIFICATION     = 0x40000005L 
 337  STATUS_GUARD_PAGE_VIOLATION     = 0x80000001L 
 338  STATUS_DATATYPE_MISALIGNMENT    = 0x80000002L 
 339  STATUS_BREAKPOINT               = 0x80000003L 
 340  STATUS_SINGLE_STEP              = 0x80000004L 
 341  STATUS_INVALID_INFO_CLASS       = 0xC0000003L 
 342  STATUS_ACCESS_VIOLATION         = 0xC0000005L 
 343  STATUS_IN_PAGE_ERROR            = 0xC0000006L 
 344  STATUS_INVALID_HANDLE           = 0xC0000008L 
 345  STATUS_NO_MEMORY                = 0xC0000017L 
 346  STATUS_ILLEGAL_INSTRUCTION      = 0xC000001DL 
 347  STATUS_NONCONTINUABLE_EXCEPTION = 0xC0000025L 
 348  STATUS_INVALID_DISPOSITION      = 0xC0000026L 
 349  STATUS_ARRAY_BOUNDS_EXCEEDED    = 0xC000008CL 
 350  STATUS_FLOAT_DENORMAL_OPERAND   = 0xC000008DL 
 351  STATUS_FLOAT_DIVIDE_BY_ZERO     = 0xC000008EL 
 352  STATUS_FLOAT_INEXACT_RESULT     = 0xC000008FL 
 353  STATUS_FLOAT_INVALID_OPERATION  = 0xC0000090L 
 354  STATUS_FLOAT_OVERFLOW           = 0xC0000091L 
 355  STATUS_FLOAT_STACK_CHECK        = 0xC0000092L 
 356  STATUS_FLOAT_UNDERFLOW          = 0xC0000093L 
 357  STATUS_INTEGER_DIVIDE_BY_ZERO   = 0xC0000094L 
 358  STATUS_INTEGER_OVERFLOW         = 0xC0000095L 
 359  STATUS_PRIVILEGED_INSTRUCTION   = 0xC0000096L 
 360  STATUS_STACK_OVERFLOW           = 0xC00000FDL 
 361  STATUS_CONTROL_C_EXIT           = 0xC000013AL 
 362  STATUS_FLOAT_MULTIPLE_FAULTS    = 0xC00002B4L 
 363  STATUS_FLOAT_MULTIPLE_TRAPS     = 0xC00002B5L 
 364  STATUS_REG_NAT_CONSUMPTION      = 0xC00002C9L 
 365  STATUS_SXS_EARLY_DEACTIVATION   = 0xC015000FL 
 366  STATUS_SXS_INVALID_DEACTIVATION = 0xC0150010L 
 367   
 368  STATUS_STACK_BUFFER_OVERRUN     = 0xC0000409L 
 369  STATUS_WX86_BREAKPOINT          = 0x4000001FL 
 370  STATUS_HEAP_CORRUPTION          = 0xC0000374L 
 371   
 372  STATUS_POSSIBLE_DEADLOCK        = 0xC0000194L 
 373   
 374  STATUS_UNWIND_CONSOLIDATE       = 0x80000029L 
 375   
 376  # Exception codes 
 377   
 378  EXCEPTION_ACCESS_VIOLATION          = STATUS_ACCESS_VIOLATION 
 379  EXCEPTION_ARRAY_BOUNDS_EXCEEDED     = STATUS_ARRAY_BOUNDS_EXCEEDED 
 380  EXCEPTION_BREAKPOINT                = STATUS_BREAKPOINT 
 381  EXCEPTION_DATATYPE_MISALIGNMENT     = STATUS_DATATYPE_MISALIGNMENT 
 382  EXCEPTION_FLT_DENORMAL_OPERAND      = STATUS_FLOAT_DENORMAL_OPERAND 
 383  EXCEPTION_FLT_DIVIDE_BY_ZERO        = STATUS_FLOAT_DIVIDE_BY_ZERO 
 384  EXCEPTION_FLT_INEXACT_RESULT        = STATUS_FLOAT_INEXACT_RESULT 
 385  EXCEPTION_FLT_INVALID_OPERATION     = STATUS_FLOAT_INVALID_OPERATION 
 386  EXCEPTION_FLT_OVERFLOW              = STATUS_FLOAT_OVERFLOW 
 387  EXCEPTION_FLT_STACK_CHECK           = STATUS_FLOAT_STACK_CHECK 
 388  EXCEPTION_FLT_UNDERFLOW             = STATUS_FLOAT_UNDERFLOW 
 389  EXCEPTION_ILLEGAL_INSTRUCTION       = STATUS_ILLEGAL_INSTRUCTION 
 390  EXCEPTION_IN_PAGE_ERROR             = STATUS_IN_PAGE_ERROR 
 391  EXCEPTION_INT_DIVIDE_BY_ZERO        = STATUS_INTEGER_DIVIDE_BY_ZERO 
 392  EXCEPTION_INT_OVERFLOW              = STATUS_INTEGER_OVERFLOW 
 393  EXCEPTION_INVALID_DISPOSITION       = STATUS_INVALID_DISPOSITION 
 394  EXCEPTION_NONCONTINUABLE_EXCEPTION  = STATUS_NONCONTINUABLE_EXCEPTION 
 395  EXCEPTION_PRIV_INSTRUCTION          = STATUS_PRIVILEGED_INSTRUCTION 
 396  EXCEPTION_SINGLE_STEP               = STATUS_SINGLE_STEP 
 397  EXCEPTION_STACK_OVERFLOW            = STATUS_STACK_OVERFLOW 
 398   
 399  EXCEPTION_GUARD_PAGE                = STATUS_GUARD_PAGE_VIOLATION 
 400  EXCEPTION_INVALID_HANDLE            = STATUS_INVALID_HANDLE 
 401  EXCEPTION_POSSIBLE_DEADLOCK         = STATUS_POSSIBLE_DEADLOCK 
 402  EXCEPTION_WX86_BREAKPOINT           = STATUS_WX86_BREAKPOINT 
 403   
 404  CONTROL_C_EXIT                      = STATUS_CONTROL_C_EXIT 
 405   
 406  DBG_CONTROL_C                       = 0x40010005L 
 407  MS_VC_EXCEPTION                     = 0x406D1388L 
 408   
 409  # Access violation types 
 410  ACCESS_VIOLATION_TYPE_READ      = EXCEPTION_READ_FAULT 
 411  ACCESS_VIOLATION_TYPE_WRITE     = EXCEPTION_WRITE_FAULT 
 412  ACCESS_VIOLATION_TYPE_DEP       = EXCEPTION_EXECUTE_FAULT 
 413   
 414  # DuplicateHandle constants 
 415  DUPLICATE_CLOSE_SOURCE      = 0x00000001 
 416  DUPLICATE_SAME_ACCESS       = 0x00000002 
 417   
 418  # GetFinalPathNameByHandle constants 
 419  FILE_NAME_NORMALIZED        = 0x0 
 420  FILE_NAME_OPENED            = 0x8 
 421  VOLUME_NAME_DOS             = 0x0 
 422  VOLUME_NAME_GUID            = 0x1 
 423  VOLUME_NAME_NONE            = 0x4 
 424  VOLUME_NAME_NT              = 0x2 
 425   
 426  # GetProductInfo constants 
 427  PRODUCT_BUSINESS = 0x00000006 
 428  PRODUCT_BUSINESS_N = 0x00000010 
 429  PRODUCT_CLUSTER_SERVER = 0x00000012 
 430  PRODUCT_DATACENTER_SERVER = 0x00000008 
 431  PRODUCT_DATACENTER_SERVER_CORE = 0x0000000C 
 432  PRODUCT_DATACENTER_SERVER_CORE_V = 0x00000027 
 433  PRODUCT_DATACENTER_SERVER_V = 0x00000025 
 434  PRODUCT_ENTERPRISE = 0x00000004 
 435  PRODUCT_ENTERPRISE_E = 0x00000046 
 436  PRODUCT_ENTERPRISE_N = 0x0000001B 
 437  PRODUCT_ENTERPRISE_SERVER = 0x0000000A 
 438  PRODUCT_ENTERPRISE_SERVER_CORE = 0x0000000E 
 439  PRODUCT_ENTERPRISE_SERVER_CORE_V = 0x00000029 
 440  PRODUCT_ENTERPRISE_SERVER_IA64 = 0x0000000F 
 441  PRODUCT_ENTERPRISE_SERVER_V = 0x00000026 
 442  PRODUCT_HOME_BASIC = 0x00000002 
 443  PRODUCT_HOME_BASIC_E = 0x00000043 
 444  PRODUCT_HOME_BASIC_N = 0x00000005 
 445  PRODUCT_HOME_PREMIUM = 0x00000003 
 446  PRODUCT_HOME_PREMIUM_E = 0x00000044 
 447  PRODUCT_HOME_PREMIUM_N = 0x0000001A 
 448  PRODUCT_HYPERV = 0x0000002A 
 449  PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT = 0x0000001E 
 450  PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING = 0x00000020 
 451  PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY = 0x0000001F 
 452  PRODUCT_PROFESSIONAL = 0x00000030 
 453  PRODUCT_PROFESSIONAL_E = 0x00000045 
 454  PRODUCT_PROFESSIONAL_N = 0x00000031 
 455  PRODUCT_SERVER_FOR_SMALLBUSINESS = 0x00000018 
 456  PRODUCT_SERVER_FOR_SMALLBUSINESS_V = 0x00000023 
 457  PRODUCT_SERVER_FOUNDATION = 0x00000021 
 458  PRODUCT_SMALLBUSINESS_SERVER = 0x00000009 
 459  PRODUCT_STANDARD_SERVER = 0x00000007 
 460  PRODUCT_STANDARD_SERVER_CORE = 0x0000000D 
 461  PRODUCT_STANDARD_SERVER_CORE_V = 0x00000028 
 462  PRODUCT_STANDARD_SERVER_V = 0x00000024 
 463  PRODUCT_STARTER = 0x0000000B 
 464  PRODUCT_STARTER_E = 0x00000042 
 465  PRODUCT_STARTER_N = 0x0000002F 
 466  PRODUCT_STORAGE_ENTERPRISE_SERVER = 0x00000017 
 467  PRODUCT_STORAGE_EXPRESS_SERVER = 0x00000014 
 468  PRODUCT_STORAGE_STANDARD_SERVER = 0x00000015 
 469  PRODUCT_STORAGE_WORKGROUP_SERVER = 0x00000016 
 470  PRODUCT_UNDEFINED = 0x00000000 
 471  PRODUCT_UNLICENSED = 0xABCDABCD 
 472  PRODUCT_ULTIMATE = 0x00000001 
 473  PRODUCT_ULTIMATE_E = 0x00000047 
 474  PRODUCT_ULTIMATE_N = 0x0000001C 
 475  PRODUCT_WEB_SERVER = 0x00000011 
 476  PRODUCT_WEB_SERVER_CORE = 0x0000001D 
477 478 #--- Handle wrappers ---------------------------------------------------------- 479 480 -class Handle (object):
481 """ 482 Encapsulates Win32 handles to avoid leaking them. 483 484 @see: L{ProcessHandle}, L{ThreadHandle}, L{FileHandle} 485 """ 486
487 - def __init__(self, aHandle = None, bOwnership = True):
488 """ 489 @type aHandle: int 490 @param aHandle: Win32 handle value. 491 492 @type bOwnership: bool 493 @param bOwnership: 494 C{True} if we own the handle and we need to close it. 495 C{False} if someone else will be calling L{CloseHandle}. 496 """ 497 super(Handle, self).__init__() 498 self.value = self._normalize(aHandle) 499 self.bOwnership = bOwnership
500
501 - def __del__(self):
502 """ 503 Closes the Win32 handle when the Python object is destroyed. 504 """ 505 try: 506 self.close() 507 except Exception: 508 pass
509
510 - def __copy__(self):
511 """ 512 Duplicates the Win32 handle when copying the Python object. 513 514 @rtype: L{Handle} 515 @return: A new handle to the same Win32 object. 516 """ 517 return self.dup()
518
519 - def __deepcopy__(self):
520 """ 521 Duplicates the Win32 handle when copying the Python object. 522 523 @rtype: L{Handle} 524 @return: A new handle to the same win32 object. 525 """ 526 return self.dup()
527 528 @property
529 - def _as_parameter_(self):
530 """ 531 Compatibility with ctypes. 532 Allows passing transparently a Handle object to an API call. 533 """ 534 return HANDLE(self.value)
535 536 @staticmethod
537 - def from_param(value):
538 """ 539 Compatibility with ctypes. 540 Allows passing transparently a Handle object to an API call. 541 542 @type value: int 543 @param value: Numeric handle value. 544 """ 545 return HANDLE(value)
546
547 - def close(self):
548 """ 549 Closes the Win32 handle. 550 """ 551 if self.bOwnership and self.value not in (None, INVALID_HANDLE_VALUE): 552 try: 553 CloseHandle(self.value) 554 finally: 555 self.value = None
556
557 - def dup(self):
558 """ 559 @rtype: L{Handle} 560 @return: A new handle to the same Win32 object. 561 """ 562 return DuplicateHandle(self.value)
563 564 @staticmethod
565 - def _normalize(value):
566 """ 567 Normalize handle values. 568 """ 569 if value is None: 570 value = 0 571 elif hasattr(value, 'value'): 572 value = value.value 573 else: 574 value = long(value) 575 return value
576
577 - def wait(self, dwMilliseconds = None):
578 """ 579 Wait for the Win32 object to be signaled. 580 581 @type dwMilliseconds: int 582 @param dwMilliseconds: (Optional) Timeout value in milliseconds. 583 Use C{INFINITE} or C{None} for no timeout. 584 """ 585 if dwMilliseconds is None: 586 dwMilliseconds = INFINITE 587 r = WaitForSingleObject(self.value, dwMilliseconds) 588 if r != WAIT_OBJECT_0: 589 raise ctypes.WinError(r)
590
591 -class ProcessHandle (Handle):
592 """ 593 Win32 process handle. 594 595 @see: L{Handle} 596 """ 597
598 - def get_pid(self):
599 """ 600 @rtype: int 601 @return: Process global ID. 602 """ 603 return GetProcessId(self.value)
604
605 -class ThreadHandle (Handle):
606 """ 607 Win32 thread handle. 608 609 @see: L{Handle} 610 """ 611
612 - def get_tid(self):
613 """ 614 @rtype: int 615 @return: Thread global ID. 616 """ 617 return GetThreadId(self.value)
618
619 # TODO 620 # maybe add file mapping support here? 621 -class FileHandle (Handle):
622 """ 623 Win32 file handle. 624 625 @see: L{Handle} 626 """ 627
628 - def get_filename(self):
629 """ 630 @rtype: None or str 631 @return: Name of the open file, or C{None} if unavailable. 632 """ 633 # 634 # XXX BUG 635 # 636 # This code truncates the first two bytes of the path. 637 # It seems to be the expected behavior of NtQueryInformationFile. 638 # 639 # My guess is it only returns the NT pathname, without the device name. 640 # It's like dropping the drive letter in a Win32 pathname. 641 # 642 # Note that using the "official" GetFileInformationByHandleEx 643 # API introduced in Vista doesn't change the results! 644 # 645 dwBufferSize = 0x1004 646 lpFileInformation = ctypes.create_string_buffer(dwBufferSize) 647 try: 648 GetFileInformationByHandleEx(self.value, 649 FILE_INFO_BY_HANDLE_CLASS.FileNameInfo, 650 lpFileInformation, dwBufferSize) 651 except AttributeError: 652 from ntdll import NtQueryInformationFile, \ 653 FileNameInformation, \ 654 FILE_NAME_INFORMATION 655 NtQueryInformationFile(self.value, 656 FileNameInformation, 657 lpFileInformation, 658 dwBufferSize) 659 FileName = unicode(lpFileInformation.raw[sizeof(DWORD):], 'U16') 660 FileName = ctypes.create_unicode_buffer(FileName).value 661 if not FileName: 662 FileName = None 663 return FileName
664
665 #--- Structure wrappers ------------------------------------------------------- 666 667 -class ProcessInformation (object):
668 """ 669 Process information object returned by L{CreateProcess}. 670 """ 671
672 - def __init__(self, pi):
673 self.hProcess = ProcessHandle(pi.hProcess) 674 self.hThread = ThreadHandle(pi.hThread) 675 self.dwProcessId = pi.dwProcessId 676 self.dwThreadId = pi.dwThreadId
677
678 -class MemoryBasicInformation (object):
679 """ 680 Memory information object returned by L{VirtualQueryEx}. 681 """ 682 683 READABLE = ( 684 PAGE_EXECUTE_READ | 685 PAGE_EXECUTE_READWRITE | 686 PAGE_EXECUTE_WRITECOPY | 687 PAGE_READONLY | 688 PAGE_READWRITE | 689 PAGE_WRITECOPY 690 ) 691 692 WRITEABLE = ( 693 PAGE_EXECUTE_READWRITE | 694 PAGE_EXECUTE_WRITECOPY | 695 PAGE_READWRITE | 696 PAGE_WRITECOPY 697 ) 698 699 COPY_ON_WRITE = ( 700 PAGE_EXECUTE_WRITECOPY | 701 PAGE_WRITECOPY 702 ) 703 704 EXECUTABLE = ( 705 PAGE_EXECUTE | 706 PAGE_EXECUTE_READ | 707 PAGE_EXECUTE_READWRITE | 708 PAGE_EXECUTE_WRITECOPY 709 ) 710 711 EXECUTABLE_AND_WRITEABLE = ( 712 PAGE_EXECUTE_READWRITE | 713 PAGE_EXECUTE_WRITECOPY 714 ) 715
716 - def __init__(self, mbi):
717 self.BaseAddress = mbi.BaseAddress 718 self.AllocationBase = mbi.AllocationBase 719 self.AllocationProtect = mbi.AllocationProtect 720 self.RegionSize = mbi.RegionSize 721 self.State = mbi.State 722 self.Protect = mbi.Protect 723 self.Type = mbi.Type
724
725 - def is_free(self):
726 return self.State == MEM_FREE
727
728 - def is_reserved(self):
729 return self.State == MEM_RESERVE
730
731 - def is_commited(self):
732 return self.State == MEM_COMMIT
733
734 - def is_guard(self):
735 return self.is_commited() and bool(self.Protect & PAGE_GUARD)
736
737 - def has_content(self):
738 return self.is_commited() and not bool(self.Protect & (PAGE_GUARD | PAGE_NOACCESS))
739
740 - def is_readable(self):
741 return self.has_content() and bool(self.Protect & self.READABLE)
742
743 - def is_writeable(self):
744 return self.has_content() and bool(self.Protect & self.WRITEABLE)
745
746 - def is_copy_on_write(self):
747 return self.has_content() and bool(self.Protect & self.COPY_ON_WRITE)
748
749 - def is_executable(self):
750 return self.has_content() and bool(self.Protect & self.EXECUTABLE)
751
753 return self.has_content() and bool(self.Protect & self.EXECUTABLE_AND_WRITEABLE)
754
755 -class ProcThreadAttributeList (object):
756 """ 757 Extended process and thread attribute support. 758 759 To be used with L{STARTUPINFOEX}. 760 Only available for Windows Vista and above. 761 762 @type AttributeList: list of tuple( int, ctypes-compatible object ) 763 @ivar AttributeList: List of (Attribute, Value) pairs. 764 765 @type AttributeListBuffer: L{LPPROC_THREAD_ATTRIBUTE_LIST} 766 @ivar AttributeListBuffer: Memory buffer used to store the attribute list. 767 L{InitializeProcThreadAttributeList}, 768 L{UpdateProcThreadAttribute}, 769 L{DeleteProcThreadAttributeList} and 770 L{STARTUPINFOEX}. 771 """ 772
773 - def __init__(self, AttributeList):
774 """ 775 @type AttributeList: list of tuple( int, ctypes-compatible object ) 776 @param AttributeList: List of (Attribute, Value) pairs. 777 """ 778 self.AttributeList = AttributeList 779 self.AttributeListBuffer = InitializeProcThreadAttributeList( 780 len(AttributeList)) 781 try: 782 for Attribute, Value in AttributeList: 783 UpdateProcThreadAttribute(self.AttributeListBuffer, 784 Attribute, Value) 785 except: 786 ProcThreadAttributeList.__del__(self) 787 raise
788
789 - def __del__(self):
790 try: 791 DeleteProcThreadAttributeList(self.AttributeListBuffer) 792 del self.AttributeListBuffer 793 except Exception: 794 pass
795
796 - def __copy__(self):
797 return self.__deepcopy__()
798
799 - def __deepcopy__(self):
800 return self.__class__(self.AttributeList)
801 802 @property
803 - def value(self):
804 return ctypes.cast(ctypes.pointer(self.AttributeListBuffer), LPVOID)
805 806 @property
807 - def _as_parameter_(self):
808 return self.value
809 810 # XXX TODO 811 @staticmethod
812 - def from_param(value):
813 raise NotImplementedError
814
815 #--- OVERLAPPED structure ----------------------------------------------------- 816 817 # typedef struct _OVERLAPPED { 818 # ULONG_PTR Internal; 819 # ULONG_PTR InternalHigh; 820 # union { 821 # struct { 822 # DWORD Offset; 823 # DWORD OffsetHigh; 824 # } ; 825 # PVOID Pointer; 826 # } ; 827 # HANDLE hEvent; 828 # }OVERLAPPED, *LPOVERLAPPED; 829 -class _OVERLAPPED_STRUCT(Structure):
830 _fields_ = [ 831 ('Offset', DWORD), 832 ('OffsetHigh', DWORD), 833 ]
834 -class _OVERLAPPED_UNION(Union):
835 _fields_ = [ 836 ('s', _OVERLAPPED_STRUCT), 837 ('Pointer', PVOID), 838 ]
839 -class OVERLAPPED(Structure):
840 _fields_ = [ 841 ('Internal', ULONG_PTR), 842 ('InternalHigh', ULONG_PTR), 843 ('u', _OVERLAPPED_UNION), 844 ('hEvent', HANDLE), 845 ]
846 LPOVERLAPPED = POINTER(OVERLAPPED)
847 848 #--- SECURITY_ATTRIBUTES structure -------------------------------------------- 849 850 # typedef struct _SECURITY_ATTRIBUTES { 851 # DWORD nLength; 852 # LPVOID lpSecurityDescriptor; 853 # BOOL bInheritHandle; 854 # } SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES; 855 -class SECURITY_ATTRIBUTES(Structure):
856 _fields_ = [ 857 ('nLength', DWORD), 858 ('lpSecurityDescriptor', LPVOID), 859 ('bInheritHandle', BOOL), 860 ]
861 LPSECURITY_ATTRIBUTES = POINTER(SECURITY_ATTRIBUTES) 862 863 # --- Extended process and thread attribute support --------------------------- 864 865 PPROC_THREAD_ATTRIBUTE_LIST = LPVOID 866 LPPROC_THREAD_ATTRIBUTE_LIST = PPROC_THREAD_ATTRIBUTE_LIST 867 868 PROC_THREAD_ATTRIBUTE_NUMBER = 0x0000FFFF 869 PROC_THREAD_ATTRIBUTE_THREAD = 0x00010000 # Attribute may be used with thread creation 870 PROC_THREAD_ATTRIBUTE_INPUT = 0x00020000 # Attribute is input only 871 PROC_THREAD_ATTRIBUTE_ADDITIVE = 0x00040000 # Attribute may be "accumulated," e.g. bitmasks, counters, etc. 872 873 # PROC_THREAD_ATTRIBUTE_NUM 874 ProcThreadAttributeParentProcess = 0 875 ProcThreadAttributeExtendedFlags = 1 876 ProcThreadAttributeHandleList = 2 877 ProcThreadAttributeGroupAffinity = 3 878 ProcThreadAttributePreferredNode = 4 879 ProcThreadAttributeIdealProcessor = 5 880 ProcThreadAttributeUmsThread = 6 881 ProcThreadAttributeMitigationPolicy = 7 882 ProcThreadAttributeMax = 8 883 884 PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = ProcThreadAttributeParentProcess | PROC_THREAD_ATTRIBUTE_INPUT 885 PROC_THREAD_ATTRIBUTE_EXTENDED_FLAGS = ProcThreadAttributeExtendedFlags | PROC_THREAD_ATTRIBUTE_INPUT | PROC_THREAD_ATTRIBUTE_ADDITIVE 886 PROC_THREAD_ATTRIBUTE_HANDLE_LIST = ProcThreadAttributeHandleList | PROC_THREAD_ATTRIBUTE_INPUT 887 PROC_THREAD_ATTRIBUTE_GROUP_AFFINITY = ProcThreadAttributeGroupAffinity | PROC_THREAD_ATTRIBUTE_THREAD | PROC_THREAD_ATTRIBUTE_INPUT 888 PROC_THREAD_ATTRIBUTE_PREFERRED_NODE = ProcThreadAttributePreferredNode | PROC_THREAD_ATTRIBUTE_INPUT 889 PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR = ProcThreadAttributeIdealProcessor | PROC_THREAD_ATTRIBUTE_THREAD | PROC_THREAD_ATTRIBUTE_INPUT 890 PROC_THREAD_ATTRIBUTE_UMS_THREAD = ProcThreadAttributeUmsThread | PROC_THREAD_ATTRIBUTE_THREAD | PROC_THREAD_ATTRIBUTE_INPUT 891 PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY = ProcThreadAttributeMitigationPolicy | PROC_THREAD_ATTRIBUTE_INPUT 892 893 PROCESS_CREATION_MITIGATION_POLICY_DEP_ENABLE = 0x01 894 PROCESS_CREATION_MITIGATION_POLICY_DEP_ATL_THUNK_ENABLE = 0x02 895 PROCESS_CREATION_MITIGATION_POLICY_SEHOP_ENABLE = 0x04
896 897 #--- VS_FIXEDFILEINFO structure ----------------------------------------------- 898 899 # struct VS_FIXEDFILEINFO { 900 # DWORD dwSignature; 901 # DWORD dwStrucVersion; 902 # DWORD dwFileVersionMS; 903 # DWORD dwFileVersionLS; 904 # DWORD dwProductVersionMS; 905 # DWORD dwProductVersionLS; 906 # DWORD dwFileFlagsMask; 907 # DWORD dwFileFlags; 908 # DWORD dwFileOS; 909 # DWORD dwFileType; 910 # DWORD dwFileSubtype; 911 # DWORD dwFileDateMS; 912 # DWORD dwFileDateLS; 913 # }; 914 -class VS_FIXEDFILEINFO (Structure):
915 _fields_ = [ 916 ("dwSignature", DWORD), # 0xFEEF04BD 917 ("dwStrucVersion", DWORD), 918 ("dwFileVersionMS", DWORD), 919 ("dwFileVersionLS", DWORD), 920 ("dwProductVersionMS", DWORD), 921 ("dwProductVersionLS", DWORD), 922 ("dwFileFlagsMask", DWORD), 923 ("dwFileFlags", DWORD), 924 ("dwFileOS", DWORD), 925 ("dwFileType", DWORD), 926 ("dwFileSubtype", DWORD), 927 ("dwFileDateMS", DWORD), 928 ("dwFileDateLS", DWORD), 929 ]
930
931 #--- THREADNAME_INFO structure ------------------------------------------------ 932 933 # typedef struct tagTHREADNAME_INFO 934 # { 935 # DWORD dwType; // Must be 0x1000. 936 # LPCSTR szName; // Pointer to name (in user addr space). 937 # DWORD dwThreadID; // Thread ID (-1=caller thread). 938 # DWORD dwFlags; // Reserved for future use, must be zero. 939 # } THREADNAME_INFO; 940 -class THREADNAME_INFO(Structure):
941 _fields_ = [ 942 ("dwType", DWORD), # 0x1000 943 ("szName", LPVOID), # remote pointer 944 ("dwThreadID", DWORD), # -1 usually 945 ("dwFlags", DWORD), # 0 946 ]
947
948 #--- MEMORY_BASIC_INFORMATION structure --------------------------------------- 949 950 # typedef struct _MEMORY_BASIC_INFORMATION32 { 951 # DWORD BaseAddress; 952 # DWORD AllocationBase; 953 # DWORD AllocationProtect; 954 # DWORD RegionSize; 955 # DWORD State; 956 # DWORD Protect; 957 # DWORD Type; 958 # } MEMORY_BASIC_INFORMATION32, *PMEMORY_BASIC_INFORMATION32; 959 -class MEMORY_BASIC_INFORMATION32(Structure):
960 _fields_ = [ 961 ('BaseAddress', DWORD), # remote pointer 962 ('AllocationBase', DWORD), # remote pointer 963 ('AllocationProtect', DWORD), 964 ('RegionSize', DWORD), 965 ('State', DWORD), 966 ('Protect', DWORD), 967 ('Type', DWORD), 968 ]
969
970 # typedef struct DECLSPEC_ALIGN(16) _MEMORY_BASIC_INFORMATION64 { 971 # ULONGLONG BaseAddress; 972 # ULONGLONG AllocationBase; 973 # DWORD AllocationProtect; 974 # DWORD __alignment1; 975 # ULONGLONG RegionSize; 976 # DWORD State; 977 # DWORD Protect; 978 # DWORD Type; 979 # DWORD __alignment2; 980 # } MEMORY_BASIC_INFORMATION64, *PMEMORY_BASIC_INFORMATION64; 981 -class MEMORY_BASIC_INFORMATION64(Structure):
982 _fields_ = [ 983 ('BaseAddress', ULONGLONG), # remote pointer 984 ('AllocationBase', ULONGLONG), # remote pointer 985 ('AllocationProtect', DWORD), 986 ('__alignment1', DWORD), 987 ('RegionSize', ULONGLONG), 988 ('State', DWORD), 989 ('Protect', DWORD), 990 ('Type', DWORD), 991 ('__alignment2', DWORD), 992 ]
993 994 # typedef struct _MEMORY_BASIC_INFORMATION { 995 # PVOID BaseAddress; 996 # PVOID AllocationBase; 997 # DWORD AllocationProtect; 998 # SIZE_T RegionSize; 999 # DWORD State; 1000 # DWORD Protect; 1001 # DWORD Type; 1002 # } MEMORY_BASIC_INFORMATION, *PMEMORY_BASIC_INFORMATION; 1003 if sizeof(SIZE_T) == sizeof(DWORD):
1004 - class MEMORY_BASIC_INFORMATION(MEMORY_BASIC_INFORMATION32):
1005 pass
1006 elif sizeof(SIZE_T) == sizeof(DWORD64):
1007 - class MEMORY_BASIC_INFORMATION(MEMORY_BASIC_INFORMATION64):
1008 pass
1009 else:
1010 - class MEMORY_BASIC_INFORMATION(Structure):
1011 _fields_ = [ 1012 ('BaseAddress', SIZE_T), # remote pointer 1013 ('AllocationBase', SIZE_T), # remote pointer 1014 ('AllocationProtect', DWORD), 1015 ('RegionSize', SIZE_T), 1016 ('State', DWORD), 1017 ('Protect', DWORD), 1018 ('Type', DWORD), 1019 ]
1020 PMEMORY_BASIC_INFORMATION = POINTER(MEMORY_BASIC_INFORMATION)
1021 1022 #--- BY_HANDLE_FILE_INFORMATION structure ------------------------------------- 1023 1024 # typedef struct _FILETIME { 1025 # DWORD dwLowDateTime; 1026 # DWORD dwHighDateTime; 1027 # } FILETIME, *PFILETIME; 1028 -class FILETIME(Structure):
1029 _fields_ = [ 1030 ('dwLowDateTime', DWORD), 1031 ('dwHighDateTime', DWORD), 1032 ]
1033 LPFILETIME = POINTER(FILETIME)
1034 1035 # typedef struct _SYSTEMTIME { 1036 # WORD wYear; 1037 # WORD wMonth; 1038 # WORD wDayOfWeek; 1039 # WORD wDay; 1040 # WORD wHour; 1041 # WORD wMinute; 1042 # WORD wSecond; 1043 # WORD wMilliseconds; 1044 # }SYSTEMTIME, *PSYSTEMTIME; 1045 -class SYSTEMTIME(Structure):
1046 _fields_ = [ 1047 ('wYear', WORD), 1048 ('wMonth', WORD), 1049 ('wDayOfWeek', WORD), 1050 ('wDay', WORD), 1051 ('wHour', WORD), 1052 ('wMinute', WORD), 1053 ('wSecond', WORD), 1054 ('wMilliseconds', WORD), 1055 ]
1056 LPSYSTEMTIME = POINTER(SYSTEMTIME)
1057 1058 # typedef struct _BY_HANDLE_FILE_INFORMATION { 1059 # DWORD dwFileAttributes; 1060 # FILETIME ftCreationTime; 1061 # FILETIME ftLastAccessTime; 1062 # FILETIME ftLastWriteTime; 1063 # DWORD dwVolumeSerialNumber; 1064 # DWORD nFileSizeHigh; 1065 # DWORD nFileSizeLow; 1066 # DWORD nNumberOfLinks; 1067 # DWORD nFileIndexHigh; 1068 # DWORD nFileIndexLow; 1069 # } BY_HANDLE_FILE_INFORMATION, *PBY_HANDLE_FILE_INFORMATION; 1070 -class BY_HANDLE_FILE_INFORMATION(Structure):
1071 _fields_ = [ 1072 ('dwFileAttributes', DWORD), 1073 ('ftCreationTime', FILETIME), 1074 ('ftLastAccessTime', FILETIME), 1075 ('ftLastWriteTime', FILETIME), 1076 ('dwVolumeSerialNumber', DWORD), 1077 ('nFileSizeHigh', DWORD), 1078 ('nFileSizeLow', DWORD), 1079 ('nNumberOfLinks', DWORD), 1080 ('nFileIndexHigh', DWORD), 1081 ('nFileIndexLow', DWORD), 1082 ]
1083 LPBY_HANDLE_FILE_INFORMATION = ctypes.POINTER(BY_HANDLE_FILE_INFORMATION)
1084 1085 # typedef enum _FILE_INFO_BY_HANDLE_CLASS { 1086 # FileBasicInfo = 0, 1087 # FileStandardInfo = 1, 1088 # FileNameInfo = 2, 1089 # FileRenameInfo = 3, 1090 # FileDispositionInfo = 4, 1091 # FileAllocationInfo = 5, 1092 # FileEndOfFileInfo = 6, 1093 # FileStreamInfo = 7, 1094 # FileCompressionInfo = 8, 1095 # FileAttributeTagInfo = 9, 1096 # FileIdBothDirectoryInfo = 10, 1097 # FileIdBothDirectoryRestartInfo = 11, 1098 # FileIoPriorityHintInfo = 12, 1099 # MaximumFileInfoByHandlesClass = 13 1100 # } FILE_INFO_BY_HANDLE_CLASS, *PFILE_INFO_BY_HANDLE_CLASS; 1101 -class FILE_INFO_BY_HANDLE_CLASS(object):
1102 FileBasicInfo = 0 1103 FileStandardInfo = 1 1104 FileNameInfo = 2 1105 FileRenameInfo = 3 1106 FileDispositionInfo = 4 1107 FileAllocationInfo = 5 1108 FileEndOfFileInfo = 6 1109 FileStreamInfo = 7 1110 FileCompressionInfo = 8 1111 FileAttributeTagInfo = 9 1112 FileIdBothDirectoryInfo = 10 1113 FileIdBothDirectoryRestartInfo = 11 1114 FileIoPriorityHintInfo = 12 1115 MaximumFileInfoByHandlesClass = 13
1116
1117 # typedef struct _FILE_NAME_INFO { 1118 # DWORD FileNameLength; 1119 # WCHAR FileName[1]; 1120 # } FILE_NAME_INFO, *PFILE_NAME_INFO; 1121 ##class FILE_NAME_INFO(Structure): 1122 ## _fields_ = [ 1123 ## ('FileNameLength', DWORD), 1124 ## ('FileName', WCHAR * 1), 1125 ## ] 1126 1127 # TO DO: add more structures used by GetFileInformationByHandleEx() 1128 1129 #--- PROCESS_INFORMATION structure -------------------------------------------- 1130 1131 # typedef struct _PROCESS_INFORMATION { 1132 # HANDLE hProcess; 1133 # HANDLE hThread; 1134 # DWORD dwProcessId; 1135 # DWORD dwThreadId; 1136 # } PROCESS_INFORMATION, *PPROCESS_INFORMATION, *LPPROCESS_INFORMATION; 1137 -class PROCESS_INFORMATION(Structure):
1138 _fields_ = [ 1139 ('hProcess', HANDLE), 1140 ('hThread', HANDLE), 1141 ('dwProcessId', DWORD), 1142 ('dwThreadId', DWORD), 1143 ]
1144 LPPROCESS_INFORMATION = POINTER(PROCESS_INFORMATION)
1145 1146 #--- STARTUPINFO and STARTUPINFOEX structures --------------------------------- 1147 1148 # typedef struct _STARTUPINFO { 1149 # DWORD cb; 1150 # LPTSTR lpReserved; 1151 # LPTSTR lpDesktop; 1152 # LPTSTR lpTitle; 1153 # DWORD dwX; 1154 # DWORD dwY; 1155 # DWORD dwXSize; 1156 # DWORD dwYSize; 1157 # DWORD dwXCountChars; 1158 # DWORD dwYCountChars; 1159 # DWORD dwFillAttribute; 1160 # DWORD dwFlags; 1161 # WORD wShowWindow; 1162 # WORD cbReserved2; 1163 # LPBYTE lpReserved2; 1164 # HANDLE hStdInput; 1165 # HANDLE hStdOutput; 1166 # HANDLE hStdError; 1167 # }STARTUPINFO, *LPSTARTUPINFO; 1168 -class STARTUPINFO(Structure):
1169 _fields_ = [ 1170 ('cb', DWORD), 1171 ('lpReserved', LPSTR), 1172 ('lpDesktop', LPSTR), 1173 ('lpTitle', LPSTR), 1174 ('dwX', DWORD), 1175 ('dwY', DWORD), 1176 ('dwXSize', DWORD), 1177 ('dwYSize', DWORD), 1178 ('dwXCountChars', DWORD), 1179 ('dwYCountChars', DWORD), 1180 ('dwFillAttribute', DWORD), 1181 ('dwFlags', DWORD), 1182 ('wShowWindow', WORD), 1183 ('cbReserved2', WORD), 1184 ('lpReserved2', LPVOID), # LPBYTE 1185 ('hStdInput', HANDLE), 1186 ('hStdOutput', HANDLE), 1187 ('hStdError', HANDLE), 1188 ]
1189 LPSTARTUPINFO = POINTER(STARTUPINFO)
1190 1191 # typedef struct _STARTUPINFOEX { 1192 # STARTUPINFO StartupInfo; 1193 # PPROC_THREAD_ATTRIBUTE_LIST lpAttributeList; 1194 # } STARTUPINFOEX, *LPSTARTUPINFOEX; 1195 -class STARTUPINFOEX(Structure):
1196 _fields_ = [ 1197 ('StartupInfo', STARTUPINFO), 1198 ('lpAttributeList', PPROC_THREAD_ATTRIBUTE_LIST), 1199 ]
1200 LPSTARTUPINFOEX = POINTER(STARTUPINFOEX)
1201 1202 #--- JIT_DEBUG_INFO structure ------------------------------------------------- 1203 1204 # typedef struct _JIT_DEBUG_INFO { 1205 # DWORD dwSize; 1206 # DWORD dwProcessorArchitecture; 1207 # DWORD dwThreadID; 1208 # DWORD dwReserved0; 1209 # ULONG64 lpExceptionAddress; 1210 # ULONG64 lpExceptionRecord; 1211 # ULONG64 lpContextRecord; 1212 # } JIT_DEBUG_INFO, *LPJIT_DEBUG_INFO; 1213 -class JIT_DEBUG_INFO(Structure):
1214 _fields_ = [ 1215 ('dwSize', DWORD), 1216 ('dwProcessorArchitecture', DWORD), 1217 ('dwThreadID', DWORD), 1218 ('dwReserved0', DWORD), 1219 ('lpExceptionAddress', ULONG64), 1220 ('lpExceptionRecord', ULONG64), 1221 ('lpContextRecord', ULONG64), 1222 ]
1223 JIT_DEBUG_INFO32 = JIT_DEBUG_INFO 1224 JIT_DEBUG_INFO64 = JIT_DEBUG_INFO 1225 1226 LPJIT_DEBUG_INFO = ctypes.POINTER(JIT_DEBUG_INFO) 1227 LPJIT_DEBUG_INFO32 = ctypes.POINTER(JIT_DEBUG_INFO32) 1228 LPJIT_DEBUG_INFO64 = ctypes.POINTER(JIT_DEBUG_INFO64)
1229 1230 #--- DEBUG_EVENT structure ---------------------------------------------------- 1231 1232 # typedef struct _EXCEPTION_RECORD32 { 1233 # DWORD ExceptionCode; 1234 # DWORD ExceptionFlags; 1235 # DWORD ExceptionRecord; 1236 # DWORD ExceptionAddress; 1237 # DWORD NumberParameters; 1238 # DWORD ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS]; 1239 # } EXCEPTION_RECORD32, *PEXCEPTION_RECORD32; 1240 -class EXCEPTION_RECORD32(Structure):
1241 _fields_ = [ 1242 ('ExceptionCode', DWORD), 1243 ('ExceptionFlags', DWORD), 1244 ('ExceptionRecord', DWORD), 1245 ('ExceptionAddress', DWORD), 1246 ('NumberParameters', DWORD), 1247 ('ExceptionInformation', DWORD * EXCEPTION_MAXIMUM_PARAMETERS), 1248 ]
1249 1250 PEXCEPTION_RECORD32 = POINTER(EXCEPTION_RECORD32)
1251 1252 # typedef struct _EXCEPTION_RECORD64 { 1253 # DWORD ExceptionCode; 1254 # DWORD ExceptionFlags; 1255 # DWORD64 ExceptionRecord; 1256 # DWORD64 ExceptionAddress; 1257 # DWORD NumberParameters; 1258 # DWORD __unusedAlignment; 1259 # DWORD64 ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS]; 1260 # } EXCEPTION_RECORD64, *PEXCEPTION_RECORD64; 1261 -class EXCEPTION_RECORD64(Structure):
1262 _fields_ = [ 1263 ('ExceptionCode', DWORD), 1264 ('ExceptionFlags', DWORD), 1265 ('ExceptionRecord', DWORD64), 1266 ('ExceptionAddress', DWORD64), 1267 ('NumberParameters', DWORD), 1268 ('__unusedAlignment', DWORD), 1269 ('ExceptionInformation', DWORD64 * EXCEPTION_MAXIMUM_PARAMETERS), 1270 ]
1271 1272 PEXCEPTION_RECORD64 = POINTER(EXCEPTION_RECORD64) 1273 1274 if sizeof(SIZE_T) == sizeof(DWORD): 1275 EXCEPTION_RECORD = EXCEPTION_RECORD32 1276 elif sizeof(SIZE_T) == sizeof(DWORD64): 1277 EXCEPTION_RECORD = EXCEPTION_RECORD64 1278 else:
1279 # typedef struct _EXCEPTION_RECORD { 1280 # DWORD ExceptionCode; 1281 # DWORD ExceptionFlags; 1282 # LPVOID ExceptionRecord; 1283 # LPVOID ExceptionAddress; 1284 # DWORD NumberParameters; 1285 # LPVOID ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS]; 1286 # } EXCEPTION_RECORD, *PEXCEPTION_RECORD; 1287 - class EXCEPTION_RECORD(Structure):
1288 _fields_ = [ 1289 ('ExceptionCode', DWORD), 1290 ('ExceptionFlags', DWORD), 1291 ('ExceptionRecord', LPVOID), 1292 ('ExceptionAddress', LPVOID), 1293 ('NumberParameters', DWORD), 1294 ('ExceptionInformation', LPVOID * EXCEPTION_MAXIMUM_PARAMETERS), 1295 ]
1296 PEXCEPTION_RECORD = POINTER(EXCEPTION_RECORD)
1297 1298 # typedef struct _EXCEPTION_DEBUG_INFO { 1299 # EXCEPTION_RECORD ExceptionRecord; 1300 # DWORD dwFirstChance; 1301 # } EXCEPTION_DEBUG_INFO; 1302 -class EXCEPTION_DEBUG_INFO(Structure):
1303 _fields_ = [ 1304 ('ExceptionRecord', EXCEPTION_RECORD), 1305 ('dwFirstChance', DWORD), 1306 ]
1307
1308 # typedef struct _CREATE_THREAD_DEBUG_INFO { 1309 # HANDLE hThread; 1310 # LPVOID lpThreadLocalBase; 1311 # LPTHREAD_START_ROUTINE lpStartAddress; 1312 # } CREATE_THREAD_DEBUG_INFO; 1313 -class CREATE_THREAD_DEBUG_INFO(Structure):
1314 _fields_ = [ 1315 ('hThread', HANDLE), 1316 ('lpThreadLocalBase', LPVOID), 1317 ('lpStartAddress', LPVOID), 1318 ]
1319
1320 # typedef struct _CREATE_PROCESS_DEBUG_INFO { 1321 # HANDLE hFile; 1322 # HANDLE hProcess; 1323 # HANDLE hThread; 1324 # LPVOID lpBaseOfImage; 1325 # DWORD dwDebugInfoFileOffset; 1326 # DWORD nDebugInfoSize; 1327 # LPVOID lpThreadLocalBase; 1328 # LPTHREAD_START_ROUTINE lpStartAddress; 1329 # LPVOID lpImageName; 1330 # WORD fUnicode; 1331 # } CREATE_PROCESS_DEBUG_INFO; 1332 -class CREATE_PROCESS_DEBUG_INFO(Structure):
1333 _fields_ = [ 1334 ('hFile', HANDLE), 1335 ('hProcess', HANDLE), 1336 ('hThread', HANDLE), 1337 ('lpBaseOfImage', LPVOID), 1338 ('dwDebugInfoFileOffset', DWORD), 1339 ('nDebugInfoSize', DWORD), 1340 ('lpThreadLocalBase', LPVOID), 1341 ('lpStartAddress', LPVOID), 1342 ('lpImageName', LPVOID), 1343 ('fUnicode', WORD), 1344 ]
1345
1346 # typedef struct _EXIT_THREAD_DEBUG_INFO { 1347 # DWORD dwExitCode; 1348 # } EXIT_THREAD_DEBUG_INFO; 1349 -class EXIT_THREAD_DEBUG_INFO(Structure):
1350 _fields_ = [ 1351 ('dwExitCode', DWORD), 1352 ]
1353
1354 # typedef struct _EXIT_PROCESS_DEBUG_INFO { 1355 # DWORD dwExitCode; 1356 # } EXIT_PROCESS_DEBUG_INFO; 1357 -class EXIT_PROCESS_DEBUG_INFO(Structure):
1358 _fields_ = [ 1359 ('dwExitCode', DWORD), 1360 ]
1361
1362 # typedef struct _LOAD_DLL_DEBUG_INFO { 1363 # HANDLE hFile; 1364 # LPVOID lpBaseOfDll; 1365 # DWORD dwDebugInfoFileOffset; 1366 # DWORD nDebugInfoSize; 1367 # LPVOID lpImageName; 1368 # WORD fUnicode; 1369 # } LOAD_DLL_DEBUG_INFO; 1370 -class LOAD_DLL_DEBUG_INFO(Structure):
1371 _fields_ = [ 1372 ('hFile', HANDLE), 1373 ('lpBaseOfDll', LPVOID), 1374 ('dwDebugInfoFileOffset', DWORD), 1375 ('nDebugInfoSize', DWORD), 1376 ('lpImageName', LPVOID), 1377 ('fUnicode', WORD), 1378 ]
1379
1380 # typedef struct _UNLOAD_DLL_DEBUG_INFO { 1381 # LPVOID lpBaseOfDll; 1382 # } UNLOAD_DLL_DEBUG_INFO; 1383 -class UNLOAD_DLL_DEBUG_INFO(Structure):
1384 _fields_ = [ 1385 ('lpBaseOfDll', LPVOID), 1386 ]
1387
1388 # typedef struct _OUTPUT_DEBUG_STRING_INFO { 1389 # LPSTR lpDebugStringData; 1390 # WORD fUnicode; 1391 # WORD nDebugStringLength; 1392 # } OUTPUT_DEBUG_STRING_INFO; 1393 -class OUTPUT_DEBUG_STRING_INFO(Structure):
1394 _fields_ = [ 1395 ('lpDebugStringData', LPVOID), # don't use LPSTR 1396 ('fUnicode', WORD), 1397 ('nDebugStringLength', WORD), 1398 ]
1399
1400 # typedef struct _RIP_INFO { 1401 # DWORD dwError; 1402 # DWORD dwType; 1403 # } RIP_INFO, *LPRIP_INFO; 1404 -class RIP_INFO(Structure):
1405 _fields_ = [ 1406 ('dwError', DWORD), 1407 ('dwType', DWORD), 1408 ]
1409
1410 # typedef struct _DEBUG_EVENT { 1411 # DWORD dwDebugEventCode; 1412 # DWORD dwProcessId; 1413 # DWORD dwThreadId; 1414 # union { 1415 # EXCEPTION_DEBUG_INFO Exception; 1416 # CREATE_THREAD_DEBUG_INFO CreateThread; 1417 # CREATE_PROCESS_DEBUG_INFO CreateProcessInfo; 1418 # EXIT_THREAD_DEBUG_INFO ExitThread; 1419 # EXIT_PROCESS_DEBUG_INFO ExitProcess; 1420 # LOAD_DLL_DEBUG_INFO LoadDll; 1421 # UNLOAD_DLL_DEBUG_INFO UnloadDll; 1422 # OUTPUT_DEBUG_STRING_INFO DebugString; 1423 # RIP_INFO RipInfo; 1424 # } u; 1425 # } DEBUG_EVENT;. 1426 -class _DEBUG_EVENT_UNION_(Union):
1427 _fields_ = [ 1428 ('Exception', EXCEPTION_DEBUG_INFO), 1429 ('CreateThread', CREATE_THREAD_DEBUG_INFO), 1430 ('CreateProcessInfo', CREATE_PROCESS_DEBUG_INFO), 1431 ('ExitThread', EXIT_THREAD_DEBUG_INFO), 1432 ('ExitProcess', EXIT_PROCESS_DEBUG_INFO), 1433 ('LoadDll', LOAD_DLL_DEBUG_INFO), 1434 ('UnloadDll', UNLOAD_DLL_DEBUG_INFO), 1435 ('DebugString', OUTPUT_DEBUG_STRING_INFO), 1436 ('RipInfo', RIP_INFO), 1437 ]
1438 -class DEBUG_EVENT(Structure):
1439 _fields_ = [ 1440 ('dwDebugEventCode', DWORD), 1441 ('dwProcessId', DWORD), 1442 ('dwThreadId', DWORD), 1443 ('u', _DEBUG_EVENT_UNION_), 1444 ]
1445 LPDEBUG_EVENT = ctypes.POINTER(DEBUG_EVENT) 1446 1447 #--- WOW64 CONTEXT structure and constants ------------------------------------ 1448 1449 # Value of SegCs in a Wow64 thread when running in 32 bits mode 1450 WOW64_CS32 = 0x23 1451 1452 WOW64_CONTEXT_i386 = 0x00010000L 1453 WOW64_CONTEXT_i486 = 0x00010000L 1454 1455 WOW64_CONTEXT_CONTROL = (WOW64_CONTEXT_i386 | 0x00000001L) 1456 WOW64_CONTEXT_INTEGER = (WOW64_CONTEXT_i386 | 0x00000002L) 1457 WOW64_CONTEXT_SEGMENTS = (WOW64_CONTEXT_i386 | 0x00000004L) 1458 WOW64_CONTEXT_FLOATING_POINT = (WOW64_CONTEXT_i386 | 0x00000008L) 1459 WOW64_CONTEXT_DEBUG_REGISTERS = (WOW64_CONTEXT_i386 | 0x00000010L) 1460 WOW64_CONTEXT_EXTENDED_REGISTERS = (WOW64_CONTEXT_i386 | 0x00000020L) 1461 1462 WOW64_CONTEXT_FULL = (WOW64_CONTEXT_CONTROL | WOW64_CONTEXT_INTEGER | WOW64_CONTEXT_SEGMENTS) 1463 WOW64_CONTEXT_ALL = (WOW64_CONTEXT_CONTROL | WOW64_CONTEXT_INTEGER | WOW64_CONTEXT_SEGMENTS | WOW64_CONTEXT_FLOATING_POINT | WOW64_CONTEXT_DEBUG_REGISTERS | WOW64_CONTEXT_EXTENDED_REGISTERS) 1464 1465 WOW64_SIZE_OF_80387_REGISTERS = 80 1466 WOW64_MAXIMUM_SUPPORTED_EXTENSION = 512
1467 1468 -class WOW64_FLOATING_SAVE_AREA (context_i386.FLOATING_SAVE_AREA):
1469 pass
1470
1471 -class WOW64_CONTEXT (context_i386.CONTEXT):
1472 pass
1473
1474 -class WOW64_LDT_ENTRY (context_i386.LDT_ENTRY):
1475 pass
1476 1477 PWOW64_FLOATING_SAVE_AREA = POINTER(WOW64_FLOATING_SAVE_AREA) 1478 PWOW64_CONTEXT = POINTER(WOW64_CONTEXT) 1479 PWOW64_LDT_ENTRY = POINTER(WOW64_LDT_ENTRY) 1480 1481 #--- Toolhelp library defines and structures ---------------------------------- 1482 1483 TH32CS_SNAPHEAPLIST = 0x00000001 1484 TH32CS_SNAPPROCESS = 0x00000002 1485 TH32CS_SNAPTHREAD = 0x00000004 1486 TH32CS_SNAPMODULE = 0x00000008 1487 TH32CS_INHERIT = 0x80000000 1488 TH32CS_SNAPALL = (TH32CS_SNAPHEAPLIST | TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD | TH32CS_SNAPMODULE)
1489 1490 # typedef struct tagTHREADENTRY32 { 1491 # DWORD dwSize; 1492 # DWORD cntUsage; 1493 # DWORD th32ThreadID; 1494 # DWORD th32OwnerProcessID; 1495 # LONG tpBasePri; 1496 # LONG tpDeltaPri; 1497 # DWORD dwFlags; 1498 # } THREADENTRY32, *PTHREADENTRY32; 1499 -class THREADENTRY32(Structure):
1500 _fields_ = [ 1501 ('dwSize', DWORD), 1502 ('cntUsage', DWORD), 1503 ('th32ThreadID', DWORD), 1504 ('th32OwnerProcessID', DWORD), 1505 ('tpBasePri', LONG), 1506 ('tpDeltaPri', LONG), 1507 ('dwFlags', DWORD), 1508 ]
1509 LPTHREADENTRY32 = ctypes.POINTER(THREADENTRY32)
1510 1511 # typedef struct tagPROCESSENTRY32 { 1512 # DWORD dwSize; 1513 # DWORD cntUsage; 1514 # DWORD th32ProcessID; 1515 # ULONG_PTR th32DefaultHeapID; 1516 # DWORD th32ModuleID; 1517 # DWORD cntThreads; 1518 # DWORD th32ParentProcessID; 1519 # LONG pcPriClassBase; 1520 # DWORD dwFlags; 1521 # TCHAR szExeFile[MAX_PATH]; 1522 # } PROCESSENTRY32, *PPROCESSENTRY32; 1523 -class PROCESSENTRY32(Structure):
1524 _fields_ = [ 1525 ('dwSize', DWORD), 1526 ('cntUsage', DWORD), 1527 ('th32ProcessID', DWORD), 1528 ('th32DefaultHeapID', LPVOID), # remote pointer 1529 ('th32ModuleID', DWORD), 1530 ('cntThreads', DWORD), 1531 ('th32ParentProcessID', DWORD), 1532 ('pcPriClassBase', LONG), 1533 ('dwFlags', DWORD), 1534 ('szExeFile', TCHAR * 260), 1535 ]
1536 LPPROCESSENTRY32 = ctypes.POINTER(PROCESSENTRY32)
1537 1538 # typedef struct tagMODULEENTRY32 { 1539 # DWORD dwSize; 1540 # DWORD th32ModuleID; 1541 # DWORD th32ProcessID; 1542 # DWORD GlblcntUsage; 1543 # DWORD ProccntUsage; 1544 # BYTE* modBaseAddr; 1545 # DWORD modBaseSize; 1546 # HMODULE hModule; 1547 # TCHAR szModule[MAX_MODULE_NAME32 + 1]; 1548 # TCHAR szExePath[MAX_PATH]; 1549 # } MODULEENTRY32, *PMODULEENTRY32; 1550 -class MODULEENTRY32(Structure):
1551 _fields_ = [ 1552 ("dwSize", DWORD), 1553 ("th32ModuleID", DWORD), 1554 ("th32ProcessID", DWORD), 1555 ("GlblcntUsage", DWORD), 1556 ("ProccntUsage", DWORD), 1557 ("modBaseAddr", LPVOID), # BYTE* 1558 ("modBaseSize", DWORD), 1559 ("hModule", HMODULE), 1560 ("szModule", TCHAR * (MAX_MODULE_NAME32 + 1)), 1561 ("szExePath", TCHAR * MAX_PATH), 1562 ]
1563 LPMODULEENTRY32 = ctypes.POINTER(MODULEENTRY32)
1564 1565 # typedef struct tagHEAPENTRY32 { 1566 # SIZE_T dwSize; 1567 # HANDLE hHandle; 1568 # ULONG_PTR dwAddress; 1569 # SIZE_T dwBlockSize; 1570 # DWORD dwFlags; 1571 # DWORD dwLockCount; 1572 # DWORD dwResvd; 1573 # DWORD th32ProcessID; 1574 # ULONG_PTR th32HeapID; 1575 # } HEAPENTRY32, 1576 # *PHEAPENTRY32; 1577 -class HEAPENTRY32(Structure):
1578 _fields_ = [ 1579 ("dwSize", SIZE_T), 1580 ("hHandle", HANDLE), 1581 ("dwAddress", LPVOID), # remote pointer 1582 ("dwBlockSize", SIZE_T), 1583 ("dwFlags", DWORD), 1584 ("dwLockCount", DWORD), 1585 ("dwResvd", DWORD), 1586 ("th32ProcessID", DWORD), 1587 ("th32HeapID", LPVOID), # remote pointer 1588 ]
1589 LPHEAPENTRY32 = ctypes.POINTER(HEAPENTRY32)
1590 1591 # typedef struct tagHEAPLIST32 { 1592 # SIZE_T dwSize; 1593 # DWORD th32ProcessID; 1594 # ULONG_PTR th32HeapID; 1595 # DWORD dwFlags; 1596 # } HEAPLIST32, 1597 # *PHEAPLIST32; 1598 -class HEAPLIST32(Structure):
1599 _fields_ = [ 1600 ("dwSize", SIZE_T), 1601 ("th32ProcessID", DWORD), 1602 ("th32HeapID", LPVOID), # remote pointer 1603 ("dwFlags", DWORD), 1604 ]
1605 LPHEAPLIST32 = POINTER(HEAPLIST32)
1606 1607 #--- kernel32.dll ------------------------------------------------------------- 1608 1609 # DWORD WINAPI GetLastError(void); 1610 -def GetLastError():
1611 _GetLastError = windll.kernel32.GetLastError 1612 _GetLastError.argtypes = [] 1613 _GetLastError.restype = DWORD 1614 return _GetLastError()
1615
1616 # void WINAPI SetLastError( 1617 # __in DWORD dwErrCode 1618 # ); 1619 -def SetLastError(dwErrCode):
1620 _SetLastError = windll.kernel32.SetLastError 1621 _SetLastError.argtypes = [DWORD] 1622 _SetLastError.restype = None 1623 _SetLastError(dwErrCode)
1624
1625 # void WINAPI SetLastErrorEx( 1626 # __in DWORD dwErrCode, 1627 # __in DWORD dwType 1628 # ); 1629 -def SetLastErrorEx(dwErrCode, dwType):
1630 _SetLastErrorEx = windll.kernel32.SetLastErrorEx 1631 _SetLastErrorEx.argtypes = [DWORD, DWORD] 1632 _SetLastErrorEx.restype = None 1633 _SetLastErrorEx(dwErrCode, dwType)
1634
1635 # BOOL WINAPI CloseHandle( 1636 # __in HANDLE hObject 1637 # ); 1638 -def CloseHandle(hHandle):
1639 if isinstance(hHandle, Handle): 1640 # Prevents the handle from being closed without notifying the Handle object. 1641 hHandle.close() 1642 else: 1643 _CloseHandle = windll.kernel32.CloseHandle 1644 _CloseHandle.argtypes = [HANDLE] 1645 _CloseHandle.restype = bool 1646 _CloseHandle.errcheck = RaiseIfZero 1647 _CloseHandle(hHandle)
1648
1649 # BOOL WINAPI DuplicateHandle( 1650 # __in HANDLE hSourceProcessHandle, 1651 # __in HANDLE hSourceHandle, 1652 # __in HANDLE hTargetProcessHandle, 1653 # __out LPHANDLE lpTargetHandle, 1654 # __in DWORD dwDesiredAccess, 1655 # __in BOOL bInheritHandle, 1656 # __in DWORD dwOptions 1657 # ); 1658 -def DuplicateHandle(hSourceHandle, hSourceProcessHandle = None, hTargetProcessHandle = None, dwDesiredAccess = STANDARD_RIGHTS_ALL, bInheritHandle = False, dwOptions = DUPLICATE_SAME_ACCESS):
1659 _DuplicateHandle = windll.kernel32.DuplicateHandle 1660 _DuplicateHandle.argtypes = [HANDLE, HANDLE, HANDLE, LPHANDLE, DWORD, BOOL, DWORD] 1661 _DuplicateHandle.restype = bool 1662 _DuplicateHandle.errcheck = RaiseIfZero 1663 1664 if hSourceProcessHandle is None: 1665 hSourceProcessHandle = GetCurrentProcess() 1666 if hTargetProcessHandle is None: 1667 hTargetProcessHandle = hSourceProcessHandle 1668 lpTargetHandle = HANDLE(INVALID_HANDLE_VALUE) 1669 _DuplicateHandle(hSourceHandle, hSourceProcessHandle, hTargetProcessHandle, ctypes.byref(lpTargetHandle), dwDesiredAccess, bool(bInheritHandle), dwOptions) 1670 return Handle(lpTargetHandle.value)
1671
1672 # void WINAPI OutputDebugString( 1673 # __in_opt LPCTSTR lpOutputString 1674 # ); 1675 -def OutputDebugStringA(lpOutputString):
1676 _OutputDebugStringA = windll.kernel32.OutputDebugStringA 1677 _OutputDebugStringA.argtypes = [LPSTR] 1678 _OutputDebugStringA.restype = None 1679 _OutputDebugStringA(lpOutputString)
1680
1681 -def OutputDebugStringW(lpOutputString):
1682 _OutputDebugStringW = windll.kernel32.OutputDebugStringW 1683 _OutputDebugStringW.argtypes = [LPWSTR] 1684 _OutputDebugStringW.restype = None 1685 _OutputDebugStringW(lpOutputString)
1686 1687 OutputDebugString = GuessStringType(OutputDebugStringA, OutputDebugStringW)
1688 1689 # BOOL WINAPI SetDllDirectory( 1690 # __in_opt LPCTSTR lpPathName 1691 # ); 1692 -def SetDllDirectoryA(lpPathName):
1693 _SetDllDirectoryA = windll.kernel32.SetDllDirectoryA 1694 _SetDllDirectoryA.argytpes = [LPSTR] 1695 _SetDllDirectoryA.restype = bool 1696 _SetDllDirectoryA.errcheck = RaiseIfZero 1697 _SetDllDirectoryA(lpPathName)
1698
1699 -def SetDllDirectoryW(lpPathName):
1700 _SetDllDirectoryW = windll.kernel32.SetDllDirectoryW 1701 _SetDllDirectoryW.argytpes = [LPWSTR] 1702 _SetDllDirectoryW.restype = bool 1703 _SetDllDirectoryW.errcheck = RaiseIfZero 1704 _SetDllDirectoryW(lpPathName)
1705 1706 SetDllDirectory = GuessStringType(SetDllDirectoryA, SetDllDirectoryW)
1707 1708 # HMODULE WINAPI LoadLibrary( 1709 # __in LPCTSTR lpFileName 1710 # ); 1711 -def LoadLibraryA(pszLibrary):
1712 _LoadLibraryA = windll.kernel32.LoadLibraryA 1713 _LoadLibraryA.argtypes = LPSTR 1714 _LoadLibraryA.restype = HMODULE 1715 hModule = _LoadLibraryA(pszLibrary) 1716 if hModule == NULL: 1717 raise ctypes.WinError() 1718 return hModule
1719
1720 -def LoadLibraryW(pszLibrary):
1721 _LoadLibraryW = windll.kernel32.LoadLibraryW 1722 _LoadLibraryW.argtypes = LPWSTR 1723 _LoadLibraryW.restype = HMODULE 1724 hModule = _LoadLibraryW(pszLibrary) 1725 if hModule == NULL: 1726 raise ctypes.WinError() 1727 return hModule
1728 1729 LoadLibrary = GuessStringType(LoadLibraryA, LoadLibraryW)
1730 1731 # HMODULE WINAPI LoadLibraryEx( 1732 # __in LPCTSTR lpFileName, 1733 # __reserved HANDLE hFile, 1734 # __in DWORD dwFlags 1735 # ); 1736 -def LoadLibraryExA(pszLibrary, dwFlags = 0):
1737 _LoadLibraryExA = windll.kernel32.LoadLibraryExA 1738 _LoadLibraryExA.argtypes = LPSTR, HANDLE, DWORD 1739 _LoadLibraryExA.restype = HMODULE 1740 hModule = _LoadLibraryExA(pszLibrary, NULL, dwFlags) 1741 if hModule == NULL: 1742 raise ctypes.WinError() 1743 return hModule
1744
1745 -def LoadLibraryExW(pszLibrary, dwFlags = 0):
1746 _LoadLibraryExW = windll.kernel32.LoadLibraryExW 1747 _LoadLibraryExW.argtypes = LPWSTR, HANDLE, DWORD 1748 _LoadLibraryExW.restype = HMODULE 1749 hModule = _LoadLibraryExW(pszLibrary, NULL, dwFlags) 1750 if hModule == NULL: 1751 raise ctypes.WinError() 1752 return hModule
1753 1754 LoadLibraryEx = GuessStringType(LoadLibraryExA, LoadLibraryExW)
1755 1756 # HMODULE WINAPI GetModuleHandle( 1757 # __in_opt LPCTSTR lpModuleName 1758 # ); 1759 -def GetModuleHandleA(lpModuleName):
1760 _GetModuleHandleA = windll.kernel32.GetModuleHandleA 1761 _GetModuleHandleA.argtypes = [LPSTR] 1762 _GetModuleHandleA.restype = HMODULE 1763 hModule = _GetModuleHandleA(lpModuleName) 1764 if hModule == NULL: 1765 raise ctypes.WinError() 1766 return hModule
1767
1768 -def GetModuleHandleW(lpModuleName):
1769 _GetModuleHandleW = windll.kernel32.GetModuleHandleW 1770 _GetModuleHandleW.argtypes = [LPWSTR] 1771 _GetModuleHandleW.restype = HMODULE 1772 hModule = _GetModuleHandleW(lpModuleName) 1773 if hModule == NULL: 1774 raise ctypes.WinError() 1775 return hModule
1776 1777 GetModuleHandle = GuessStringType(GetModuleHandleA, GetModuleHandleW)
1778 1779 # FARPROC WINAPI GetProcAddress( 1780 # __in HMODULE hModule, 1781 # __in LPCSTR lpProcName 1782 # ); 1783 -def GetProcAddress(hModule, lpProcName):
1784 _GetProcAddress = windll.kernel32.GetProcAddress 1785 _GetProcAddress.argtypes = [HMODULE, LPVOID] 1786 _GetProcAddress.restype = LPVOID 1787 1788 try: 1789 lpProcName = ctypes.c_char_p(lpProcName) 1790 except TypeError: 1791 lpProcName = LPVOID(lpProcName) 1792 if lpProcName.value & (~0xFFFF): 1793 raise ValueError, 'Ordinal number too large: %d' % lpProcName.value 1794 return _GetProcAddress(hModule, lpProcName)
1795
1796 # BOOL WINAPI FreeLibrary( 1797 # __in HMODULE hModule 1798 # ); 1799 -def FreeLibrary(hModule):
1800 _FreeLibrary = windll.kernel32.FreeLibrary 1801 _FreeLibrary.argtypes = [HMODULE] 1802 _FreeLibrary.restype = bool 1803 _FreeLibrary.errcheck = RaiseIfZero 1804 _FreeLibrary(hModule)
1805
1806 # BOOL WINAPI QueryFullProcessImageName( 1807 # __in HANDLE hProcess, 1808 # __in DWORD dwFlags, 1809 # __out LPTSTR lpExeName, 1810 # __inout PDWORD lpdwSize 1811 # ); 1812 -def QueryFullProcessImageNameA(hProcess, dwFlags = 0):
1813 _QueryFullProcessImageNameA = windll.kernel32.QueryFullProcessImageNameA 1814 _QueryFullProcessImageNameA.argtypes = [HANDLE, DWORD, LPSTR, PDWORD] 1815 _QueryFullProcessImageNameA.restype = bool 1816 1817 lpdwSize = DWORD(0) 1818 _QueryFullProcessImageNameA(hProcess, dwFlags, None, ctypes.byref(lpdwSize)) 1819 if lpdwSize.value == 0: 1820 raise ctypes.WinError() 1821 lpExeName = ctypes.create_string_buffer('', lpdwSize.value + 1) 1822 success = _QueryFullProcessImageNameA(hProcess, dwFlags, lpExeName, ctypes.byref(lpdwSize)) 1823 if not success: 1824 raise ctypes.WinError() 1825 return lpExeName.value
1826
1827 -def QueryFullProcessImageNameW(hProcess, dwFlags = 0):
1828 _QueryFullProcessImageNameW = windll.kernel32.QueryFullProcessImageNameW 1829 _QueryFullProcessImageNameW.argtypes = [HANDLE, DWORD, LPWSTR, PDWORD] 1830 _QueryFullProcessImageNameW.restype = bool 1831 1832 lpdwSize = DWORD(0) 1833 _QueryFullProcessImageNameW(hProcess, dwFlags, None, ctypes.byref(lpdwSize)) 1834 if lpdwSize.value == 0: 1835 raise ctypes.WinError() 1836 lpExeName = ctypes.create_unicode_buffer(u'', lpdwSize.value + 1) 1837 success = _QueryFullProcessImageNameW(hProcess, dwFlags, lpExeName, ctypes.byref(lpdwSize)) 1838 if not success: 1839 raise ctypes.WinError() 1840 return lpExeName.value
1841 1842 QueryFullProcessImageName = GuessStringType(QueryFullProcessImageNameA, QueryFullProcessImageNameW)
1843 1844 # DWORD WINAPI GetLogicalDriveStrings( 1845 # __in DWORD nBufferLength, 1846 # __out LPTSTR lpBuffer 1847 # ); 1848 -def GetLogicalDriveStringsA():
1849 _GetLogicalDriveStringsA = windll.kernel32.GetLogicalDriveStringsA 1850 _GetLogicalDriveStringsA.argtypes = [DWORD, LPSTR] 1851 _GetLogicalDriveStringsA.restype = DWORD 1852 _GetLogicalDriveStringsA.errcheck = RaiseIfZero 1853 1854 nBufferLength = 0x1000 1855 lpBuffer = ctypes.create_string_buffer('', nBufferLength) 1856 _GetLogicalDriveStringsA(nBufferLength, ctypes.byref(lpBuffer)) 1857 return lpBuffer.value
1858
1859 -def GetLogicalDriveStringsW():
1860 _GetLogicalDriveStringsW = windll.kernel32.GetLogicalDriveStringsW 1861 _GetLogicalDriveStringsW.argtypes = [DWORD, LPWSTR] 1862 _GetLogicalDriveStringsW.restype = DWORD 1863 _GetLogicalDriveStringsW.errcheck = RaiseIfZero 1864 1865 nBufferLength = 0x1000 1866 lpBuffer = ctypes.create_unicode_buffer('', nBufferLength) 1867 _GetLogicalDriveStringsW(nBufferLength, ctypes.byref(lpBuffer)) 1868 return lpBuffer.value
1869 1870 GetLogicalDriveStrings = GuessStringType(GetLogicalDriveStringsA, GetLogicalDriveStringsW)
1871 1872 # DWORD WINAPI QueryDosDevice( 1873 # __in_opt LPCTSTR lpDeviceName, 1874 # __out LPTSTR lpTargetPath, 1875 # __in DWORD ucchMax 1876 # ); 1877 -def QueryDosDeviceA(lpDeviceName = None):
1878 _QueryDosDeviceA = windll.kernel32.QueryDosDeviceA 1879 _QueryDosDeviceA.argtypes = [LPSTR, LPSTR, DWORD] 1880 _QueryDosDeviceA.restype = DWORD 1881 _QueryDosDeviceA.errcheck = RaiseIfZero 1882 1883 if not lpDeviceName: 1884 lpDeviceName = None 1885 ucchMax = 0x1000 1886 lpTargetPath = ctypes.create_string_buffer('', ucchMax) 1887 _QueryDosDeviceA(lpDeviceName, lpTargetPath, ucchMax) 1888 return lpTargetPath.value
1889
1890 -def QueryDosDeviceW(lpDeviceName):
1891 _QueryDosDeviceW = windll.kernel32.QueryDosDeviceW 1892 _QueryDosDeviceW.argtypes = [LPWSTR, LPWSTR, DWORD] 1893 _QueryDosDeviceW.restype = DWORD 1894 _QueryDosDeviceW.errcheck = RaiseIfZero 1895 1896 if not lpDeviceName: 1897 lpDeviceName = None 1898 ucchMax = 0x1000 1899 lpTargetPath = ctypes.create_unicode_buffer(u'', ucchMax) 1900 _QueryDosDeviceW(lpDeviceName, lpTargetPath, ucchMax) 1901 return lpTargetPath.value
1902 1903 QueryDosDevice = GuessStringType(QueryDosDeviceA, QueryDosDeviceW)
1904 1905 # LPVOID WINAPI MapViewOfFile( 1906 # __in HANDLE hFileMappingObject, 1907 # __in DWORD dwDesiredAccess, 1908 # __in DWORD dwFileOffsetHigh, 1909 # __in DWORD dwFileOffsetLow, 1910 # __in SIZE_T dwNumberOfBytesToMap 1911 # ); 1912 -def MapViewOfFile(hFileMappingObject, dwDesiredAccess = FILE_MAP_ALL_ACCESS | FILE_MAP_EXECUTE, dwFileOffsetHigh = 0, dwFileOffsetLow = 0, dwNumberOfBytesToMap = 0):
1913 _MapViewOfFile = windll.kernel32.MapViewOfFile 1914 _MapViewOfFile.argtypes = [HANDLE, DWORD, DWORD, DWORD, SIZE_T] 1915 _MapViewOfFile.restype = LPVOID 1916 lpBaseAddress = _MapViewOfFile(hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh, dwFileOffsetLow, dwNumberOfBytesToMap) 1917 if lpBaseAddress == NULL: 1918 raise ctypes.WinError() 1919 return lpBaseAddress
1920
1921 # BOOL WINAPI UnmapViewOfFile( 1922 # __in LPCVOID lpBaseAddress 1923 # ); 1924 -def UnmapViewOfFile(lpBaseAddress):
1925 _UnmapViewOfFile = windll.kernel32.UnmapViewOfFile 1926 _UnmapViewOfFile.argtypes = [LPVOID] 1927 _UnmapViewOfFile.restype = bool 1928 _UnmapViewOfFile.errcheck = RaiseIfZero 1929 _UnmapViewOfFile(lpBaseAddress)
1930
1931 # HANDLE WINAPI OpenFileMapping( 1932 # __in DWORD dwDesiredAccess, 1933 # __in BOOL bInheritHandle, 1934 # __in LPCTSTR lpName 1935 # ); 1936 -def OpenFileMappingA(dwDesiredAccess, bInheritHandle, lpName):
1937 _OpenFileMappingA = windll.kernel32.OpenFileMappingA 1938 _OpenFileMappingA.argtypes = [DWORD, BOOL, LPSTR] 1939 _OpenFileMappingA.restype = HANDLE 1940 hFileMappingObject = _OpenFileMappingA(dwDesiredAccess, bool(bInheritHandle), lpName) 1941 if hFileMappingObject == INVALID_HANDLE_VALUE: 1942 raise ctypes.WinError() 1943 return Handle(hFileMappingObject)
1944
1945 -def OpenFileMappingW(dwDesiredAccess, bInheritHandle, lpName):
1946 _OpenFileMappingW = windll.kernel32.OpenFileMappingW 1947 _OpenFileMappingW.argtypes = [DWORD, BOOL, LPWSTR] 1948 _OpenFileMappingW.restype = HANDLE 1949 hFileMappingObject = _OpenFileMappingW(dwDesiredAccess, bool(bInheritHandle), lpName) 1950 if hFileMappingObject == INVALID_HANDLE_VALUE: 1951 raise ctypes.WinError() 1952 return Handle(hFileMappingObject)
1953 1954 OpenFileMapping = GuessStringType(OpenFileMappingA, OpenFileMappingW)
1955 1956 # HANDLE WINAPI CreateFileMapping( 1957 # __in HANDLE hFile, 1958 # __in_opt LPSECURITY_ATTRIBUTES lpAttributes, 1959 # __in DWORD flProtect, 1960 # __in DWORD dwMaximumSizeHigh, 1961 # __in DWORD dwMaximumSizeLow, 1962 # __in_opt LPCTSTR lpName 1963 # ); 1964 -def CreateFileMappingA(hFile, lpAttributes = None, flProtect = PAGE_EXECUTE_READWRITE, dwMaximumSizeHigh = 0, dwMaximumSizeLow = 0, lpName = None):
1965 _CreateFileMappingA = windll.kernel32.CreateFileMappingA 1966 _CreateFileMappingA.argtypes = [HANDLE, LPVOID, DWORD, DWORD, DWORD, LPSTR] 1967 _CreateFileMappingA.restype = HANDLE 1968 1969 if lpAttributes: 1970 lpAttributes = ctypes.pointer(lpAttributes) 1971 if not lpName: 1972 lpName = None 1973 hFileMappingObject = _CreateFileMappingA(hFile, lpAttributes, flProtect, dwMaximumSizeHigh, dwMaximumSizeLow, lpName) 1974 if hFileMappingObject == INVALID_HANDLE_VALUE: 1975 raise ctypes.WinError() 1976 return Handle(hFileMappingObject)
1977
1978 -def CreateFileMappingW(hFile, lpAttributes = None, flProtect = PAGE_EXECUTE_READWRITE, dwMaximumSizeHigh = 0, dwMaximumSizeLow = 0, lpName = None):
1979 _CreateFileMappingW = windll.kernel32.CreateFileMappingW 1980 _CreateFileMappingW.argtypes = [HANDLE, LPVOID, DWORD, DWORD, DWORD, LPWSTR] 1981 _CreateFileMappingW.restype = HANDLE 1982 1983 if lpAttributes: 1984 lpAttributes = ctypes.pointer(lpAttributes) 1985 if not lpName: 1986 lpName = None 1987 hFileMappingObject = _CreateFileMappingW(hFile, lpAttributes, flProtect, dwMaximumSizeHigh, dwMaximumSizeLow, lpName) 1988 if hFileMappingObject == INVALID_HANDLE_VALUE: 1989 raise ctypes.WinError() 1990 return Handle(hFileMappingObject)
1991 1992 CreateFileMapping = GuessStringType(CreateFileMappingA, CreateFileMappingW)
1993 1994 # HANDLE WINAPI CreateFile( 1995 # __in LPCTSTR lpFileName, 1996 # __in DWORD dwDesiredAccess, 1997 # __in DWORD dwShareMode, 1998 # __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes, 1999 # __in DWORD dwCreationDisposition, 2000 # __in DWORD dwFlagsAndAttributes, 2001 # __in_opt HANDLE hTemplateFile 2002 # ); 2003 -def CreateFileA(lpFileName, dwDesiredAccess = GENERIC_ALL, dwShareMode = 0, lpSecurityAttributes = None, dwCreationDisposition = OPEN_ALWAYS, dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL, hTemplateFile = None):
2004 _CreateFileA = windll.kernel32.CreateFileA 2005 _CreateFileA.argtypes = [LPSTR, DWORD, DWORD, LPVOID, DWORD, DWORD, HANDLE] 2006 _CreateFileA.restype = HANDLE 2007 2008 if not lpFileName: 2009 lpFileName = None 2010 if lpSecurityAttributes: 2011 lpSecurityAttributes = ctypes.pointer(lpSecurityAttributes) 2012 hFile = _CreateFileA(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile) 2013 if hFile == INVALID_HANDLE_VALUE: 2014 raise ctypes.WinError() 2015 return Handle(hFile)
2016
2017 -def CreateFileW(lpFileName, dwDesiredAccess = GENERIC_ALL, dwShareMode = 0, lpSecurityAttributes = None, dwCreationDisposition = OPEN_ALWAYS, dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL, hTemplateFile = None):
2018 _CreateFileW = windll.kernel32.CreateFileW 2019 _CreateFileW.argtypes = [LPWSTR, DWORD, DWORD, LPVOID, DWORD, DWORD, HANDLE] 2020 _CreateFileW.restype = HANDLE 2021 2022 if not lpFileName: 2023 lpFileName = None 2024 if lpSecurityAttributes: 2025 lpSecurityAttributes = ctypes.pointer(lpSecurityAttributes) 2026 hFile = _CreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile) 2027 if hFile == INVALID_HANDLE_VALUE: 2028 raise ctypes.WinError() 2029 return Handle(hFile)
2030 2031 CreateFile = GuessStringType(CreateFileA, CreateFileW)
2032 2033 # BOOL WINAPI FlushFileBuffers( 2034 # __in HANDLE hFile 2035 # ); 2036 -def FlushFileBuffers(hFile):
2037 _FlushFileBuffers = windll.kernel32.FlushFileBuffers 2038 _FlushFileBuffers.argtypes = [HANDLE] 2039 _FlushFileBuffers.restype = bool 2040 _FlushFileBuffers.errcheck = RaiseIfZero 2041 _FlushFileBuffers(hFile)
2042
2043 # BOOL WINAPI FlushViewOfFile( 2044 # __in LPCVOID lpBaseAddress, 2045 # __in SIZE_T dwNumberOfBytesToFlush 2046 # ); 2047 -def FlushViewOfFile(lpBaseAddress, dwNumberOfBytesToFlush = 0):
2048 _FlushViewOfFile = windll.kernel32.FlushViewOfFile 2049 _FlushViewOfFile.argtypes = [LPVOID, SIZE_T] 2050 _FlushViewOfFile.restype = bool 2051 _FlushViewOfFile.errcheck = RaiseIfZero 2052 _FlushViewOfFile(lpBaseAddress, dwNumberOfBytesToFlush)
2053
2054 # DWORD WINAPI SearchPath( 2055 # __in_opt LPCTSTR lpPath, 2056 # __in LPCTSTR lpFileName, 2057 # __in_opt LPCTSTR lpExtension, 2058 # __in DWORD nBufferLength, 2059 # __out LPTSTR lpBuffer, 2060 # __out_opt LPTSTR *lpFilePart 2061 # ); 2062 -def SearchPathA(lpPath, lpFileName, lpExtension):
2063 _SearchPathA = windll.kernel32.SearchPathA 2064 _SearchPathA.argtypes = [LPSTR, LPSTR, LPSTR, DWORD, LPSTR, ctypes.POINTER(LPSTR)] 2065 _SearchPathA.restype = DWORD 2066 _SearchPathA.errcheck = RaiseIfZero 2067 2068 if not lpPath: 2069 lpPath = None 2070 if not lpExtension: 2071 lpExtension = None 2072 nBufferLength = _SearchPathA(lpPath, lpFileName, lpExtension, 0, None, None) 2073 lpBuffer = ctypes.create_string_buffer('', nBufferLength + 1) 2074 lpFilePart = LPSTR() 2075 nCount = _SearchPathA(lpPath, lpFileName, lpExtension, nBufferLength, lpBuffer, ctypes.byref(lpFilePart)) 2076 lpFilePart = lpFilePart.value 2077 lpBuffer = lpBuffer.value 2078 if lpBuffer == '': 2079 if GetLastError() == 0: 2080 SetLastError(ERROR_FILE_NOT_FOUND) 2081 raise ctypes.WinError() 2082 return (lpBuffer, lpFilePart)
2083
2084 -def SearchPathW(lpPath, lpFileName, lpExtension):
2085 _SearchPathW = windll.kernel32.SearchPathW 2086 _SearchPathW.argtypes = [LPWSTR, LPWSTR, LPWSTR, DWORD, LPWSTR, POINTER(LPWSTR)] 2087 _SearchPathW.restype = DWORD 2088 _SearchPathW.errcheck = RaiseIfZero 2089 2090 if not lpPath: 2091 lpPath = None 2092 if not lpExtension: 2093 lpExtension = None 2094 nBufferLength = _SearchPathW(lpPath, lpFileName, lpExtension, 0, None, None) 2095 lpBuffer = ctypes.create_unicode_buffer(u'', nBufferLength + 1) 2096 lpFilePart = LPWSTR() 2097 nCount = _SearchPathW(lpPath, lpFileName, lpExtension, nBufferLength, lpBuffer, ctypes.byref(lpFilePart)) 2098 lpFilePart = lpFilePart.value 2099 lpBuffer = lpBuffer.value 2100 if lpBuffer == u'': 2101 if GetLastError() == 0: 2102 SetLastError(ERROR_FILE_NOT_FOUND) 2103 raise ctypes.WinError() 2104 return (lpBuffer, lpFilePart)
2105 2106 SearchPath = GuessStringType(SearchPathA, SearchPathW)
2107 2108 # BOOL SetSearchPathMode( 2109 # __in DWORD Flags 2110 # ); 2111 -def SetSearchPathMode(Flags):
2112 _SetSearchPathMode = windll.kernel32.SetSearchPathMode 2113 _SetSearchPathMode.argtypes = [DWORD] 2114 _SetSearchPathMode.restype = bool 2115 _SetSearchPathMode.errcheck = RaiseIfZero 2116 _SetSearchPathMode(Flags)
2117
2118 # BOOL WINAPI DeviceIoControl( 2119 # __in HANDLE hDevice, 2120 # __in DWORD dwIoControlCode, 2121 # __in_opt LPVOID lpInBuffer, 2122 # __in DWORD nInBufferSize, 2123 # __out_opt LPVOID lpOutBuffer, 2124 # __in DWORD nOutBufferSize, 2125 # __out_opt LPDWORD lpBytesReturned, 2126 # __inout_opt LPOVERLAPPED lpOverlapped 2127 # ); 2128 -def DeviceIoControl(hDevice, dwIoControlCode, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, lpOverlapped):
2129 _DeviceIoControl = windll.kernel32.DeviceIoControl 2130 _DeviceIoControl.argtypes = [HANDLE, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPOVERLAPPED] 2131 _DeviceIoControl.restype = bool 2132 _DeviceIoControl.errcheck = RaiseIfZero 2133 2134 if not lpInBuffer: 2135 lpInBuffer = None 2136 if not lpOutBuffer: 2137 lpOutBuffer = None 2138 if lpOverlapped: 2139 lpOverlapped = ctypes.pointer(lpOverlapped) 2140 lpBytesReturned = DWORD(0) 2141 _DeviceIoControl(hDevice, dwIoControlCode, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, ctypes.byref(lpBytesReturned), lpOverlapped) 2142 return lpBytesReturned.value
2143
2144 # BOOL GetFileInformationByHandle( 2145 # HANDLE hFile, 2146 # LPBY_HANDLE_FILE_INFORMATION lpFileInformation 2147 # ); 2148 -def GetFileInformationByHandle(hFile):
2149 _GetFileInformationByHandle = windll.kernel32.GetFileInformationByHandle 2150 _GetFileInformationByHandle.argtypes = [HANDLE, LPBY_HANDLE_FILE_INFORMATION] 2151 _GetFileInformationByHandle.restype = bool 2152 _GetFileInformationByHandle.errcheck = RaiseIfZero 2153 2154 lpFileInformation = BY_HANDLE_FILE_INFORMATION() 2155 _GetFileInformationByHandle(hFile, ctypes.byref(lpFileInformation)) 2156 return lpFileInformation
2157
2158 # BOOL WINAPI GetFileInformationByHandleEx( 2159 # __in HANDLE hFile, 2160 # __in FILE_INFO_BY_HANDLE_CLASS FileInformationClass, 2161 # __out LPVOID lpFileInformation, 2162 # __in DWORD dwBufferSize 2163 # ); 2164 -def GetFileInformationByHandleEx(hFile, FileInformationClass, lpFileInformation, dwBufferSize):
2165 _GetFileInformationByHandleEx = windll.kernel32.GetFileInformationByHandleEx 2166 _GetFileInformationByHandleEx.argtypes = [HANDLE, DWORD, LPVOID, DWORD] 2167 _GetFileInformationByHandleEx.restype = bool 2168 _GetFileInformationByHandleEx.errcheck = RaiseIfZero 2169 # XXX TODO 2170 # support each FileInformationClass so the function can allocate the 2171 # corresponding structure for the lpFileInformation parameter 2172 _GetFileInformationByHandleEx(hFile, FileInformationClass, ctypes.byref(lpFileInformation), dwBufferSize)
2173
2174 # DWORD WINAPI GetFinalPathNameByHandle( 2175 # __in HANDLE hFile, 2176 # __out LPTSTR lpszFilePath, 2177 # __in DWORD cchFilePath, 2178 # __in DWORD dwFlags 2179 # ); 2180 -def GetFinalPathNameByHandleA(hFile, dwFlags = FILE_NAME_NORMALIZED | VOLUME_NAME_DOS):
2181 _GetFinalPathNameByHandleA = windll.kernel32.GetFinalPathNameByHandleA 2182 _GetFinalPathNameByHandleA.argtypes = [HANDLE, LPSTR, DWORD, DWORD] 2183 _GetFinalPathNameByHandleA.restype = DWORD 2184 2185 cchFilePath = _GetFinalPathNameByHandleA(hFile, None, 0, dwFlags) 2186 if cchFilePath == 0: 2187 raise ctypes.WinError() 2188 lpszFilePath = ctypes.create_string_buffer('', cchFilePath + 1) 2189 nCopied = _GetFinalPathNameByHandleA(hFile, lpszFilePath, cchFilePath, dwFlags) 2190 if nCopied <= 0 or nCopied > cchFilePath: 2191 raise ctypes.WinError() 2192 return lpszFilePath.value
2193
2194 -def GetFinalPathNameByHandleW(hFile, dwFlags = FILE_NAME_NORMALIZED | VOLUME_NAME_DOS):
2195 _GetFinalPathNameByHandleW = windll.kernel32.GetFinalPathNameByHandleW 2196 _GetFinalPathNameByHandleW.argtypes = [HANDLE, LPWSTR, DWORD, DWORD] 2197 _GetFinalPathNameByHandleW.restype = DWORD 2198 2199 cchFilePath = _GetFinalPathNameByHandleW(hFile, None, 0, dwFlags) 2200 if cchFilePath == 0: 2201 raise ctypes.WinError() 2202 lpszFilePath = ctypes.create_unicode_buffer(u'', cchFilePath + 1) 2203 nCopied = _GetFinalPathNameByHandleW(hFile, lpszFilePath, cchFilePath, dwFlags) 2204 if nCopied <= 0 or nCopied > cchFilePath: 2205 raise ctypes.WinError() 2206 return lpszFilePath.value
2207 2208 GetFinalPathNameByHandle = GuessStringType(GetFinalPathNameByHandleA, GetFinalPathNameByHandleW)
2209 2210 # DWORD GetFullPathName( 2211 # LPCTSTR lpFileName, 2212 # DWORD nBufferLength, 2213 # LPTSTR lpBuffer, 2214 # LPTSTR* lpFilePart 2215 # ); 2216 -def GetFullPathNameA(lpFileName):
2217 _GetFullPathNameA = windll.kernel32.GetFullPathNameA 2218 _GetFullPathNameA.argtypes = [LPSTR, DWORD, LPSTR, ctypes.POINTER(LPSTR)] 2219 _GetFullPathNameA.restype = DWORD 2220 2221 nBufferLength = _GetFullPathNameA(lpFileName, 0, None, None) 2222 if nBufferLength <= 0: 2223 raise ctypes.WinError() 2224 lpBuffer = ctypes.create_string_buffer('', nBufferLength + 1) 2225 lpFilePart = LPSTR 2226 nCopied = _GetFullPathNameA(lpFileName, nBufferLength, lpBuffer, ctypes.byref(lpFilePart)) 2227 if nCopied > nBufferLength or nCopied == 0: 2228 raise ctypes.WinError() 2229 return lpBuffer.value, lpFilePart.value
2230
2231 -def GetFullPathNameW(lpFileName):
2232 _GetFullPathNameW = windll.kernel32.GetFullPathNameW 2233 _GetFullPathNameW.argtypes = [LPWSTR, DWORD, LPWSTR, POINTER(LPWSTR)] 2234 _GetFullPathNameW.restype = DWORD 2235 2236 nBufferLength = _GetFullPathNameW(lpFileName, 0, None, None) 2237 if nBufferLength <= 0: 2238 raise ctypes.WinError() 2239 lpBuffer = ctypes.create_unicode_buffer(u'', nBufferLength + 1) 2240 lpFilePart = LPSTR 2241 nCopied = _GetFullPathNameW(lpFileName, nBufferLength, lpBuffer, ctypes.byref(lpFilePart)) 2242 if nCopied > nBufferLength or nCopied == 0: 2243 raise ctypes.WinError() 2244 return lpBuffer.value, lpFilePart.value
2245 2246 GetFullPathName = GuessStringType(GetFullPathNameA, GetFullPathNameW)
2247 2248 # DWORD WINAPI GetTempPath( 2249 # __in DWORD nBufferLength, 2250 # __out LPTSTR lpBuffer 2251 # ); 2252 -def GetTempPathA():
2253 _GetTempPathA = windll.kernel32.GetTempPathA 2254 _GetTempPathA.argtypes = [DWORD, LPSTR] 2255 _GetTempPathA.restype = DWORD 2256 2257 nBufferLength = _GetTempPathA(0, None) 2258 if nBufferLength <= 0: 2259 raise ctypes.WinError() 2260 lpBuffer = ctypes.create_string_buffer('', nBufferLength) 2261 nCopied = _GetTempPathA(nBufferLength, lpBuffer) 2262 if nCopied > nBufferLength or nCopied == 0: 2263 raise ctypes.WinError() 2264 return lpBuffer.value
2265
2266 -def GetTempPathW():
2267 _GetTempPathW = windll.kernel32.GetTempPathW 2268 _GetTempPathW.argtypes = [DWORD, LPSTR] 2269 _GetTempPathW.restype = DWORD 2270 2271 nBufferLength = _GetTempPathW(0, None) 2272 if nBufferLength <= 0: 2273 raise ctypes.WinError() 2274 lpBuffer = ctypes.create_unicode_buffer(u'', nBufferLength) 2275 nCopied = _GetTempPathW(nBufferLength, lpBuffer) 2276 if nCopied > nBufferLength or nCopied == 0: 2277 raise ctypes.WinError() 2278 return lpBuffer.value
2279 2280 GetTempPath = GuessStringType(GetTempPathA, GetTempPathW)
2281 2282 # UINT WINAPI GetTempFileName( 2283 # __in LPCTSTR lpPathName, 2284 # __in LPCTSTR lpPrefixString, 2285 # __in UINT uUnique, 2286 # __out LPTSTR lpTempFileName 2287 # ); 2288 -def GetTempFileNameA(lpPathName = None, lpPrefixString = "TMP", uUnique = 0):
2289 _GetTempFileNameA = windll.kernel32.GetTempFileNameA 2290 _GetTempFileNameA.argtypes = [LPSTR, LPSTR, UINT, LPSTR] 2291 _GetTempFileNameA.restype = UINT 2292 2293 if lpPathName is None: 2294 lpPathName = GetTempPathA() 2295 lpTempFileName = ctypes.create_string_buffer('', MAX_PATH) 2296 uUnique = _GetTempFileNameA(lpPathName, lpPrefixString, uUnique, lpTempFileName) 2297 if uUnique == 0: 2298 raise ctypes.WinError() 2299 return lpTempFileName.value, uUnique
2300
2301 -def GetTempFileNameW(lpPathName = None, lpPrefixString = u"TMP", uUnique = 0):
2302 _GetTempFileNameW = windll.kernel32.GetTempFileNameW 2303 _GetTempFileNameW.argtypes = [LPSTR, LPSTR, UINT, LPSTR] 2304 _GetTempFileNameW.restype = UINT 2305 2306 if lpPathName is None: 2307 lpPathName = GetTempPathW() 2308 lpTempFileName = ctypes.create_unicode_buffer(u'', MAX_PATH) 2309 uUnique = _GetTempFileNameW(lpPathName, lpPrefixString, uUnique, lpTempFileName) 2310 if uUnique == 0: 2311 raise ctypes.WinError() 2312 return lpTempFileName.value, uUnique
2313 2314 GetTempFileName = GuessStringType(GetTempFileNameA, GetTempFileNameW)
2315 2316 # DWORD WINAPI GetCurrentDirectory( 2317 # __in DWORD nBufferLength, 2318 # __out LPTSTR lpBuffer 2319 # ); 2320 -def GetCurrentDirectoryA():
2321 _GetCurrentDirectoryA = windll.kernel32.GetCurrentDirectoryA 2322 _GetCurrentDirectoryA.argtypes = [DWORD, LPSTR] 2323 _GetCurrentDirectoryA.restype = DWORD 2324 2325 nBufferLength = _GetCurrentDirectoryA(0, None) 2326 if nBufferLength <= 0: 2327 raise ctypes.WinError() 2328 lpBuffer = ctypes.create_string_buffer('', nBufferLength) 2329 nCopied = _GetCurrentDirectoryA(nBufferLength, lpBuffer) 2330 if nCopied > nBufferLength or nCopied == 0: 2331 raise ctypes.WinError() 2332 return lpBuffer.value
2333
2334 -def GetCurrentDirectoryW():
2335 _GetCurrentDirectoryW = windll.kernel32.GetCurrentDirectoryW 2336 _GetCurrentDirectoryW.argtypes = [DWORD, LPWSTR] 2337 _GetCurrentDirectoryW.restype = DWORD 2338 2339 nBufferLength = _GetCurrentDirectoryW(0, None) 2340 if nBufferLength <= 0: 2341 raise ctypes.WinError() 2342 lpBuffer = ctypes.create_unicode_buffer(u'', nBufferLength) 2343 nCopied = _GetCurrentDirectoryW(nBufferLength, lpBuffer) 2344 if nCopied > nBufferLength or nCopied == 0: 2345 raise ctypes.WinError() 2346 return lpBuffer.value
2347 2348 GetCurrentDirectory = GuessStringType(GetCurrentDirectoryA, GetCurrentDirectoryW)
2349 2350 # HLOCAL WINAPI LocalFree( 2351 # __in HLOCAL hMem 2352 # ); 2353 -def LocalFree(hMem):
2354 _LocalFree = windll.kernel32.LocalFree 2355 _LocalFree.argtypes = [HLOCAL] 2356 _LocalFree.restype = HLOCAL 2357 2358 result = _LocalFree(hMem) 2359 if result != NULL: 2360 ctypes.WinError()
2361 2362 # BOOL WINAPI HandlerRoutine( 2363 # __in DWORD dwCtrlType 2364 # ); 2365 PHANDLER_ROUTINE = ctypes.WINFUNCTYPE(BOOL, DWORD)
2366 2367 # BOOL WINAPI SetConsoleCtrlHandler( 2368 # __in_opt PHANDLER_ROUTINE HandlerRoutine, 2369 # __in BOOL Add 2370 # ); 2371 -def SetConsoleCtrlHandler(HandlerRoutine = None, Add = True):
2372 _SetConsoleCtrlHandler = windll.kernel32.SetConsoleCtrlHandler 2373 _SetConsoleCtrlHandler.argtypes = [PHANDLER_ROUTINE, BOOL] 2374 _SetConsoleCtrlHandler.restype = bool 2375 _SetConsoleCtrlHandler.errcheck = RaiseIfZero 2376 2377 if callable(HandlerRoutine): 2378 HandlerRoutine = PHANDLER_ROUTINE(HandlerRoutine) 2379 elif not HandlerRoutine: 2380 HandlerRoutine = None 2381 else: 2382 raise ValueError, "Bad argument for HandlerRoutine: %r" % HandlerRoutine 2383 _SetConsoleCtrlHandler(HandlerRoutine, bool(Add))
2384
2385 # BOOL WINAPI GenerateConsoleCtrlEvent( 2386 # __in DWORD dwCtrlEvent, 2387 # __in DWORD dwProcessGroupId 2388 # ); 2389 -def GenerateConsoleCtrlEvent(dwCtrlEvent, dwProcessGroupId):
2390 _GenerateConsoleCtrlEvent = windll.kernel32.GenerateConsoleCtrlEvent 2391 _GenerateConsoleCtrlEvent.argtypes = [DWORD, DWORD] 2392 _GenerateConsoleCtrlEvent.restype = bool 2393 _GenerateConsoleCtrlEvent.errcheck = RaiseIfZero 2394 _GenerateConsoleCtrlEvent(dwCtrlEvent, dwProcessGroupId)
2395
2396 # DWORD WINAPI WaitForSingleObject( 2397 # HANDLE hHandle, 2398 # DWORD dwMilliseconds 2399 # ); 2400 -def WaitForSingleObject(hHandle, dwMilliseconds = INFINITE):
2401 _WaitForSingleObject = windll.kernel32.WaitForSingleObject 2402 _WaitForSingleObject.argtypes = [HANDLE, DWORD] 2403 _WaitForSingleObject.restype = DWORD 2404 2405 if not dwMilliseconds and dwMilliseconds != 0: 2406 dwMilliseconds = INFINITE 2407 if dwMilliseconds != INFINITE: 2408 r = _WaitForSingleObject(hHandle, dwMilliseconds) 2409 if r == WAIT_FAILED: 2410 raise ctypes.WinError() 2411 else: 2412 while 1: 2413 r = _WaitForSingleObject(hHandle, 100) 2414 if r == WAIT_FAILED: 2415 raise ctypes.WinError() 2416 if r != WAIT_TIMEOUT: 2417 break 2418 return r
2419
2420 # DWORD WINAPI WaitForSingleObjectEx( 2421 # HANDLE hHandle, 2422 # DWORD dwMilliseconds, 2423 # BOOL bAlertable 2424 # ); 2425 -def WaitForSingleObjectEx(hHandle, dwMilliseconds = INFINITE, bAlertable = True):
2426 _WaitForSingleObjectEx = windll.kernel32.WaitForSingleObjectEx 2427 _WaitForSingleObjectEx.argtypes = [HANDLE, DWORD, BOOL] 2428 _WaitForSingleObjectEx.restype = DWORD 2429 2430 if not dwMilliseconds and dwMilliseconds != 0: 2431 dwMilliseconds = INFINITE 2432 if dwMilliseconds != INFINITE: 2433 r = _WaitForSingleObjectEx(hHandle, dwMilliseconds, bool(bAlertable)) 2434 if r == WAIT_FAILED: 2435 raise ctypes.WinError() 2436 else: 2437 while 1: 2438 r = _WaitForSingleObjectEx(hHandle, 100, bool(bAlertable)) 2439 if r == WAIT_FAILED: 2440 raise ctypes.WinError() 2441 if r != WAIT_TIMEOUT: 2442 break 2443 return r
2444
2445 # DWORD WINAPI WaitForMultipleObjects( 2446 # DWORD nCount, 2447 # const HANDLE *lpHandles, 2448 # BOOL bWaitAll, 2449 # DWORD dwMilliseconds 2450 # ); 2451 -def WaitForMultipleObjects(handles, bWaitAll = False, dwMilliseconds = INFINITE):
2452 _WaitForMultipleObjects = windll.kernel32.WaitForMultipleObjects 2453 _WaitForMultipleObjects.argtypes = [DWORD, ctypes.POINTER(HANDLE), BOOL, DWORD] 2454 _WaitForMultipleObjects.restype = DWORD 2455 2456 if not dwMilliseconds and dwMilliseconds != 0: 2457 dwMilliseconds = INFINITE 2458 nCount = len(handles) 2459 lpHandlesType = HANDLE * nCount 2460 lpHandles = lpHandlesType(*handles) 2461 if dwMilliseconds != INFINITE: 2462 r = _WaitForMultipleObjects(ctypes.byref(lpHandles), bool(bWaitAll), dwMilliseconds) 2463 if r == WAIT_FAILED: 2464 raise ctypes.WinError() 2465 else: 2466 while 1: 2467 r = _WaitForMultipleObjects(ctypes.byref(lpHandles), bool(bWaitAll), 100) 2468 if r == WAIT_FAILED: 2469 raise ctypes.WinError() 2470 if r != WAIT_TIMEOUT: 2471 break 2472 return r
2473
2474 # DWORD WINAPI WaitForMultipleObjectsEx( 2475 # DWORD nCount, 2476 # const HANDLE *lpHandles, 2477 # BOOL bWaitAll, 2478 # DWORD dwMilliseconds, 2479 # BOOL bAlertable 2480 # ); 2481 -def WaitForMultipleObjectsEx(handles, bWaitAll = False, dwMilliseconds = INFINITE):
2482 _WaitForMultipleObjectsEx = windll.kernel32.WaitForMultipleObjectsEx 2483 _WaitForMultipleObjectsEx.argtypes = [DWORD, ctypes.POINTER(HANDLE), BOOL, DWORD] 2484 _WaitForMultipleObjectsEx.restype = DWORD 2485 2486 if not dwMilliseconds and dwMilliseconds != 0: 2487 dwMilliseconds = INFINITE 2488 nCount = len(handles) 2489 lpHandlesType = HANDLES * nCount 2490 lpHandles = lpHandlesType(*handles) 2491 if dwMilliseconds != INFINITE: 2492 r = _WaitForMultipleObjectsEx(ctypes.byref(lpHandles), bool(bWaitAll), dwMilliseconds, bool(bAlertable)) 2493 if r == WAIT_FAILED: 2494 raise ctypes.WinError() 2495 else: 2496 while 1: 2497 r = _WaitForMultipleObjectsEx(ctypes.byref(lpHandles), bool(bWaitAll), 100, bool(bAlertable)) 2498 if r == WAIT_FAILED: 2499 raise ctypes.WinError() 2500 if r != WAIT_TIMEOUT: 2501 break 2502 return r
2503
2504 # BOOL WaitForDebugEvent( 2505 # LPDEBUG_EVENT lpDebugEvent, 2506 # DWORD dwMilliseconds 2507 # ); 2508 -def WaitForDebugEvent(dwMilliseconds = INFINITE):
2509 _WaitForDebugEvent = windll.kernel32.WaitForDebugEvent 2510 _WaitForDebugEvent.argtypes = [LPDEBUG_EVENT, DWORD] 2511 _WaitForDebugEvent.restype = DWORD 2512 2513 if not dwMilliseconds and dwMilliseconds != 0: 2514 dwMilliseconds = INFINITE 2515 lpDebugEvent = DEBUG_EVENT() 2516 lpDebugEvent.dwDebugEventCode = 0 2517 lpDebugEvent.dwProcessId = 0 2518 lpDebugEvent.dwThreadId = 0 2519 if dwMilliseconds != INFINITE: 2520 success = _WaitForDebugEvent(ctypes.byref(lpDebugEvent), dwMilliseconds) 2521 if success == 0: 2522 raise ctypes.WinError() 2523 else: 2524 while 1: 2525 success = _WaitForDebugEvent(ctypes.byref(lpDebugEvent), 100) 2526 if success != 0: 2527 break 2528 code = GetLastError() 2529 if code not in (ERROR_SEM_TIMEOUT, WAIT_TIMEOUT): 2530 raise ctypes.WinError(code) 2531 return lpDebugEvent
2532
2533 # BOOL ContinueDebugEvent( 2534 # DWORD dwProcessId, 2535 # DWORD dwThreadId, 2536 # DWORD dwContinueStatus 2537 # ); 2538 -def ContinueDebugEvent(dwProcessId, dwThreadId, dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED):
2539 _ContinueDebugEvent = windll.kernel32.ContinueDebugEvent 2540 _ContinueDebugEvent.argtypes = [DWORD, DWORD, DWORD] 2541 _ContinueDebugEvent.restype = bool 2542 _ContinueDebugEvent.errcheck = RaiseIfZero 2543 _ContinueDebugEvent(dwProcessId, dwThreadId, dwContinueStatus)
2544
2545 # BOOL WINAPI FlushInstructionCache( 2546 # __in HANDLE hProcess, 2547 # __in LPCVOID lpBaseAddress, 2548 # __in SIZE_T dwSize 2549 # ); 2550 -def FlushInstructionCache(hProcess, lpBaseAddress = None, dwSize = 0):
2551 # http://blogs.msdn.com/oldnewthing/archive/2003/12/08/55954.aspx#55958 2552 _FlushInstructionCache = windll.kernel32.FlushInstructionCache 2553 _FlushInstructionCache.argtypes = [HANDLE, LPVOID, SIZE_T] 2554 _FlushInstructionCache.restype = bool 2555 _FlushInstructionCache.errcheck = RaiseIfZero 2556 _FlushInstructionCache(hProcess, lpBaseAddress, dwSize)
2557
2558 # BOOL DebugActiveProcess( 2559 # DWORD dwProcessId 2560 # ); 2561 -def DebugActiveProcess(dwProcessId):
2562 _DebugActiveProcess = windll.kernel32.DebugActiveProcess 2563 _DebugActiveProcess.argtypes = [DWORD] 2564 _DebugActiveProcess.restype = bool 2565 _DebugActiveProcess.errcheck = RaiseIfZero 2566 _DebugActiveProcess(dwProcessId)
2567
2568 # BOOL DebugActiveProcessStop( 2569 # DWORD dwProcessId 2570 # ); 2571 -def DebugActiveProcessStop(dwProcessId):
2572 _DebugActiveProcessStop = windll.kernel32.DebugActiveProcessStop 2573 _DebugActiveProcessStop.argtypes = [DWORD] 2574 _DebugActiveProcessStop.restype = bool 2575 _DebugActiveProcessStop.errcheck = RaiseIfZero 2576 _DebugActiveProcessStop(dwProcessId)
2577
2578 # BOOL WINAPI CreateProcess( 2579 # __in_opt LPCTSTR lpApplicationName, 2580 # __inout_opt LPTSTR lpCommandLine, 2581 # __in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes, 2582 # __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, 2583 # __in BOOL bInheritHandles, 2584 # __in DWORD dwCreationFlags, 2585 # __in_opt LPVOID lpEnvironment, 2586 # __in_opt LPCTSTR lpCurrentDirectory, 2587 # __in LPSTARTUPINFO lpStartupInfo, 2588 # __out LPPROCESS_INFORMATION lpProcessInformation 2589 # ); 2590 -def CreateProcessA(lpApplicationName, lpCommandLine=None, lpProcessAttributes=None, lpThreadAttributes=None, bInheritHandles=False, dwCreationFlags=0, lpEnvironment=None, lpCurrentDirectory=None, lpStartupInfo=None):
2591 _CreateProcessA = windll.kernel32.CreateProcessA 2592 _CreateProcessA.argtypes = [LPSTR, LPSTR, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPSTR, LPVOID, LPPROCESS_INFORMATION] 2593 _CreateProcessA.restype = bool 2594 _CreateProcessA.errcheck = RaiseIfZero 2595 2596 if not lpApplicationName: 2597 lpApplicationName = None 2598 if not lpCommandLine: 2599 lpCommandLine = None 2600 else: 2601 lpCommandLine = ctypes.create_string_buffer(lpCommandLine, MAX_PATH) 2602 if not lpEnvironment: 2603 lpEnvironment = None 2604 else: 2605 lpEnvironment = ctypes.create_string_buffer(lpEnvironment) 2606 if not lpCurrentDirectory: 2607 lpCurrentDirectory = None 2608 if not lpProcessAttributes: 2609 lpProcessAttributes = None 2610 else: 2611 lpProcessAttributes = ctypes.byref(lpProcessAttributes) 2612 if not lpThreadAttributes: 2613 lpThreadAttributes = None 2614 else: 2615 lpThreadAttributes = ctypes.byref(lpThreadAttributes) 2616 if not lpStartupInfo: 2617 lpStartupInfo = STARTUPINFO() 2618 lpStartupInfo.cb = sizeof(STARTUPINFO) 2619 lpStartupInfo.lpReserved = 0 2620 lpStartupInfo.lpDesktop = 0 2621 lpStartupInfo.lpTitle = 0 2622 lpStartupInfo.dwFlags = 0 2623 lpStartupInfo.cbReserved2 = 0 2624 lpStartupInfo.lpReserved2 = 0 2625 lpProcessInformation = PROCESS_INFORMATION() 2626 lpProcessInformation.hProcess = INVALID_HANDLE_VALUE 2627 lpProcessInformation.hThread = INVALID_HANDLE_VALUE 2628 lpProcessInformation.dwProcessId = 0 2629 lpProcessInformation.dwThreadId = 0 2630 _CreateProcessA(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bool(bInheritHandles), dwCreationFlags, lpEnvironment, lpCurrentDirectory, ctypes.byref(lpStartupInfo), ctypes.byref(lpProcessInformation)) 2631 return ProcessInformation(lpProcessInformation)
2632
2633 -def CreateProcessW(lpApplicationName, lpCommandLine=None, lpProcessAttributes=None, lpThreadAttributes=None, bInheritHandles=False, dwCreationFlags=0, lpEnvironment=None, lpCurrentDirectory=None, lpStartupInfo=None):
2634 _CreateProcessW = windll.kernel32.CreateProcessW 2635 _CreateProcessW.argtypes = [LPWSTR, LPWSTR, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPWSTR, LPVOID, LPPROCESS_INFORMATION] 2636 _CreateProcessW.restype = bool 2637 _CreateProcessW.errcheck = RaiseIfZero 2638 2639 if not lpApplicationName: 2640 lpApplicationName = None 2641 if not lpCommandLine: 2642 lpCommandLine = None 2643 else: 2644 lpCommandLine = ctypes.create_unicode_buffer(lpCommandLine, MAX_PATH) 2645 if not lpEnvironment: 2646 lpEnvironment = None 2647 else: 2648 lpEnvironment = ctypes.create_unicode_buffer(lpEnvironment) 2649 if not lpCurrentDirectory: 2650 lpCurrentDirectory = None 2651 if not lpProcessAttributes: 2652 lpProcessAttributes = None 2653 else: 2654 lpProcessAttributes = ctypes.byref(lpProcessAttributes) 2655 if not lpThreadAttributes: 2656 lpThreadAttributes = None 2657 else: 2658 lpThreadAttributes = ctypes.byref(lpThreadAttributes) 2659 if not lpStartupInfo: 2660 lpStartupInfo = STARTUPINFO() 2661 lpStartupInfo.cb = sizeof(STARTUPINFO) 2662 lpStartupInfo.lpReserved = 0 2663 lpStartupInfo.lpDesktop = 0 2664 lpStartupInfo.lpTitle = 0 2665 lpStartupInfo.dwFlags = 0 2666 lpStartupInfo.cbReserved2 = 0 2667 lpStartupInfo.lpReserved2 = 0 2668 lpProcessInformation = PROCESS_INFORMATION() 2669 lpProcessInformation.hProcess = INVALID_HANDLE_VALUE 2670 lpProcessInformation.hThread = INVALID_HANDLE_VALUE 2671 lpProcessInformation.dwProcessId = 0 2672 lpProcessInformation.dwThreadId = 0 2673 _CreateProcessW(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bool(bInheritHandles), dwCreationFlags, lpEnvironment, lpCurrentDirectory, ctypes.byref(lpStartupInfo), ctypes.byref(lpProcessInformation)) 2674 return ProcessInformation(lpProcessInformation)
2675 2676 CreateProcess = GuessStringType(CreateProcessA, CreateProcessW)
2677 2678 # BOOL WINAPI CreateProcessAsUser( 2679 # __in_opt HANDLE hToken, 2680 # __in_opt LPCTSTR lpApplicationName, 2681 # __inout_opt LPTSTR lpCommandLine, 2682 # __in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes, 2683 # __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, 2684 # __in BOOL bInheritHandles, 2685 # __in DWORD dwCreationFlags, 2686 # __in_opt LPVOID lpEnvironment, 2687 # __in_opt LPCTSTR lpCurrentDirectory, 2688 # __in LPSTARTUPINFO lpStartupInfo, 2689 # __out LPPROCESS_INFORMATION lpProcessInformation 2690 # ); 2691 -def CreateProcessAsUserA(hToken, lpApplicationName, lpCommandLine=None, lpProcessAttributes=None, lpThreadAttributes=None, bInheritHandles=False, dwCreationFlags=0, lpEnvironment=None, lpCurrentDirectory=None, lpStartupInfo=None):
2692 _CreateProcessAsUserA = windll.kernel32.CreateProcessAsUserA 2693 _CreateProcessAsUserA.argtypes = [HANDLE, LPSTR, LPSTR, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPSTR, LPVOID, LPPROCESS_INFORMATION] 2694 _CreateProcessAsUserA.restype = bool 2695 _CreateProcessAsUserA.errcheck = RaiseIfZero 2696 2697 if not lpApplicationName: 2698 lpApplicationName = None 2699 if not lpCommandLine: 2700 lpCommandLine = None 2701 else: 2702 lpCommandLine = ctypes.create_string_buffer(lpCommandLine, MAX_PATH) 2703 if not lpEnvironment: 2704 lpEnvironment = None 2705 else: 2706 lpEnvironment = ctypes.create_string_buffer(lpEnvironment) 2707 if not lpCurrentDirectory: 2708 lpCurrentDirectory = None 2709 if not lpProcessAttributes: 2710 lpProcessAttributes = None 2711 else: 2712 lpProcessAttributes = ctypes.byref(lpProcessAttributes) 2713 if not lpThreadAttributes: 2714 lpThreadAttributes = None 2715 else: 2716 lpThreadAttributes = ctypes.byref(lpThreadAttributes) 2717 if not lpStartupInfo: 2718 lpStartupInfo = STARTUPINFO() 2719 lpStartupInfo.cb = sizeof(STARTUPINFO) 2720 lpStartupInfo.lpReserved = 0 2721 lpStartupInfo.lpDesktop = 0 2722 lpStartupInfo.lpTitle = 0 2723 lpStartupInfo.dwFlags = 0 2724 lpStartupInfo.cbReserved2 = 0 2725 lpStartupInfo.lpReserved2 = 0 2726 lpProcessInformation = PROCESS_INFORMATION() 2727 lpProcessInformation.hProcess = INVALID_HANDLE_VALUE 2728 lpProcessInformation.hThread = INVALID_HANDLE_VALUE 2729 lpProcessInformation.dwProcessId = 0 2730 lpProcessInformation.dwThreadId = 0 2731 _CreateProcessAsUserA(hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bool(bInheritHandles), dwCreationFlags, lpEnvironment, lpCurrentDirectory, ctypes.byref(lpStartupInfo), ctypes.byref(lpProcessInformation)) 2732 return ProcessInformation(lpProcessInformation)
2733
2734 -def CreateProcessAsUserW(hToken, lpApplicationName, lpCommandLine=None, lpProcessAttributes=None, lpThreadAttributes=None, bInheritHandles=False, dwCreationFlags=0, lpEnvironment=None, lpCurrentDirectory=None, lpStartupInfo=None):
2735 _CreateProcessAsUserW = windll.kernel32.CreateProcessAsUserW 2736 _CreateProcessAsUserW.argtypes = [HANDLE, LPWSTR, LPWSTR, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPWSTR, LPVOID, LPPROCESS_INFORMATION] 2737 _CreateProcessAsUserW.restype = bool 2738 _CreateProcessAsUserW.errcheck = RaiseIfZero 2739 2740 if not lpApplicationName: 2741 lpApplicationName = None 2742 if not lpCommandLine: 2743 lpCommandLine = None 2744 else: 2745 lpCommandLine = ctypes.create_unicode_buffer(lpCommandLine, MAX_PATH) 2746 if not lpEnvironment: 2747 lpEnvironment = None 2748 else: 2749 lpEnvironment = ctypes.create_unicode_buffer(lpEnvironment) 2750 if not lpCurrentDirectory: 2751 lpCurrentDirectory = None 2752 if not lpProcessAttributes: 2753 lpProcessAttributes = None 2754 else: 2755 lpProcessAttributes = ctypes.byref(lpProcessAttributes) 2756 if not lpThreadAttributes: 2757 lpThreadAttributes = None 2758 else: 2759 lpThreadAttributes = ctypes.byref(lpThreadAttributes) 2760 if not lpStartupInfo: 2761 lpStartupInfo = STARTUPINFO() 2762 lpStartupInfo.cb = sizeof(STARTUPINFO) 2763 lpStartupInfo.lpReserved = 0 2764 lpStartupInfo.lpDesktop = 0 2765 lpStartupInfo.lpTitle = 0 2766 lpStartupInfo.dwFlags = 0 2767 lpStartupInfo.cbReserved2 = 0 2768 lpStartupInfo.lpReserved2 = 0 2769 lpProcessInformation = PROCESS_INFORMATION() 2770 lpProcessInformation.hProcess = INVALID_HANDLE_VALUE 2771 lpProcessInformation.hThread = INVALID_HANDLE_VALUE 2772 lpProcessInformation.dwProcessId = 0 2773 lpProcessInformation.dwThreadId = 0 2774 _CreateProcessAsUserW(hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bool(bInheritHandles), dwCreationFlags, lpEnvironment, lpCurrentDirectory, ctypes.byref(lpStartupInfo), ctypes.byref(lpProcessInformation)) 2775 return ProcessInformation(lpProcessInformation)
2776 2777 CreateProcessAsUser = GuessStringType(CreateProcessAsUserA, CreateProcessAsUserW)
2778 2779 # BOOL WINAPI InitializeProcThreadAttributeList( 2780 # __out_opt LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, 2781 # __in DWORD dwAttributeCount, 2782 # __reserved DWORD dwFlags, 2783 # __inout PSIZE_T lpSize 2784 # ); 2785 -def InitializeProcThreadAttributeList(dwAttributeCount):
2786 _InitializeProcThreadAttributeList = windll.kernel32.InitializeProcThreadAttributeList 2787 _InitializeProcThreadAttributeList.argtypes = [LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T] 2788 _InitializeProcThreadAttributeList.restype = bool 2789 2790 Size = SIZE_T(0) 2791 _InitializeProcThreadAttributeList(None, dwAttributeCount, 0, ctypes.byref(Size)) 2792 RaiseIfZero(Size.value) 2793 AttributeList = (BYTE * Size.value)() 2794 success = _InitializeProcThreadAttributeList(ctypes.byref(AttributeList), dwAttributeCount, 0, ctypes.byref(Size)) 2795 RaiseIfZero(success) 2796 return AttributeList
2797
2798 # BOOL WINAPI UpdateProcThreadAttribute( 2799 # __inout LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, 2800 # __in DWORD dwFlags, 2801 # __in DWORD_PTR Attribute, 2802 # __in PVOID lpValue, 2803 # __in SIZE_T cbSize, 2804 # __out_opt PVOID lpPreviousValue, 2805 # __in_opt PSIZE_T lpReturnSize 2806 # ); 2807 -def UpdateProcThreadAttribute(lpAttributeList, Attribute, Value, cbSize = None):
2808 _UpdateProcThreadAttribute = windll.kernel32.UpdateProcThreadAttribute 2809 _UpdateProcThreadAttribute.argtypes = [LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, SIZE_T, PVOID, SIZE_T, PVOID, PSIZE_T] 2810 _UpdateProcThreadAttribute.restype = bool 2811 _UpdateProcThreadAttribute.errcheck = RaiseIfZero 2812 2813 if cbSize is None: 2814 cbSize = ctypes.sizeof(Value) 2815 _UpdateProcThreadAttribute(ctypes.byref(lpAttributeList), 0, Attribute, ctypes.byref(Value), cbSize, None, None)
2816
2817 # VOID WINAPI DeleteProcThreadAttributeList( 2818 # __inout LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList 2819 # ); 2820 -def DeleteProcThreadAttributeList(lpAttributeList):
2821 _DeleteProcThreadAttributeList = windll.kernel32.DeleteProcThreadAttributeList 2822 _DeleteProcThreadAttributeList.restype = None 2823 _DeleteProcThreadAttributeList(ctypes.byref(lpAttributeList))
2824
2825 # HANDLE WINAPI OpenProcess( 2826 # __in DWORD dwDesiredAccess, 2827 # __in BOOL bInheritHandle, 2828 # __in DWORD dwProcessId 2829 # ); 2830 -def OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId):
2831 _OpenProcess = windll.kernel32.OpenProcess 2832 _OpenProcess.argtypes = [DWORD, BOOL, DWORD] 2833 _OpenProcess.restype = HANDLE 2834 2835 hProcess = _OpenProcess(dwDesiredAccess, bool(bInheritHandle), dwProcessId) 2836 if hProcess == NULL: 2837 raise ctypes.WinError() 2838 return ProcessHandle(hProcess)
2839
2840 # HANDLE WINAPI OpenThread( 2841 # __in DWORD dwDesiredAccess, 2842 # __in BOOL bInheritHandle, 2843 # __in DWORD dwThreadId 2844 # ); 2845 -def OpenThread(dwDesiredAccess, bInheritHandle, dwThreadId):
2846 _OpenThread = windll.kernel32.OpenThread 2847 _OpenThread.argtypes = [DWORD, BOOL, DWORD] 2848 _OpenThread.restype = HANDLE 2849 2850 hProcess = _OpenThread(dwDesiredAccess, bool(bInheritHandle), dwThreadId) 2851 if hProcess == NULL: 2852 raise ctypes.WinError() 2853 return ThreadHandle(hProcess)
2854
2855 # DWORD WINAPI SuspendThread( 2856 # __in HANDLE hThread 2857 # ); 2858 -def SuspendThread(hThread):
2859 _SuspendThread = windll.kernel32.SuspendThread 2860 _SuspendThread.argtypes = [HANDLE] 2861 _SuspendThread.restype = DWORD 2862 2863 previousCount = _SuspendThread(hThread) 2864 if previousCount == DWORD(-1).value: 2865 raise ctypes.WinError() 2866 return previousCount
2867
2868 # DWORD WINAPI ResumeThread( 2869 # __in HANDLE hThread 2870 # ); 2871 -def ResumeThread(hThread):
2872 _ResumeThread = windll.kernel32.ResumeThread 2873 _ResumeThread.argtypes = [HANDLE] 2874 _ResumeThread.restype = DWORD 2875 2876 previousCount = _ResumeThread(hThread) 2877 if previousCount == DWORD(-1).value: 2878 raise ctypes.WinError() 2879 return previousCount
2880
2881 # BOOL WINAPI TerminateThread( 2882 # __inout HANDLE hThread, 2883 # __in DWORD dwExitCode 2884 # ); 2885 -def TerminateThread(hThread, dwExitCode = 0):
2886 _TerminateThread = windll.kernel32.TerminateThread 2887 _TerminateThread.argtypes = [HANDLE, DWORD] 2888 _TerminateThread.restype = bool 2889 _TerminateThread.errcheck = RaiseIfZero 2890 _TerminateThread(hThread, dwExitCode)
2891
2892 # BOOL WINAPI TerminateProcess( 2893 # __inout HANDLE hProcess, 2894 # __in DWORD dwExitCode 2895 # ); 2896 -def TerminateProcess(hProcess, dwExitCode = 0):
2897 _TerminateProcess = windll.kernel32.TerminateProcess 2898 _TerminateProcess.argtypes = [HANDLE, DWORD] 2899 _TerminateProcess.restype = bool 2900 _TerminateProcess.errcheck = RaiseIfZero 2901 _TerminateProcess(hProcess, dwExitCode)
2902
2903 # BOOL WINAPI ReadProcessMemory( 2904 # __in HANDLE hProcess, 2905 # __in LPCVOID lpBaseAddress, 2906 # __out LPVOID lpBuffer, 2907 # __in SIZE_T nSize, 2908 # __out SIZE_T* lpNumberOfBytesRead 2909 # ); 2910 -def ReadProcessMemory(hProcess, lpBaseAddress, nSize):
2911 _ReadProcessMemory = windll.kernel32.ReadProcessMemory 2912 _ReadProcessMemory.argtypes = [HANDLE, LPVOID, LPVOID, SIZE_T, POINTER(SIZE_T)] 2913 _ReadProcessMemory.restype = bool 2914 2915 lpBuffer = ctypes.create_string_buffer('', nSize) 2916 lpNumberOfBytesRead = SIZE_T(0) 2917 success = _ReadProcessMemory(hProcess, lpBaseAddress, lpBuffer, nSize, ctypes.byref(lpNumberOfBytesRead)) 2918 if not success and GetLastError() != ERROR_PARTIAL_COPY: 2919 raise ctypes.WinError() 2920 return str(lpBuffer.raw)[:lpNumberOfBytesRead.value]
2921
2922 # BOOL WINAPI WriteProcessMemory( 2923 # __in HANDLE hProcess, 2924 # __in LPCVOID lpBaseAddress, 2925 # __in LPVOID lpBuffer, 2926 # __in SIZE_T nSize, 2927 # __out SIZE_T* lpNumberOfBytesWritten 2928 # ); 2929 -def WriteProcessMemory(hProcess, lpBaseAddress, lpBuffer):
2930 _WriteProcessMemory = windll.kernel32.WriteProcessMemory 2931 _WriteProcessMemory.argtypes = [HANDLE, LPVOID, LPVOID, SIZE_T, ctypes.POINTER(SIZE_T)] 2932 _WriteProcessMemory.restype = bool 2933 2934 nSize = len(lpBuffer) 2935 lpBuffer = ctypes.create_string_buffer(lpBuffer) 2936 lpNumberOfBytesWritten = SIZE_T(0) 2937 success = _WriteProcessMemory(hProcess, lpBaseAddress, lpBuffer, nSize, ctypes.byref(lpNumberOfBytesWritten)) 2938 if not success and GetLastError() != ERROR_PARTIAL_COPY: 2939 raise ctypes.WinError() 2940 return lpNumberOfBytesWritten.value
2941
2942 # LPVOID WINAPI VirtualAllocEx( 2943 # __in HANDLE hProcess, 2944 # __in_opt LPVOID lpAddress, 2945 # __in SIZE_T dwSize, 2946 # __in DWORD flAllocationType, 2947 # __in DWORD flProtect 2948 # ); 2949 -def VirtualAllocEx(hProcess, lpAddress = 0, dwSize = 0x1000, flAllocationType = MEM_COMMIT | MEM_RESERVE, flProtect = PAGE_EXECUTE_READWRITE):
2950 _VirtualAllocEx = windll.kernel32.VirtualAllocEx 2951 _VirtualAllocEx.argtypes = [HANDLE, LPVOID, SIZE_T, DWORD, DWORD] 2952 _VirtualAllocEx.restype = LPVOID 2953 2954 lpAddress = _VirtualAllocEx(hProcess, lpAddress, dwSize, flAllocationType, flProtect) 2955 if lpAddress == NULL: 2956 raise ctypes.WinError() 2957 return lpAddress
2958
2959 # SIZE_T WINAPI VirtualQueryEx( 2960 # __in HANDLE hProcess, 2961 # __in_opt LPCVOID lpAddress, 2962 # __out PMEMORY_BASIC_INFORMATION lpBuffer, 2963 # __in SIZE_T dwLength 2964 # ); 2965 -def VirtualQueryEx(hProcess, lpAddress):
2966 _VirtualQueryEx = windll.kernel32.VirtualQueryEx 2967 _VirtualQueryEx.argtypes = [HANDLE, LPVOID, PMEMORY_BASIC_INFORMATION, SIZE_T] 2968 _VirtualQueryEx.restype = SIZE_T 2969 2970 lpBuffer = MEMORY_BASIC_INFORMATION() 2971 dwLength = sizeof(MEMORY_BASIC_INFORMATION) 2972 success = _VirtualQueryEx(hProcess, lpAddress, ctypes.byref(lpBuffer), dwLength) 2973 if success == 0: 2974 raise ctypes.WinError() 2975 return MemoryBasicInformation(lpBuffer)
2976
2977 # BOOL WINAPI VirtualProtectEx( 2978 # __in HANDLE hProcess, 2979 # __in LPVOID lpAddress, 2980 # __in SIZE_T dwSize, 2981 # __in DWORD flNewProtect, 2982 # __out PDWORD lpflOldProtect 2983 # ); 2984 -def VirtualProtectEx(hProcess, lpAddress, dwSize, flNewProtect = PAGE_EXECUTE_READWRITE):
2985 _VirtualProtectEx = windll.kernel32.VirtualProtectEx 2986 _VirtualProtectEx.argtypes = [HANDLE, LPVOID, SIZE_T, DWORD, PDWORD] 2987 _VirtualProtectEx.restype = bool 2988 _VirtualProtectEx.errcheck = RaiseIfZero 2989 2990 flOldProtect = DWORD(0) 2991 _VirtualProtectEx(hProcess, lpAddress, dwSize, flNewProtect, ctypes.byref(flOldProtect)) 2992 return flOldProtect.value
2993
2994 # BOOL WINAPI VirtualFreeEx( 2995 # __in HANDLE hProcess, 2996 # __in LPVOID lpAddress, 2997 # __in SIZE_T dwSize, 2998 # __in DWORD dwFreeType 2999 # ); 3000 -def VirtualFreeEx(hProcess, lpAddress, dwSize = 0, dwFreeType = MEM_RELEASE):
3001 _VirtualFreeEx = windll.kernel32.VirtualFreeEx 3002 _VirtualFreeEx.argtypes = [HANDLE, LPVOID, SIZE_T, DWORD] 3003 _VirtualFreeEx.restype = bool 3004 _VirtualFreeEx.errcheck = RaiseIfZero 3005 _VirtualFreeEx(hProcess, lpAddress, dwSize, dwFreeType)
3006
3007 # HANDLE WINAPI CreateRemoteThread( 3008 # __in HANDLE hProcess, 3009 # __in LPSECURITY_ATTRIBUTES lpThreadAttributes, 3010 # __in SIZE_T dwStackSize, 3011 # __in LPTHREAD_START_ROUTINE lpStartAddress, 3012 # __in LPVOID lpParameter, 3013 # __in DWORD dwCreationFlags, 3014 # __out LPDWORD lpThreadId 3015 # ); 3016 -def CreateRemoteThread(hProcess, lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags):
3017 _CreateRemoteThread = windll.kernel32.CreateRemoteThread 3018 _CreateRemoteThread.argtypes = [HANDLE, LPSECURITY_ATTRIBUTES, SIZE_T, LPVOID, LPVOID, DWORD, LPDWORD] 3019 _CreateRemoteThread.restype = HANDLE 3020 3021 if not lpThreadAttributes: 3022 lpThreadAttributes = None 3023 else: 3024 lpThreadAttributes = ctypes.byref(lpThreadAttributes) 3025 dwThreadId = DWORD(0) 3026 hThread = _CreateRemoteThread(hProcess, lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, ctypes.byref(dwThreadId)) 3027 if hThread == INVALID_HANDLE_VALUE: 3028 raise ctypes.WinError() 3029 return ThreadHandle(hThread), dwThreadId.value
3030
3031 # HANDLE WINAPI GetCurrentProcess(void); 3032 -def GetCurrentProcess():
3033 _GetCurrentProcess = windll.kernel32.GetCurrentProcess 3034 _GetCurrentProcess.argtypes = [] 3035 _GetCurrentProcess.restype = HANDLE 3036 return _GetCurrentProcess()
3037
3038 # HANDLE WINAPI GetCurrentThread(void); 3039 -def GetCurrentThread():
3040 GetCurrentThread = windll.kernel32.GetCurrentThread 3041 _GetCurrentThread.argtypes = [] 3042 _GetCurrentThread.restype = HANDLE 3043 return _GetCurrentThread()
3044
3045 # DWORD WINAPI GetProcessId( 3046 # __in HANDLE hProcess 3047 # ); 3048 -def GetProcessId(hProcess):
3049 _GetProcessId = windll.kernel32.GetProcessId 3050 _GetProcessId.argtypes = [HANDLE] 3051 _GetProcessId.restype = DWORD 3052 _GetProcessId.errcheck = RaiseIfZero 3053 return _GetProcessId(hProcess)
3054
3055 # DWORD WINAPI GetThreadId( 3056 # __in HANDLE hThread 3057 # ); 3058 -def GetThreadId(hThread):
3059 _GetThreadId = windll.kernel32._GetThreadId 3060 _GetThreadId.argtypes = [HANDLE] 3061 _GetThreadId.restype = DWORD 3062 3063 dwThreadId = _GetThreadId(hThread) 3064 if dwThreadId == 0: 3065 raise ctypes.WinError() 3066 return dwThreadId
3067
3068 # DWORD WINAPI GetProcessIdOfThread( 3069 # __in HANDLE hThread 3070 # ); 3071 -def GetProcessIdOfThread(hThread):
3072 _GetProcessIdOfThread = windll.kernel32.GetProcessIdOfThread 3073 _GetProcessIdOfThread.argtypes = [HANDLE] 3074 _GetProcessIdOfThread.restype = DWORD 3075 3076 dwProcessId = _GetProcessIdOfThread(hThread) 3077 if dwProcessId == 0: 3078 raise ctypes.WinError() 3079 return dwProcessId
3080
3081 # BOOL WINAPI GetExitCodeProcess( 3082 # __in HANDLE hProcess, 3083 # __out LPDWORD lpExitCode 3084 # ); 3085 -def GetExitCodeProcess(hProcess):
3086 _GetExitCodeProcess = windll.kernel32.GetExitCodeProcess 3087 _GetExitCodeProcess.argtypes = [HANDLE] 3088 _GetExitCodeProcess.restype = bool 3089 _GetExitCodeProcess.errcheck = RaiseIfZero 3090 3091 lpExitCode = DWORD(0) 3092 _GetExitCodeProcess(hProcess, ctypes.byref(lpExitCode)) 3093 return lpExitCode.value
3094
3095 # BOOL WINAPI GetExitCodeThread( 3096 # __in HANDLE hThread, 3097 # __out LPDWORD lpExitCode 3098 # ); 3099 -def GetExitCodeThread(hThread):
3100 _GetExitCodeThread = windll.kernel32.GetExitCodeThread 3101 _GetExitCodeThread.argtypes = [HANDLE] 3102 _GetExitCodeThread.restype = bool 3103 _GetExitCodeThread.errcheck = RaiseIfZero 3104 3105 lpExitCode = DWORD(0) 3106 _GetExitCodeThread(hThread, ctypes.byref(lpExitCode)) 3107 return lpExitCode.value
3108
3109 # DWORD WINAPI GetProcessVersion( 3110 # __in DWORD ProcessId 3111 # ); 3112 -def GetProcessVersion(ProcessId):
3113 _GetProcessVersion = windll.kernel32.GetProcessVersion 3114 _GetProcessVersion.argtypes = [DWORD] 3115 _GetProcessVersion.restype = DWORD 3116 3117 retval = _GetProcessVersion(ProcessId) 3118 if retval == 0: 3119 raise ctypes.WinError() 3120 return retval
3121
3122 # DWORD WINAPI GetPriorityClass( 3123 # __in HANDLE hProcess 3124 # ); 3125 -def GetPriorityClass(hProcess):
3126 _GetPriorityClass = windll.kernel32.GetPriorityClass 3127 _GetPriorityClass.argtypes = [HANDLE] 3128 _GetPriorityClass.restype = DWORD 3129 3130 retval = _GetPriorityClass(hProcess) 3131 if retval == 0: 3132 raise ctypes.WinError() 3133 return retval
3134
3135 # BOOL WINAPI SetPriorityClass( 3136 # __in HANDLE hProcess, 3137 # __in DWORD dwPriorityClass 3138 # ); 3139 -def SetPriorityClass(hProcess, dwPriorityClass = NORMAL_PRIORITY_CLASS):
3140 _SetPriorityClass = windll.kernel32.SetPriorityClass 3141 _SetPriorityClass.argtypes = [HANDLE, DWORD] 3142 _SetPriorityClass.restype = bool 3143 _SetPriorityClass.errcheck = RaiseIfZero 3144 _SetPriorityClass(hProcess, dwPriorityClass)
3145
3146 # BOOL WINAPI GetProcessPriorityBoost( 3147 # __in HANDLE hProcess, 3148 # __out PBOOL pDisablePriorityBoost 3149 # ); 3150 -def GetProcessPriorityBoost(hProcess):
3151 _GetProcessPriorityBoost = windll.kernel32.GetProcessPriorityBoost 3152 _GetProcessPriorityBoost.argtypes = [HANDLE, PBOOL] 3153 _GetProcessPriorityBoost.restype = bool 3154 _GetProcessPriorityBoost.errcheck = RaiseIfZero 3155 3156 pDisablePriorityBoost = BOOL(False) 3157 _GetProcessPriorityBoost(hProcess, ctypes.byref(pDisablePriorityBoost)) 3158 return bool(pDisablePriorityBoost.value)
3159
3160 # BOOL WINAPI SetProcessPriorityBoost( 3161 # __in HANDLE hProcess, 3162 # __in BOOL DisablePriorityBoost 3163 # ); 3164 -def SetProcessPriorityBoost(hProcess, DisablePriorityBoost):
3165 _SetProcessPriorityBoost = windll.kernel32.SetProcessPriorityBoost 3166 _SetProcessPriorityBoost.argtypes = [HANDLE, BOOL] 3167 _SetProcessPriorityBoost.restype = bool 3168 _SetProcessPriorityBoost.errcheck = RaiseIfZero 3169 _SetProcessPriorityBoost(hProcess, bool(DisablePriorityBoost))
3170
3171 # BOOL WINAPI GetProcessAffinityMask( 3172 # __in HANDLE hProcess, 3173 # __out PDWORD_PTR lpProcessAffinityMask, 3174 # __out PDWORD_PTR lpSystemAffinityMask 3175 # ); 3176 -def GetProcessAffinityMask(hProcess):
3177 _GetProcessAffinityMask = windll.kernel32.GetProcessAffinityMask 3178 _GetProcessAffinityMask.argtypes = [HANDLE, PDWORD_PTR, PDWORD_PTR] 3179 _GetProcessAffinityMask.restype = bool 3180 _GetProcessAffinityMask.errcheck = RaiseIfZero 3181 3182 lpProcessAffinityMask = DWORD_PTR(NULL) 3183 lpSystemAffinityMask = DWORD_PTR(NULL) 3184 _GetProcessAffinityMask(hProcess, ctypes.byref(lpProcessAffinityMask), ctypes.byref(lpSystemAffinityMask)) 3185 return lpProcessAffinityMask.value, lpSystemAffinityMask.value
3186
3187 # BOOL WINAPI SetProcessAffinityMask( 3188 # __in HANDLE hProcess, 3189 # __in DWORD_PTR dwProcessAffinityMask 3190 # ); 3191 -def SetProcessAffinityMask(hProcess, dwProcessAffinityMask):
3192 _SetProcessAffinityMask = windll.kernel32.SetProcessAffinityMask 3193 _SetProcessAffinityMask.argtypes = [HANDLE, DWORD_PTR] 3194 _SetProcessAffinityMask.restype = bool 3195 _SetProcessAffinityMask.errcheck = RaiseIfZero 3196 _SetProcessAffinityMask(hProcess, dwProcessAffinityMask)
3197
3198 # BOOL CheckRemoteDebuggerPresent( 3199 # HANDLE hProcess, 3200 # PBOOL pbDebuggerPresent 3201 # ); 3202 -def CheckRemoteDebuggerPresent(hProcess):
3203 _CheckRemoteDebuggerPresent = windll.kernel32.CheckRemoteDebuggerPresent 3204 _CheckRemoteDebuggerPresent.argtypes = [HANDLE, PBOOL] 3205 _CheckRemoteDebuggerPresent.restype = bool 3206 _CheckRemoteDebuggerPresent.errcheck = RaiseIfZero 3207 3208 pbDebuggerPresent = BOOL(0) 3209 _CheckRemoteDebuggerPresent(hProcess, ctypes.byref(pbDebuggerPresent)) 3210 return bool(pbDebuggerPresent.value)
3211
3212 # BOOL DebugSetProcessKillOnExit( 3213 # BOOL KillOnExit 3214 # ); 3215 -def DebugSetProcessKillOnExit(KillOnExit):
3216 _DebugSetProcessKillOnExit = windll.kernel32.DebugSetProcessKillOnExit 3217 _DebugSetProcessKillOnExit.argtypes = [BOOL] 3218 _DebugSetProcessKillOnExit.restype = bool 3219 _DebugSetProcessKillOnExit.errcheck = RaiseIfZero 3220 _DebugSetProcessKillOnExit(bool(KillOnExit))
3221
3222 # BOOL DebugBreakProcess( 3223 # HANDLE Process 3224 # ); 3225 -def DebugBreakProcess(hProcess):
3226 _DebugBreakProcess = windll.kernel32.DebugBreakProcess 3227 _DebugBreakProcess.argtypes = [HANDLE] 3228 _DebugBreakProcess.restype = bool 3229 _DebugBreakProcess.errcheck = RaiseIfZero 3230 _DebugBreakProcess(hProcess)
3231
3232 # HANDLE WINAPI CreateToolhelp32Snapshot( 3233 # __in DWORD dwFlags, 3234 # __in DWORD th32ProcessID 3235 # ); 3236 -def CreateToolhelp32Snapshot(dwFlags = TH32CS_SNAPALL, th32ProcessID = 0):
3237 _CreateToolhelp32Snapshot = windll.kernel32.CreateToolhelp32Snapshot 3238 _CreateToolhelp32Snapshot.argtypes = [DWORD, DWORD] 3239 _CreateToolhelp32Snapshot.restype = HANDLE 3240 3241 hSnapshot = _CreateToolhelp32Snapshot(dwFlags, th32ProcessID) 3242 if hSnapshot == INVALID_HANDLE_VALUE: 3243 raise ctypes.WinError() 3244 return Handle(hSnapshot)
3245
3246 # BOOL WINAPI Process32First( 3247 # __in HANDLE hSnapshot, 3248 # __inout LPPROCESSENTRY32 lppe 3249 # ); 3250 -def Process32First(hSnapshot):
3251 _Process32First = windll.kernel32.Process32First 3252 _Process32First.argtypes = [HANDLE, LPPROCESSENTRY32] 3253 _Process32First.restype = bool 3254 3255 pe = PROCESSENTRY32() 3256 pe.dwSize = sizeof(PROCESSENTRY32) 3257 success = _Process32First(hSnapshot, ctypes.byref(pe)) 3258 if not success: 3259 if GetLastError() == ERROR_NO_MORE_FILES: 3260 return None 3261 raise ctypes.WinError() 3262 return pe
3263
3264 # BOOL WINAPI Process32Next( 3265 # __in HANDLE hSnapshot, 3266 # __out LPPROCESSENTRY32 lppe 3267 # ); 3268 -def Process32Next(hSnapshot, pe = None):
3269 _Process32Next = windll.kernel32.Process32Next 3270 _Process32Next.argtypes = [HANDLE, LPPROCESSENTRY32] 3271 _Process32Next.restype = bool 3272 3273 if pe is None: 3274 pe = PROCESSENTRY32() 3275 pe.dwSize = sizeof(PROCESSENTRY32) 3276 success = _Process32Next(hSnapshot, ctypes.byref(pe)) 3277 if not success: 3278 if GetLastError() == ERROR_NO_MORE_FILES: 3279 return None 3280 raise ctypes.WinError() 3281 return pe
3282
3283 # BOOL WINAPI Thread32First( 3284 # __in HANDLE hSnapshot, 3285 # __inout LPTHREADENTRY32 lpte 3286 # ); 3287 -def Thread32First(hSnapshot):
3288 _Thread32First = windll.kernel32.Thread32First 3289 _Thread32First.argtypes = [HANDLE, LPTHREADENTRY32] 3290 _Thread32First.restype = bool 3291 3292 te = THREADENTRY32() 3293 te.dwSize = sizeof(THREADENTRY32) 3294 success = _Thread32First(hSnapshot, ctypes.byref(te)) 3295 if not success: 3296 if GetLastError() == ERROR_NO_MORE_FILES: 3297 return None 3298 raise ctypes.WinError() 3299 return te
3300
3301 # BOOL WINAPI Thread32Next( 3302 # __in HANDLE hSnapshot, 3303 # __out LPTHREADENTRY32 lpte 3304 # ); 3305 -def Thread32Next(hSnapshot, te = None):
3306 _Thread32Next = windll.kernel32.Thread32Next 3307 _Thread32Next.argtypes = [HANDLE, LPTHREADENTRY32] 3308 _Thread32Next.restype = bool 3309 3310 if te is None: 3311 te = THREADENTRY32() 3312 te.dwSize = sizeof(THREADENTRY32) 3313 success = _Thread32Next(hSnapshot, ctypes.byref(te)) 3314 if not success: 3315 if GetLastError() == ERROR_NO_MORE_FILES: 3316 return None 3317 raise ctypes.WinError() 3318 return te
3319
3320 # BOOL WINAPI Module32First( 3321 # __in HANDLE hSnapshot, 3322 # __inout LPMODULEENTRY32 lpme 3323 # ); 3324 -def Module32First(hSnapshot):
3325 _Module32First = windll.kernel32.Module32First 3326 _Module32First.argtypes = [HANDLE, LPMODULEENTRY32] 3327 _Module32First.restype = bool 3328 3329 me = MODULEENTRY32() 3330 me.dwSize = sizeof(MODULEENTRY32) 3331 success = _Module32First(hSnapshot, ctypes.byref(me)) 3332 if not success: 3333 if GetLastError() == ERROR_NO_MORE_FILES: 3334 return None 3335 raise ctypes.WinError() 3336 return me
3337
3338 # BOOL WINAPI Module32Next( 3339 # __in HANDLE hSnapshot, 3340 # __out LPMODULEENTRY32 lpme 3341 # ); 3342 -def Module32Next(hSnapshot, me = None):
3343 _Module32Next = windll.kernel32.Module32Next 3344 _Module32Next.argtypes = [HANDLE, LPMODULEENTRY32] 3345 _Module32Next.restype = bool 3346 3347 if me is None: 3348 me = MODULEENTRY32() 3349 me.dwSize = sizeof(MODULEENTRY32) 3350 success = _Module32Next(hSnapshot, ctypes.byref(me)) 3351 if not success: 3352 if GetLastError() == ERROR_NO_MORE_FILES: 3353 return None 3354 raise ctypes.WinError() 3355 return me
3356
3357 # BOOL WINAPI Heap32First( 3358 # __inout LPHEAPENTRY32 lphe, 3359 # __in DWORD th32ProcessID, 3360 # __in ULONG_PTR th32HeapID 3361 # ); 3362 -def Heap32First(th32ProcessID, th32HeapID):
3363 _Heap32First = windll.kernel32.Heap32First 3364 _Heap32First.argtypes = [LPHEAPENTRY32, DWORD, LPVOID] 3365 _Heap32First.restype = bool 3366 3367 he = HEAPENTRY32() 3368 he.dwSize = sizeof(HEAPENTRY32) 3369 success = _Heap32First(ctypes.byref(he), th32ProcessID, th32HeapID) 3370 if not success: 3371 if GetLastError() == ERROR_NO_MORE_FILES: 3372 return None 3373 raise ctypes.WinError() 3374 return he
3375
3376 # BOOL WINAPI Heap32Next( 3377 # __out LPHEAPENTRY32 lphe 3378 # ); 3379 -def Heap32Next(he):
3380 _Heap32Next = windll.kernel32.Heap32Next 3381 _Heap32Next.argtypes = [LPHEAPENTRY32] 3382 _Heap32Next.restype = bool 3383 3384 he.dwSize = sizeof(HEAPENTRY32) 3385 success = _Heap32Next(ctypes.byref(he)) 3386 if not success: 3387 if GetLastError() == ERROR_NO_MORE_FILES: 3388 return None 3389 raise ctypes.WinError() 3390 return he
3391
3392 # BOOL WINAPI Heap32ListFirst( 3393 # __in HANDLE hSnapshot, 3394 # __inout LPHEAPLIST32 lphl 3395 # ); 3396 -def Heap32ListFirst(hSnapshot):
3397 _Heap32ListFirst = windll.kernel32.Heap32ListFirst 3398 _Heap32ListFirst.argtypes = [HANDLE, LPHEAPLIST32] 3399 _Heap32ListFirst.restype = bool 3400 3401 hl = HEAPLIST32() 3402 hl.dwSize = sizeof(HEAPLIST32) 3403 success = _Heap32ListFirst(hSnapshot, ctypes.byref(hl)) 3404 if not success: 3405 if GetLastError() == ERROR_NO_MORE_FILES: 3406 return None 3407 raise ctypes.WinError() 3408 return hl
3409
3410 # BOOL WINAPI Heap32ListNext( 3411 # __in HANDLE hSnapshot, 3412 # __out LPHEAPLIST32 lphl 3413 # ); 3414 -def Heap32ListNext(hSnapshot, hl = None):
3415 _Heap32ListNext = windll.kernel32.Heap32ListNext 3416 _Heap32ListNext.argtypes = [HANDLE, LPHEAPLIST32] 3417 _Heap32ListNext.restype = bool 3418 3419 if hl is None: 3420 hl = HEAPLIST32() 3421 hl.dwSize = sizeof(HEAPLIST32) 3422 success = _Heap32ListNext(hSnapshot, ctypes.byref(hl)) 3423 if not success: 3424 if GetLastError() == ERROR_NO_MORE_FILES: 3425 return None 3426 raise ctypes.WinError() 3427 return hl
3428
3429 # BOOL WINAPI Toolhelp32ReadProcessMemory( 3430 # __in DWORD th32ProcessID, 3431 # __in LPCVOID lpBaseAddress, 3432 # __out LPVOID lpBuffer, 3433 # __in SIZE_T cbRead, 3434 # __out SIZE_T lpNumberOfBytesRead 3435 # ); 3436 -def Toolhelp32ReadProcessMemory(th32ProcessID, lpBaseAddress, cbRead):
3437 _Toolhelp32ReadProcessMemory = windll.kernel32.Toolhelp32ReadProcessMemory 3438 _Toolhelp32ReadProcessMemory.argtypes = [DWORD, LPVOID, LPVOID, SIZE_T, POINTER(SIZE_T)] 3439 _Toolhelp32ReadProcessMemory.restype = bool 3440 3441 lpBuffer = ctypes.create_string_buffer('', cbRead) 3442 lpNumberOfBytesRead = SIZE_T(0) 3443 success = _Toolhelp32ReadProcessMemory(th32ProcessID, lpBaseAddress, lpBuffer, cbRead, ctypes.byref(lpNumberOfBytesRead)) 3444 if not success and GetLastError() != ERROR_PARTIAL_COPY: 3445 raise ctypes.WinError() 3446 return str(lpBuffer.raw)[:lpNumberOfBytesRead.value]
3447
3448 # DWORD WINAPI GetCurrentProcessorNumber(void); 3449 -def GetCurrentProcessorNumber():
3450 _GetCurrentProcessorNumber = windll.kernel32.GetCurrentProcessorNumber 3451 _GetCurrentProcessorNumber.argtypes = [] 3452 _GetCurrentProcessorNumber.restype = DWORD 3453 _GetCurrentProcessorNumber.errcheck = RaiseIfZero 3454 return _GetCurrentProcessorNumber()
3455
3456 # VOID WINAPI FlushProcessWriteBuffers(void); 3457 -def FlushProcessWriteBuffers():
3458 _FlushProcessWriteBuffers = windll.kernel32.FlushProcessWriteBuffers 3459 _FlushProcessWriteBuffers.argtypes = [] 3460 _FlushProcessWriteBuffers.restype = None 3461 _FlushProcessWriteBuffers()
3462
3463 # BOOL WINAPI GetLogicalProcessorInformation( 3464 # __out PSYSTEM_LOGICAL_PROCESSOR_INFORMATION Buffer, 3465 # __inout PDWORD ReturnLength 3466 # ); 3467 3468 # TO DO http://msdn.microsoft.com/en-us/library/ms683194(VS.85).aspx 3469 3470 # BOOL WINAPI GetProcessIoCounters( 3471 # __in HANDLE hProcess, 3472 # __out PIO_COUNTERS lpIoCounters 3473 # ); 3474 3475 # TO DO http://msdn.microsoft.com/en-us/library/ms683218(VS.85).aspx 3476 3477 # DWORD WINAPI GetGuiResources( 3478 # __in HANDLE hProcess, 3479 # __in DWORD uiFlags 3480 # ); 3481 -def GetGuiResources(hProcess, uiFlags = GR_GDIOBJECTS):
3482 _GetGuiResources = windll.kernel32.GetGuiResources 3483 _GetGuiResources.argtypes = [HANDLE, DWORD] 3484 _GetGuiResources.restype = DWORD 3485 3486 dwCount = _GetGuiResources(hProcess, uiFlags) 3487 if dwCount == 0: 3488 errcode = GetLastError() 3489 if errcode != ERROR_SUCCESS: 3490 raise ctypes.WinError(errcode) 3491 return dwCount
3492
3493 # BOOL WINAPI GetProcessHandleCount( 3494 # __in HANDLE hProcess, 3495 # __inout PDWORD pdwHandleCount 3496 # ); 3497 -def GetProcessHandleCount(hProcess):
3498 _GetProcessHandleCount = windll.kernel32.GetProcessHandleCount 3499 _GetProcessHandleCount.argtypes = [HANDLE, PDWORD] 3500 _GetProcessHandleCount.restype = DWORD 3501 _GetProcessHandleCount.errcheck = RaiseIfZero 3502 3503 pdwHandleCount = DWORD(0) 3504 _GetProcessHandleCount(hProcess, ctypes.byref(pdwHandleCount)) 3505 return pdwHandleCount.value
3506
3507 # BOOL WINAPI GetProcessTimes( 3508 # __in HANDLE hProcess, 3509 # __out LPFILETIME lpCreationTime, 3510 # __out LPFILETIME lpExitTime, 3511 # __out LPFILETIME lpKernelTime, 3512 # __out LPFILETIME lpUserTime 3513 # ); 3514 -def GetProcessTimes(hProcess):
3515 _GetProcessTimes = windll.kernel32.GetProcessTimes 3516 _GetProcessTimes.argtypes = [HANDLE, LPFILETIME, LPFILETIME, LPFILETIME] 3517 _GetProcessTimes.restype = bool 3518 _GetProcessTimes.errcheck = RaiseIfZero 3519 3520 CreationTime = FILETIME() 3521 ExitTime = FILETIME() 3522 KernelTime = FILETIME() 3523 UserTime = FILETIME() 3524 3525 _GetProcessTimes(hProcess, ctypes.byref(CreationTime), ctypes.byref(ExitTime), ctypes.byref(KernelTime), ctypes.byref(UserTime)) 3526 3527 ## CreationTime = CreationTime.dwLowDateTime + (CreationTime.dwHighDateTime << 32) 3528 ## ExitTime = ExitTime.dwLowDateTime + (ExitTime.dwHighDateTime << 32) 3529 KernelTime = KernelTime.dwLowDateTime + (KernelTime.dwHighDateTime << 32) 3530 UserTime = UserTime.dwLowDateTime + (UserTime.dwHighDateTime << 32) 3531 3532 CreationTime = FileTimeToSystemTime(CreationTime) 3533 ExitTime = FileTimeToSystemTime(ExitTime) 3534 3535 return (CreationTime, ExitTime, KernelTime, UserTime)
3536
3537 # BOOL WINAPI FileTimeToSystemTime( 3538 # __in const FILETIME *lpFileTime, 3539 # __out LPSYSTEMTIME lpSystemTime 3540 # ); 3541 -def FileTimeToSystemTime(lpFileTime):
3542 _FileTimeToSystemTime = windll.kernel32.FileTimeToSystemTime 3543 _FileTimeToSystemTime.argtypes = [LPFILETIME, LPSYSTEMTIME] 3544 _FileTimeToSystemTime.restype = bool 3545 _FileTimeToSystemTime.errcheck = RaiseIfZero 3546 3547 if isinstance(lpFileTime, FILETIME): 3548 FileTime = lpFileTime 3549 else: 3550 FileTime = FILETIME() 3551 FileTime.dwLowDateTime = lpFileTime & 0xFFFFFFFF 3552 FileTime.dwHighDateTime = lpFileTime >> 32 3553 SystemTime = SYSTEMTIME() 3554 _FileTimeToSystemTime(ctypes.byref(FileTime), ctypes.byref(SystemTime)) 3555 return SystemTime
3556
3557 #------------------------------------------------------------------------------ 3558 # Wow64 3559 3560 # BOOL WINAPI IsWow64Process( 3561 # __in HANDLE hProcess, 3562 # __out PBOOL Wow64Process 3563 # ); 3564 -def IsWow64Process(hProcess):
3565 _IsWow64Process = windll.kernel32.IsWow64Process 3566 _IsWow64Process.argtypes = [HANDLE, PBOOL] 3567 _IsWow64Process.restype = bool 3568 _IsWow64Process.errcheck = RaiseIfZero 3569 3570 Wow64Process = BOOL(FALSE) 3571 _IsWow64Process(hProcess, ctypes.byref(Wow64Process)) 3572 return bool(Wow64Process)
3573 3574 #============================================================================== 3575 # Mark functions that Psyco cannot compile. 3576 # In your programs, don't use psyco.full(). 3577 # Call psyco.bind() on your main function instead. 3578 3579 try: 3580 import psyco 3581 psyco.cannotcompile(WaitForDebugEvent) 3582 psyco.cannotcompile(WaitForSingleObject) 3583 psyco.cannotcompile(WaitForSingleObjectEx) 3584 psyco.cannotcompile(WaitForMultipleObjects) 3585 psyco.cannotcompile(WaitForMultipleObjectsEx) 3586 except ImportError: 3587 pass 3588