1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 """
32 Wrapper for kernel32.dll in ctypes.
33 """
34
35 __revision__ = "$Id: kernel32.py 1299 2013-12-20 09:30:55Z qvasimodo $"
36
37 import warnings
38
39 from defines import *
40
41 import context_i386
42 import context_amd64
43
44
45
46 _all = None
47 _all = set(vars().keys())
48 _all.add('version')
49
50
51 from version import *
57 """
58 Error checking for Win32 API calls with no error-specific return value.
59
60 Regardless of the return value, the function calls GetLastError(). If the
61 code is not C{ERROR_SUCCESS} then a C{WindowsError} exception is raised.
62
63 For this to work, the user MUST call SetLastError(ERROR_SUCCESS) prior to
64 calling the API. Otherwise an exception may be raised even on success,
65 since most API calls don't clear the error status code.
66 """
67 code = GetLastError()
68 if code != ERROR_SUCCESS:
69 raise ctypes.WinError(code)
70 return result
71
72
73
74 ContextArchMask = 0x0FFF0000
75
76 if arch == ARCH_I386:
77 from context_i386 import *
78 elif arch == ARCH_AMD64:
79 if bits == 64:
80 from context_amd64 import *
81 else:
82 from context_i386 import *
83 else:
84 warnings.warn("Unknown or unsupported architecture: %s" % arch)
85
86
87
88 STILL_ACTIVE = 259
89
90 WAIT_TIMEOUT = 0x102
91 WAIT_FAILED = -1
92 WAIT_OBJECT_0 = 0
93
94 EXCEPTION_NONCONTINUABLE = 0x1
95 EXCEPTION_MAXIMUM_PARAMETERS = 15
96 MAXIMUM_WAIT_OBJECTS = 64
97 MAXIMUM_SUSPEND_COUNT = 0x7f
98
99 FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100
100 FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000
101
102 GR_GDIOBJECTS = 0
103 GR_USEROBJECTS = 1
104
105 PROCESS_NAME_NATIVE = 1
106
107 MAXINTATOM = 0xC000
108
109 STD_INPUT_HANDLE = 0xFFFFFFF6
110 STD_OUTPUT_HANDLE = 0xFFFFFFF5
111 STD_ERROR_HANDLE = 0xFFFFFFF4
112
113 ATTACH_PARENT_PROCESS = 0xFFFFFFFF
114
115
116 DONT_RESOLVE_DLL_REFERENCES = 0x00000001
117 LOAD_LIBRARY_AS_DATAFILE = 0x00000002
118 LOAD_WITH_ALTERED_SEARCH_PATH = 0x00000008
119 LOAD_IGNORE_CODE_AUTHZ_LEVEL = 0x00000010
120 LOAD_LIBRARY_AS_IMAGE_RESOURCE = 0x00000020
121 LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE = 0x00000040
122
123
124
125
126
127
128
129
130 CTRL_C_EVENT = 0
131 CTRL_BREAK_EVENT = 1
132 CTRL_CLOSE_EVENT = 2
133 CTRL_LOGOFF_EVENT = 5
134 CTRL_SHUTDOWN_EVENT = 6
135
136
137 HEAP_NO_SERIALIZE = 0x00000001
138 HEAP_GENERATE_EXCEPTIONS = 0x00000004
139 HEAP_ZERO_MEMORY = 0x00000008
140 HEAP_CREATE_ENABLE_EXECUTE = 0x00040000
141
142
143 DELETE = (0x00010000L)
144 READ_CONTROL = (0x00020000L)
145 WRITE_DAC = (0x00040000L)
146 WRITE_OWNER = (0x00080000L)
147 SYNCHRONIZE = (0x00100000L)
148 STANDARD_RIGHTS_REQUIRED = (0x000F0000L)
149 STANDARD_RIGHTS_READ = (READ_CONTROL)
150 STANDARD_RIGHTS_WRITE = (READ_CONTROL)
151 STANDARD_RIGHTS_EXECUTE = (READ_CONTROL)
152 STANDARD_RIGHTS_ALL = (0x001F0000L)
153 SPECIFIC_RIGHTS_ALL = (0x0000FFFFL)
154
155
156 MUTEX_ALL_ACCESS = 0x1F0001
157 MUTEX_MODIFY_STATE = 1
158
159
160 EVENT_ALL_ACCESS = 0x1F0003
161 EVENT_MODIFY_STATE = 2
162
163
164 SEMAPHORE_ALL_ACCESS = 0x1F0003
165 SEMAPHORE_MODIFY_STATE = 2
166
167
168 TIMER_ALL_ACCESS = 0x1F0003
169 TIMER_MODIFY_STATE = 2
170 TIMER_QUERY_STATE = 1
171
172
173 PROCESS_TERMINATE = 0x0001
174 PROCESS_CREATE_THREAD = 0x0002
175 PROCESS_SET_SESSIONID = 0x0004
176 PROCESS_VM_OPERATION = 0x0008
177 PROCESS_VM_READ = 0x0010
178 PROCESS_VM_WRITE = 0x0020
179 PROCESS_DUP_HANDLE = 0x0040
180 PROCESS_CREATE_PROCESS = 0x0080
181 PROCESS_SET_QUOTA = 0x0100
182 PROCESS_SET_INFORMATION = 0x0200
183 PROCESS_QUERY_INFORMATION = 0x0400
184 PROCESS_SUSPEND_RESUME = 0x0800
185 PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
186
187
188 THREAD_TERMINATE = 0x0001
189 THREAD_SUSPEND_RESUME = 0x0002
190 THREAD_ALERT = 0x0004
191 THREAD_GET_CONTEXT = 0x0008
192 THREAD_SET_CONTEXT = 0x0010
193 THREAD_SET_INFORMATION = 0x0020
194 THREAD_QUERY_INFORMATION = 0x0040
195 THREAD_SET_THREAD_TOKEN = 0x0080
196 THREAD_IMPERSONATE = 0x0100
197 THREAD_DIRECT_IMPERSONATION = 0x0200
198 THREAD_SET_LIMITED_INFORMATION = 0x0400
199 THREAD_QUERY_LIMITED_INFORMATION = 0x0800
200
201
202 PROCESS_ALL_ACCESS_NT = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFF)
203 PROCESS_ALL_ACCESS_VISTA = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFFF)
204 THREAD_ALL_ACCESS_NT = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3FF)
205 THREAD_ALL_ACCESS_VISTA = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFFF)
206 if NTDDI_VERSION < NTDDI_VISTA:
207 PROCESS_ALL_ACCESS = PROCESS_ALL_ACCESS_NT
208 THREAD_ALL_ACCESS = THREAD_ALL_ACCESS_NT
209 else:
210 PROCESS_ALL_ACCESS = PROCESS_ALL_ACCESS_VISTA
211 THREAD_ALL_ACCESS = THREAD_ALL_ACCESS_VISTA
212
213
214
215 IDLE_PRIORITY_CLASS = 0x00000040
216 BELOW_NORMAL_PRIORITY_CLASS = 0x00004000
217 NORMAL_PRIORITY_CLASS = 0x00000020
218 ABOVE_NORMAL_PRIORITY_CLASS = 0x00008000
219 HIGH_PRIORITY_CLASS = 0x00000080
220 REALTIME_PRIORITY_CLASS = 0x00000100
221
222 PROCESS_MODE_BACKGROUND_BEGIN = 0x00100000
223 PROCESS_MODE_BACKGROUND_END = 0x00200000
224
225
226
227 DEBUG_PROCESS = 0x00000001
228 DEBUG_ONLY_THIS_PROCESS = 0x00000002
229 CREATE_SUSPENDED = 0x00000004
230 DETACHED_PROCESS = 0x00000008
231 CREATE_NEW_CONSOLE = 0x00000010
232 NORMAL_PRIORITY_CLASS = 0x00000020
233 IDLE_PRIORITY_CLASS = 0x00000040
234 HIGH_PRIORITY_CLASS = 0x00000080
235 REALTIME_PRIORITY_CLASS = 0x00000100
236 CREATE_NEW_PROCESS_GROUP = 0x00000200
237 CREATE_UNICODE_ENVIRONMENT = 0x00000400
238 CREATE_SEPARATE_WOW_VDM = 0x00000800
239 CREATE_SHARED_WOW_VDM = 0x00001000
240 CREATE_FORCEDOS = 0x00002000
241 BELOW_NORMAL_PRIORITY_CLASS = 0x00004000
242 ABOVE_NORMAL_PRIORITY_CLASS = 0x00008000
243 INHERIT_PARENT_AFFINITY = 0x00010000
244 STACK_SIZE_PARAM_IS_A_RESERVATION = 0x00010000
245 INHERIT_CALLER_PRIORITY = 0x00020000
246 CREATE_PROTECTED_PROCESS = 0x00040000
247 EXTENDED_STARTUPINFO_PRESENT = 0x00080000
248 PROCESS_MODE_BACKGROUND_BEGIN = 0x00100000
249 PROCESS_MODE_BACKGROUND_END = 0x00200000
250 CREATE_BREAKAWAY_FROM_JOB = 0x01000000
251 CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000
252 CREATE_DEFAULT_ERROR_MODE = 0x04000000
253 CREATE_NO_WINDOW = 0x08000000
254 PROFILE_USER = 0x10000000
255 PROFILE_KERNEL = 0x20000000
256 PROFILE_SERVER = 0x40000000
257 CREATE_IGNORE_SYSTEM_DEFAULT = 0x80000000
258
259
260
261 THREAD_BASE_PRIORITY_LOWRT = 15
262 THREAD_BASE_PRIORITY_MAX = 2
263 THREAD_BASE_PRIORITY_MIN = (-2)
264 THREAD_BASE_PRIORITY_IDLE = (-15)
265
266 THREAD_PRIORITY_LOWEST = THREAD_BASE_PRIORITY_MIN
267 THREAD_PRIORITY_BELOW_NORMAL = (THREAD_PRIORITY_LOWEST+1)
268 THREAD_PRIORITY_NORMAL = 0
269 THREAD_PRIORITY_HIGHEST = THREAD_BASE_PRIORITY_MAX
270 THREAD_PRIORITY_ABOVE_NORMAL = (THREAD_PRIORITY_HIGHEST-1)
271 THREAD_PRIORITY_ERROR_RETURN = (0xFFFFFFFFL)
272
273 THREAD_PRIORITY_TIME_CRITICAL = THREAD_BASE_PRIORITY_LOWRT
274 THREAD_PRIORITY_IDLE = THREAD_BASE_PRIORITY_IDLE
275
276
277 SECTION_QUERY = 0x0001
278 SECTION_MAP_WRITE = 0x0002
279 SECTION_MAP_READ = 0x0004
280 SECTION_MAP_EXECUTE = 0x0008
281 SECTION_EXTEND_SIZE = 0x0010
282 SECTION_MAP_EXECUTE_EXPLICIT = 0x0020
283
284 SECTION_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED|SECTION_QUERY|\
285 SECTION_MAP_WRITE | \
286 SECTION_MAP_READ | \
287 SECTION_MAP_EXECUTE | \
288 SECTION_EXTEND_SIZE)
289 PAGE_NOACCESS = 0x01
290 PAGE_READONLY = 0x02
291 PAGE_READWRITE = 0x04
292 PAGE_WRITECOPY = 0x08
293 PAGE_EXECUTE = 0x10
294 PAGE_EXECUTE_READ = 0x20
295 PAGE_EXECUTE_READWRITE = 0x40
296 PAGE_EXECUTE_WRITECOPY = 0x80
297 PAGE_GUARD = 0x100
298 PAGE_NOCACHE = 0x200
299 PAGE_WRITECOMBINE = 0x400
300 MEM_COMMIT = 0x1000
301 MEM_RESERVE = 0x2000
302 MEM_DECOMMIT = 0x4000
303 MEM_RELEASE = 0x8000
304 MEM_FREE = 0x10000
305 MEM_PRIVATE = 0x20000
306 MEM_MAPPED = 0x40000
307 MEM_RESET = 0x80000
308 MEM_TOP_DOWN = 0x100000
309 MEM_WRITE_WATCH = 0x200000
310 MEM_PHYSICAL = 0x400000
311 MEM_LARGE_PAGES = 0x20000000
312 MEM_4MB_PAGES = 0x80000000
313 SEC_FILE = 0x800000
314 SEC_IMAGE = 0x1000000
315 SEC_RESERVE = 0x4000000
316 SEC_COMMIT = 0x8000000
317 SEC_NOCACHE = 0x10000000
318 SEC_LARGE_PAGES = 0x80000000
319 MEM_IMAGE = SEC_IMAGE
320 WRITE_WATCH_FLAG_RESET = 0x01
321 FILE_MAP_ALL_ACCESS = 0xF001F
322
323 SECTION_QUERY = 0x0001
324 SECTION_MAP_WRITE = 0x0002
325 SECTION_MAP_READ = 0x0004
326 SECTION_MAP_EXECUTE = 0x0008
327 SECTION_EXTEND_SIZE = 0x0010
328 SECTION_MAP_EXECUTE_EXPLICIT = 0x0020
329
330 SECTION_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED|SECTION_QUERY|\
331 SECTION_MAP_WRITE | \
332 SECTION_MAP_READ | \
333 SECTION_MAP_EXECUTE | \
334 SECTION_EXTEND_SIZE)
335
336 FILE_MAP_COPY = SECTION_QUERY
337 FILE_MAP_WRITE = SECTION_MAP_WRITE
338 FILE_MAP_READ = SECTION_MAP_READ
339 FILE_MAP_ALL_ACCESS = SECTION_ALL_ACCESS
340 FILE_MAP_EXECUTE = SECTION_MAP_EXECUTE_EXPLICIT
341
342 GENERIC_READ = 0x80000000
343 GENERIC_WRITE = 0x40000000
344 GENERIC_EXECUTE = 0x20000000
345 GENERIC_ALL = 0x10000000
346
347 FILE_SHARE_READ = 0x00000001
348 FILE_SHARE_WRITE = 0x00000002
349 FILE_SHARE_DELETE = 0x00000004
350
351 CREATE_NEW = 1
352 CREATE_ALWAYS = 2
353 OPEN_EXISTING = 3
354 OPEN_ALWAYS = 4
355 TRUNCATE_EXISTING = 5
356
357 FILE_ATTRIBUTE_READONLY = 0x00000001
358 FILE_ATTRIBUTE_NORMAL = 0x00000080
359 FILE_ATTRIBUTE_TEMPORARY = 0x00000100
360
361 FILE_FLAG_WRITE_THROUGH = 0x80000000
362 FILE_FLAG_NO_BUFFERING = 0x20000000
363 FILE_FLAG_RANDOM_ACCESS = 0x10000000
364 FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000
365 FILE_FLAG_DELETE_ON_CLOSE = 0x04000000
366 FILE_FLAG_OVERLAPPED = 0x40000000
367
368 FILE_ATTRIBUTE_READONLY = 0x00000001
369 FILE_ATTRIBUTE_HIDDEN = 0x00000002
370 FILE_ATTRIBUTE_SYSTEM = 0x00000004
371 FILE_ATTRIBUTE_DIRECTORY = 0x00000010
372 FILE_ATTRIBUTE_ARCHIVE = 0x00000020
373 FILE_ATTRIBUTE_DEVICE = 0x00000040
374 FILE_ATTRIBUTE_NORMAL = 0x00000080
375 FILE_ATTRIBUTE_TEMPORARY = 0x00000100
376
377
378 EXCEPTION_DEBUG_EVENT = 1
379 CREATE_THREAD_DEBUG_EVENT = 2
380 CREATE_PROCESS_DEBUG_EVENT = 3
381 EXIT_THREAD_DEBUG_EVENT = 4
382 EXIT_PROCESS_DEBUG_EVENT = 5
383 LOAD_DLL_DEBUG_EVENT = 6
384 UNLOAD_DLL_DEBUG_EVENT = 7
385 OUTPUT_DEBUG_STRING_EVENT = 8
386 RIP_EVENT = 9
387
388
389 DBG_EXCEPTION_HANDLED = 0x00010001L
390 DBG_CONTINUE = 0x00010002L
391 DBG_REPLY_LATER = 0x40010001L
392 DBG_UNABLE_TO_PROVIDE_HANDLE = 0x40010002L
393 DBG_TERMINATE_THREAD = 0x40010003L
394 DBG_TERMINATE_PROCESS = 0x40010004L
395 DBG_CONTROL_C = 0x40010005L
396 DBG_PRINTEXCEPTION_C = 0x40010006L
397 DBG_RIPEXCEPTION = 0x40010007L
398 DBG_CONTROL_BREAK = 0x40010008L
399 DBG_COMMAND_EXCEPTION = 0x40010009L
400 DBG_EXCEPTION_NOT_HANDLED = 0x80010001L
401 DBG_NO_STATE_CHANGE = 0xC0010001L
402 DBG_APP_NOT_IDLE = 0xC0010002L
403
404
405 STATUS_WAIT_0 = 0x00000000L
406 STATUS_ABANDONED_WAIT_0 = 0x00000080L
407 STATUS_USER_APC = 0x000000C0L
408 STATUS_TIMEOUT = 0x00000102L
409 STATUS_PENDING = 0x00000103L
410 STATUS_SEGMENT_NOTIFICATION = 0x40000005L
411 STATUS_GUARD_PAGE_VIOLATION = 0x80000001L
412 STATUS_DATATYPE_MISALIGNMENT = 0x80000002L
413 STATUS_BREAKPOINT = 0x80000003L
414 STATUS_SINGLE_STEP = 0x80000004L
415 STATUS_INVALID_INFO_CLASS = 0xC0000003L
416 STATUS_ACCESS_VIOLATION = 0xC0000005L
417 STATUS_IN_PAGE_ERROR = 0xC0000006L
418 STATUS_INVALID_HANDLE = 0xC0000008L
419 STATUS_NO_MEMORY = 0xC0000017L
420 STATUS_ILLEGAL_INSTRUCTION = 0xC000001DL
421 STATUS_NONCONTINUABLE_EXCEPTION = 0xC0000025L
422 STATUS_INVALID_DISPOSITION = 0xC0000026L
423 STATUS_ARRAY_BOUNDS_EXCEEDED = 0xC000008CL
424 STATUS_FLOAT_DENORMAL_OPERAND = 0xC000008DL
425 STATUS_FLOAT_DIVIDE_BY_ZERO = 0xC000008EL
426 STATUS_FLOAT_INEXACT_RESULT = 0xC000008FL
427 STATUS_FLOAT_INVALID_OPERATION = 0xC0000090L
428 STATUS_FLOAT_OVERFLOW = 0xC0000091L
429 STATUS_FLOAT_STACK_CHECK = 0xC0000092L
430 STATUS_FLOAT_UNDERFLOW = 0xC0000093L
431 STATUS_INTEGER_DIVIDE_BY_ZERO = 0xC0000094L
432 STATUS_INTEGER_OVERFLOW = 0xC0000095L
433 STATUS_PRIVILEGED_INSTRUCTION = 0xC0000096L
434 STATUS_STACK_OVERFLOW = 0xC00000FDL
435 STATUS_CONTROL_C_EXIT = 0xC000013AL
436 STATUS_FLOAT_MULTIPLE_FAULTS = 0xC00002B4L
437 STATUS_FLOAT_MULTIPLE_TRAPS = 0xC00002B5L
438 STATUS_REG_NAT_CONSUMPTION = 0xC00002C9L
439 STATUS_SXS_EARLY_DEACTIVATION = 0xC015000FL
440 STATUS_SXS_INVALID_DEACTIVATION = 0xC0150010L
441
442 STATUS_STACK_BUFFER_OVERRUN = 0xC0000409L
443 STATUS_WX86_BREAKPOINT = 0x4000001FL
444 STATUS_HEAP_CORRUPTION = 0xC0000374L
445
446 STATUS_POSSIBLE_DEADLOCK = 0xC0000194L
447
448 STATUS_UNWIND_CONSOLIDATE = 0x80000029L
449
450
451
452 EXCEPTION_ACCESS_VIOLATION = STATUS_ACCESS_VIOLATION
453 EXCEPTION_ARRAY_BOUNDS_EXCEEDED = STATUS_ARRAY_BOUNDS_EXCEEDED
454 EXCEPTION_BREAKPOINT = STATUS_BREAKPOINT
455 EXCEPTION_DATATYPE_MISALIGNMENT = STATUS_DATATYPE_MISALIGNMENT
456 EXCEPTION_FLT_DENORMAL_OPERAND = STATUS_FLOAT_DENORMAL_OPERAND
457 EXCEPTION_FLT_DIVIDE_BY_ZERO = STATUS_FLOAT_DIVIDE_BY_ZERO
458 EXCEPTION_FLT_INEXACT_RESULT = STATUS_FLOAT_INEXACT_RESULT
459 EXCEPTION_FLT_INVALID_OPERATION = STATUS_FLOAT_INVALID_OPERATION
460 EXCEPTION_FLT_OVERFLOW = STATUS_FLOAT_OVERFLOW
461 EXCEPTION_FLT_STACK_CHECK = STATUS_FLOAT_STACK_CHECK
462 EXCEPTION_FLT_UNDERFLOW = STATUS_FLOAT_UNDERFLOW
463 EXCEPTION_ILLEGAL_INSTRUCTION = STATUS_ILLEGAL_INSTRUCTION
464 EXCEPTION_IN_PAGE_ERROR = STATUS_IN_PAGE_ERROR
465 EXCEPTION_INT_DIVIDE_BY_ZERO = STATUS_INTEGER_DIVIDE_BY_ZERO
466 EXCEPTION_INT_OVERFLOW = STATUS_INTEGER_OVERFLOW
467 EXCEPTION_INVALID_DISPOSITION = STATUS_INVALID_DISPOSITION
468 EXCEPTION_NONCONTINUABLE_EXCEPTION = STATUS_NONCONTINUABLE_EXCEPTION
469 EXCEPTION_PRIV_INSTRUCTION = STATUS_PRIVILEGED_INSTRUCTION
470 EXCEPTION_SINGLE_STEP = STATUS_SINGLE_STEP
471 EXCEPTION_STACK_OVERFLOW = STATUS_STACK_OVERFLOW
472
473 EXCEPTION_GUARD_PAGE = STATUS_GUARD_PAGE_VIOLATION
474 EXCEPTION_INVALID_HANDLE = STATUS_INVALID_HANDLE
475 EXCEPTION_POSSIBLE_DEADLOCK = STATUS_POSSIBLE_DEADLOCK
476 EXCEPTION_WX86_BREAKPOINT = STATUS_WX86_BREAKPOINT
477
478 CONTROL_C_EXIT = STATUS_CONTROL_C_EXIT
479
480 DBG_CONTROL_C = 0x40010005L
481 MS_VC_EXCEPTION = 0x406D1388L
482
483
484 ACCESS_VIOLATION_TYPE_READ = EXCEPTION_READ_FAULT
485 ACCESS_VIOLATION_TYPE_WRITE = EXCEPTION_WRITE_FAULT
486 ACCESS_VIOLATION_TYPE_DEP = EXCEPTION_EXECUTE_FAULT
487
488
489 SLE_ERROR = 1
490 SLE_MINORERROR = 2
491 SLE_WARNING = 3
492
493
494 DUPLICATE_CLOSE_SOURCE = 0x00000001
495 DUPLICATE_SAME_ACCESS = 0x00000002
496
497
498 FILE_NAME_NORMALIZED = 0x0
499 FILE_NAME_OPENED = 0x8
500 VOLUME_NAME_DOS = 0x0
501 VOLUME_NAME_GUID = 0x1
502 VOLUME_NAME_NONE = 0x4
503 VOLUME_NAME_NT = 0x2
504
505
506 PRODUCT_BUSINESS = 0x00000006
507 PRODUCT_BUSINESS_N = 0x00000010
508 PRODUCT_CLUSTER_SERVER = 0x00000012
509 PRODUCT_DATACENTER_SERVER = 0x00000008
510 PRODUCT_DATACENTER_SERVER_CORE = 0x0000000C
511 PRODUCT_DATACENTER_SERVER_CORE_V = 0x00000027
512 PRODUCT_DATACENTER_SERVER_V = 0x00000025
513 PRODUCT_ENTERPRISE = 0x00000004
514 PRODUCT_ENTERPRISE_E = 0x00000046
515 PRODUCT_ENTERPRISE_N = 0x0000001B
516 PRODUCT_ENTERPRISE_SERVER = 0x0000000A
517 PRODUCT_ENTERPRISE_SERVER_CORE = 0x0000000E
518 PRODUCT_ENTERPRISE_SERVER_CORE_V = 0x00000029
519 PRODUCT_ENTERPRISE_SERVER_IA64 = 0x0000000F
520 PRODUCT_ENTERPRISE_SERVER_V = 0x00000026
521 PRODUCT_HOME_BASIC = 0x00000002
522 PRODUCT_HOME_BASIC_E = 0x00000043
523 PRODUCT_HOME_BASIC_N = 0x00000005
524 PRODUCT_HOME_PREMIUM = 0x00000003
525 PRODUCT_HOME_PREMIUM_E = 0x00000044
526 PRODUCT_HOME_PREMIUM_N = 0x0000001A
527 PRODUCT_HYPERV = 0x0000002A
528 PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT = 0x0000001E
529 PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING = 0x00000020
530 PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY = 0x0000001F
531 PRODUCT_PROFESSIONAL = 0x00000030
532 PRODUCT_PROFESSIONAL_E = 0x00000045
533 PRODUCT_PROFESSIONAL_N = 0x00000031
534 PRODUCT_SERVER_FOR_SMALLBUSINESS = 0x00000018
535 PRODUCT_SERVER_FOR_SMALLBUSINESS_V = 0x00000023
536 PRODUCT_SERVER_FOUNDATION = 0x00000021
537 PRODUCT_SMALLBUSINESS_SERVER = 0x00000009
538 PRODUCT_STANDARD_SERVER = 0x00000007
539 PRODUCT_STANDARD_SERVER_CORE = 0x0000000D
540 PRODUCT_STANDARD_SERVER_CORE_V = 0x00000028
541 PRODUCT_STANDARD_SERVER_V = 0x00000024
542 PRODUCT_STARTER = 0x0000000B
543 PRODUCT_STARTER_E = 0x00000042
544 PRODUCT_STARTER_N = 0x0000002F
545 PRODUCT_STORAGE_ENTERPRISE_SERVER = 0x00000017
546 PRODUCT_STORAGE_EXPRESS_SERVER = 0x00000014
547 PRODUCT_STORAGE_STANDARD_SERVER = 0x00000015
548 PRODUCT_STORAGE_WORKGROUP_SERVER = 0x00000016
549 PRODUCT_UNDEFINED = 0x00000000
550 PRODUCT_UNLICENSED = 0xABCDABCD
551 PRODUCT_ULTIMATE = 0x00000001
552 PRODUCT_ULTIMATE_E = 0x00000047
553 PRODUCT_ULTIMATE_N = 0x0000001C
554 PRODUCT_WEB_SERVER = 0x00000011
555 PRODUCT_WEB_SERVER_CORE = 0x0000001D
556
557
558 PROCESS_DEP_ENABLE = 1
559 PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION = 2
560
561
562 SEM_FAILCRITICALERRORS = 0x001
563 SEM_NOGPFAULTERRORBOX = 0x002
564 SEM_NOALIGNMENTFAULTEXCEPT = 0x004
565 SEM_NOOPENFILEERRORBOX = 0x800
566
567
568 HANDLE_FLAG_INHERIT = 0x00000001
569 HANDLE_FLAG_PROTECT_FROM_CLOSE = 0x00000002
570
571
572
573 -class Handle (object):
574 """
575 Encapsulates Win32 handles to avoid leaking them.
576
577 @type inherit: bool
578 @ivar inherit: C{True} if the handle is to be inherited by child processes,
579 C{False} otherwise.
580
581 @type protectFromClose: bool
582 @ivar protectFromClose: Set to C{True} to prevent the handle from being
583 closed. Must be set to C{False} before you're done using the handle,
584 or it will be left open until the debugger exits. Use with care!
585
586 @see:
587 L{ProcessHandle}, L{ThreadHandle}, L{FileHandle}, L{SnapshotHandle}
588 """
589
590
591
592
593
594 __bLeakDetection = False
595
596 - def __init__(self, aHandle = None, bOwnership = True):
597 """
598 @type aHandle: int
599 @param aHandle: Win32 handle value.
600
601 @type bOwnership: bool
602 @param bOwnership:
603 C{True} if we own the handle and we need to close it.
604 C{False} if someone else will be calling L{CloseHandle}.
605 """
606 super(Handle, self).__init__()
607 self._value = self._normalize(aHandle)
608 self.bOwnership = bOwnership
609 if Handle.__bLeakDetection:
610 print "INIT HANDLE (%r) %r" % (self.value, self)
611
612 @property
615
617 """
618 Closes the Win32 handle when the Python object is destroyed.
619 """
620 try:
621 if Handle.__bLeakDetection:
622 print "DEL HANDLE %r" % self
623 self.close()
624 except Exception:
625 pass
626
628 """
629 Compatibility with the "C{with}" Python statement.
630 """
631 if Handle.__bLeakDetection:
632 print "ENTER HANDLE %r" % self
633 return self
634
635 - def __exit__(self, type, value, traceback):
636 """
637 Compatibility with the "C{with}" Python statement.
638 """
639 if Handle.__bLeakDetection:
640 print "EXIT HANDLE %r" % self
641 try:
642 self.close()
643 except Exception:
644 pass
645
647 """
648 Duplicates the Win32 handle when copying the Python object.
649
650 @rtype: L{Handle}
651 @return: A new handle to the same Win32 object.
652 """
653 return self.dup()
654
656 """
657 Duplicates the Win32 handle when copying the Python object.
658
659 @rtype: L{Handle}
660 @return: A new handle to the same win32 object.
661 """
662 return self.dup()
663
664 @property
666 """
667 Compatibility with ctypes.
668 Allows passing transparently a Handle object to an API call.
669 """
670 return HANDLE(self.value)
671
672 @staticmethod
674 """
675 Compatibility with ctypes.
676 Allows passing transparently a Handle object to an API call.
677
678 @type value: int
679 @param value: Numeric handle value.
680 """
681 return HANDLE(value)
682
694
696 """
697 Low-level close method.
698 This is a private method, do not call it.
699 """
700 CloseHandle(self.value)
701
703 """
704 @rtype: L{Handle}
705 @return: A new handle to the same Win32 object.
706 """
707 if self.value is None:
708 raise ValueError("Closed handles can't be duplicated!")
709 new_handle = DuplicateHandle(self.value)
710 if Handle.__bLeakDetection:
711 print "DUP HANDLE (%d -> %d) %r %r" % \
712 (self.value, new_handle.value, self, new_handle)
713 return new_handle
714
715 @staticmethod
725
726 - def wait(self, dwMilliseconds = None):
727 """
728 Wait for the Win32 object to be signaled.
729
730 @type dwMilliseconds: int
731 @param dwMilliseconds: (Optional) Timeout value in milliseconds.
732 Use C{INFINITE} or C{None} for no timeout.
733 """
734 if self.value is None:
735 raise ValueError("Handle is already closed!")
736 if dwMilliseconds is None:
737 dwMilliseconds = INFINITE
738 r = WaitForSingleObject(self.value, dwMilliseconds)
739 if r != WAIT_OBJECT_0:
740 raise ctypes.WinError(r)
741
743 return '<%s: %s>' % (self.__class__.__name__, self.value)
744
749
755
756 inherit = property(__get_inherit, __set_inherit)
757
762
768
769 protectFromClose = property(__get_protectFromClose, __set_protectFromClose)
770
772 """
773 Base class for non-kernel handles. Generally this means they are closed
774 by special Win32 API functions instead of CloseHandle() and some standard
775 operations (synchronizing, duplicating, inheritance) are not supported.
776
777 @type _TYPE: C type
778 @cvar _TYPE: C type to translate this handle to.
779 Subclasses should override this.
780 Defaults to L{HANDLE}.
781 """
782
783
784 _TYPE = HANDLE
785
786
788 raise NotImplementedError()
789
790
791 @property
794
795
796 @staticmethod
799
800
801 @property
804
805
806 @property
809
810
812 raise NotImplementedError()
813
814
815 - def wait(self, dwMilliseconds = None):
816 raise NotImplementedError()
817
819 """
820 Win32 process handle.
821
822 @type dwAccess: int
823 @ivar dwAccess: Current access flags to this handle.
824 This is the same value passed to L{OpenProcess}.
825 Can only be C{None} if C{aHandle} is also C{None}.
826 Defaults to L{PROCESS_ALL_ACCESS}.
827
828 @see: L{Handle}
829 """
830
833 """
834 @type aHandle: int
835 @param aHandle: Win32 handle value.
836
837 @type bOwnership: bool
838 @param bOwnership:
839 C{True} if we own the handle and we need to close it.
840 C{False} if someone else will be calling L{CloseHandle}.
841
842 @type dwAccess: int
843 @param dwAccess: Current access flags to this handle.
844 This is the same value passed to L{OpenProcess}.
845 Can only be C{None} if C{aHandle} is also C{None}.
846 Defaults to L{PROCESS_ALL_ACCESS}.
847 """
848 super(ProcessHandle, self).__init__(aHandle, bOwnership)
849 self.dwAccess = dwAccess
850 if aHandle is not None and dwAccess is None:
851 msg = "Missing access flags for process handle: %x" % aHandle
852 raise TypeError(msg)
853
855 """
856 @rtype: int
857 @return: Process global ID.
858 """
859 return GetProcessId(self.value)
860
862 """
863 Win32 thread handle.
864
865 @type dwAccess: int
866 @ivar dwAccess: Current access flags to this handle.
867 This is the same value passed to L{OpenThread}.
868 Can only be C{None} if C{aHandle} is also C{None}.
869 Defaults to L{THREAD_ALL_ACCESS}.
870
871 @see: L{Handle}
872 """
873
876 """
877 @type aHandle: int
878 @param aHandle: Win32 handle value.
879
880 @type bOwnership: bool
881 @param bOwnership:
882 C{True} if we own the handle and we need to close it.
883 C{False} if someone else will be calling L{CloseHandle}.
884
885 @type dwAccess: int
886 @param dwAccess: Current access flags to this handle.
887 This is the same value passed to L{OpenThread}.
888 Can only be C{None} if C{aHandle} is also C{None}.
889 Defaults to L{THREAD_ALL_ACCESS}.
890 """
891 super(ThreadHandle, self).__init__(aHandle, bOwnership)
892 self.dwAccess = dwAccess
893 if aHandle is not None and dwAccess is None:
894 msg = "Missing access flags for thread handle: %x" % aHandle
895 raise TypeError(msg)
896
898 """
899 @rtype: int
900 @return: Thread global ID.
901 """
902 return GetThreadId(self.value)
903
905 """
906 Win32 file handle.
907
908 @see: L{Handle}
909 """
910
912 """
913 @rtype: None or str
914 @return: Name of the open file, or C{None} if unavailable.
915 """
916
917
918
919
920
921
922
923
924
925
926
927
928 dwBufferSize = 0x1004
929 lpFileInformation = ctypes.create_string_buffer(dwBufferSize)
930 try:
931 GetFileInformationByHandleEx(self.value,
932 FILE_INFO_BY_HANDLE_CLASS.FileNameInfo,
933 lpFileInformation, dwBufferSize)
934 except AttributeError:
935 from ntdll import NtQueryInformationFile, \
936 FileNameInformation, \
937 FILE_NAME_INFORMATION
938 NtQueryInformationFile(self.value,
939 FileNameInformation,
940 lpFileInformation,
941 dwBufferSize)
942 FileName = unicode(lpFileInformation.raw[sizeof(DWORD):], 'U16')
943 FileName = ctypes.create_unicode_buffer(FileName).value
944 if not FileName:
945 FileName = None
946 elif FileName[1:2] != ':':
947
948
949 import os
950 FileName = os.environ['SYSTEMROOT'][:2] + FileName
951 return FileName
952
954 """
955 File mapping handle.
956
957 @see: L{Handle}
958 """
959 pass
960
963 """
964 Toolhelp32 snapshot handle.
965
966 @see: L{Handle}
967 """
968 pass
969
982
1164
1166 """
1167 Extended process and thread attribute support.
1168
1169 To be used with L{STARTUPINFOEX}.
1170 Only available for Windows Vista and above.
1171
1172 @type AttributeList: list of tuple( int, ctypes-compatible object )
1173 @ivar AttributeList: List of (Attribute, Value) pairs.
1174
1175 @type AttributeListBuffer: L{LPPROC_THREAD_ATTRIBUTE_LIST}
1176 @ivar AttributeListBuffer: Memory buffer used to store the attribute list.
1177 L{InitializeProcThreadAttributeList},
1178 L{UpdateProcThreadAttribute},
1179 L{DeleteProcThreadAttributeList} and
1180 L{STARTUPINFOEX}.
1181 """
1182
1198
1205
1208
1210 return self.__class__(self.AttributeList)
1211
1212 @property
1214 return ctypes.cast(ctypes.pointer(self.AttributeListBuffer), LPVOID)
1215
1216 @property
1219
1220
1221 @staticmethod
1223 raise NotImplementedError()
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239 -class _OVERLAPPED_STRUCT(Structure):
1240 _fields_ = [
1241 ('Offset', DWORD),
1242 ('OffsetHigh', DWORD),
1243 ]
1250 _fields_ = [
1251 ('Internal', ULONG_PTR),
1252 ('InternalHigh', ULONG_PTR),
1253 ('u', _OVERLAPPED_UNION),
1254 ('hEvent', HANDLE),
1255 ]
1256 LPOVERLAPPED = POINTER(OVERLAPPED)
1266 _fields_ = [
1267 ('nLength', DWORD),
1268 ('lpSecurityDescriptor', LPVOID),
1269 ('bInheritHandle', BOOL),
1270 ]
1271 LPSECURITY_ATTRIBUTES = POINTER(SECURITY_ATTRIBUTES)
1272
1273
1274
1275 PPROC_THREAD_ATTRIBUTE_LIST = LPVOID
1276 LPPROC_THREAD_ATTRIBUTE_LIST = PPROC_THREAD_ATTRIBUTE_LIST
1277
1278 PROC_THREAD_ATTRIBUTE_NUMBER = 0x0000FFFF
1279 PROC_THREAD_ATTRIBUTE_THREAD = 0x00010000
1280 PROC_THREAD_ATTRIBUTE_INPUT = 0x00020000
1281 PROC_THREAD_ATTRIBUTE_ADDITIVE = 0x00040000
1282
1283
1284 ProcThreadAttributeParentProcess = 0
1285 ProcThreadAttributeExtendedFlags = 1
1286 ProcThreadAttributeHandleList = 2
1287 ProcThreadAttributeGroupAffinity = 3
1288 ProcThreadAttributePreferredNode = 4
1289 ProcThreadAttributeIdealProcessor = 5
1290 ProcThreadAttributeUmsThread = 6
1291 ProcThreadAttributeMitigationPolicy = 7
1292 ProcThreadAttributeMax = 8
1293
1294 PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = ProcThreadAttributeParentProcess | PROC_THREAD_ATTRIBUTE_INPUT
1295 PROC_THREAD_ATTRIBUTE_EXTENDED_FLAGS = ProcThreadAttributeExtendedFlags | PROC_THREAD_ATTRIBUTE_INPUT | PROC_THREAD_ATTRIBUTE_ADDITIVE
1296 PROC_THREAD_ATTRIBUTE_HANDLE_LIST = ProcThreadAttributeHandleList | PROC_THREAD_ATTRIBUTE_INPUT
1297 PROC_THREAD_ATTRIBUTE_GROUP_AFFINITY = ProcThreadAttributeGroupAffinity | PROC_THREAD_ATTRIBUTE_THREAD | PROC_THREAD_ATTRIBUTE_INPUT
1298 PROC_THREAD_ATTRIBUTE_PREFERRED_NODE = ProcThreadAttributePreferredNode | PROC_THREAD_ATTRIBUTE_INPUT
1299 PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR = ProcThreadAttributeIdealProcessor | PROC_THREAD_ATTRIBUTE_THREAD | PROC_THREAD_ATTRIBUTE_INPUT
1300 PROC_THREAD_ATTRIBUTE_UMS_THREAD = ProcThreadAttributeUmsThread | PROC_THREAD_ATTRIBUTE_THREAD | PROC_THREAD_ATTRIBUTE_INPUT
1301 PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY = ProcThreadAttributeMitigationPolicy | PROC_THREAD_ATTRIBUTE_INPUT
1302
1303 PROCESS_CREATION_MITIGATION_POLICY_DEP_ENABLE = 0x01
1304 PROCESS_CREATION_MITIGATION_POLICY_DEP_ATL_THUNK_ENABLE = 0x02
1305 PROCESS_CREATION_MITIGATION_POLICY_SEHOP_ENABLE = 0x04
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324 -class VS_FIXEDFILEINFO (Structure):
1325 _fields_ = [
1326 ("dwSignature", DWORD),
1327 ("dwStrucVersion", DWORD),
1328 ("dwFileVersionMS", DWORD),
1329 ("dwFileVersionLS", DWORD),
1330 ("dwProductVersionMS", DWORD),
1331 ("dwProductVersionLS", DWORD),
1332 ("dwFileFlagsMask", DWORD),
1333 ("dwFileFlags", DWORD),
1334 ("dwFileOS", DWORD),
1335 ("dwFileType", DWORD),
1336 ("dwFileSubtype", DWORD),
1337 ("dwFileDateMS", DWORD),
1338 ("dwFileDateLS", DWORD),
1339 ]
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350 -class THREADNAME_INFO(Structure):
1351 _fields_ = [
1352 ("dwType", DWORD),
1353 ("szName", LPVOID),
1354 ("dwThreadID", DWORD),
1355 ("dwFlags", DWORD),
1356 ]
1357
1379
1403
1423 PMEMORY_BASIC_INFORMATION = POINTER(MEMORY_BASIC_INFORMATION)
1424
1425
1426
1427
1428
1429
1430
1431 -class FILETIME(Structure):
1432 _fields_ = [
1433 ('dwLowDateTime', DWORD),
1434 ('dwHighDateTime', DWORD),
1435 ]
1436 LPFILETIME = POINTER(FILETIME)
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448 -class SYSTEMTIME(Structure):
1449 _fields_ = [
1450 ('wYear', WORD),
1451 ('wMonth', WORD),
1452 ('wDayOfWeek', WORD),
1453 ('wDay', WORD),
1454 ('wHour', WORD),
1455 ('wMinute', WORD),
1456 ('wSecond', WORD),
1457 ('wMilliseconds', WORD),
1458 ]
1459 LPSYSTEMTIME = POINTER(SYSTEMTIME)
1486 LPBY_HANDLE_FILE_INFORMATION = POINTER(BY_HANDLE_FILE_INFORMATION)
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504 -class FILE_INFO_BY_HANDLE_CLASS(object):
1519
1547 LPPROCESS_INFORMATION = POINTER(PROCESS_INFORMATION)
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571 -class STARTUPINFO(Structure):
1572 _fields_ = [
1573 ('cb', DWORD),
1574 ('lpReserved', LPSTR),
1575 ('lpDesktop', LPSTR),
1576 ('lpTitle', LPSTR),
1577 ('dwX', DWORD),
1578 ('dwY', DWORD),
1579 ('dwXSize', DWORD),
1580 ('dwYSize', DWORD),
1581 ('dwXCountChars', DWORD),
1582 ('dwYCountChars', DWORD),
1583 ('dwFillAttribute', DWORD),
1584 ('dwFlags', DWORD),
1585 ('wShowWindow', WORD),
1586 ('cbReserved2', WORD),
1587 ('lpReserved2', LPVOID),
1588 ('hStdInput', HANDLE),
1589 ('hStdOutput', HANDLE),
1590 ('hStdError', HANDLE),
1591 ]
1592 LPSTARTUPINFO = POINTER(STARTUPINFO)
1599 _fields_ = [
1600 ('StartupInfo', STARTUPINFO),
1601 ('lpAttributeList', PPROC_THREAD_ATTRIBUTE_LIST),
1602 ]
1603 LPSTARTUPINFOEX = POINTER(STARTUPINFOEX)
1606 _fields_ = [
1607 ('cb', DWORD),
1608 ('lpReserved', LPWSTR),
1609 ('lpDesktop', LPWSTR),
1610 ('lpTitle', LPWSTR),
1611 ('dwX', DWORD),
1612 ('dwY', DWORD),
1613 ('dwXSize', DWORD),
1614 ('dwYSize', DWORD),
1615 ('dwXCountChars', DWORD),
1616 ('dwYCountChars', DWORD),
1617 ('dwFillAttribute', DWORD),
1618 ('dwFlags', DWORD),
1619 ('wShowWindow', WORD),
1620 ('cbReserved2', WORD),
1621 ('lpReserved2', LPVOID),
1622 ('hStdInput', HANDLE),
1623 ('hStdOutput', HANDLE),
1624 ('hStdError', HANDLE),
1625 ]
1626 LPSTARTUPINFOW = POINTER(STARTUPINFOW)
1629 _fields_ = [
1630 ('StartupInfo', STARTUPINFOW),
1631 ('lpAttributeList', PPROC_THREAD_ATTRIBUTE_LIST),
1632 ]
1633 LPSTARTUPINFOEXW = POINTER(STARTUPINFOEXW)
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646 -class JIT_DEBUG_INFO(Structure):
1647 _fields_ = [
1648 ('dwSize', DWORD),
1649 ('dwProcessorArchitecture', DWORD),
1650 ('dwThreadID', DWORD),
1651 ('dwReserved0', DWORD),
1652 ('lpExceptionAddress', ULONG64),
1653 ('lpExceptionRecord', ULONG64),
1654 ('lpContextRecord', ULONG64),
1655 ]
1656 JIT_DEBUG_INFO32 = JIT_DEBUG_INFO
1657 JIT_DEBUG_INFO64 = JIT_DEBUG_INFO
1658
1659 LPJIT_DEBUG_INFO = POINTER(JIT_DEBUG_INFO)
1660 LPJIT_DEBUG_INFO32 = POINTER(JIT_DEBUG_INFO32)
1661 LPJIT_DEBUG_INFO64 = POINTER(JIT_DEBUG_INFO64)
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673 -class EXCEPTION_RECORD32(Structure):
1674 _fields_ = [
1675 ('ExceptionCode', DWORD),
1676 ('ExceptionFlags', DWORD),
1677 ('ExceptionRecord', DWORD),
1678 ('ExceptionAddress', DWORD),
1679 ('NumberParameters', DWORD),
1680 ('ExceptionInformation', DWORD * EXCEPTION_MAXIMUM_PARAMETERS),
1681 ]
1682
1683 PEXCEPTION_RECORD32 = POINTER(EXCEPTION_RECORD32)
1695 _fields_ = [
1696 ('ExceptionCode', DWORD),
1697 ('ExceptionFlags', DWORD),
1698 ('ExceptionRecord', DWORD64),
1699 ('ExceptionAddress', DWORD64),
1700 ('NumberParameters', DWORD),
1701 ('__unusedAlignment', DWORD),
1702 ('ExceptionInformation', DWORD64 * EXCEPTION_MAXIMUM_PARAMETERS),
1703 ]
1704
1705 PEXCEPTION_RECORD64 = POINTER(EXCEPTION_RECORD64)
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715 -class EXCEPTION_RECORD(Structure):
1717 PEXCEPTION_RECORD = POINTER(EXCEPTION_RECORD)
1718 EXCEPTION_RECORD._fields_ = [
1719 ('ExceptionCode', DWORD),
1720 ('ExceptionFlags', DWORD),
1721 ('ExceptionRecord', PEXCEPTION_RECORD),
1722 ('ExceptionAddress', LPVOID),
1723 ('NumberParameters', DWORD),
1724 ('ExceptionInformation', LPVOID * EXCEPTION_MAXIMUM_PARAMETERS),
1725 ]
1736
1743 _fields_ = [
1744 ('hThread', HANDLE),
1745 ('lpThreadLocalBase', LPVOID),
1746 ('lpStartAddress', LPVOID),
1747 ]
1748
1762 _fields_ = [
1763 ('hFile', HANDLE),
1764 ('hProcess', HANDLE),
1765 ('hThread', HANDLE),
1766 ('lpBaseOfImage', LPVOID),
1767 ('dwDebugInfoFileOffset', DWORD),
1768 ('nDebugInfoSize', DWORD),
1769 ('lpThreadLocalBase', LPVOID),
1770 ('lpStartAddress', LPVOID),
1771 ('lpImageName', LPVOID),
1772 ('fUnicode', WORD),
1773 ]
1774
1779 _fields_ = [
1780 ('dwExitCode', DWORD),
1781 ]
1782
1787 _fields_ = [
1788 ('dwExitCode', DWORD),
1789 ]
1790
1800 _fields_ = [
1801 ('hFile', HANDLE),
1802 ('lpBaseOfDll', LPVOID),
1803 ('dwDebugInfoFileOffset', DWORD),
1804 ('nDebugInfoSize', DWORD),
1805 ('lpImageName', LPVOID),
1806 ('fUnicode', WORD),
1807 ]
1808
1813 _fields_ = [
1814 ('lpBaseOfDll', LPVOID),
1815 ]
1816
1823 _fields_ = [
1824 ('lpDebugStringData', LPVOID),
1825 ('fUnicode', WORD),
1826 ('nDebugStringLength', WORD),
1827 ]
1828
1829
1830
1831
1832
1833 -class RIP_INFO(Structure):
1834 _fields_ = [
1835 ('dwError', DWORD),
1836 ('dwType', DWORD),
1837 ]
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855 -class _DEBUG_EVENT_UNION_(Union):
1856 _fields_ = [
1857 ('Exception', EXCEPTION_DEBUG_INFO),
1858 ('CreateThread', CREATE_THREAD_DEBUG_INFO),
1859 ('CreateProcessInfo', CREATE_PROCESS_DEBUG_INFO),
1860 ('ExitThread', EXIT_THREAD_DEBUG_INFO),
1861 ('ExitProcess', EXIT_PROCESS_DEBUG_INFO),
1862 ('LoadDll', LOAD_DLL_DEBUG_INFO),
1863 ('UnloadDll', UNLOAD_DLL_DEBUG_INFO),
1864 ('DebugString', OUTPUT_DEBUG_STRING_INFO),
1865 ('RipInfo', RIP_INFO),
1866 ]
1868 _fields_ = [
1869 ('dwDebugEventCode', DWORD),
1870 ('dwProcessId', DWORD),
1871 ('dwThreadId', DWORD),
1872 ('u', _DEBUG_EVENT_UNION_),
1873 ]
1874 LPDEBUG_EVENT = POINTER(DEBUG_EVENT)
1875
1876
1877
1878 FOREGROUND_MASK = 0x000F
1879 BACKGROUND_MASK = 0x00F0
1880 COMMON_LVB_MASK = 0xFF00
1881
1882 FOREGROUND_BLACK = 0x0000
1883 FOREGROUND_BLUE = 0x0001
1884 FOREGROUND_GREEN = 0x0002
1885 FOREGROUND_CYAN = 0x0003
1886 FOREGROUND_RED = 0x0004
1887 FOREGROUND_MAGENTA = 0x0005
1888 FOREGROUND_YELLOW = 0x0006
1889 FOREGROUND_GREY = 0x0007
1890 FOREGROUND_INTENSITY = 0x0008
1891
1892 BACKGROUND_BLACK = 0x0000
1893 BACKGROUND_BLUE = 0x0010
1894 BACKGROUND_GREEN = 0x0020
1895 BACKGROUND_CYAN = 0x0030
1896 BACKGROUND_RED = 0x0040
1897 BACKGROUND_MAGENTA = 0x0050
1898 BACKGROUND_YELLOW = 0x0060
1899 BACKGROUND_GREY = 0x0070
1900 BACKGROUND_INTENSITY = 0x0080
1901
1902 COMMON_LVB_LEADING_BYTE = 0x0100
1903 COMMON_LVB_TRAILING_BYTE = 0x0200
1904 COMMON_LVB_GRID_HORIZONTAL = 0x0400
1905 COMMON_LVB_GRID_LVERTICAL = 0x0800
1906 COMMON_LVB_GRID_RVERTICAL = 0x1000
1907 COMMON_LVB_REVERSE_VIDEO = 0x4000
1908 COMMON_LVB_UNDERSCORE = 0x8000
1918 _fields_ = [
1919 ('UnicodeChar', WCHAR),
1920 ('AsciiChar', CHAR),
1921 ]
1927 PCHAR_INFO = POINTER(CHAR_INFO)
1928
1929
1930
1931
1932
1933 -class COORD(Structure):
1934 _fields_ = [
1935 ('X', SHORT),
1936 ('Y', SHORT),
1937 ]
1938 PCOORD = POINTER(COORD)
1939
1940
1941
1942
1943
1944
1945
1946 -class SMALL_RECT(Structure):
1947 _fields_ = [
1948 ('Left', SHORT),
1949 ('Top', SHORT),
1950 ('Right', SHORT),
1951 ('Bottom', SHORT),
1952 ]
1953 PSMALL_RECT = POINTER(SMALL_RECT)
1963 _fields_ = [
1964 ('dwSize', COORD),
1965 ('dwCursorPosition', COORD),
1966 ('wAttributes', WORD),
1967 ('srWindow', SMALL_RECT),
1968 ('dwMaximumWindowSize', COORD),
1969 ]
1970 PCONSOLE_SCREEN_BUFFER_INFO = POINTER(CONSOLE_SCREEN_BUFFER_INFO)
1971
1972
1973
1974 TH32CS_SNAPHEAPLIST = 0x00000001
1975 TH32CS_SNAPPROCESS = 0x00000002
1976 TH32CS_SNAPTHREAD = 0x00000004
1977 TH32CS_SNAPMODULE = 0x00000008
1978 TH32CS_INHERIT = 0x80000000
1979 TH32CS_SNAPALL = (TH32CS_SNAPHEAPLIST | TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD | TH32CS_SNAPMODULE)
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990 -class THREADENTRY32(Structure):
1991 _fields_ = [
1992 ('dwSize', DWORD),
1993 ('cntUsage', DWORD),
1994 ('th32ThreadID', DWORD),
1995 ('th32OwnerProcessID', DWORD),
1996 ('tpBasePri', LONG),
1997 ('tpDeltaPri', LONG),
1998 ('dwFlags', DWORD),
1999 ]
2000 LPTHREADENTRY32 = POINTER(THREADENTRY32)
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014 -class PROCESSENTRY32(Structure):
2015 _fields_ = [
2016 ('dwSize', DWORD),
2017 ('cntUsage', DWORD),
2018 ('th32ProcessID', DWORD),
2019 ('th32DefaultHeapID', ULONG_PTR),
2020 ('th32ModuleID', DWORD),
2021 ('cntThreads', DWORD),
2022 ('th32ParentProcessID', DWORD),
2023 ('pcPriClassBase', LONG),
2024 ('dwFlags', DWORD),
2025 ('szExeFile', TCHAR * 260),
2026 ]
2027 LPPROCESSENTRY32 = POINTER(PROCESSENTRY32)
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041 -class MODULEENTRY32(Structure):
2042 _fields_ = [
2043 ("dwSize", DWORD),
2044 ("th32ModuleID", DWORD),
2045 ("th32ProcessID", DWORD),
2046 ("GlblcntUsage", DWORD),
2047 ("ProccntUsage", DWORD),
2048 ("modBaseAddr", LPVOID),
2049 ("modBaseSize", DWORD),
2050 ("hModule", HMODULE),
2051 ("szModule", TCHAR * (MAX_MODULE_NAME32 + 1)),
2052 ("szExePath", TCHAR * MAX_PATH),
2053 ]
2054 LPMODULEENTRY32 = POINTER(MODULEENTRY32)
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068 -class HEAPENTRY32(Structure):
2069 _fields_ = [
2070 ("dwSize", SIZE_T),
2071 ("hHandle", HANDLE),
2072 ("dwAddress", ULONG_PTR),
2073 ("dwBlockSize", SIZE_T),
2074 ("dwFlags", DWORD),
2075 ("dwLockCount", DWORD),
2076 ("dwResvd", DWORD),
2077 ("th32ProcessID", DWORD),
2078 ("th32HeapID", ULONG_PTR),
2079 ]
2080 LPHEAPENTRY32 = POINTER(HEAPENTRY32)
2081
2082
2083
2084
2085
2086
2087
2088
2089 -class HEAPLIST32(Structure):
2090 _fields_ = [
2091 ("dwSize", SIZE_T),
2092 ("th32ProcessID", DWORD),
2093 ("th32HeapID", ULONG_PTR),
2094 ("dwFlags", DWORD),
2095 ]
2096 LPHEAPLIST32 = POINTER(HEAPLIST32)
2102 _GetLastError = windll.kernel32.GetLastError
2103 _GetLastError.argtypes = []
2104 _GetLastError.restype = DWORD
2105 return _GetLastError()
2106
2111 _SetLastError = windll.kernel32.SetLastError
2112 _SetLastError.argtypes = [DWORD]
2113 _SetLastError.restype = None
2114 _SetLastError(dwErrCode)
2115
2118 _GetErrorMode = windll.kernel32.GetErrorMode
2119 _GetErrorMode.argtypes = []
2120 _GetErrorMode.restype = UINT
2121 return _GetErrorMode()
2122
2127 _SetErrorMode = windll.kernel32.SetErrorMode
2128 _SetErrorMode.argtypes = [UINT]
2129 _SetErrorMode.restype = UINT
2130 return _SetErrorMode(dwErrCode)
2131
2134 _GetThreadErrorMode = windll.kernel32.GetThreadErrorMode
2135 _GetThreadErrorMode.argtypes = []
2136 _GetThreadErrorMode.restype = DWORD
2137 return _GetThreadErrorMode()
2138
2144 _SetThreadErrorMode = windll.kernel32.SetThreadErrorMode
2145 _SetThreadErrorMode.argtypes = [DWORD, LPDWORD]
2146 _SetThreadErrorMode.restype = BOOL
2147 _SetThreadErrorMode.errcheck = RaiseIfZero
2148
2149 old = DWORD(0)
2150 _SetThreadErrorMode(dwErrCode, byref(old))
2151 return old.value
2152
2166
2177 _DuplicateHandle = windll.kernel32.DuplicateHandle
2178 _DuplicateHandle.argtypes = [HANDLE, HANDLE, HANDLE, LPHANDLE, DWORD, BOOL, DWORD]
2179 _DuplicateHandle.restype = bool
2180 _DuplicateHandle.errcheck = RaiseIfZero
2181
2182
2183
2184
2185 if hSourceProcessHandle is None:
2186 hSourceProcessHandle = GetCurrentProcess()
2187 if hTargetProcessHandle is None:
2188 hTargetProcessHandle = hSourceProcessHandle
2189 lpTargetHandle = HANDLE(INVALID_HANDLE_VALUE)
2190 _DuplicateHandle(hSourceProcessHandle, hSourceHandle, hTargetProcessHandle, byref(lpTargetHandle), dwDesiredAccess, bool(bInheritHandle), dwOptions)
2191 if isinstance(hSourceHandle, Handle):
2192 HandleClass = hSourceHandle.__class__
2193 else:
2194 HandleClass = Handle
2195 if hasattr(hSourceHandle, 'dwAccess'):
2196 return HandleClass(lpTargetHandle.value, dwAccess = hSourceHandle.dwAccess)
2197 else:
2198 return HandleClass(lpTargetHandle.value)
2199
2204 _LocalFree = windll.kernel32.LocalFree
2205 _LocalFree.argtypes = [HLOCAL]
2206 _LocalFree.restype = HLOCAL
2207
2208 result = _LocalFree(hMem)
2209 if result != NULL:
2210 ctypes.WinError()
2211
2212
2213
2214
2215
2216
2217
2218 -def GetStdHandle(nStdHandle):
2219 _GetStdHandle = windll.kernel32.GetStdHandle
2220 _GetStdHandle.argytpes = [DWORD]
2221 _GetStdHandle.restype = HANDLE
2222 _GetStdHandle.errcheck = RaiseIfZero
2223 return Handle( _GetStdHandle(nStdHandle), bOwnership = False )
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233 -def GetConsoleCP():
2234 _GetConsoleCP = windll.kernel32.GetConsoleCP
2235 _GetConsoleCP.argytpes = []
2236 _GetConsoleCP.restype = UINT
2237 return _GetConsoleCP()
2238
2241 _GetConsoleOutputCP = windll.kernel32.GetConsoleOutputCP
2242 _GetConsoleOutputCP.argytpes = []
2243 _GetConsoleOutputCP.restype = UINT
2244 return _GetConsoleOutputCP()
2245
2250 _SetConsoleCP = windll.kernel32.SetConsoleCP
2251 _SetConsoleCP.argytpes = [UINT]
2252 _SetConsoleCP.restype = bool
2253 _SetConsoleCP.errcheck = RaiseIfZero
2254 _SetConsoleCP(wCodePageID)
2255
2260 _SetConsoleOutputCP = windll.kernel32.SetConsoleOutputCP
2261 _SetConsoleOutputCP.argytpes = [UINT]
2262 _SetConsoleOutputCP.restype = bool
2263 _SetConsoleOutputCP.errcheck = RaiseIfZero
2264 _SetConsoleOutputCP(wCodePageID)
2265
2288
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317 -def SetConsoleWindowInfo(hConsoleOutput, bAbsolute, lpConsoleWindow):
2318 _SetConsoleWindowInfo = windll.kernel32.SetConsoleWindowInfo
2319 _SetConsoleWindowInfo.argytpes = [HANDLE, BOOL, PSMALL_RECT]
2320 _SetConsoleWindowInfo.restype = bool
2321 _SetConsoleWindowInfo.errcheck = RaiseIfZero
2322
2323 if hConsoleOutput is None:
2324 hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE)
2325 if isinstance(lpConsoleWindow, SMALL_RECT):
2326 ConsoleWindow = lpConsoleWindow
2327 else:
2328 ConsoleWindow = SMALL_RECT(*lpConsoleWindow)
2329 _SetConsoleWindowInfo(hConsoleOutput, bAbsolute, byref(ConsoleWindow))
2330
2331
2332
2333
2334
2335 -def SetConsoleTextAttribute(hConsoleOutput = None, wAttributes = 0):
2336 _SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute
2337 _SetConsoleTextAttribute.argytpes = [HANDLE, WORD]
2338 _SetConsoleTextAttribute.restype = bool
2339 _SetConsoleTextAttribute.errcheck = RaiseIfZero
2340
2341 if hConsoleOutput is None:
2342 hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE)
2343 _SetConsoleTextAttribute(hConsoleOutput, wAttributes)
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356 -def AllocConsole():
2362
2372
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420 -def GetDllDirectoryA():
2421 _GetDllDirectoryA = windll.kernel32.GetDllDirectoryA
2422 _GetDllDirectoryA.argytpes = [DWORD, LPSTR]
2423 _GetDllDirectoryA.restype = DWORD
2424
2425 nBufferLength = _GetDllDirectoryA(0, None)
2426 if nBufferLength == 0:
2427 return None
2428 lpBuffer = ctypes.create_string_buffer("", nBufferLength)
2429 _GetDllDirectoryA(nBufferLength, byref(lpBuffer))
2430 return lpBuffer.value
2431
2433 _GetDllDirectoryW = windll.kernel32.GetDllDirectoryW
2434 _GetDllDirectoryW.argytpes = [DWORD, LPWSTR]
2435 _GetDllDirectoryW.restype = DWORD
2436
2437 nBufferLength = _GetDllDirectoryW(0, None)
2438 if nBufferLength == 0:
2439 return None
2440 lpBuffer = ctypes.create_unicode_buffer(u"", nBufferLength)
2441 _GetDllDirectoryW(nBufferLength, byref(lpBuffer))
2442 return lpBuffer.value
2443
2444 GetDllDirectory = GuessStringType(GetDllDirectoryA, GetDllDirectoryW)
2450 _SetDllDirectoryA = windll.kernel32.SetDllDirectoryA
2451 _SetDllDirectoryA.argytpes = [LPSTR]
2452 _SetDllDirectoryA.restype = bool
2453 _SetDllDirectoryA.errcheck = RaiseIfZero
2454 _SetDllDirectoryA(lpPathName)
2455
2457 _SetDllDirectoryW = windll.kernel32.SetDllDirectoryW
2458 _SetDllDirectoryW.argytpes = [LPWSTR]
2459 _SetDllDirectoryW.restype = bool
2460 _SetDllDirectoryW.errcheck = RaiseIfZero
2461 _SetDllDirectoryW(lpPathName)
2462
2463 SetDllDirectory = GuessStringType(SetDllDirectoryA, SetDllDirectoryW)
2476
2485
2486 LoadLibrary = GuessStringType(LoadLibraryA, LoadLibraryW)
2487
2488
2489
2490
2491
2492
2493 -def LoadLibraryExA(pszLibrary, dwFlags = 0):
2501
2510
2511 LoadLibraryEx = GuessStringType(LoadLibraryExA, LoadLibraryExW)
2524
2533
2534 GetModuleHandle = GuessStringType(GetModuleHandleA, GetModuleHandleW)
2541 _GetProcAddress = windll.kernel32.GetProcAddress
2542 _GetProcAddress.argtypes = [HMODULE, LPVOID]
2543 _GetProcAddress.restype = LPVOID
2544
2545 if type(lpProcName) in (type(0), type(0L)):
2546 lpProcName = LPVOID(lpProcName)
2547 if lpProcName.value & (~0xFFFF):
2548 raise ValueError('Ordinal number too large: %d' % lpProcName.value)
2549 elif type(lpProcName) == type(""):
2550 lpProcName = ctypes.c_char_p(lpProcName)
2551 else:
2552 raise TypeError(str(type(lpProcName)))
2553 return _GetProcAddress(hModule, lpProcName)
2554
2555 GetProcAddressW = MakeWideVersion(GetProcAddressA)
2556 GetProcAddress = GuessStringType(GetProcAddressA, GetProcAddressW)
2567
2580
2597
2609
2645
2667
2668 QueryFullProcessImageName = GuessStringType(QueryFullProcessImageNameA, QueryFullProcessImageNameW)
2675 _GetLogicalDriveStringsA = ctypes.windll.kernel32.GetLogicalDriveStringsA
2676 _GetLogicalDriveStringsA.argtypes = [DWORD, LPSTR]
2677 _GetLogicalDriveStringsA.restype = DWORD
2678 _GetLogicalDriveStringsA.errcheck = RaiseIfZero
2679
2680 nBufferLength = (4 * 26) + 1
2681 lpBuffer = ctypes.create_string_buffer('', nBufferLength)
2682 _GetLogicalDriveStringsA(nBufferLength, lpBuffer)
2683 drive_strings = list()
2684 string_p = addressof(lpBuffer)
2685 sizeof_char = sizeof(ctypes.c_char)
2686 while True:
2687 string_v = ctypes.string_at(string_p)
2688 if string_v == '':
2689 break
2690 drive_strings.append(string_v)
2691 string_p += len(string_v) + sizeof_char
2692 return drive_strings
2693
2695 _GetLogicalDriveStringsW = ctypes.windll.kernel32.GetLogicalDriveStringsW
2696 _GetLogicalDriveStringsW.argtypes = [DWORD, LPWSTR]
2697 _GetLogicalDriveStringsW.restype = DWORD
2698 _GetLogicalDriveStringsW.errcheck = RaiseIfZero
2699
2700 nBufferLength = (4 * 26) + 1
2701 lpBuffer = ctypes.create_unicode_buffer(u'', nBufferLength)
2702 _GetLogicalDriveStringsW(nBufferLength, lpBuffer)
2703 drive_strings = list()
2704 string_p = addressof(lpBuffer)
2705 sizeof_wchar = sizeof(ctypes.c_wchar)
2706 while True:
2707 string_v = ctypes.wstring_at(string_p)
2708 if string_v == u'':
2709 break
2710 drive_strings.append(string_v)
2711 string_p += (len(string_v) * sizeof_wchar) + sizeof_wchar
2712 return drive_strings
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762 GetLogicalDriveStrings = GuessStringType(GetLogicalDriveStringsA, GetLogicalDriveStringsW)
2770 _QueryDosDeviceA = windll.kernel32.QueryDosDeviceA
2771 _QueryDosDeviceA.argtypes = [LPSTR, LPSTR, DWORD]
2772 _QueryDosDeviceA.restype = DWORD
2773 _QueryDosDeviceA.errcheck = RaiseIfZero
2774
2775 if not lpDeviceName:
2776 lpDeviceName = None
2777 ucchMax = 0x1000
2778 lpTargetPath = ctypes.create_string_buffer('', ucchMax)
2779 _QueryDosDeviceA(lpDeviceName, lpTargetPath, ucchMax)
2780 return lpTargetPath.value
2781
2783 _QueryDosDeviceW = windll.kernel32.QueryDosDeviceW
2784 _QueryDosDeviceW.argtypes = [LPWSTR, LPWSTR, DWORD]
2785 _QueryDosDeviceW.restype = DWORD
2786 _QueryDosDeviceW.errcheck = RaiseIfZero
2787
2788 if not lpDeviceName:
2789 lpDeviceName = None
2790 ucchMax = 0x1000
2791 lpTargetPath = ctypes.create_unicode_buffer(u'', ucchMax)
2792 _QueryDosDeviceW(lpDeviceName, lpTargetPath, ucchMax)
2793 return lpTargetPath.value
2794
2795 QueryDosDevice = GuessStringType(QueryDosDeviceA, QueryDosDeviceW)
2805 _MapViewOfFile = windll.kernel32.MapViewOfFile
2806 _MapViewOfFile.argtypes = [HANDLE, DWORD, DWORD, DWORD, SIZE_T]
2807 _MapViewOfFile.restype = LPVOID
2808 lpBaseAddress = _MapViewOfFile(hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh, dwFileOffsetLow, dwNumberOfBytesToMap)
2809 if lpBaseAddress == NULL:
2810 raise ctypes.WinError()
2811 return lpBaseAddress
2812
2817 _UnmapViewOfFile = windll.kernel32.UnmapViewOfFile
2818 _UnmapViewOfFile.argtypes = [LPVOID]
2819 _UnmapViewOfFile.restype = bool
2820 _UnmapViewOfFile.errcheck = RaiseIfZero
2821 _UnmapViewOfFile(lpBaseAddress)
2822
2823
2824
2825
2826
2827
2828 -def OpenFileMappingA(dwDesiredAccess, bInheritHandle, lpName):
2835
2843
2844 OpenFileMapping = GuessStringType(OpenFileMappingA, OpenFileMappingW)
2855 _CreateFileMappingA = windll.kernel32.CreateFileMappingA
2856 _CreateFileMappingA.argtypes = [HANDLE, LPVOID, DWORD, DWORD, DWORD, LPSTR]
2857 _CreateFileMappingA.restype = HANDLE
2858 _CreateFileMappingA.errcheck = RaiseIfZero
2859
2860 if lpAttributes:
2861 lpAttributes = ctypes.pointer(lpAttributes)
2862 if not lpName:
2863 lpName = None
2864 hFileMappingObject = _CreateFileMappingA(hFile, lpAttributes, flProtect, dwMaximumSizeHigh, dwMaximumSizeLow, lpName)
2865 return FileMappingHandle(hFileMappingObject)
2866
2868 _CreateFileMappingW = windll.kernel32.CreateFileMappingW
2869 _CreateFileMappingW.argtypes = [HANDLE, LPVOID, DWORD, DWORD, DWORD, LPWSTR]
2870 _CreateFileMappingW.restype = HANDLE
2871 _CreateFileMappingW.errcheck = RaiseIfZero
2872
2873 if lpAttributes:
2874 lpAttributes = ctypes.pointer(lpAttributes)
2875 if not lpName:
2876 lpName = None
2877 hFileMappingObject = _CreateFileMappingW(hFile, lpAttributes, flProtect, dwMaximumSizeHigh, dwMaximumSizeLow, lpName)
2878 return FileMappingHandle(hFileMappingObject)
2879
2880 CreateFileMapping = GuessStringType(CreateFileMappingA, CreateFileMappingW)
2892 _CreateFileA = windll.kernel32.CreateFileA
2893 _CreateFileA.argtypes = [LPSTR, DWORD, DWORD, LPVOID, DWORD, DWORD, HANDLE]
2894 _CreateFileA.restype = HANDLE
2895
2896 if not lpFileName:
2897 lpFileName = None
2898 if lpSecurityAttributes:
2899 lpSecurityAttributes = ctypes.pointer(lpSecurityAttributes)
2900 hFile = _CreateFileA(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile)
2901 if hFile == INVALID_HANDLE_VALUE:
2902 raise ctypes.WinError()
2903 return FileHandle(hFile)
2904
2906 _CreateFileW = windll.kernel32.CreateFileW
2907 _CreateFileW.argtypes = [LPWSTR, DWORD, DWORD, LPVOID, DWORD, DWORD, HANDLE]
2908 _CreateFileW.restype = HANDLE
2909
2910 if not lpFileName:
2911 lpFileName = None
2912 if lpSecurityAttributes:
2913 lpSecurityAttributes = ctypes.pointer(lpSecurityAttributes)
2914 hFile = _CreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile)
2915 if hFile == INVALID_HANDLE_VALUE:
2916 raise ctypes.WinError()
2917 return FileHandle(hFile)
2918
2919 CreateFile = GuessStringType(CreateFileA, CreateFileW)
2930
2931
2932
2933
2934
2935 -def FlushViewOfFile(lpBaseAddress, dwNumberOfBytesToFlush = 0):
2936 _FlushViewOfFile = windll.kernel32.FlushViewOfFile
2937 _FlushViewOfFile.argtypes = [LPVOID, SIZE_T]
2938 _FlushViewOfFile.restype = bool
2939 _FlushViewOfFile.errcheck = RaiseIfZero
2940 _FlushViewOfFile(lpBaseAddress, dwNumberOfBytesToFlush)
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950 -def SearchPathA(lpPath, lpFileName, lpExtension):
2951 _SearchPathA = windll.kernel32.SearchPathA
2952 _SearchPathA.argtypes = [LPSTR, LPSTR, LPSTR, DWORD, LPSTR, POINTER(LPSTR)]
2953 _SearchPathA.restype = DWORD
2954 _SearchPathA.errcheck = RaiseIfZero
2955
2956 if not lpPath:
2957 lpPath = None
2958 if not lpExtension:
2959 lpExtension = None
2960 nBufferLength = _SearchPathA(lpPath, lpFileName, lpExtension, 0, None, None)
2961 lpBuffer = ctypes.create_string_buffer('', nBufferLength + 1)
2962 lpFilePart = LPSTR()
2963 _SearchPathA(lpPath, lpFileName, lpExtension, nBufferLength, lpBuffer, byref(lpFilePart))
2964 lpFilePart = lpFilePart.value
2965 lpBuffer = lpBuffer.value
2966 if lpBuffer == '':
2967 if GetLastError() == ERROR_SUCCESS:
2968 raise ctypes.WinError(ERROR_FILE_NOT_FOUND)
2969 raise ctypes.WinError()
2970 return (lpBuffer, lpFilePart)
2971
2973 _SearchPathW = windll.kernel32.SearchPathW
2974 _SearchPathW.argtypes = [LPWSTR, LPWSTR, LPWSTR, DWORD, LPWSTR, POINTER(LPWSTR)]
2975 _SearchPathW.restype = DWORD
2976 _SearchPathW.errcheck = RaiseIfZero
2977
2978 if not lpPath:
2979 lpPath = None
2980 if not lpExtension:
2981 lpExtension = None
2982 nBufferLength = _SearchPathW(lpPath, lpFileName, lpExtension, 0, None, None)
2983 lpBuffer = ctypes.create_unicode_buffer(u'', nBufferLength + 1)
2984 lpFilePart = LPWSTR()
2985 _SearchPathW(lpPath, lpFileName, lpExtension, nBufferLength, lpBuffer, byref(lpFilePart))
2986 lpFilePart = lpFilePart.value
2987 lpBuffer = lpBuffer.value
2988 if lpBuffer == u'':
2989 if GetLastError() == ERROR_SUCCESS:
2990 raise ctypes.WinError(ERROR_FILE_NOT_FOUND)
2991 raise ctypes.WinError()
2992 return (lpBuffer, lpFilePart)
2993
2994 SearchPath = GuessStringType(SearchPathA, SearchPathW)
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016 -def DeviceIoControl(hDevice, dwIoControlCode, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, lpOverlapped):
3017 _DeviceIoControl = windll.kernel32.DeviceIoControl
3018 _DeviceIoControl.argtypes = [HANDLE, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPOVERLAPPED]
3019 _DeviceIoControl.restype = bool
3020 _DeviceIoControl.errcheck = RaiseIfZero
3021
3022 if not lpInBuffer:
3023 lpInBuffer = None
3024 if not lpOutBuffer:
3025 lpOutBuffer = None
3026 if lpOverlapped:
3027 lpOverlapped = ctypes.pointer(lpOverlapped)
3028 lpBytesReturned = DWORD(0)
3029 _DeviceIoControl(hDevice, dwIoControlCode, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, byref(lpBytesReturned), lpOverlapped)
3030 return lpBytesReturned.value
3031
3045
3061
3069 _GetFinalPathNameByHandleA = windll.kernel32.GetFinalPathNameByHandleA
3070 _GetFinalPathNameByHandleA.argtypes = [HANDLE, LPSTR, DWORD, DWORD]
3071 _GetFinalPathNameByHandleA.restype = DWORD
3072
3073 cchFilePath = _GetFinalPathNameByHandleA(hFile, None, 0, dwFlags)
3074 if cchFilePath == 0:
3075 raise ctypes.WinError()
3076 lpszFilePath = ctypes.create_string_buffer('', cchFilePath + 1)
3077 nCopied = _GetFinalPathNameByHandleA(hFile, lpszFilePath, cchFilePath, dwFlags)
3078 if nCopied <= 0 or nCopied > cchFilePath:
3079 raise ctypes.WinError()
3080 return lpszFilePath.value
3081
3083 _GetFinalPathNameByHandleW = windll.kernel32.GetFinalPathNameByHandleW
3084 _GetFinalPathNameByHandleW.argtypes = [HANDLE, LPWSTR, DWORD, DWORD]
3085 _GetFinalPathNameByHandleW.restype = DWORD
3086
3087 cchFilePath = _GetFinalPathNameByHandleW(hFile, None, 0, dwFlags)
3088 if cchFilePath == 0:
3089 raise ctypes.WinError()
3090 lpszFilePath = ctypes.create_unicode_buffer(u'', cchFilePath + 1)
3091 nCopied = _GetFinalPathNameByHandleW(hFile, lpszFilePath, cchFilePath, dwFlags)
3092 if nCopied <= 0 or nCopied > cchFilePath:
3093 raise ctypes.WinError()
3094 return lpszFilePath.value
3095
3096 GetFinalPathNameByHandle = GuessStringType(GetFinalPathNameByHandleA, GetFinalPathNameByHandleW)
3105 _GetFullPathNameA = windll.kernel32.GetFullPathNameA
3106 _GetFullPathNameA.argtypes = [LPSTR, DWORD, LPSTR, POINTER(LPSTR)]
3107 _GetFullPathNameA.restype = DWORD
3108
3109 nBufferLength = _GetFullPathNameA(lpFileName, 0, None, None)
3110 if nBufferLength <= 0:
3111 raise ctypes.WinError()
3112 lpBuffer = ctypes.create_string_buffer('', nBufferLength + 1)
3113 lpFilePart = LPSTR()
3114 nCopied = _GetFullPathNameA(lpFileName, nBufferLength, lpBuffer, byref(lpFilePart))
3115 if nCopied > nBufferLength or nCopied == 0:
3116 raise ctypes.WinError()
3117 return lpBuffer.value, lpFilePart.value
3118
3120 _GetFullPathNameW = windll.kernel32.GetFullPathNameW
3121 _GetFullPathNameW.argtypes = [LPWSTR, DWORD, LPWSTR, POINTER(LPWSTR)]
3122 _GetFullPathNameW.restype = DWORD
3123
3124 nBufferLength = _GetFullPathNameW(lpFileName, 0, None, None)
3125 if nBufferLength <= 0:
3126 raise ctypes.WinError()
3127 lpBuffer = ctypes.create_unicode_buffer(u'', nBufferLength + 1)
3128 lpFilePart = LPWSTR()
3129 nCopied = _GetFullPathNameW(lpFileName, nBufferLength, lpBuffer, byref(lpFilePart))
3130 if nCopied > nBufferLength or nCopied == 0:
3131 raise ctypes.WinError()
3132 return lpBuffer.value, lpFilePart.value
3133
3134 GetFullPathName = GuessStringType(GetFullPathNameA, GetFullPathNameW)
3141 _GetTempPathA = windll.kernel32.GetTempPathA
3142 _GetTempPathA.argtypes = [DWORD, LPSTR]
3143 _GetTempPathA.restype = DWORD
3144
3145 nBufferLength = _GetTempPathA(0, None)
3146 if nBufferLength <= 0:
3147 raise ctypes.WinError()
3148 lpBuffer = ctypes.create_string_buffer('', nBufferLength)
3149 nCopied = _GetTempPathA(nBufferLength, lpBuffer)
3150 if nCopied > nBufferLength or nCopied == 0:
3151 raise ctypes.WinError()
3152 return lpBuffer.value
3153
3155 _GetTempPathW = windll.kernel32.GetTempPathW
3156 _GetTempPathW.argtypes = [DWORD, LPWSTR]
3157 _GetTempPathW.restype = DWORD
3158
3159 nBufferLength = _GetTempPathW(0, None)
3160 if nBufferLength <= 0:
3161 raise ctypes.WinError()
3162 lpBuffer = ctypes.create_unicode_buffer(u'', nBufferLength)
3163 nCopied = _GetTempPathW(nBufferLength, lpBuffer)
3164 if nCopied > nBufferLength or nCopied == 0:
3165 raise ctypes.WinError()
3166 return lpBuffer.value
3167
3168 GetTempPath = GuessStringType(GetTempPathA, GetTempPathW)
3169
3170
3171
3172
3173
3174
3175
3176 -def GetTempFileNameA(lpPathName = None, lpPrefixString = "TMP", uUnique = 0):
3177 _GetTempFileNameA = windll.kernel32.GetTempFileNameA
3178 _GetTempFileNameA.argtypes = [LPSTR, LPSTR, UINT, LPSTR]
3179 _GetTempFileNameA.restype = UINT
3180
3181 if lpPathName is None:
3182 lpPathName = GetTempPathA()
3183 lpTempFileName = ctypes.create_string_buffer('', MAX_PATH)
3184 uUnique = _GetTempFileNameA(lpPathName, lpPrefixString, uUnique, lpTempFileName)
3185 if uUnique == 0:
3186 raise ctypes.WinError()
3187 return lpTempFileName.value, uUnique
3188
3190 _GetTempFileNameW = windll.kernel32.GetTempFileNameW
3191 _GetTempFileNameW.argtypes = [LPWSTR, LPWSTR, UINT, LPWSTR]
3192 _GetTempFileNameW.restype = UINT
3193
3194 if lpPathName is None:
3195 lpPathName = GetTempPathW()
3196 lpTempFileName = ctypes.create_unicode_buffer(u'', MAX_PATH)
3197 uUnique = _GetTempFileNameW(lpPathName, lpPrefixString, uUnique, lpTempFileName)
3198 if uUnique == 0:
3199 raise ctypes.WinError()
3200 return lpTempFileName.value, uUnique
3201
3202 GetTempFileName = GuessStringType(GetTempFileNameA, GetTempFileNameW)
3209 _GetCurrentDirectoryA = windll.kernel32.GetCurrentDirectoryA
3210 _GetCurrentDirectoryA.argtypes = [DWORD, LPSTR]
3211 _GetCurrentDirectoryA.restype = DWORD
3212
3213 nBufferLength = _GetCurrentDirectoryA(0, None)
3214 if nBufferLength <= 0:
3215 raise ctypes.WinError()
3216 lpBuffer = ctypes.create_string_buffer('', nBufferLength)
3217 nCopied = _GetCurrentDirectoryA(nBufferLength, lpBuffer)
3218 if nCopied > nBufferLength or nCopied == 0:
3219 raise ctypes.WinError()
3220 return lpBuffer.value
3221
3223 _GetCurrentDirectoryW = windll.kernel32.GetCurrentDirectoryW
3224 _GetCurrentDirectoryW.argtypes = [DWORD, LPWSTR]
3225 _GetCurrentDirectoryW.restype = DWORD
3226
3227 nBufferLength = _GetCurrentDirectoryW(0, None)
3228 if nBufferLength <= 0:
3229 raise ctypes.WinError()
3230 lpBuffer = ctypes.create_unicode_buffer(u'', nBufferLength)
3231 nCopied = _GetCurrentDirectoryW(nBufferLength, lpBuffer)
3232 if nCopied > nBufferLength or nCopied == 0:
3233 raise ctypes.WinError()
3234 return lpBuffer.value
3235
3236 GetCurrentDirectory = GuessStringType(GetCurrentDirectoryA, GetCurrentDirectoryW)
3237
3238
3239
3240
3241
3242
3243
3244 PHANDLER_ROUTINE = ctypes.WINFUNCTYPE(BOOL, DWORD)
3256
3265 _GenerateConsoleCtrlEvent = windll.kernel32.GenerateConsoleCtrlEvent
3266 _GenerateConsoleCtrlEvent.argtypes = [DWORD, DWORD]
3267 _GenerateConsoleCtrlEvent.restype = bool
3268 _GenerateConsoleCtrlEvent.errcheck = RaiseIfZero
3269 _GenerateConsoleCtrlEvent(dwCtrlEvent, dwProcessGroupId)
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288 -def WaitForSingleObject(hHandle, dwMilliseconds = INFINITE):
3307
3332
3361
3391
3392
3393
3394
3395
3396
3397 -def CreateMutexA(lpMutexAttributes = None, bInitialOwner = True, lpName = None):
3398 _CreateMutexA = windll.kernel32.CreateMutexA
3399 _CreateMutexA.argtypes = [LPVOID, BOOL, LPSTR]
3400 _CreateMutexA.restype = HANDLE
3401 _CreateMutexA.errcheck = RaiseIfZero
3402 return Handle( _CreateMutexA(lpMutexAttributes, bInitialOwner, lpName) )
3403
3404 -def CreateMutexW(lpMutexAttributes = None, bInitialOwner = True, lpName = None):
3405 _CreateMutexW = windll.kernel32.CreateMutexW
3406 _CreateMutexW.argtypes = [LPVOID, BOOL, LPWSTR]
3407 _CreateMutexW.restype = HANDLE
3408 _CreateMutexW.errcheck = RaiseIfZero
3409 return Handle( _CreateMutexW(lpMutexAttributes, bInitialOwner, lpName) )
3410
3411 CreateMutex = GuessStringType(CreateMutexA, CreateMutexW)
3419 _OpenMutexA = windll.kernel32.OpenMutexA
3420 _OpenMutexA.argtypes = [DWORD, BOOL, LPSTR]
3421 _OpenMutexA.restype = HANDLE
3422 _OpenMutexA.errcheck = RaiseIfZero
3423 return Handle( _OpenMutexA(lpMutexAttributes, bInitialOwner, lpName) )
3424
3426 _OpenMutexW = windll.kernel32.OpenMutexW
3427 _OpenMutexW.argtypes = [DWORD, BOOL, LPWSTR]
3428 _OpenMutexW.restype = HANDLE
3429 _OpenMutexW.errcheck = RaiseIfZero
3430 return Handle( _OpenMutexW(lpMutexAttributes, bInitialOwner, lpName) )
3431
3432 OpenMutex = GuessStringType(OpenMutexA, OpenMutexW)
3433
3434
3435
3436
3437
3438
3439
3440 -def CreateEventA(lpMutexAttributes = None, bManualReset = False, bInitialState = False, lpName = None):
3441 _CreateEventA = windll.kernel32.CreateEventA
3442 _CreateEventA.argtypes = [LPVOID, BOOL, BOOL, LPSTR]
3443 _CreateEventA.restype = HANDLE
3444 _CreateEventA.errcheck = RaiseIfZero
3445 return Handle( _CreateEventA(lpMutexAttributes, bManualReset, bInitialState, lpName) )
3446
3447 -def CreateEventW(lpMutexAttributes = None, bManualReset = False, bInitialState = False, lpName = None):
3448 _CreateEventW = windll.kernel32.CreateEventW
3449 _CreateEventW.argtypes = [LPVOID, BOOL, BOOL, LPWSTR]
3450 _CreateEventW.restype = HANDLE
3451 _CreateEventW.errcheck = RaiseIfZero
3452 return Handle( _CreateEventW(lpMutexAttributes, bManualReset, bInitialState, lpName) )
3453
3454 CreateEvent = GuessStringType(CreateEventA, CreateEventW)
3467
3474
3475 OpenEvent = GuessStringType(OpenEventA, OpenEventW)
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497 -def ReleaseMutex(hMutex):
3498 _ReleaseMutex = windll.kernel32.ReleaseMutex
3499 _ReleaseMutex.argtypes = [HANDLE]
3500 _ReleaseMutex.restype = bool
3501 _ReleaseMutex.errcheck = RaiseIfZero
3502 _ReleaseMutex(hMutex)
3503
3513
3523
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549 -def WaitForDebugEvent(dwMilliseconds = INFINITE):
3574
3586
3599
3609
3619
3625 _CheckRemoteDebuggerPresent = windll.kernel32.CheckRemoteDebuggerPresent
3626 _CheckRemoteDebuggerPresent.argtypes = [HANDLE, PBOOL]
3627 _CheckRemoteDebuggerPresent.restype = bool
3628 _CheckRemoteDebuggerPresent.errcheck = RaiseIfZero
3629
3630 pbDebuggerPresent = BOOL(0)
3631 _CheckRemoteDebuggerPresent(hProcess, byref(pbDebuggerPresent))
3632 return bool(pbDebuggerPresent.value)
3633
3638 _DebugSetProcessKillOnExit = windll.kernel32.DebugSetProcessKillOnExit
3639 _DebugSetProcessKillOnExit.argtypes = [BOOL]
3640 _DebugSetProcessKillOnExit.restype = bool
3641 _DebugSetProcessKillOnExit.errcheck = RaiseIfZero
3642 _DebugSetProcessKillOnExit(bool(KillOnExit))
3643
3653
3658 _OutputDebugStringA = windll.kernel32.OutputDebugStringA
3659 _OutputDebugStringA.argtypes = [LPSTR]
3660 _OutputDebugStringA.restype = None
3661 _OutputDebugStringA(lpOutputString)
3662
3664 _OutputDebugStringW = windll.kernel32.OutputDebugStringW
3665 _OutputDebugStringW.argtypes = [LPWSTR]
3666 _OutputDebugStringW.restype = None
3667 _OutputDebugStringW(lpOutputString)
3668
3669 OutputDebugString = GuessStringType(OutputDebugStringA, OutputDebugStringW)
3670
3671
3672
3673
3674
3675
3676
3677
3678 -def ReadProcessMemory(hProcess, lpBaseAddress, nSize):
3679 _ReadProcessMemory = windll.kernel32.ReadProcessMemory
3680 _ReadProcessMemory.argtypes = [HANDLE, LPVOID, LPVOID, SIZE_T, POINTER(SIZE_T)]
3681 _ReadProcessMemory.restype = bool
3682
3683 lpBuffer = ctypes.create_string_buffer('', nSize)
3684 lpNumberOfBytesRead = SIZE_T(0)
3685 success = _ReadProcessMemory(hProcess, lpBaseAddress, lpBuffer, nSize, byref(lpNumberOfBytesRead))
3686 if not success and GetLastError() != ERROR_PARTIAL_COPY:
3687 raise ctypes.WinError()
3688 return str(lpBuffer.raw)[:lpNumberOfBytesRead.value]
3689
3690
3691
3692
3693
3694
3695
3696
3697 -def WriteProcessMemory(hProcess, lpBaseAddress, lpBuffer):
3698 _WriteProcessMemory = windll.kernel32.WriteProcessMemory
3699 _WriteProcessMemory.argtypes = [HANDLE, LPVOID, LPVOID, SIZE_T, POINTER(SIZE_T)]
3700 _WriteProcessMemory.restype = bool
3701
3702 nSize = len(lpBuffer)
3703 lpBuffer = ctypes.create_string_buffer(lpBuffer)
3704 lpNumberOfBytesWritten = SIZE_T(0)
3705 success = _WriteProcessMemory(hProcess, lpBaseAddress, lpBuffer, nSize, byref(lpNumberOfBytesWritten))
3706 if not success and GetLastError() != ERROR_PARTIAL_COPY:
3707 raise ctypes.WinError()
3708 return lpNumberOfBytesWritten.value
3709
3718 _VirtualAllocEx = windll.kernel32.VirtualAllocEx
3719 _VirtualAllocEx.argtypes = [HANDLE, LPVOID, SIZE_T, DWORD, DWORD]
3720 _VirtualAllocEx.restype = LPVOID
3721
3722 lpAddress = _VirtualAllocEx(hProcess, lpAddress, dwSize, flAllocationType, flProtect)
3723 if lpAddress == NULL:
3724 raise ctypes.WinError()
3725 return lpAddress
3726
3727
3728
3729
3730
3731
3732
3733 -def VirtualQueryEx(hProcess, lpAddress):
3744
3753 _VirtualProtectEx = windll.kernel32.VirtualProtectEx
3754 _VirtualProtectEx.argtypes = [HANDLE, LPVOID, SIZE_T, DWORD, PDWORD]
3755 _VirtualProtectEx.restype = bool
3756 _VirtualProtectEx.errcheck = RaiseIfZero
3757
3758 flOldProtect = DWORD(0)
3759 _VirtualProtectEx(hProcess, lpAddress, dwSize, flNewProtect, byref(flOldProtect))
3760 return flOldProtect.value
3761
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784 -def CreateRemoteThread(hProcess, lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags):
3785 _CreateRemoteThread = windll.kernel32.CreateRemoteThread
3786 _CreateRemoteThread.argtypes = [HANDLE, LPSECURITY_ATTRIBUTES, SIZE_T, LPVOID, LPVOID, DWORD, LPDWORD]
3787 _CreateRemoteThread.restype = HANDLE
3788
3789 if not lpThreadAttributes:
3790 lpThreadAttributes = None
3791 else:
3792 lpThreadAttributes = byref(lpThreadAttributes)
3793 dwThreadId = DWORD(0)
3794 hThread = _CreateRemoteThread(hProcess, lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, byref(dwThreadId))
3795 if not hThread:
3796 raise ctypes.WinError()
3797 return ThreadHandle(hThread), dwThreadId.value
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814 -def CreateProcessA(lpApplicationName, lpCommandLine=None, lpProcessAttributes=None, lpThreadAttributes=None, bInheritHandles=False, dwCreationFlags=0, lpEnvironment=None, lpCurrentDirectory=None, lpStartupInfo=None):
3815 _CreateProcessA = windll.kernel32.CreateProcessA
3816 _CreateProcessA.argtypes = [LPSTR, LPSTR, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPSTR, LPVOID, LPPROCESS_INFORMATION]
3817 _CreateProcessA.restype = bool
3818 _CreateProcessA.errcheck = RaiseIfZero
3819
3820 if not lpApplicationName:
3821 lpApplicationName = None
3822 if not lpCommandLine:
3823 lpCommandLine = None
3824 else:
3825 lpCommandLine = ctypes.create_string_buffer(lpCommandLine, max(MAX_PATH, len(lpCommandLine)))
3826 if not lpEnvironment:
3827 lpEnvironment = None
3828 else:
3829 lpEnvironment = ctypes.create_string_buffer(lpEnvironment)
3830 if not lpCurrentDirectory:
3831 lpCurrentDirectory = None
3832 if not lpProcessAttributes:
3833 lpProcessAttributes = None
3834 else:
3835 lpProcessAttributes = byref(lpProcessAttributes)
3836 if not lpThreadAttributes:
3837 lpThreadAttributes = None
3838 else:
3839 lpThreadAttributes = byref(lpThreadAttributes)
3840 if not lpStartupInfo:
3841 lpStartupInfo = STARTUPINFO()
3842 lpStartupInfo.cb = sizeof(STARTUPINFO)
3843 lpStartupInfo.lpReserved = 0
3844 lpStartupInfo.lpDesktop = 0
3845 lpStartupInfo.lpTitle = 0
3846 lpStartupInfo.dwFlags = 0
3847 lpStartupInfo.cbReserved2 = 0
3848 lpStartupInfo.lpReserved2 = 0
3849 lpProcessInformation = PROCESS_INFORMATION()
3850 lpProcessInformation.hProcess = INVALID_HANDLE_VALUE
3851 lpProcessInformation.hThread = INVALID_HANDLE_VALUE
3852 lpProcessInformation.dwProcessId = 0
3853 lpProcessInformation.dwThreadId = 0
3854 _CreateProcessA(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bool(bInheritHandles), dwCreationFlags, lpEnvironment, lpCurrentDirectory, byref(lpStartupInfo), byref(lpProcessInformation))
3855 return ProcessInformation(lpProcessInformation)
3856
3857 -def CreateProcessW(lpApplicationName, lpCommandLine=None, lpProcessAttributes=None, lpThreadAttributes=None, bInheritHandles=False, dwCreationFlags=0, lpEnvironment=None, lpCurrentDirectory=None, lpStartupInfo=None):
3858 _CreateProcessW = windll.kernel32.CreateProcessW
3859 _CreateProcessW.argtypes = [LPWSTR, LPWSTR, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPWSTR, LPVOID, LPPROCESS_INFORMATION]
3860 _CreateProcessW.restype = bool
3861 _CreateProcessW.errcheck = RaiseIfZero
3862
3863 if not lpApplicationName:
3864 lpApplicationName = None
3865 if not lpCommandLine:
3866 lpCommandLine = None
3867 else:
3868 lpCommandLine = ctypes.create_unicode_buffer(lpCommandLine, max(MAX_PATH, len(lpCommandLine)))
3869 if not lpEnvironment:
3870 lpEnvironment = None
3871 else:
3872 lpEnvironment = ctypes.create_unicode_buffer(lpEnvironment)
3873 if not lpCurrentDirectory:
3874 lpCurrentDirectory = None
3875 if not lpProcessAttributes:
3876 lpProcessAttributes = None
3877 else:
3878 lpProcessAttributes = byref(lpProcessAttributes)
3879 if not lpThreadAttributes:
3880 lpThreadAttributes = None
3881 else:
3882 lpThreadAttributes = byref(lpThreadAttributes)
3883 if not lpStartupInfo:
3884 lpStartupInfo = STARTUPINFO()
3885 lpStartupInfo.cb = sizeof(STARTUPINFO)
3886 lpStartupInfo.lpReserved = 0
3887 lpStartupInfo.lpDesktop = 0
3888 lpStartupInfo.lpTitle = 0
3889 lpStartupInfo.dwFlags = 0
3890 lpStartupInfo.cbReserved2 = 0
3891 lpStartupInfo.lpReserved2 = 0
3892 lpProcessInformation = PROCESS_INFORMATION()
3893 lpProcessInformation.hProcess = INVALID_HANDLE_VALUE
3894 lpProcessInformation.hThread = INVALID_HANDLE_VALUE
3895 lpProcessInformation.dwProcessId = 0
3896 lpProcessInformation.dwThreadId = 0
3897 _CreateProcessW(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bool(bInheritHandles), dwCreationFlags, lpEnvironment, lpCurrentDirectory, byref(lpStartupInfo), byref(lpProcessInformation))
3898 return ProcessInformation(lpProcessInformation)
3899
3900 CreateProcess = GuessStringType(CreateProcessA, CreateProcessW)
3909 _InitializeProcThreadAttributeList = windll.kernel32.InitializeProcThreadAttributeList
3910 _InitializeProcThreadAttributeList.argtypes = [LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T]
3911 _InitializeProcThreadAttributeList.restype = bool
3912
3913 Size = SIZE_T(0)
3914 _InitializeProcThreadAttributeList(None, dwAttributeCount, 0, byref(Size))
3915 RaiseIfZero(Size.value)
3916 AttributeList = (BYTE * Size.value)()
3917 success = _InitializeProcThreadAttributeList(byref(AttributeList), dwAttributeCount, 0, byref(Size))
3918 RaiseIfZero(success)
3919 return AttributeList
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930 -def UpdateProcThreadAttribute(lpAttributeList, Attribute, Value, cbSize = None):
3931 _UpdateProcThreadAttribute = windll.kernel32.UpdateProcThreadAttribute
3932 _UpdateProcThreadAttribute.argtypes = [LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T]
3933 _UpdateProcThreadAttribute.restype = bool
3934 _UpdateProcThreadAttribute.errcheck = RaiseIfZero
3935
3936 if cbSize is None:
3937 cbSize = sizeof(Value)
3938 _UpdateProcThreadAttribute(byref(lpAttributeList), 0, Attribute, byref(Value), cbSize, None, None)
3939
3947
3948
3949
3950
3951
3952
3953 -def OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId):
3962
3963
3964
3965
3966
3967
3968 -def OpenThread(dwDesiredAccess, bInheritHandle, dwThreadId):
3977
3982 _SuspendThread = windll.kernel32.SuspendThread
3983 _SuspendThread.argtypes = [HANDLE]
3984 _SuspendThread.restype = DWORD
3985
3986 previousCount = _SuspendThread(hThread)
3987 if previousCount == DWORD(-1).value:
3988 raise ctypes.WinError()
3989 return previousCount
3990
3995 _ResumeThread = windll.kernel32.ResumeThread
3996 _ResumeThread.argtypes = [HANDLE]
3997 _ResumeThread.restype = DWORD
3998
3999 previousCount = _ResumeThread(hThread)
4000 if previousCount == DWORD(-1).value:
4001 raise ctypes.WinError()
4002 return previousCount
4003
4014
4025
4028 _GetCurrentProcessId = windll.kernel32.GetCurrentProcessId
4029 _GetCurrentProcessId.argtypes = []
4030 _GetCurrentProcessId.restype = DWORD
4031 return _GetCurrentProcessId()
4032
4035 _GetCurrentThreadId = windll.kernel32.GetCurrentThreadId
4036 _GetCurrentThreadId.argtypes = []
4037 _GetCurrentThreadId.restype = DWORD
4038 return _GetCurrentThreadId()
4039
4049
4062
4075
4081 _GetExitCodeProcess = windll.kernel32.GetExitCodeProcess
4082 _GetExitCodeProcess.argtypes = [HANDLE]
4083 _GetExitCodeProcess.restype = bool
4084 _GetExitCodeProcess.errcheck = RaiseIfZero
4085
4086 lpExitCode = DWORD(0)
4087 _GetExitCodeProcess(hProcess, byref(lpExitCode))
4088 return lpExitCode.value
4089
4095 _GetExitCodeThread = windll.kernel32.GetExitCodeThread
4096 _GetExitCodeThread.argtypes = [HANDLE]
4097 _GetExitCodeThread.restype = bool
4098 _GetExitCodeThread.errcheck = RaiseIfZero
4099
4100 lpExitCode = DWORD(0)
4101 _GetExitCodeThread(hThread, byref(lpExitCode))
4102 return lpExitCode.value
4103
4108 _GetProcessVersion = windll.kernel32.GetProcessVersion
4109 _GetProcessVersion.argtypes = [DWORD]
4110 _GetProcessVersion.restype = DWORD
4111
4112 retval = _GetProcessVersion(ProcessId)
4113 if retval == 0:
4114 raise ctypes.WinError()
4115 return retval
4116
4121 _GetPriorityClass = windll.kernel32.GetPriorityClass
4122 _GetPriorityClass.argtypes = [HANDLE]
4123 _GetPriorityClass.restype = DWORD
4124
4125 retval = _GetPriorityClass(hProcess)
4126 if retval == 0:
4127 raise ctypes.WinError()
4128 return retval
4129
4140
4146 _GetProcessPriorityBoost = windll.kernel32.GetProcessPriorityBoost
4147 _GetProcessPriorityBoost.argtypes = [HANDLE, PBOOL]
4148 _GetProcessPriorityBoost.restype = bool
4149 _GetProcessPriorityBoost.errcheck = RaiseIfZero
4150
4151 pDisablePriorityBoost = BOOL(False)
4152 _GetProcessPriorityBoost(hProcess, byref(pDisablePriorityBoost))
4153 return bool(pDisablePriorityBoost.value)
4154
4160 _SetProcessPriorityBoost = windll.kernel32.SetProcessPriorityBoost
4161 _SetProcessPriorityBoost.argtypes = [HANDLE, BOOL]
4162 _SetProcessPriorityBoost.restype = bool
4163 _SetProcessPriorityBoost.errcheck = RaiseIfZero
4164 _SetProcessPriorityBoost(hProcess, bool(DisablePriorityBoost))
4165
4172 _GetProcessAffinityMask = windll.kernel32.GetProcessAffinityMask
4173 _GetProcessAffinityMask.argtypes = [HANDLE, PDWORD_PTR, PDWORD_PTR]
4174 _GetProcessAffinityMask.restype = bool
4175 _GetProcessAffinityMask.errcheck = RaiseIfZero
4176
4177 lpProcessAffinityMask = DWORD_PTR(0)
4178 lpSystemAffinityMask = DWORD_PTR(0)
4179 _GetProcessAffinityMask(hProcess, byref(lpProcessAffinityMask), byref(lpSystemAffinityMask))
4180 return lpProcessAffinityMask.value, lpSystemAffinityMask.value
4181
4187 _SetProcessAffinityMask = windll.kernel32.SetProcessAffinityMask
4188 _SetProcessAffinityMask.argtypes = [HANDLE, DWORD_PTR]
4189 _SetProcessAffinityMask.restype = bool
4190 _SetProcessAffinityMask.errcheck = RaiseIfZero
4191 _SetProcessAffinityMask(hProcess, dwProcessAffinityMask)
4192
4209
4227
4246
4264
4265
4266
4267
4268
4269 -def Thread32Next(hSnapshot, te = None):
4283
4301
4302
4303
4304
4305
4306 -def Module32Next(hSnapshot, me = None):
4320
4321
4322
4323
4324
4325
4326 -def Heap32First(th32ProcessID, th32HeapID):
4339
4355
4373
4392
4411
4423 _GetProcessDEPPolicy = windll.kernel32.GetProcessDEPPolicy
4424 _GetProcessDEPPolicy.argtypes = [HANDLE, LPDWORD, PBOOL]
4425 _GetProcessDEPPolicy.restype = bool
4426 _GetProcessDEPPolicy.errcheck = RaiseIfZero
4427
4428 lpFlags = DWORD(0)
4429 lpPermanent = BOOL(0)
4430 _GetProcessDEPPolicy(hProcess, byref(lpFlags), byref(lpPermanent))
4431 return (lpFlags.value, lpPermanent.value)
4432
4435 _GetCurrentProcessorNumber = windll.kernel32.GetCurrentProcessorNumber
4436 _GetCurrentProcessorNumber.argtypes = []
4437 _GetCurrentProcessorNumber.restype = DWORD
4438 _GetCurrentProcessorNumber.errcheck = RaiseIfZero
4439 return _GetCurrentProcessorNumber()
4440
4443 _FlushProcessWriteBuffers = windll.kernel32.FlushProcessWriteBuffers
4444 _FlushProcessWriteBuffers.argtypes = []
4445 _FlushProcessWriteBuffers.restype = None
4446 _FlushProcessWriteBuffers()
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466 -def GetGuiResources(hProcess, uiFlags = GR_GDIOBJECTS):
4467 _GetGuiResources = windll.kernel32.GetGuiResources
4468 _GetGuiResources.argtypes = [HANDLE, DWORD]
4469 _GetGuiResources.restype = DWORD
4470
4471 dwCount = _GetGuiResources(hProcess, uiFlags)
4472 if dwCount == 0:
4473 errcode = GetLastError()
4474 if errcode != ERROR_SUCCESS:
4475 raise ctypes.WinError(errcode)
4476 return dwCount
4477
4483 _GetProcessHandleCount = windll.kernel32.GetProcessHandleCount
4484 _GetProcessHandleCount.argtypes = [HANDLE, PDWORD]
4485 _GetProcessHandleCount.restype = DWORD
4486 _GetProcessHandleCount.errcheck = RaiseIfZero
4487
4488 pdwHandleCount = DWORD(0)
4489 _GetProcessHandleCount(hProcess, byref(pdwHandleCount))
4490 return pdwHandleCount.value
4491
4500 _GetProcessTimes = windll.kernel32.GetProcessTimes
4501 _GetProcessTimes.argtypes = [HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME]
4502 _GetProcessTimes.restype = bool
4503 _GetProcessTimes.errcheck = RaiseIfZero
4504
4505 if hProcess is None:
4506 hProcess = GetCurrentProcess()
4507
4508 CreationTime = FILETIME()
4509 ExitTime = FILETIME()
4510 KernelTime = FILETIME()
4511 UserTime = FILETIME()
4512
4513 _GetProcessTimes(hProcess, byref(CreationTime), byref(ExitTime), byref(KernelTime), byref(UserTime))
4514
4515 return (CreationTime, ExitTime, KernelTime, UserTime)
4516
4536
4548
4556 _GlobalAddAtomA = windll.kernel32.GlobalAddAtomA
4557 _GlobalAddAtomA.argtypes = [LPSTR]
4558 _GlobalAddAtomA.restype = ATOM
4559 _GlobalAddAtomA.errcheck = RaiseIfZero
4560 return _GlobalAddAtomA(lpString)
4561
4563 _GlobalAddAtomW = windll.kernel32.GlobalAddAtomW
4564 _GlobalAddAtomW.argtypes = [LPWSTR]
4565 _GlobalAddAtomW.restype = ATOM
4566 _GlobalAddAtomW.errcheck = RaiseIfZero
4567 return _GlobalAddAtomW(lpString)
4568
4569 GlobalAddAtom = GuessStringType(GlobalAddAtomA, GlobalAddAtomW)
4575 _GlobalFindAtomA = windll.kernel32.GlobalFindAtomA
4576 _GlobalFindAtomA.argtypes = [LPSTR]
4577 _GlobalFindAtomA.restype = ATOM
4578 _GlobalFindAtomA.errcheck = RaiseIfZero
4579 return _GlobalFindAtomA(lpString)
4580
4582 _GlobalFindAtomW = windll.kernel32.GlobalFindAtomW
4583 _GlobalFindAtomW.argtypes = [LPWSTR]
4584 _GlobalFindAtomW.restype = ATOM
4585 _GlobalFindAtomW.errcheck = RaiseIfZero
4586 return _GlobalFindAtomW(lpString)
4587
4588 GlobalFindAtom = GuessStringType(GlobalFindAtomA, GlobalFindAtomW)
4596 _GlobalGetAtomNameA = windll.kernel32.GlobalGetAtomNameA
4597 _GlobalGetAtomNameA.argtypes = [ATOM, LPSTR, ctypes.c_int]
4598 _GlobalGetAtomNameA.restype = UINT
4599 _GlobalGetAtomNameA.errcheck = RaiseIfZero
4600
4601 nSize = 64
4602 while 1:
4603 lpBuffer = ctypes.create_string_buffer("", nSize)
4604 nCopied = _GlobalGetAtomNameA(nAtom, lpBuffer, nSize)
4605 if nCopied < nSize - 1:
4606 break
4607 nSize = nSize + 64
4608 return lpBuffer.value
4609
4611 _GlobalGetAtomNameW = windll.kernel32.GlobalGetAtomNameW
4612 _GlobalGetAtomNameW.argtypes = [ATOM, LPWSTR, ctypes.c_int]
4613 _GlobalGetAtomNameW.restype = UINT
4614 _GlobalGetAtomNameW.errcheck = RaiseIfZero
4615
4616 nSize = 64
4617 while 1:
4618 lpBuffer = ctypes.create_unicode_buffer(u"", nSize)
4619 nCopied = _GlobalGetAtomNameW(nAtom, lpBuffer, nSize)
4620 if nCopied < nSize - 1:
4621 break
4622 nSize = nSize + 64
4623 return lpBuffer.value
4624
4625 GlobalGetAtomName = GuessStringType(GlobalGetAtomNameA, GlobalGetAtomNameW)
4639
4647 _Wow64SuspendThread = windll.kernel32.Wow64SuspendThread
4648 _Wow64SuspendThread.argtypes = [HANDLE]
4649 _Wow64SuspendThread.restype = DWORD
4650
4651 previousCount = _Wow64SuspendThread(hThread)
4652 if previousCount == DWORD(-1).value:
4653 raise ctypes.WinError()
4654 return previousCount
4655
4660 """
4661 This function may not work reliably when there are nested calls. Therefore,
4662 this function has been replaced by the L{Wow64DisableWow64FsRedirection}
4663 and L{Wow64RevertWow64FsRedirection} functions.
4664
4665 @see: U{http://msdn.microsoft.com/en-us/library/windows/desktop/aa365744(v=vs.85).aspx}
4666 """
4667 _Wow64EnableWow64FsRedirection = windll.kernel32.Wow64EnableWow64FsRedirection
4668 _Wow64EnableWow64FsRedirection.argtypes = [BOOLEAN]
4669 _Wow64EnableWow64FsRedirection.restype = BOOLEAN
4670 _Wow64EnableWow64FsRedirection.errcheck = RaiseIfZero
4671
4676 _Wow64DisableWow64FsRedirection = windll.kernel32.Wow64DisableWow64FsRedirection
4677 _Wow64DisableWow64FsRedirection.argtypes = [PPVOID]
4678 _Wow64DisableWow64FsRedirection.restype = BOOL
4679 _Wow64DisableWow64FsRedirection.errcheck = RaiseIfZero
4680
4681 OldValue = PVOID(None)
4682 _Wow64DisableWow64FsRedirection(byref(OldValue))
4683 return OldValue
4684
4689 _Wow64RevertWow64FsRedirection = windll.kernel32.Wow64RevertWow64FsRedirection
4690 _Wow64RevertWow64FsRedirection.argtypes = [PVOID]
4691 _Wow64RevertWow64FsRedirection.restype = BOOL
4692 _Wow64RevertWow64FsRedirection.errcheck = RaiseIfZero
4693 _Wow64RevertWow64FsRedirection(OldValue)
4694
4695
4696
4697 _all = set(vars().keys()).difference(_all)
4698 __all__ = [_x for _x in _all if not _x.startswith('_')]
4699 __all__.sort()
4700
4701
4702
4703
4704
4705
4706
4707 try:
4708 import psyco
4709 psyco.cannotcompile(WaitForDebugEvent)
4710 psyco.cannotcompile(WaitForSingleObject)
4711 psyco.cannotcompile(WaitForSingleObjectEx)
4712 psyco.cannotcompile(WaitForMultipleObjects)
4713 psyco.cannotcompile(WaitForMultipleObjectsEx)
4714 except ImportError:
4715 pass
4716
4717