viztracer 1.1.0__cp314-cp314-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of viztracer might be problematic. Click here for more details.

Files changed (109) hide show
  1. viztracer/__init__.py +19 -0
  2. viztracer/__main__.py +8 -0
  3. viztracer/attach.py +67 -0
  4. viztracer/attach_process/LICENSE +203 -0
  5. viztracer/attach_process/__init__.py +0 -0
  6. viztracer/attach_process/add_code_to_python_process.py +582 -0
  7. viztracer/attach_process/attach_x86.dll +0 -0
  8. viztracer/attach_process/inject_dll_amd64.exe +0 -0
  9. viztracer/attach_process/linux_and_mac/lldb_prepare.py +54 -0
  10. viztracer/attach_process/run_code_on_dllmain_amd64.dll +0 -0
  11. viztracer/attach_process/run_code_on_dllmain_x86.dll +0 -0
  12. viztracer/cellmagic.py +70 -0
  13. viztracer/code_monkey.py +353 -0
  14. viztracer/decorator.py +164 -0
  15. viztracer/event_base.py +81 -0
  16. viztracer/functree.py +135 -0
  17. viztracer/html/flamegraph.html +34 -0
  18. viztracer/html/trace_viewer_embedder.html +203 -0
  19. viztracer/html/trace_viewer_full.html +10207 -0
  20. viztracer/main.py +699 -0
  21. viztracer/modules/eventnode.c +172 -0
  22. viztracer/modules/eventnode.h +73 -0
  23. viztracer/modules/pythoncapi_compat.h +1726 -0
  24. viztracer/modules/quicktime.c +177 -0
  25. viztracer/modules/quicktime.h +104 -0
  26. viztracer/modules/snaptrace.c +2205 -0
  27. viztracer/modules/snaptrace.h +134 -0
  28. viztracer/modules/snaptrace_member.c +483 -0
  29. viztracer/modules/util.c +45 -0
  30. viztracer/modules/util.h +22 -0
  31. viztracer/modules/vcompressor/vc_dump.c +1131 -0
  32. viztracer/modules/vcompressor/vc_dump.h +49 -0
  33. viztracer/modules/vcompressor/vcompressor.c +396 -0
  34. viztracer/modules/vcompressor/vcompressor.h +15 -0
  35. viztracer/patch.py +307 -0
  36. viztracer/report_builder.py +311 -0
  37. viztracer/snaptrace.cp314-win32.pyd +0 -0
  38. viztracer/snaptrace.pyi +77 -0
  39. viztracer/util.py +196 -0
  40. viztracer/vcompressor.cp314-win32.pyd +0 -0
  41. viztracer/vcompressor.pyi +10 -0
  42. viztracer/viewer.py +528 -0
  43. viztracer/vizcounter.py +20 -0
  44. viztracer/vizevent.py +31 -0
  45. viztracer/vizlogging.py +20 -0
  46. viztracer/vizobject.py +28 -0
  47. viztracer/vizplugin.py +143 -0
  48. viztracer/viztracer.py +472 -0
  49. viztracer/web_dist/LICENSE +189 -0
  50. viztracer/web_dist/index.html +127 -0
  51. viztracer/web_dist/service_worker.js +279 -0
  52. viztracer/web_dist/trace_processor +300 -0
  53. viztracer/web_dist/v52.0-6b9586def/assets/MaterialSymbolsOutlined.woff2 +0 -0
  54. viztracer/web_dist/v52.0-6b9586def/assets/Roboto-100.woff2 +0 -0
  55. viztracer/web_dist/v52.0-6b9586def/assets/Roboto-300.woff2 +0 -0
  56. viztracer/web_dist/v52.0-6b9586def/assets/Roboto-400.woff2 +0 -0
  57. viztracer/web_dist/v52.0-6b9586def/assets/Roboto-500.woff2 +0 -0
  58. viztracer/web_dist/v52.0-6b9586def/assets/RobotoCondensed-Light.woff2 +0 -0
  59. viztracer/web_dist/v52.0-6b9586def/assets/RobotoCondensed-Regular.woff2 +0 -0
  60. viztracer/web_dist/v52.0-6b9586def/assets/RobotoMono-Regular.woff2 +0 -0
  61. viztracer/web_dist/v52.0-6b9586def/assets/brand.png +0 -0
  62. viztracer/web_dist/v52.0-6b9586def/assets/catapult_trace_viewer.html +3946 -0
  63. viztracer/web_dist/v52.0-6b9586def/assets/catapult_trace_viewer.js +7539 -0
  64. viztracer/web_dist/v52.0-6b9586def/assets/favicon.png +0 -0
  65. viztracer/web_dist/v52.0-6b9586def/assets/logo-128.png +0 -0
  66. viztracer/web_dist/v52.0-6b9586def/assets/logo-3d.png +0 -0
  67. viztracer/web_dist/v52.0-6b9586def/assets/rec_atrace.png +0 -0
  68. viztracer/web_dist/v52.0-6b9586def/assets/rec_battery_counters.png +0 -0
  69. viztracer/web_dist/v52.0-6b9586def/assets/rec_board_voltage.png +0 -0
  70. viztracer/web_dist/v52.0-6b9586def/assets/rec_cpu_coarse.png +0 -0
  71. viztracer/web_dist/v52.0-6b9586def/assets/rec_cpu_fine.png +0 -0
  72. viztracer/web_dist/v52.0-6b9586def/assets/rec_cpu_freq.png +0 -0
  73. viztracer/web_dist/v52.0-6b9586def/assets/rec_cpu_voltage.png +0 -0
  74. viztracer/web_dist/v52.0-6b9586def/assets/rec_frame_timeline.png +0 -0
  75. viztracer/web_dist/v52.0-6b9586def/assets/rec_ftrace.png +0 -0
  76. viztracer/web_dist/v52.0-6b9586def/assets/rec_gpu_mem_total.png +0 -0
  77. viztracer/web_dist/v52.0-6b9586def/assets/rec_java_heap_dump.png +0 -0
  78. viztracer/web_dist/v52.0-6b9586def/assets/rec_lmk.png +0 -0
  79. viztracer/web_dist/v52.0-6b9586def/assets/rec_logcat.png +0 -0
  80. viztracer/web_dist/v52.0-6b9586def/assets/rec_long_trace.png +0 -0
  81. viztracer/web_dist/v52.0-6b9586def/assets/rec_mem_hifreq.png +0 -0
  82. viztracer/web_dist/v52.0-6b9586def/assets/rec_meminfo.png +0 -0
  83. viztracer/web_dist/v52.0-6b9586def/assets/rec_native_heap_profiler.png +0 -0
  84. viztracer/web_dist/v52.0-6b9586def/assets/rec_one_shot.png +0 -0
  85. viztracer/web_dist/v52.0-6b9586def/assets/rec_profiling.png +0 -0
  86. viztracer/web_dist/v52.0-6b9586def/assets/rec_ps_stats.png +0 -0
  87. viztracer/web_dist/v52.0-6b9586def/assets/rec_ring_buf.png +0 -0
  88. viztracer/web_dist/v52.0-6b9586def/assets/rec_syscalls.png +0 -0
  89. viztracer/web_dist/v52.0-6b9586def/assets/rec_vmstat.png +0 -0
  90. viztracer/web_dist/v52.0-6b9586def/assets/scheduling_latency.png +0 -0
  91. viztracer/web_dist/v52.0-6b9586def/assets/vscode-icon.png +0 -0
  92. viztracer/web_dist/v52.0-6b9586def/engine_bundle.js +3 -0
  93. viztracer/web_dist/v52.0-6b9586def/frontend_bundle.js +5495 -0
  94. viztracer/web_dist/v52.0-6b9586def/index.html +127 -0
  95. viztracer/web_dist/v52.0-6b9586def/manifest.json +52 -0
  96. viztracer/web_dist/v52.0-6b9586def/perfetto.css +5737 -0
  97. viztracer/web_dist/v52.0-6b9586def/stdlib_docs.json +1 -0
  98. viztracer/web_dist/v52.0-6b9586def/trace_config_utils.wasm +0 -0
  99. viztracer/web_dist/v52.0-6b9586def/trace_processor.wasm +0 -0
  100. viztracer/web_dist/v52.0-6b9586def/trace_processor_memory64.wasm +0 -0
  101. viztracer/web_dist/v52.0-6b9586def/traceconv.wasm +0 -0
  102. viztracer/web_dist/v52.0-6b9586def/traceconv_bundle.js +2 -0
  103. viztracer-1.1.0.dist-info/METADATA +316 -0
  104. viztracer-1.1.0.dist-info/RECORD +109 -0
  105. viztracer-1.1.0.dist-info/WHEEL +5 -0
  106. viztracer-1.1.0.dist-info/entry_points.txt +3 -0
  107. viztracer-1.1.0.dist-info/licenses/LICENSE +222 -0
  108. viztracer-1.1.0.dist-info/licenses/NOTICE.txt +27 -0
  109. viztracer-1.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,582 @@
1
+ # type: ignore
2
+
3
+ r'''
4
+ Copyright: Brainwy Software Ltda.
5
+
6
+ License: EPL.
7
+ =============
8
+
9
+ Works for Windows by using an executable that'll inject a dll to a process and call a function.
10
+
11
+ Note: https://github.com/fabioz/winappdbg is used just to determine if the target process is 32 or 64 bits.
12
+
13
+ Works for Linux relying on gdb.
14
+
15
+ Limitations:
16
+ ============
17
+
18
+ Linux:
19
+ ------
20
+
21
+ 1. It possible that ptrace is disabled: /etc/sysctl.d/10-ptrace.conf
22
+
23
+ Note that even enabling it in /etc/sysctl.d/10-ptrace.conf (i.e.: making the
24
+ ptrace_scope=0), it's possible that we need to run the application that'll use ptrace (or
25
+ gdb in this case) as root (so, we must sudo the python which'll run this module).
26
+
27
+ 2. It currently doesn't work in debug builds (i.e.: python_d)
28
+
29
+
30
+ Other implementations:
31
+ - pyrasite.com:
32
+ GPL
33
+ Windows/linux (in Linux it also uses gdb to connect -- although specifics are different as we use a dll to execute
34
+ code with other threads stopped). It's Windows approach is more limited because it doesn't seem to deal properly with
35
+ Python 3 if threading is disabled.
36
+
37
+ - https://github.com/google/pyringe:
38
+ Apache v2.
39
+ Only linux/Python 2.
40
+
41
+ - http://pytools.codeplex.com:
42
+ Apache V2
43
+ Windows Only (but supports mixed mode debugging)
44
+ Our own code relies heavily on a part of it: http://pytools.codeplex.com/SourceControl/latest#Python/Product/PyDebugAttach/PyDebugAttach.cpp
45
+ to overcome some limitations of attaching and running code in the target python executable on Python 3.
46
+ See: attach.cpp
47
+
48
+ Linux: References if we wanted to use a pure-python debugger:
49
+ https://bitbucket.org/haypo/python-ptrace/
50
+ http://stackoverflow.com/questions/7841573/how-to-get-an-error-message-for-errno-value-in-python
51
+ Jugaad:
52
+ https://www.defcon.org/images/defcon-19/dc-19-presentations/Jakhar/DEFCON-19-Jakhar-Jugaad-Linux-Thread-Injection.pdf
53
+ https://github.com/aseemjakhar/jugaad
54
+
55
+ Something else (general and not Python related):
56
+ - http://www.codeproject.com/Articles/4610/Three-Ways-to-Inject-Your-Code-into-Another-Proces
57
+
58
+ Other references:
59
+ - https://github.com/haypo/faulthandler
60
+ - http://nedbatchelder.com/text/trace-function.html
61
+ - https://github.com/python-git/python/blob/master/Python/sysmodule.c (sys_settrace)
62
+ - https://github.com/python-git/python/blob/master/Python/ceval.c (PyEval_SetTrace)
63
+ - https://github.com/python-git/python/blob/master/Python/thread.c (PyThread_get_key_value)
64
+
65
+
66
+ To build the dlls needed on windows, visual studio express 13 was used (see compile_dll.bat)
67
+
68
+ See: attach_pydevd.py to attach the pydev debugger to a running python process.
69
+ '''
70
+
71
+ # Note: to work with nasm compiling asm to code and decompiling to see asm with shellcode:
72
+ # x:\nasm\nasm-2.07-win32\nasm-2.07\nasm.exe
73
+ # nasm.asm&x:\nasm\nasm-2.07-win32\nasm-2.07\ndisasm.exe -b arch nasm
74
+ import ctypes
75
+ import os
76
+ import struct
77
+ import subprocess
78
+ import sys
79
+ import time
80
+ from contextlib import contextmanager
81
+ import platform
82
+ import traceback
83
+
84
+ try:
85
+ TimeoutError = TimeoutError # @ReservedAssignment
86
+ except NameError:
87
+
88
+ class TimeoutError(RuntimeError): # @ReservedAssignment
89
+ pass
90
+
91
+
92
+ @contextmanager
93
+ def _create_win_event(name):
94
+ from winappdbg.win32.kernel32 import CreateEventA, WaitForSingleObject, CloseHandle
95
+
96
+ manual_reset = False # i.e.: after someone waits it, automatically set to False.
97
+ initial_state = False
98
+ if not isinstance(name, bytes):
99
+ name = name.encode('utf-8')
100
+ event = CreateEventA(None, manual_reset, initial_state, name)
101
+ if not event:
102
+ raise ctypes.WinError()
103
+
104
+ class _WinEvent(object):
105
+
106
+ def wait_for_event_set(self, timeout=None):
107
+ '''
108
+ :param timeout: in seconds
109
+ '''
110
+ if timeout is None:
111
+ timeout = 0xFFFFFFFF
112
+ else:
113
+ timeout = int(timeout * 1000)
114
+ ret = WaitForSingleObject(event, timeout)
115
+ if ret in (0, 0x80):
116
+ return True
117
+ elif ret == 0x102:
118
+ # Timed out
119
+ return False
120
+ else:
121
+ raise ctypes.WinError()
122
+
123
+ try:
124
+ yield _WinEvent()
125
+ finally:
126
+ CloseHandle(event)
127
+
128
+
129
+ IS_WINDOWS = sys.platform == 'win32'
130
+ IS_LINUX = sys.platform in ('linux', 'linux2')
131
+ IS_MAC = sys.platform == 'darwin'
132
+
133
+
134
+ def is_python_64bit():
135
+ return (struct.calcsize('P') == 8)
136
+
137
+
138
+ def get_target_filename(is_target_process_64=None, prefix=None, extension=None):
139
+ # Note: we have an independent (and similar -- but not equal) version of this method in
140
+ # `pydevd_tracing.py` which should be kept synchronized with this one (we do a copy
141
+ # because the `pydevd_attach_to_process` is mostly independent and shouldn't be imported in the
142
+ # debugger -- the only situation where it's imported is if the user actually does an attach to
143
+ # process, through `attach_pydevd.py`, but this should usually be called from the IDE directly
144
+ # and not from the debugger).
145
+ libdir = os.path.dirname(__file__)
146
+
147
+ if is_target_process_64 is None:
148
+ if IS_WINDOWS:
149
+ # i.e.: On windows the target process could have a different bitness (32bit is emulated on 64bit).
150
+ raise AssertionError("On windows it's expected that the target bitness is specified.")
151
+
152
+ # For other platforms, just use the the same bitness of the process we're running in.
153
+ is_target_process_64 = is_python_64bit()
154
+
155
+ arch = ''
156
+ if IS_WINDOWS:
157
+ # prefer not using platform.machine() when possible (it's a bit heavyweight as it may
158
+ # spawn a subprocess).
159
+ arch = os.environ.get("PROCESSOR_ARCHITEW6432", os.environ.get('PROCESSOR_ARCHITECTURE', ''))
160
+
161
+ if not arch:
162
+ arch = platform.machine()
163
+ if not arch:
164
+ print('platform.machine() did not return valid value.') # This shouldn't happen...
165
+ return None
166
+
167
+ if IS_WINDOWS:
168
+ if not extension:
169
+ extension = '.dll'
170
+ suffix_64 = 'amd64'
171
+ suffix_32 = 'x86'
172
+
173
+ elif IS_LINUX:
174
+ if not extension:
175
+ extension = '.so'
176
+ suffix_64 = 'amd64'
177
+ suffix_32 = 'x86'
178
+
179
+ elif IS_MAC:
180
+ if not extension:
181
+ extension = '.dylib'
182
+ suffix_64 = 'x86_64'
183
+ suffix_32 = 'x86'
184
+
185
+ else:
186
+ print('Unable to attach to process in platform: %s', sys.platform)
187
+ return None
188
+
189
+ if arch.lower() not in ('amd64', 'x86', 'x86_64', 'i386', 'x86'):
190
+ # We don't support this processor by default. Still, let's support the case where the
191
+ # user manually compiled it himself with some heuristics.
192
+ #
193
+ # Ideally the user would provide a library in the format: "attach_<arch>.<extension>"
194
+ # based on the way it's currently compiled -- see:
195
+ # - windows/compile_windows.bat
196
+ # - linux_and_mac/compile_linux.sh
197
+ # - linux_and_mac/compile_mac.sh
198
+
199
+ try:
200
+ found = [name for name in os.listdir(libdir) if name.startswith('attach_') and name.endswith(extension)]
201
+ except:
202
+ print('Error listing dir: %s' % (libdir,))
203
+ traceback.print_exc()
204
+ return None
205
+
206
+ if prefix:
207
+ expected_name = prefix + arch + extension
208
+ expected_name_linux = prefix + 'linux_' + arch + extension
209
+ else:
210
+ # Default is looking for the attach_ / attach_linux
211
+ expected_name = 'attach_' + arch + extension
212
+ expected_name_linux = 'attach_linux_' + arch + extension
213
+
214
+ filename = None
215
+ if expected_name in found: # Heuristic: user compiled with "attach_<arch>.<extension>"
216
+ filename = os.path.join(libdir, expected_name)
217
+
218
+ elif IS_LINUX and expected_name_linux in found: # Heuristic: user compiled with "attach_linux_<arch>.<extension>"
219
+ filename = os.path.join(libdir, expected_name_linux)
220
+
221
+ elif len(found) == 1: # Heuristic: user removed all libraries and just left his own lib.
222
+ filename = os.path.join(libdir, found[0])
223
+
224
+ else: # Heuristic: there's one additional library which doesn't seem to be our own. Find the odd one.
225
+ filtered = [name for name in found if not name.endswith((suffix_64 + extension, suffix_32 + extension))]
226
+ if len(filtered) == 1: # If more than one is available we can't be sure...
227
+ filename = os.path.join(libdir, found[0])
228
+
229
+ if filename is None:
230
+ print(
231
+ 'Unable to attach to process in arch: %s (did not find %s in %s).' % (
232
+ arch, expected_name, libdir
233
+ )
234
+ )
235
+ return None
236
+
237
+ print('Using %s in arch: %s.' % (filename, arch))
238
+
239
+ else:
240
+ if is_target_process_64:
241
+ suffix = suffix_64
242
+ else:
243
+ suffix = suffix_32
244
+
245
+ if not prefix:
246
+ # Default is looking for the attach_ / attach_linux
247
+ if IS_WINDOWS or IS_MAC: # just the extension changes
248
+ prefix = 'attach_'
249
+ elif IS_LINUX:
250
+ prefix = 'attach_linux_' # historically it has a different name
251
+ else:
252
+ print('Unable to attach to process in platform: %s' % (sys.platform,))
253
+ return None
254
+
255
+ filename = os.path.join(libdir, '%s%s%s' % (prefix, suffix, extension))
256
+
257
+ if not os.path.exists(filename):
258
+ print('Expected: %s to exist.' % (filename,))
259
+ return None
260
+
261
+ return filename
262
+
263
+
264
+ def run_python_code_windows(pid, python_code, connect_debugger_tracing=False, show_debug_info=0):
265
+ assert '\'' not in python_code, 'Having a single quote messes with our command.'
266
+ from winappdbg.process import Process
267
+ if not isinstance(python_code, bytes):
268
+ python_code = python_code.encode('utf-8')
269
+
270
+ process = Process(pid)
271
+ bits = process.get_bits()
272
+ is_target_process_64 = bits == 64
273
+
274
+ # Note: this restriction no longer applies (we create a process with the proper bitness from
275
+ # this process so that the attach works).
276
+ # if is_target_process_64 != is_python_64bit():
277
+ # raise RuntimeError("The architecture of the Python used to connect doesn't match the architecture of the target.\n"
278
+ # "Target 64 bits: %s\n"
279
+ # "Current Python 64 bits: %s" % (is_target_process_64, is_python_64bit()))
280
+
281
+ with _acquire_mutex('_pydevd_pid_attach_mutex_%s' % (pid,), 10):
282
+ # print('--- Connecting to %s bits target (current process is: %s) ---' % (bits, 64 if is_python_64bit() else 32))
283
+
284
+ with _win_write_to_shared_named_memory(python_code, pid):
285
+
286
+ target_executable = get_target_filename(is_target_process_64, 'inject_dll_', '.exe')
287
+ if not target_executable:
288
+ raise RuntimeError('Could not find expected .exe file to inject dll in attach to process.')
289
+
290
+ target_dll = get_target_filename(is_target_process_64)
291
+ if not target_dll:
292
+ raise RuntimeError('Could not find expected .dll file in attach to process.')
293
+
294
+ # print('\n--- Injecting attach dll: %s into pid: %s ---' % (os.path.basename(target_dll), pid))
295
+ args = [target_executable, str(pid), target_dll]
296
+ subprocess.check_call(args)
297
+
298
+ # Now, if the first injection worked, go on to the second which will actually
299
+ # run the code.
300
+ target_dll_run_on_dllmain = get_target_filename(is_target_process_64, 'run_code_on_dllmain_', '.dll')
301
+ if not target_dll_run_on_dllmain:
302
+ raise RuntimeError('Could not find expected .dll in attach to process.')
303
+
304
+ with _create_win_event('_pydevd_pid_event_%s' % (pid,)) as event:
305
+ # print('\n--- Injecting run code dll: %s into pid: %s ---' % (os.path.basename(target_dll_run_on_dllmain), pid))
306
+ args = [target_executable, str(pid), target_dll_run_on_dllmain]
307
+ subprocess.check_call(args)
308
+
309
+ if not event.wait_for_event_set(10):
310
+ print('Timeout error: the attach may not have completed.')
311
+ # print('--- Finished dll injection ---\n')
312
+
313
+ return 0, b"", b""
314
+
315
+
316
+ @contextmanager
317
+ def _acquire_mutex(mutex_name, timeout):
318
+ '''
319
+ Only one process may be attaching to a pid, so, create a system mutex
320
+ to make sure this holds in practice.
321
+ '''
322
+ from winappdbg.win32.kernel32 import CreateMutex, GetLastError, CloseHandle
323
+ from winappdbg.win32.defines import ERROR_ALREADY_EXISTS
324
+
325
+ initial_time = time.time()
326
+ while True:
327
+ mutex = CreateMutex(None, True, mutex_name)
328
+ acquired = GetLastError() != ERROR_ALREADY_EXISTS
329
+ if acquired:
330
+ break
331
+ if time.time() - initial_time > timeout:
332
+ raise TimeoutError('Unable to acquire mutex to make attach before timeout.')
333
+ time.sleep(.2)
334
+
335
+ try:
336
+ yield
337
+ finally:
338
+ CloseHandle(mutex)
339
+
340
+
341
+ @contextmanager
342
+ def _win_write_to_shared_named_memory(python_code, pid):
343
+ # Use the definitions from winappdbg when possible.
344
+ from winappdbg.win32 import defines
345
+ from winappdbg.win32.kernel32 import (
346
+ CreateFileMapping,
347
+ MapViewOfFile,
348
+ CloseHandle,
349
+ UnmapViewOfFile,
350
+ )
351
+
352
+ memmove = ctypes.cdll.msvcrt.memmove
353
+ memmove.argtypes = [
354
+ ctypes.c_void_p,
355
+ ctypes.c_void_p,
356
+ defines.SIZE_T,
357
+ ]
358
+ memmove.restype = ctypes.c_void_p
359
+
360
+ # Note: BUFSIZE must be the same from run_code_in_memory.hpp
361
+ BUFSIZE = 2048
362
+ assert isinstance(python_code, bytes)
363
+ assert len(python_code) > 0, 'Python code must not be empty.'
364
+ # Note: -1 so that we're sure we'll add a \0 to the end.
365
+ assert len(python_code) < BUFSIZE - 1, 'Python code must have at most %s bytes (found: %s)' % (BUFSIZE - 1, len(python_code))
366
+
367
+ python_code += b'\0' * (BUFSIZE - len(python_code))
368
+ assert python_code.endswith(b'\0')
369
+
370
+ INVALID_HANDLE_VALUE = -1
371
+ PAGE_READWRITE = 0x4
372
+ FILE_MAP_WRITE = 0x2
373
+ filemap = CreateFileMapping(
374
+ INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, BUFSIZE, u"__pydevd_pid_code_to_run__%s" % (pid,))
375
+
376
+ if filemap == INVALID_HANDLE_VALUE or filemap is None:
377
+ raise Exception("Failed to create named file mapping (ctypes: CreateFileMapping): %s" % (filemap,))
378
+ try:
379
+ view = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0)
380
+ if not view:
381
+ raise Exception("Failed to create view of named file mapping (ctypes: MapViewOfFile).")
382
+
383
+ try:
384
+ memmove(view, python_code, BUFSIZE)
385
+ yield
386
+ finally:
387
+ UnmapViewOfFile(view)
388
+ finally:
389
+ CloseHandle(filemap)
390
+
391
+
392
+ def run_python_code_linux(pid, python_code, connect_debugger_tracing=False, show_debug_info=0):
393
+ assert '\'' not in python_code, 'Having a single quote messes with our command.'
394
+
395
+ target_dll = get_target_filename()
396
+ if not target_dll:
397
+ raise RuntimeError('Could not find .so for attach to process.')
398
+ target_dll_name = os.path.splitext(os.path.basename(target_dll))[0]
399
+
400
+ # Note: we currently don't support debug builds
401
+ is_debug = 0
402
+ # Note that the space in the beginning of each line in the multi-line is important!
403
+ cmd = [
404
+ 'gdb',
405
+ '--nw', # no gui interface
406
+ '--nh', # no ~/.gdbinit
407
+ '--nx', # no .gdbinit
408
+ # '--quiet', # no version number on startup
409
+ '--pid',
410
+ str(pid),
411
+ '--batch',
412
+ # '--batch-silent',
413
+ ]
414
+
415
+ cmd.extend(["--eval-command='set scheduler-locking off'"]) # If on we'll deadlock.
416
+
417
+ # Leave auto by default (it should do the right thing as we're attaching to a process in the
418
+ # current host).
419
+ cmd.extend(["--eval-command='set architecture auto'"])
420
+
421
+ cmd.extend([
422
+ "--eval-command='call (void*)dlopen(\"%s\", 2)'" % target_dll,
423
+ "--eval-command='sharedlibrary %s'" % target_dll_name,
424
+ "--eval-command='call (int)DoAttach(%s, \"%s\", %s)'" % (
425
+ is_debug, python_code, show_debug_info)
426
+ ])
427
+
428
+ # print ' '.join(cmd)
429
+
430
+ env = os.environ.copy()
431
+ # Remove the PYTHONPATH (if gdb has a builtin Python it could fail if we
432
+ # have the PYTHONPATH for a different python version or some forced encoding).
433
+ env.pop('PYTHONIOENCODING', None)
434
+ env.pop('PYTHONPATH', None)
435
+ # print('Running: %s' % (' '.join(cmd)))
436
+ p = subprocess.Popen(
437
+ ' '.join(cmd),
438
+ shell=True,
439
+ env=env,
440
+ stdout=subprocess.PIPE,
441
+ stderr=subprocess.PIPE,
442
+ )
443
+ # print('Running gdb in target process.')
444
+ out, err = p.communicate()
445
+ # print('stdout: %s' % (out,))
446
+ # print('stderr: %s' % (err,))
447
+ return p.returncode, out, err
448
+
449
+
450
+ def find_helper_script(filedir, script_name):
451
+ target_filename = os.path.join(filedir, 'linux_and_mac', script_name)
452
+ target_filename = os.path.normpath(target_filename)
453
+ if not os.path.exists(target_filename):
454
+ raise RuntimeError('Could not find helper script: %s' % target_filename)
455
+
456
+ return target_filename
457
+
458
+
459
+ def run_python_code_mac(pid, python_code, connect_debugger_tracing=False, show_debug_info=0):
460
+ assert '\'' not in python_code, 'Having a single quote messes with our command.'
461
+
462
+ target_dll = get_target_filename()
463
+ if not target_dll:
464
+ raise RuntimeError('Could not find .dylib for attach to process.')
465
+
466
+ libdir = os.path.dirname(__file__)
467
+ lldb_prepare_file = find_helper_script(libdir, 'lldb_prepare.py')
468
+ # Note: we currently don't support debug builds
469
+
470
+ is_debug = 0
471
+ # Note that the space in the beginning of each line in the multi-line is important!
472
+ cmd = [
473
+ 'lldb',
474
+ '--no-lldbinit', # Do not automatically parse any '.lldbinit' files.
475
+ # '--attach-pid',
476
+ # str(pid),
477
+ # '--arch',
478
+ # arch,
479
+ '--script-language',
480
+ 'Python'
481
+ # '--batch-silent',
482
+ ]
483
+
484
+ cmd.extend([
485
+ "-o 'process attach --pid %d'" % pid,
486
+ "-o 'command script import \"%s\"'" % (lldb_prepare_file,),
487
+ "-o 'load_lib_and_attach \"%s\" %s \"%s\" %s'" % (target_dll,
488
+ is_debug, python_code, show_debug_info),
489
+ ])
490
+
491
+ cmd.extend([
492
+ "-o 'process detach'",
493
+ "-o 'script import os; os._exit(0)'",
494
+ ])
495
+
496
+ # print ' '.join(cmd)
497
+
498
+ env = os.environ.copy()
499
+ # Remove the PYTHONPATH (if gdb has a builtin Python it could fail if we
500
+ # have the PYTHONPATH for a different python version or some forced encoding).
501
+ env.pop('PYTHONIOENCODING', None)
502
+ env.pop('PYTHONPATH', None)
503
+ # print('Running: %s' % (' '.join(cmd)))
504
+ p = subprocess.Popen(
505
+ ' '.join(cmd),
506
+ shell=True,
507
+ env=env,
508
+ stdout=subprocess.PIPE,
509
+ stderr=subprocess.PIPE,
510
+ )
511
+ # print('Running lldb in target process.')
512
+ out, err = p.communicate()
513
+ # print('stdout: %s' % (out,))
514
+ # print('stderr: %s' % (err,))
515
+ return p.returncode, out, err
516
+
517
+
518
+ if IS_WINDOWS:
519
+ run_python_code = run_python_code_windows
520
+ elif IS_MAC:
521
+ run_python_code = run_python_code_mac
522
+ elif IS_LINUX:
523
+ run_python_code = run_python_code_linux
524
+ else:
525
+
526
+ def run_python_code(*args, **kwargs):
527
+ print('Unable to attach to process in platform: %s', sys.platform)
528
+
529
+
530
+ sys.path.append(os.path.dirname(__file__))
531
+
532
+
533
+ def test():
534
+ print('Running with: %s' % (sys.executable,))
535
+ code = '''
536
+ import os, time, sys
537
+ print(os.getpid())
538
+ #from threading import Thread
539
+ #Thread(target=str).start()
540
+ if __name__ == '__main__':
541
+ while True:
542
+ time.sleep(.5)
543
+ sys.stdout.write('.\\n')
544
+ sys.stdout.flush()
545
+ '''
546
+
547
+ p = subprocess.Popen([sys.executable, '-u', '-c', code])
548
+ try:
549
+ code = 'print("It worked!")\n'
550
+
551
+ # Real code will be something as:
552
+ # code = '''import sys;sys.path.append(r'X:\winappdbg-code\examples'); import imported;'''
553
+ run_python_code(p.pid, python_code=code)
554
+ print('\nRun a 2nd time...\n')
555
+ run_python_code(p.pid, python_code=code)
556
+
557
+ time.sleep(3)
558
+ finally:
559
+ p.kill()
560
+
561
+
562
+ def main(args):
563
+ # Otherwise, assume the first parameter is the pid and anything else is code to be executed
564
+ # in the target process.
565
+ pid = int(args[0])
566
+ del args[0]
567
+ python_code = ';'.join(args)
568
+
569
+ # Note: on Linux the python code may not have a single quote char: '
570
+ run_python_code(pid, python_code)
571
+
572
+
573
+ if __name__ == '__main__':
574
+ args = sys.argv[1:]
575
+ if not args:
576
+ print('Expected pid and Python code to execute in target process.')
577
+ else:
578
+ if '--test' == args[0]:
579
+ test()
580
+ else:
581
+ main(args)
582
+
Binary file
@@ -0,0 +1,54 @@
1
+ # This file is meant to be run inside lldb
2
+ # It registers command to load library and invoke attach function
3
+ # Also it marks process threads to to distinguish them from debugger
4
+ # threads later while settings trace in threads
5
+
6
+ def load_lib_and_attach(debugger, command, result, internal_dict):
7
+ import shlex
8
+ args = shlex.split(command)
9
+
10
+ dll = args[0]
11
+ is_debug = args[1]
12
+ python_code = args[2]
13
+ show_debug_info = args[3]
14
+
15
+ import lldb
16
+ options = lldb.SBExpressionOptions()
17
+ options.SetFetchDynamicValue()
18
+ options.SetTryAllThreads(run_others=False)
19
+ options.SetTimeoutInMicroSeconds(timeout=60000000)
20
+
21
+ print(dll)
22
+ target = debugger.GetSelectedTarget()
23
+ res = target.EvaluateExpression("(void*)dlopen(\"%s\", 2);" % (
24
+ dll), options)
25
+ error = res.GetError()
26
+ if error:
27
+ print(error)
28
+
29
+ print(python_code)
30
+ res = target.EvaluateExpression("(int)DoAttach(%s, \"%s\", %s);" % (
31
+ is_debug, python_code.replace('"', "'"), show_debug_info), options)
32
+ error = res.GetError()
33
+ if error:
34
+ print(error)
35
+
36
+ def __lldb_init_module(debugger, internal_dict):
37
+ import lldb
38
+
39
+ debugger.HandleCommand('command script add -f lldb_prepare.load_lib_and_attach load_lib_and_attach')
40
+
41
+ try:
42
+ target = debugger.GetSelectedTarget()
43
+ if target:
44
+ process = target.GetProcess()
45
+ if process:
46
+ for thread in process:
47
+ # print('Marking process thread %d'%thread.GetThreadID())
48
+ internal_dict['_thread_%d' % thread.GetThreadID()] = True
49
+ # thread.Suspend()
50
+ except:
51
+ import traceback;traceback.print_exc()
52
+
53
+
54
+