Debian Codegraph @

rpython/rlib/rvmprof/cintf.py

raw symbols SCIP
1 from __future__ import print_function
2
3 import platform as host_platform
4 import py
5 import sys
6 import shutil
7 from rpython.tool.udir import udir
8 from rpython.tool.version import rpythonroot
9 from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
10 from rpython.rtyper.lltypesystem.lloperation import llop
11 from rpython.translator.tool.cbuild import ExternalCompilationInfo
12 from rpython.rtyper.tool import rffi_platform as platform
13 from rpython.rlib import rthread, jit
14 from rpython.rlib.objectmodel import we_are_translated
15 from rpython.config.translationoption import get_translation_config
16 from rpython.jit.backend import detect_cpu
17
18 class VMProfPlatformUnsupported(Exception):
19 pass
20
21 # vmprof works only on x86 for now
22 IS_SUPPORTED = False
23 NATIVE_PROFILING_SUPPORTED = False
24 if sys.platform in ('darwin', 'linux', 'linux2') or sys.platform.startswith('freebsd'):
25 try:
26 proc = detect_cpu.autodetect()
27 IS_SUPPORTED = (proc.startswith('x86')
28 or proc == 'aarch64'
29 or proc == 'riscv64')
30 NATIVE_PROFILING_SUPPORTED = proc.startswith('x86')
31 except detect_cpu.ProcessorAutodetectError:
32 print("PROCESSOR NOT DETECTED, SKIPPING VMPROF")
33
34 ROOT = py.path.local(rpythonroot).join('rpython', 'rlib', 'rvmprof')
35 SRC = ROOT.join('src')
36 SHARED = SRC.join('shared')
37 BACKTRACE = SHARED.join('libbacktrace')
38
39 def make_eci():
40 if make_eci.called:
41 raise ValueError("make_eci() should be called at most once")
42 #
43 compile_extra = ['-DRPYTHON_VMPROF']
44 separate_module_files = [
45 SHARED.join('symboltable.c'),
46 SHARED.join('vmprof_unix.c')
47 ]
48 if sys.platform.startswith('linux'):
49 separate_module_files += [
50 BACKTRACE.join('atomic.c'),
51 BACKTRACE.join('backtrace.c'),
52 BACKTRACE.join('state.c'),
53 BACKTRACE.join('elf.c'),
54 BACKTRACE.join('dwarf.c'),
55 BACKTRACE.join('fileline.c'),
56 BACKTRACE.join('mmap.c'),
57 BACKTRACE.join('mmapio.c'),
58 BACKTRACE.join('posix.c'),
59 BACKTRACE.join('sort.c'),
60 ]
61 _libs = ['dl']
62 compile_extra += ['-DVMPROF_UNIX']
63 compile_extra += ['-DVMPROF_LINUX']
64 elif sys.platform == 'win32':
65 compile_extra += ['-DVMPROF_WINDOWS']
66 separate_module_files = [SHARED.join('vmprof_win.c')]
67 _libs = []
68 else:
69 # Guessing a BSD-like Unix platform
70 compile_extra += ['-DVMPROF_UNIX']
71 if sys.platform.startswith('darwin'):
72 compile_extra += ['-DVMPROF_APPLE']
73 if sys.platform.startswith('freebsd'):
74 _libs = ['unwind']
75 else:
76 _libs = []
77
78 eci_kwds = dict(
79 include_dirs = [SRC, SHARED, BACKTRACE],
80 includes = ['rvmprof.h','vmprof_stack.h'],
81 libraries = _libs,
82 separate_module_files = [
83 SRC.join('rvmprof.c'),
84 SHARED.join('compat.c'),
85 SHARED.join('machine.c'),
86 SHARED.join('vmp_stack.c'),
87 SHARED.join('vmprof_memory.c'),
88 SHARED.join('vmprof_common.c'),
89 # symbol table already in separate_module_files
90 ] + separate_module_files,
91 post_include_bits=[],
92 compile_extra=compile_extra
93 )
94 if sys.platform != 'win32':
95 eci_kwds['separate_module_files'].append(
96 SHARED.join('vmprof_mt.c'),
97 )
98 make_eci.called = True
99 return ExternalCompilationInfo(**eci_kwds), eci_kwds
100 make_eci.called = False
101
102 def configure_libbacktrace_linux():
103 bits = 32 if sys.maxsize == 2**31-1 else 64
104 # FIXME well, the config generated on x86 seems to work on s390x and ppc
105 # vmprof is currently not supported there! we just need to pass compilation
106 specific_config = 'config-x86_%d.h' % bits
107 config = BACKTRACE.join('config.h')
108 shutil.copy(str(BACKTRACE.join(specific_config)), str(config))
109
110 def setup():
111 if not IS_SUPPORTED:
112 raise VMProfPlatformUnsupported
113
114 if sys.platform.startswith('linux'):
115 configure_libbacktrace_linux()
116
117 eci, eci_kwds = make_eci()
118 eci_kwds['compile_extra'].append('-DRPYTHON_LL2CTYPES')
119 platform.verify_eci(ExternalCompilationInfo(
120 **eci_kwds))
121
122 vmprof_init = rffi.llexternal("vmprof_init",
123 [rffi.INT, rffi.DOUBLE, rffi.INT, rffi.INT,
124 rffi.CCHARP, rffi.INT, rffi.INT],
125 rffi.CCHARP, compilation_info=eci)
126 vmprof_enable = rffi.llexternal("vmprof_enable", [rffi.INT, rffi.INT, rffi.INT],
127 rffi.INT,
128 compilation_info=eci,
129 save_err=rffi.RFFI_SAVE_ERRNO)
130 vmprof_disable = rffi.llexternal("vmprof_disable", [], rffi.INT,
131 compilation_info=eci,
132 save_err=rffi.RFFI_SAVE_ERRNO)
133 vmprof_register_virtual_function = rffi.llexternal(
134 "vmprof_register_virtual_function",
135 [rffi.CCHARP, rffi.LONG, rffi.INT],
136 rffi.INT, compilation_info=eci)
137 vmprof_ignore_signals = rffi.llexternal("vmprof_ignore_signals",
138 [rffi.INT], lltype.Void,
139 compilation_info=eci,
140 _nowrapper=True)
141 vmprof_get_traceback = rffi.llexternal("vmprof_get_traceback",
142 [PVMPROFSTACK, llmemory.Address,
143 rffi.VOIDPP, lltype.Signed],
144 lltype.Signed, compilation_info=eci,
145 _nowrapper=True)
146
147 vmprof_get_profile_path = rffi.llexternal("vmprof_get_profile_path", [rffi.CCHARP, lltype.Signed],
148 lltype.Signed, compilation_info=eci,
149 _nowrapper=True)
150
151 vmprof_stop_sampling = rffi.llexternal("vmprof_stop_sampling", [],
152 rffi.INT, compilation_info=eci,
153 _nowrapper=True)
154 vmprof_start_sampling = rffi.llexternal("vmprof_start_sampling", [],
155 lltype.Void, compilation_info=eci,
156 _nowrapper=True)
157 return CInterface(locals())
158
159
160 class CInterface(object):
161 def __init__(self, namespace):
162 for k, v in namespace.iteritems():
163 setattr(self, k, v)
164
165 def _freeze_(self):
166 return True
167
168
169 # --- copy a few declarations from src/vmprof_stack.h ---
170
171 VMPROF_CODE_TAG = 1
172
173 VMPROFSTACK = lltype.ForwardReference()
174 PVMPROFSTACK = lltype.Ptr(VMPROFSTACK)
175 VMPROFSTACK.become(rffi.CStruct("vmprof_stack_s",
176 ('next', PVMPROFSTACK),
177 ('value', lltype.Signed),
178 ('kind', lltype.Signed)))
179 # ----------
180
181
182 vmprof_tl_stack = rthread.ThreadLocalField(PVMPROFSTACK, "vmprof_tl_stack")
183 do_use_eci = rffi.llexternal_use_eci(
184 ExternalCompilationInfo(includes=['vmprof_stack.h'],
185 include_dirs = [SRC]))
186
187 def enter_code(unique_id):
188 do_use_eci()
189 s = lltype.malloc(VMPROFSTACK, flavor='raw')
190 s.c_next = vmprof_tl_stack.get_or_make_raw()
191 s.c_value = unique_id
192 s.c_kind = VMPROF_CODE_TAG
193 vmprof_tl_stack.setraw(s)
194 return s
195
196 def leave_code(s):
197 if not we_are_translated():
198 assert vmprof_tl_stack.getraw() == s
199 vmprof_tl_stack.setraw(s.c_next)
200 lltype.free(s, flavor='raw')
201
202 #
203 # JIT notes:
204 #
205 # - When running JIT-generated assembler code, we have different custom
206 # code to build the VMPROFSTACK, so the functions above are not used.
207 # (It uses kind == VMPROF_JITTED_TAG and the VMPROFSTACK is allocated
208 # in the C stack.)
209 #
210 # - The jitcode for decorated_jitted_function() in rvmprof.py is
211 # special-cased by jtransform.py to produce this:
212 #
213 # rvmprof_code(0, unique_id)
214 # res = inline_call FUNC <- for func(*args)
215 # rvmprof_code(1, unique_id)
216 # return res
217 #
218 # There is no 'catch_exception', but the second 'rvmprof_code' is
219 # meant to be executed even in case there was an exception. This is
220 # done by a special case in pyjitpl.py and blackhole.py. The point
221 # is that the above simple pattern can be detected by the blackhole
222 # interp, when it first rebuilds all the intermediate RPython
223 # frames; at that point it needs to call jit_rvmprof_code(0) on all
224 # intermediate RPython frames, so it does pattern matching to
225 # recognize when it must call that and with which 'unique_id' value.
226 #
227 # - The jitcode opcode 'rvmprof_code' doesn't produce any resop. When
228 # meta-interpreting, it causes pyjitpl to call jit_rvmprof_code().
229 # As mentioned above, there is logic to call jit_rvmprof_code(1)
230 # even if we exit with an exception, even though there is no
231 # 'catch_exception'. There is similar logic inside the blackhole
232 # interpreter.
233
234
235 def jit_rvmprof_code(leaving, unique_id):
236 if leaving == 0:
237 enter_code(unique_id) # ignore the return value
238 else:
239 s = vmprof_tl_stack.getraw()
240 if s.c_value == unique_id and s.c_kind == VMPROF_CODE_TAG:
241 leave_code(s)
242 else:
243 # this is a HACK! in some strange situations related to stack
244 # overflows we end up in a situation where the stack is not
245 # properly popped somewhere, so we end up with an extra entry.
246 # instead of crashing with an assertion error (which was done
247 # previously) try to fix the situation by popping of the stack
248 # twice. if that also gives the wrong unique_id we still crash with
249 # an assert.
250
251 # the test that found this problem is test_recursive_pickle in
252 # python3 test_functools.py
253 assert (s.c_next and s.c_next.c_value == unique_id and
254 s.c_next.c_kind == VMPROF_CODE_TAG)
255 s = vmprof_tl_stack.getraw()
256 leave_code(s)
257 s = vmprof_tl_stack.getraw()
258 leave_code(s)
259
260 #
261 # traceback support
262
263 def get_rvmprof_stack():
264 return vmprof_tl_stack.get_or_make_raw()