-
Notifications
You must be signed in to change notification settings - Fork 52
/
windows_api.py
1492 lines (1150 loc) · 43.4 KB
/
windows_api.py
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Armon Dadgar
#
# Creates python interface for windows api calls that are required
#
# According to MSDN most of these calls are Windows 2K Pro and up
# Trying to replace the win32* stuff using ctypes
# Ctypes enable us to call the Windows API which written in C
import ctypes
# Needed so that we can sleep
import time
# Used for OS detection
import os
# Used for processing command output (netstat, etc)
import textops
import portable_popen
# Main Libraries
# kerneldll links to the library that has Windows Kernel Calls
kerneldll = ctypes.windll.kernel32
# memdll links to the library that has Windows Process/Thread Calls
memdll = ctypes.windll.psapi
# Types
DWORD = ctypes.c_ulong # Map Microsoft DWORD type to C long
WORD = ctypes.c_ushort # Map microsoft WORD type to C ushort
HANDLE = ctypes.c_ulong # Map Microsoft HANDLE type to C long
LONG = ctypes.c_long # Map Microsoft LONG type to C long
SIZE_T = ctypes.c_ulong # Map Microsoft SIZE_T type to C long
ULONG_PTR = ctypes.c_ulong # Map Microsoft ULONG_PTR to C long
LPTSTR = ctypes.c_char_p # Map Microsoft LPTSTR to a pointer to a string
LPCSTR = ctypes.c_char_p # Map Microsoft LPCTSTR to a pointer to a string
ULARGE_INTEGER = ctypes.c_ulonglong # Map Microsoft ULARGE_INTEGER to 64 bit int
LARGE_INTEGER = ctypes.c_longlong # Map Microsoft ULARGE_INTEGER to 64 bit int
DWORDLONG = ctypes.c_ulonglong # Map Microsoft DWORDLONG to 64 bit int
# General Constants
ULONG_MAX = 4294967295 # Maximum value for an unsigned long, 2^32 -1
# Microsoft Constants
TH32CS_SNAPTHREAD = ctypes.c_ulong(0x00000004) # Create a snapshot of all threads
TH32CS_SNAPPROCESS = ctypes.c_ulong(0x00000002) # Create a snapshot of a process
TH32CS_SNAPHEAPLIST = ctypes.c_ulong(0x00000001) # Create a snapshot of a processes heap
INVALID_HANDLE_VALUE = -1
THREAD_QUERY_INFORMATION = 0x0040
THREAD_SET_INFORMATION = 0x0020
THREAD_SUSPEND_RESUME = 0x0002
THREAD_HANDLE_RIGHTS = THREAD_SET_INFORMATION | THREAD_SUSPEND_RESUME | THREAD_QUERY_INFORMATION
PROCESS_TERMINATE = 0x0001
PROCESS_QUERY_INFORMATION = 0x0400
SYNCHRONIZE = 0x00100000L
PROCESS_SET_INFORMATION = 0x0200
PROCESS_SET_QUERY_AND_TERMINATE = PROCESS_SET_INFORMATION | PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION | SYNCHRONIZE
ERROR_ALREADY_EXISTS = 183
WAIT_FAILED = 0xFFFFFFFF
WAIT_OBJECT_0 = 0x00000000L
WAIT_ABANDONED = 0x00000080L
CE_FULL_PERMISSIONS = ctypes.c_ulong(0xFFFFFFFF)
NORMAL_PRIORITY_CLASS = ctypes.c_ulong(0x00000020)
HIGH_PRIORITY_CLASS = ctypes.c_ulong(0x00000080)
INFINITE = 0xFFFFFFFF
THREAD_PRIORITY_HIGHEST = 2
THREAD_PRIORITY_ABOVE_NORMAL = 1
THREAD_PRIORITY_NORMAL = 0
PROCESS_BELOW_NORMAL_PRIORITY_CLASS = 0x00004000
PROCESS_NORMAL_PRIORITY_CLASS = 0x00000020
PROCESS_ABOVE_NORMAL_PRIORITY_CLASS = 0x00008000
# How many times to attempt sleeping/resuming thread or proces
# before giving up with failure
ATTEMPT_MAX = 10
# Which threads should not be put to sleep?
EXCLUDED_THREADS = []
# Key Functions
# Maps Microsoft API calls to more convenient name for internal use
# Also abstracts the linking library for each function for more portability
# Load the Functions that have a common library between desktop and CE
#_suspend_thread = kerneldll.SuspendThread # Puts a thread to sleep
# This workaround is needed to keep the Python Global Interpreter Lock (GIL)
# Normal ctypes CFUNCTYPE or WINFUNCTYPE prototypes will release the GIL
# Which causes the process to infinitely deadlock
# The downside to this method, is that a ValueError Exception is always thrown
_suspend_thread_proto = ctypes.PYFUNCTYPE(DWORD)
def _suspend_thread_err_check(result, func, args):
return result
_suspend_thread_err = _suspend_thread_proto(("SuspendThread", kerneldll))
_suspend_thread_err.errcheck = _suspend_thread_err_check
def _suspend_thread(handle):
result = 0
try:
result = _suspend_thread_err(handle)
except ValueError:
pass
return result
_resume_thread = kerneldll.ResumeThread # Resumes Thread execution
_open_process = kerneldll.OpenProcess # Returns Process Handle
_create_process = kerneldll.CreateProcessW # Launches new process
_set_thread_priority = kerneldll.SetThreadPriority # Sets a threads scheduling priority
_thread_times = kerneldll.GetThreadTimes # Gets CPU time data for a thread
_process_exit_code = kerneldll.GetExitCodeProcess # Gets Process Exit code
_terminate_process = kerneldll.TerminateProcess # Kills a process
_close_handle = kerneldll.CloseHandle # Closes any(?) handle object
_get_last_error = kerneldll.GetLastError # Gets last error number of last error
_wait_for_single_object = kerneldll.WaitForSingleObject # Waits to acquire mutex
_create_mutex = kerneldll.CreateMutexW # Creates a Mutex, Unicode version
_release_mutex = kerneldll.ReleaseMutex # Releases mutex
try:
_get_tick_count = kerneldll.GetTickCount64 # Try to get the 64 bit variant
except AttributeError: # This means the function does not exist
_get_tick_count = kerneldll.GetTickCount # Use the 32bit version
_free_disk_space = kerneldll.GetDiskFreeSpaceExW # Determines free disk space
# Load the Desktop Specific functions
# These are in the kernel library on the desktop
_open_thread = kerneldll.OpenThread # Returns Thread Handle
_create_snapshot = kerneldll.CreateToolhelp32Snapshot # Makes snapshot of threads
_first_thread = kerneldll.Thread32First # Reads from Thread from snapshot
_next_thread = kerneldll.Thread32Next # Reads next Thread from snapshot
_global_memory_status = kerneldll.GlobalMemoryStatusEx # Gets global memory info
_current_thread_id = kerneldll.GetCurrentThreadId # Returns the thread_id of the current thread
# These process specific functions are only available on the desktop
_process_times = kerneldll.GetProcessTimes # Returns data about Process CPU use
_process_memory = memdll.GetProcessMemoryInfo # Returns data on Process mem use
# This is only available for desktop, sets the process wide priority
_set_process_priority = kerneldll.SetPriorityClass
# Classes
# Python Class which is converted to a C struct
# It encapsulates Thread Data, and is used in
# Windows Thread calls
class _THREADENTRY32(ctypes.Structure):
_fields_ = [('dwSize', DWORD),
('cntUsage', DWORD),
('th32thread_id', DWORD),
('th32OwnerProcessID', DWORD),
('tpBasePri', LONG),
('tpDeltaPri', LONG),
('dwFlags', DWORD)]
# It encapsulates Thread Data, and is used in
# Windows Thread calls, CE Version
class _THREADENTRY32CE(ctypes.Structure):
_fields_ = [('dwSize', DWORD),
('cntUsage', DWORD),
('th32thread_id', DWORD),
('th32OwnerProcessID', DWORD),
('tpBasePri', LONG),
('tpDeltaPri', LONG),
('dwFlags', DWORD),
('th32AccessKey', DWORD),
('th32CurrentProcessID', DWORD)]
# Python Class which is converted to a C struct
# It encapsulates Time data, with a low and high number
# We use it to get Process times (user/system/etc.)
class _FILETIME(ctypes.Structure):
_fields_ = [('dwLowDateTime', DWORD),
('dwHighDateTime', DWORD)]
# Python Class which is converted to a C struct
# It encapsulates data about a Processes
# Memory usage. A pointer to the struct is passed
# to the Windows API
class _PROCESS_MEMORY_COUNTERS(ctypes.Structure):
_fields_ = [('cb', DWORD),
('PageFaultCount', DWORD),
('PeakWorkingSetSize', SIZE_T),
('WorkingSetSize', SIZE_T),
('QuotaPeakPagedPoolUsage', SIZE_T),
('QuotaPagedPoolUsage', SIZE_T),
('QuotaPeakNonPagedPoolUsage', SIZE_T),
('QuotaNonPagedPoolUsage', SIZE_T),
('PagefileUsage', SIZE_T),
('PeakPagefileUsage', SIZE_T)]
# Python Class which is converted to a C struct
# It encapsulates data about a heap space
# see http://msdn.microsoft.com/en-us/library/ms683443(VS.85).aspx
class _HEAPENTRY32(ctypes.Structure):
_fields_ = [('dwSize', SIZE_T),
('hHandle', HANDLE),
('dwAddress', ULONG_PTR),
('dwBlockSize', SIZE_T),
('dwFlags', DWORD),
('dwLockCount', DWORD),
('dwResvd', DWORD),
('th32ProcessID', DWORD),
('th32HeapID', ULONG_PTR)]
# Python Class which is converted to a C struct
# It encapsulates data about a processes heaps
# see http://msdn.microsoft.com/en-us/library/ms683449(VS.85).aspx
class _HEAPLIST32(ctypes.Structure):
_fields_ = [('dwSize', SIZE_T),
('th32ProcessID', DWORD),
('th32HeapID', ULONG_PTR),
('dwFlags', DWORD)]
# Python Class which is converted to a C struct
# It encapsulates data about a newly created process
# see http://msdn.microsoft.com/en-us/library/ms684873(VS.85).aspx
class _PROCESS_INFORMATION(ctypes.Structure):
_fields_ = [('hProcess', HANDLE),
('hThread', HANDLE),
('dwProcessId', DWORD),
('dwThreadId', DWORD)]
# Python Class which is converted to a C struct
# It encapsulates data about a Processes
# after it is created
# see http://msdn.microsoft.com/en-us/library/ms686331(VS.85).aspx
class _STARTUPINFO(ctypes.Structure):
_fields_ = [('cb', DWORD),
('lpReserved', LPTSTR),
('lpDesktop', LPTSTR),
('lpTitle', LPTSTR),
('dwX', DWORD),
('dwY', DWORD),
('dwXSize', DWORD),
('dwYSize', DWORD),
('dwXCountChars', DWORD),
('dwYCountChars', DWORD),
('dwFillAttribute', DWORD),
('dwFlags', DWORD),
('wShowWindow', DWORD),
('cbReserved2', WORD),
('lpReserved2', WORD),
('hStdInput', HANDLE),
('hStdOutput', HANDLE),
('hStdError', HANDLE)]
# Python Class which is converted to a C struct
# It encapsulates data about global memory
# This version is for Windows Desktop, and is not limited to 4 gb of ram
# see http://msdn.microsoft.com/en-us/library/aa366770(VS.85).aspx
class _MEMORYSTATUSEX(ctypes.Structure):
_fields_ = [('dwLength', DWORD),
('dwMemoryLoad', DWORD),
('ullTotalPhys', DWORDLONG),
('ullAvailPhys', DWORDLONG),
('ullTotalPageFile', DWORDLONG),
('ullAvailPageFile', DWORDLONG),
('ullTotalVirtual', DWORDLONG),
('ullAvailVirtual', DWORDLONG),
('ullAvailExtendedVirtual', DWORDLONG)]
# Exceptions
class DeadThread(Exception):
"""Gets thrown when a Tread Handle cannot be opened"""
pass
class DeadProcess(Exception):
"""Gets thrown when a Process Handle cannot be opened. Eventually a DeadThread will get escalated to DeadProcess"""
pass
class FailedMutex(Exception):
"""Gets thrown when a Mutex cannot be created, opened, or released"""
pass
# Global variables
# For each Mutex, record the lock count to properly release
_mutex_lock_count = {}
# High level functions
# When getProcessTheads is called, it iterates through all the
# system threads, and this global counter stores the thead count
_system_thread_count = 0
# Returns list with the Thread ID of all threads associated with the pid
def get_process_threads(pid):
"""
<Purpose>
Many of the Windows functions for altering processes and threads require
thread-based handles, as opposed to process based, so this function
gets all of the threads associated with a given process
<Arguments>
pid:
The Process Identifier number for which the associated threads should be returned
<Returns>
Array of Thread Identifiers, these are not thread handles
"""
global _system_thread_count
thread_class = _THREADENTRY32
threads = [] # List object for threads
current_thread = thread_class() # Current Thread Pointer
current_thread.dwSize = ctypes.sizeof(thread_class)
# Create Handle to snapshot of all system threads
handle = _create_snapshot(TH32CS_SNAPTHREAD, 0)
# Check if handle was created successfully
if handle == INVALID_HANDLE_VALUE:
_close_handle( handle )
return []
# Attempt to read snapshot
if not _first_thread( handle, ctypes.pointer(current_thread)):
_close_handle( handle )
return []
# Reset the global counter
_system_thread_count = 0
# Loop through threads, check for threads associated with the right process
more_threads = True
while (more_threads):
# Increment the global counter
_system_thread_count += 1
# Check if current thread belongs to the process were looking for
if current_thread.th32OwnerProcessID == ctypes.c_ulong(pid).value:
threads.append(current_thread.th32thread_id)
more_threads = _next_thread(handle, ctypes.pointer(current_thread))
# Cleanup snapshot
_close_handle(handle)
return threads
def get_system_thread_count():
"""
<Purpose>
Returns the number of active threads running on the system.
<Returns>
The thread count.
"""
global _system_thread_count
# Call get_process_threads to update the global counter
get_process_threads(os.getpid()) # Use our own pid
# Return the global thread count
return _system_thread_count
# Returns a handle for thread_id
def get_thread_handle(thread_id):
"""
<Purpose>
Returns a thread handle for a given thread identifier. This is useful
because a thread identified cannot be used directly for most operations.
<Arguments>
thread_id:
The Thread Identifier, for which a handle is returned
<Side Effects>
close_thread_handle must be called before get_thread_handle is called again,
or permissions will not be set to their original level.
<Exceptions>
DeadThread on bad parameters or general error
<Returns>
Thread Handle
"""
# Open handle to thread
handle = _open_thread(THREAD_HANDLE_RIGHTS, 0, thread_id)
# Check for a successful handle
if handle:
return handle
else: # Raise exception on failure
raise DeadThread, "Error opening thread handle! thread_id: " + str(thread_id) + " Error Str: " + str(ctypes.WinError())
# Closes a thread handle
def close_thread_handle(thread_handle):
"""
<Purpose>
Closes a given thread handle.
<Arguments>
ThreadHandle:
The Thread handle which is closed
"""
# Close thread handle
_close_handle(thread_handle)
# Suspend a thread with given thread_id
def suspend_thread(thread_id):
"""
<Purpose>
Suspends the execution of a thread.
Will not execute on currently executing thread.
<Arguments>
thread_id:
The thread identifier for the thread to be suspended.
<Exceptions>
DeadThread on bad parameters or general error.
<Side Effects>
Will suspend execution of the thread until resumed or terminated.
<Returns>
True on success, false on failure
"""
global EXCLUDED_THREADS
# Check if it is a white listed thread
if thread_id in EXCLUDED_THREADS:
return True
# Open handle to thread
handle = get_thread_handle(thread_id)
# Try to suspend thread, save status of call
status = _suspend_thread(handle)
# Close thread handle
close_thread_handle(handle)
# -1 is returned on failure, anything else on success
# Translate this to True and False
return (not status == -1)
# Resume a thread with given thread_id
def resume_thread(thread_id):
"""
<Purpose>
Resumes the execution of a thread.
<Arguments>
thread_id:
The thread identifier for the thread to be resumed
<Exceptions>
DeadThread on bad parameter or general error.
<Side Effects>
Will resume execution of a thread.
<Returns>
True on success, false on failure
"""
# Get thread Handle
handle = get_thread_handle(thread_id)
# Attempt to resume thread, save status of call
val = _resume_thread(handle)
# Close Thread Handle
close_thread_handle(handle)
# -1 is returned on failure, anything else on success
# Translate this to True and False
return (not val == -1)
# Suspend a process with given pid
def suspend_process(pid):
"""
<Purpose>
Instead of manually getting a list of threads for a process and individually
suspending each, this function will do the work transparently.
<Arguments>
pid:
The Process Identifier number to be suspended.
<Side Effects>
Suspends the given process indefinitely.
<Returns>
True on success, false on failure
"""
# Get List of threads related to Process
threads = get_process_threads(pid)
# Suspend each thread serially
for t in threads:
sleep = False # Loop until thread sleeps
attempt = 0 # Number of times we've attempted to suspend thread
while not sleep:
if (attempt > ATTEMPT_MAX):
return False
attempt = attempt + 1
try:
sleep = suspend_thread(t)
except DeadThread:
# If the thread is dead, lets just say its asleep and continue
sleep = True
return True
# Resume a process with given pid
def resume_process(pid):
"""
<Purpose>
Instead of manually resuming each thread in a process, this functions
handles that transparently.
<Arguments>
pid:
The Process Identifier to be resumed.
<Side Effects>
Resumes thread execution
<Returns>
True on success, false on failure
"""
# Get list of threads related to Process
threads = get_process_threads(pid)
# Resume each thread
for t in threads:
wake = False # Loop until thread wakes up
attempt = 0 # Number of attempts to resume thread
while not wake:
if (attempt > ATTEMPT_MAX):
return False
attempt = attempt + 1
try:
wake = resume_thread(t)
except DeadThread:
# If the thread is dead, its hard to wake it up, so contiue
wake = True
return True
# Suspends a process and restarts after a given time interval
def timeout_process(pid, stime):
"""
<Purpose>
Calls suspend_process and resume_process with a specified period of sleeping.
<Arguments>
pid:
The process identifier to timeout execution.
stime:
The time period in seconds to timeout execution.
<Exceptions>
DeadProcess if there is a critical problem sleeping or resuming a thread.
<Side Effects>
Timeouts the execution of the process for specified interval.
The timeout period is blocking, and will cause a general timeout in the
calling thread.
<Returns>
True of success, false on failure.
"""
if stime==0: # Don't waste time
return True
try:
# Attempt to suspend process, return immediately on failure
if suspend_process(pid):
# Sleep for user defined period
time.sleep (stime)
# Attempt to resume process and return whether that succeeded
return resume_process(pid)
else:
return False
except DeadThread: # Escalate DeadThread to DeadProcess, because that is the underlying cause
raise DeadProcess, "Failed to sleep or resume a thread!"
# Sets the current threads priority level
def set_current_thread_priority(priority=THREAD_PRIORITY_NORMAL,exclude=True):
"""
<Purpose>
Sets the priority level of the currently executing thread.
<Arguments>
Thread priority level. Must be a predefined constant.
See THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL and THREAD_PRIORITY_HIGHEST
exclude: If true, the thread will not be put to sleep when compensating for CPU use.
<Exceptions>
See get_thread_handle
<Returns>
True on success, False on failure.
"""
global EXCLUDED_THREADS
# Get thread identifier
thread_id = _current_thread_id()
# Check if we should exclude this thread
if exclude:
# Use a list copy, so that our swap doesn't cause any issues
# if the CPU scheduler is already running
new_list = EXCLUDED_THREADS[:]
new_list.append(thread_id)
EXCLUDED_THREADS = new_list
# Open handle to thread
handle = get_thread_handle(thread_id)
# Try to change the priority
status = _set_thread_priority(handle, priority)
# Close thread handle
close_thread_handle(handle)
# Return the status of this call
if status == 0:
return False
else:
return True
# Gets a process handle
def get_process_handle(pid):
"""
<Purpose>
Get a process handle for a specified process identifier
<Arguments>
pid:
The process identifier for which a handle is returned.
<Exceptions>
DeadProcess on bad parameter or general error.
<Returns>
Process handle
"""
# Get handle to process
handle = _open_process(PROCESS_SET_QUERY_AND_TERMINATE, 0, pid)
# Check if we successfully got a handle
if handle:
return handle
else: # Raise exception on failure
raise DeadProcess, "Error opening process handle! Process ID: " + str(pid) + " Error Str: " + str(ctypes.WinError())
# Launches a new process
def launch_process(application,cmdline = None, priority = NORMAL_PRIORITY_CLASS):
"""
<Purpose>
Launches a new process.
<Arguments>
application:
The path to the application to be started
cmdline:
The command line parameters that are to be used
priority
The priority of the process. See NORMAL_PRIORITY_CLASS and HIGH_PRIORITY_CLASS
<Side Effects>
A new process is created
<Returns>
Process ID on success, None on failure.
"""
# Create struct to hold process info
process_info = _PROCESS_INFORMATION()
process_info_addr = ctypes.pointer(process_info)
# Determine what is the cmdline Parameter
if not (cmdline == None):
cmdline_param = unicode(cmdline)
else:
cmdline_param = None
# For some reason, Windows Desktop uses the first part of the second parameter as the
# Application... This is documented on MSDN under CreateProcess in the user comments
# Create struct to hold window info
window_info = _STARTUPINFO()
window_info_addr = ctypes.pointer(window_info)
cmdline_param = unicode(application) + " " + cmdline_param
application = None
# Lauch process, and save status
status = _create_process(
application,
cmdline_param,
None,
None,
False,
priority,
None,
None,
window_info_addr,
process_info_addr)
# Did we succeed?
if status:
# Close handles that we don't need
_close_handle(process_info.hProcess)
_close_handle(process_info.hThread)
# Return pid
return process_info.dwProcessId
else:
return None
# Helper function to launch a python script with some parameters
def launch_python_script(script, params=""):
"""
<Purpose>
Launches a python script with parameters
<Arguments>
script:
The python script to be started. This should be an absolute path (and quoted if it contains spaces).
params:
A string command line parameter for the script
<Side Effects>
A new process is created
<Returns>
Process ID on success, None on failure.
"""
# Get all repy constants
import repy_constants
# Create python command line string
# Use absolute path for compatibility
cmd = repy_constants.PYTHON_DEFAULT_FLAGS + " " + script + " " + params
# Launch process and store return value
retval = launch_process(repy_constants.PATH_PYTHON_INSTALL,cmd)
return retval
# Sets the current process priority level
def set_current_process_priority(priority=PROCESS_NORMAL_PRIORITY_CLASS):
"""
<Purpose>
Sets the priority level of the currently executing process.
<Arguments>
Process priority level. Must be a predefined constant.
See PROCESS_NORMAL_PRIORITY_CLASS, PROCESS_BELOW_NORMAL_PRIORITY_CLASS and PROCESS_ABOVE_NORMAL_PRIORITY_CLASS
<Exceptions>
See get_process_handle
<Returns>
True on success, False on failure.
"""
# Get our pid
pid = os.getpid()
# Get process handle
handle = get_process_handle(pid)
# Try to change the priority
status = _set_process_priority(handle, priority)
# Close Process Handle
_close_handle(handle)
# Return the status of this call
if status == 0:
return False
else:
return True
# Kill a process with specified pid
def kill_process(pid):
"""
<Purpose>
Terminates a process.
<Arguments>
pid:
The process identifier to be killed.
<Exceptions>
DeadProcess on bad parameter or general error.
<Side Effects>
Terminates the process
<Returns>
True on success, false on failure.
"""
try:
# Get process handle
handle = get_process_handle(pid)
except DeadProcess: # This is okay, since we're trying to kill it anyways
return True
dead = False # Status of Process we're trying to kill
attempt = 0 # Attempt Number
# Keep hackin' away at it
while not dead:
if (attempt > ATTEMPT_MAX):
raise DeadProcess, "Failed to kill process! Process ID: " + str(pid) + " Error Str: " + str(ctypes.WinError())
# Increment attempt count
attempt = attempt + 1
# Attempt to terminate process
# 0 is return code for failure, convert it to True/False
dead = not 0 == _terminate_process(handle, 0)
# Close Process Handle
_close_handle(handle)
return True
# Get info about a processes CPU time, normalized to seconds
def get_process_cpu_time(pid):
"""
<Purpose>
See process_times
<Arguments>
See process_times
<Exceptions>
See process_times
<Returns>
The amount of CPU time used by the kernel and user in seconds.
"""
# Get the times
times = process_times(pid)
# Add kernel and user time together... It's in units of 100ns so divide
# by 10,000,000
total_time = (times['KernelTime'] + times['UserTime'] ) / 10000000.0
return total_time
# Get information about a process CPU use times
def process_times(pid):
"""
<Purpose>
Gets information about a processes CPU time utilization.
Because Windows CE does not keep track of this information at a process level,
if a thread terminates (belonging to the pid), then it is possible for the
KernelTime and UserTime to be lower than they were previously.
<Arguments>
pid:
The process identifier about which the information is returned
<Exceptions>
DeadProcess on bad parameter or general error.
<Returns>
Dictionary with the following indices:
CreationTime: the time at which the process was created
KernelTime: the execution time of the process in the kernel
UserTime: the time spent executing user code
"""
# Open process handle
handle = get_process_handle(pid)
# Create all the structures needed to make API Call
creation_time = _FILETIME()
exit_time = _FILETIME()
kernel_time = _FILETIME()
user_time = _FILETIME()
# Pass all the structures as pointers into process_times
_process_times(handle, ctypes.pointer(creation_time), ctypes.pointer(exit_time), ctypes.pointer(kernel_time), ctypes.pointer(user_time))
# Close Process Handle
_close_handle(handle)
# Extract the values from the structures, and return then in a dictionary
return {"CreationTime":creation_time.dwLowDateTime,"KernelTime":kernel_time.dwLowDateTime,"UserTime":user_time.dwLowDateTime}
# Get the CPU time of the current thread
def get_current_thread_cpu_time():
"""
<Purpose>
Gets the total CPU time for the currently executing thread.
<Exceptions>
An Exception will be raised if the underlying system call fails.
<Returns>
A floating amount of time in seconds.
"""
# Get our thread identifier
thread_id = _current_thread_id()
# Open handle to thread
handle = get_thread_handle(thread_id)
# Create all the structures needed to make API Call
creation_time = _FILETIME()
exit_time = _FILETIME()
kernel_time = _FILETIME()
user_time = _FILETIME()
# Pass all the structures as pointers into threadTimes
res = _thread_times(handle, ctypes.pointer(creation_time), ctypes.pointer(exit_time), ctypes.pointer(kernel_time), ctypes.pointer(user_time))
# Close thread Handle
close_thread_handle(handle)
# Sum up the cpu time
time_sum = kernel_time.dwLowDateTime
time_sum += user_time.dwLowDateTime
# Units are 100 ns, so divide by 10M
time_sum /= 10000000.0
# Check the result, error if result is 0
if res == 0:
raise Exception,(res, _get_last_error(), "Error getting thread CPU time! Error Str: " + str(ctypes.WinError()))
# Return the time
return time_sum
# Wait for a process to exit
def wait_for_process(pid):
"""
<Purpose>
Blocks execution until the specified Process finishes execution.
<Arguments>
pid:
The process identifier to wait for
"""
try:
# Get process handle
handle = get_process_handle(pid)
except DeadProcess:
# Process is likely dead, so just return
return
# Pass in code as a pointer to store the output
status = _wait_for_single_object(handle, INFINITE)
if status != WAIT_OBJECT_0:
raise EnvironmentError, "Failed to wait for Process!"
# Close the Process Handle
_close_handle(handle)
# Get the exit code of a process
def process_exit_code(pid):
"""
<Purpose>
Get the exit code of a process