Debian Codegraph @

pypy/module/sys/vm.py

raw symbols SCIP
1 """
2 Implementation of interpreter-level 'sys' routines.
3 """
4
5 from rpython.rlib import jit
6 from rpython.rlib.rutf8 import MAXUNICODE
7 from rpython.rlib import debug
8 from rpython.rlib import objectmodel
9
10 from pypy.interpreter import gateway
11 from pypy.interpreter.error import oefmt, OperationError
12 from pypy.interpreter.gateway import unwrap_spec, WrappedDefault
13
14
15 # ____________________________________________________________
16
17 app_hookargs = gateway.applevel("""
18 from _structseq import structseqtype, structseqfield
19 class UnraisableHookArgs(metaclass=structseqtype):
20 exc_type = structseqfield(0, "Exception type")
21 exc_value = structseqfield(1, "Exception value")
22 exc_traceback = structseqfield(2, "Exception traceback")
23 err_msg = structseqfield(3, "Error message")
24 object = structseqfield(4, "Object causing the exception")
25 extra_line = structseqfield(6, "Extra error lines that is PyPy specific")
26 """)
27
28 @unwrap_spec(depth=int)
29 def _getframe(space, depth=0):
30 """Return a frame object from the call stack. If optional integer depth is
31 given, return the frame object that many calls below the top of the stack.
32 If that is deeper than the call stack, ValueError is raised. The default
33 for depth is zero, returning the frame at the top of the call stack.
34
35 This function should be used for internal and specialized
36 purposes only."""
37 if depth < 0:
38 raise oefmt(space.w_ValueError, "frame index must not be negative")
39 return getframe(space, depth)
40
41
42 @jit.look_inside_iff(lambda space, depth: jit.isconstant(depth))
43 def getframe(space, depth):
44 ec = space.getexecutioncontext()
45 f = ec.gettopframe_nohidden()
46 while True:
47 if f is None:
48 raise oefmt(space.w_ValueError, "call stack is not deep enough")
49 if depth == 0:
50 f.mark_as_escaped()
51 audit(space, "sys._getframe", [f])
52 return f
53 depth -= 1
54 f = ec.getnextframe_nohidden(f)
55
56
57 def _stack_check_noinline():
58 from rpython.rlib.rstack import stack_check
59 stack_check()
60 _stack_check_noinline._dont_inline_ = True
61
62 @jit.dont_look_inside
63 @unwrap_spec(new_limit="c_int")
64 def setrecursionlimit(space, new_limit):
65 """setrecursionlimit() sets the maximum number of nested calls that
66 can occur before a RecursionError is raised. On PyPy the limit
67 is approximative and checked at a lower level. The default 1000
68 reserves 768KB of stack space, which should suffice (on Linux,
69 depending on the compiler settings) for ~1400 calls. Setting the
70 value to N reserves N/1000 times 768KB of stack space.
71
72 Note that there are other factors that also limit the stack size.
73 The operating system typically sets a maximum which can be changed
74 manually (e.g. with "ulimit" on Linux) for the main thread. For other
75 threads you can configure the limit by calling "threading.stack_size()".
76 """
77 from rpython.rlib.rstack import _stack_set_length_fraction
78 from rpython.rlib.rstackovf import StackOverflow
79 from rpython.rlib.rgc import increase_root_stack_depth
80 if new_limit <= 0:
81 raise oefmt(space.w_ValueError, "recursion limit must be positive")
82 # Some programs use very large values to mean "don't check, I want to
83 # use as much as possible and then segfault". Add a silent upper bound
84 # of 10**6 here, because huge values cause huge shadowstacks to be
85 # allocated (or MemoryErrors).
86 if new_limit > 1000000:
87 new_limit = 1000000
88 try:
89 _stack_set_length_fraction(new_limit * 0.001)
90 _stack_check_noinline()
91 except StackOverflow:
92 old_limit = space.sys.recursionlimit
93 _stack_set_length_fraction(old_limit * 0.001)
94 raise oefmt(space.w_RecursionError,
95 "cannot set the recursion limit to %s at the recursion depth: the limit is too low")
96 space.sys.recursionlimit = new_limit
97 increase_root_stack_depth(int(new_limit * 0.001 * 163840))
98
99 def getrecursionlimit(space):
100 """Return the last value set by setrecursionlimit().
101 """
102 return space.newint(space.sys.recursionlimit)
103
104 @unwrap_spec(interval=int)
105 def setcheckinterval(space, interval):
106 """Tell the Python interpreter to check for asynchronous events every
107 n instructions. This also affects how often thread switches occur."""
108 space.actionflag.setcheckinterval(interval)
109
110 def getcheckinterval(space):
111 """Return the current check interval; see setcheckinterval()."""
112 # xxx to make tests and possibly some obscure apps happy, if the
113 # checkinterval is set to the minimum possible value (which is 1) we
114 # return 0. The idea is that according to the CPython docs, <= 0
115 # means "check every virtual instruction, maximizing responsiveness
116 # as well as overhead".
117 result = space.actionflag.getcheckinterval()
118 if result <= 1:
119 result = 0
120 return space.newint(result)
121
122 @unwrap_spec(interval=float)
123 def setswitchinterval(space, interval):
124 """For CPython compatibility, this maps to
125 sys.setcheckinterval(interval * 2000000)
126 """
127 # The scaling factor is chosen so that with the default
128 # checkinterval value of 10000, it corresponds to 0.005, which is
129 # the default value of the switchinterval in CPython 3.5
130 if interval <= 0.0:
131 raise oefmt(space.w_ValueError,
132 "switch interval must be strictly positive")
133 space.actionflag.setcheckinterval(int(interval * 2000000.0))
134
135 def getswitchinterval(space):
136 """For CPython compatibility, this maps to
137 sys.getcheckinterval() / 2000000
138 """
139 return space.newfloat(space.actionflag.getcheckinterval() / 2000000.0)
140
141 def exc_info(space):
142 """Return the (type, value, traceback) of the most recent exception
143 caught by an except clause in the current stack frame or in an older stack
144 frame."""
145 return exc_info_with_tb(space) # indirection for the tests
146
147 def exc_info_with_tb(space):
148 operror = space.getexecutioncontext().sys_exc_info()
149 if operror is None:
150 return space.newtuple([space.w_None, space.w_None, space.w_None])
151 else:
152 return space.newtuple([operror.w_type, operror.get_w_value(space),
153 operror.get_w_traceback(space)])
154
155 def exc_info_without_tb(space, operror):
156 return space.newtuple([operror.w_type, operror.get_w_value(space),
157 space.w_None])
158
159 def exc_info_direct(space, frame):
160 from pypy.tool import stdlib_opcode
161 # In order to make the JIT happy, we try to return (exc, val, None)
162 # instead of (exc, val, tb). We can do that only if we recognize
163 # the following pattern in the bytecode:
164 # CALL_FUNCTION/CALL_METHOD <-- invoking me
165 # LOAD_CONST 0, 1, -2 or -3
166 # BINARY_SUBSCR
167 # or:
168 # CALL_FUNCTION/CALL_METHOD
169 # LOAD_CONST any integer or None
170 # LOAD_CONST <=2
171 # BUILD_SLICE 2
172 # BINARY_SUBSCR
173 need_all_three_args = True
174 co = frame.getcode().co_code
175 p = frame.last_instr
176 if (ord(co[p]) == stdlib_opcode.CALL_FUNCTION or
177 ord(co[p]) == stdlib_opcode.CALL_METHOD):
178 if ord(co[p + 2]) == stdlib_opcode.LOAD_CONST:
179 lo = ord(co[p + 3])
180 w_constant = frame.getconstant_w(lo)
181 if ord(co[p + 4]) == stdlib_opcode.BINARY_SUBSCR:
182 if space.isinstance_w(w_constant, space.w_int):
183 constant = space.int_w(w_constant)
184 if -3 <= constant <= 1 and constant != -1:
185 need_all_three_args = False
186 elif (ord(co[p + 4]) == stdlib_opcode.LOAD_CONST and
187 ord(co[p + 6]) == stdlib_opcode.BUILD_SLICE and
188 ord(co[p + 8]) == stdlib_opcode.BINARY_SUBSCR):
189 if (space.is_w(w_constant, space.w_None) or
190 space.isinstance_w(w_constant, space.w_int)):
191 lo = ord(co[p + 5])
192 w_constant = frame.getconstant_w(lo)
193 if space.isinstance_w(w_constant, space.w_int):
194 if space.int_w(w_constant) <= 2:
195 need_all_three_args = False
196 #
197 operror = space.getexecutioncontext().sys_exc_info()
198 if need_all_three_args or operror is None or frame.hide():
199 return exc_info_with_tb(space)
200 else:
201 return exc_info_without_tb(space, operror)
202
203 def exception(space):
204 """
205 Return the current exception.
206
207 Return the most recent exception caught by an except clause
208 in the current stack frame or in an older stack frame, or None
209 if no such exception exists.
210 """
211 ec = space.getexecutioncontext()
212 operror = ec.sys_exc_info()
213 if operror is None:
214 return space.w_None
215 return operror.get_w_value(space)
216
217 def settrace(space, w_func):
218 """Set the global debug tracing function. It will be called on each
219 function call. See the debugger chapter in the library manual."""
220 space.getexecutioncontext().settrace(w_func)
221
222 def gettrace(space):
223 """Return the global debug tracing function set with sys.settrace.
224 See the debugger chapter in the library manual."""
225 return space.getexecutioncontext().gettrace()
226
227 def setprofile(space, w_func):
228 """Set the profiling function. It will be called on each function call
229 and return. See the profiler chapter in the library manual."""
230 space.getexecutioncontext().setprofile(w_func)
231
232 def getprofile(space):
233 """Return the profiling function set with sys.setprofile.
234 See the profiler chapter in the library manual."""
235 w_func = space.getexecutioncontext().getprofile()
236 if w_func is not None:
237 return w_func
238 else:
239 return space.w_None
240
241 def call_tracing(space, w_func, w_args):
242 """Call func(*args), while tracing is enabled. The tracing state is
243 saved, and restored afterwards. This is intended to be called from
244 a debugger from a checkpoint, to recursively debug some other code."""
245 return space.getexecutioncontext().call_tracing(w_func, w_args)
246
247
248 app = gateway.applevel('''
249 "NOT_RPYTHON"
250 from _structseq import structseqtype, structseqfield
251
252 class windows_version_info(metaclass=structseqtype):
253
254 name = "sys.getwindowsversion"
255
256 major = structseqfield(0, "Major version number")
257 minor = structseqfield(1, "Minor version number")
258 build = structseqfield(2, "Build number")
259 platform = structseqfield(3, "Operating system platform")
260 service_pack = structseqfield(4, "Latest Service Pack installed on the system")
261
262 # Because the indices aren't consecutive, they aren't included when
263 # unpacking and other such operations.
264 service_pack_major = structseqfield(10, "Service Pack major version number")
265 service_pack_minor = structseqfield(11, "Service Pack minor version number")
266 suite_mask = structseqfield(12, "Bit mask identifying available product suites")
267 product_type = structseqfield(13, "System product type")
268 platform_version = structseqfield(14, "Diagnostic version number")
269
270
271 class asyncgen_hooks(metaclass=structseqtype):
272 name = "asyncgen_hooks"
273
274 firstiter = structseqfield(0)
275 finalizer = structseqfield(1)
276
277 ''')
278
279
280 def getwindowsversion(space):
281 from rpython.rlib import rwin32
282 info = rwin32.GetVersionEx()
283 w_windows_version_info = app.wget(space, "windows_version_info")
284 raw_version = space.newtuple([
285 space.newint(info[0]),
286 space.newint(info[1]),
287 space.newint(info[2]),
288 space.newint(info[3]),
289 space.newtext(info[4]),
290 space.newint(info[5]),
291 space.newint(info[6]),
292 space.newint(info[7]),
293 space.newint(info[8]),
294 # leave _platform_version empty, platform.py will use the main
295 # version numbers above.
296 space.w_None,
297 ])
298 return space.call_function(w_windows_version_info, raw_version)
299
300 @jit.dont_look_inside
301 def get_dllhandle(space):
302 if not space.config.objspace.usemodules.cpyext:
303 return space.newint(0)
304
305 return _get_dllhandle(space)
306
307 def _get_dllhandle(space):
308 # Retrieve cpyext api handle
309 from pypy.module.cpyext.api import State
310 handle = space.fromcache(State).get_pythonapi_handle()
311
312 # It used to be a CDLL
313 # from pypy.module._rawffi.interp_rawffi import W_CDLL
314 # from rpython.rlib.clibffi import RawCDLL
315 # cdll = RawCDLL(handle)
316 # return W_CDLL(space, "python api", cdll)
317 # Provide a cpython-compatible int
318 from rpython.rtyper.lltypesystem import lltype, rffi
319 return space.newint(rffi.cast(lltype.Signed, handle))
320
321 getsizeof_missing = """getsizeof(...)
322 getsizeof(object, default) -> int
323
324 Return the size of object in bytes.
325
326 sys.getsizeof(object, default) will always return default on PyPy, and
327 raise a TypeError if default is not provided.
328
329 First note that the CPython documentation says that this function may
330 raise a TypeError, so if you are seeing it, it means that the program
331 you are using is not correctly handling this case.
332
333 On PyPy, though, it always raises TypeError. Before looking for
334 alternatives, please take a moment to read the following explanation as
335 to why it is the case. What you are looking for may not be possible.
336
337 A memory profiler using this function is most likely to give results
338 inconsistent with reality on PyPy. It would be possible to have
339 sys.getsizeof() return a number (with enough work), but that may or
340 may not represent how much memory the object uses. It doesn't even
341 make really sense to ask how much *one* object uses, in isolation
342 with the rest of the system. For example, instances have maps,
343 which are often shared across many instances; in this case the maps
344 would probably be ignored by an implementation of sys.getsizeof(),
345 but their overhead is important in some cases if they are many
346 instances with unique maps. Conversely, equal strings may share
347 their internal string data even if they are different objects---or
348 empty containers may share parts of their internals as long as they
349 are empty. Even stranger, some lists create objects as you read
350 them; if you try to estimate the size in memory of range(10**6) as
351 the sum of all items' size, that operation will by itself create one
352 million integer objects that never existed in the first place.
353 """
354
355 def getsizeof(space, w_object, w_default=None):
356 if w_default is None:
357 raise oefmt(space.w_TypeError, getsizeof_missing)
358 return w_default
359
360 getsizeof.__doc__ = getsizeof_missing
361
362 def intern(space, w_str):
363 """``Intern'' the given string. This enters the string in the (global)
364 table of interned strings whose purpose is to speed up dictionary lookups.
365 Return the string itself or the previously interned string object with the
366 same value."""
367 if space.is_w(space.type(w_str), space.w_unicode):
368 return space.new_interned_w_str(w_str)
369 raise oefmt(space.w_TypeError, "intern() argument must be string.")
370
371 def get_asyncgen_hooks(space):
372 """get_asyncgen_hooks()
373
374 Return a namedtuple of installed asynchronous generators hooks (firstiter, finalizer)."""
375 ec = space.getexecutioncontext()
376 w_firstiter = ec.w_asyncgen_firstiter_fn
377 if w_firstiter is None:
378 w_firstiter = space.w_None
379 w_finalizer = ec.w_asyncgen_finalizer_fn
380 if w_finalizer is None:
381 w_finalizer = space.w_None
382 w_asyncgen_hooks = app.wget(space, "asyncgen_hooks")
383 return space.call_function(
384 w_asyncgen_hooks,
385 space.newtuple([w_firstiter, w_finalizer]))
386
387 # Note: the docstring is wrong on CPython
388 def set_asyncgen_hooks(space, w_firstiter=None, w_finalizer=None):
389 """set_asyncgen_hooks(firstiter=None, finalizer=None)
390
391 Set a finalizer for async generators objects."""
392 ec = space.getexecutioncontext()
393 if space.is_w(w_finalizer, space.w_None):
394 ec.w_asyncgen_finalizer_fn = None
395 elif w_finalizer is not None:
396 if space.callable_w(w_finalizer):
397 ec.w_asyncgen_finalizer_fn = w_finalizer
398 else:
399 raise oefmt(space.w_TypeError,
400 "callable finalizer expected, got %T", w_finalizer)
401 if space.is_w(w_firstiter, space.w_None):
402 ec.w_asyncgen_firstiter_fn = None
403 elif w_firstiter is not None:
404 if space.callable_w(w_firstiter):
405 ec.w_asyncgen_firstiter_fn = w_firstiter
406 else:
407 raise oefmt(space.w_TypeError,
408 "callable firstiter expected, got %T", w_firstiter)
409
410
411 def is_finalizing(space):
412 return space.newbool(space.sys.finalizing)
413
414 def get_coroutine_origin_tracking_depth(space):
415 """get_coroutine_origin_tracking_depth()
416 Check status of origin tracking for coroutine objects in this thread.
417 """
418 ec = space.getexecutioncontext()
419 return space.newint(ec.coroutine_origin_tracking_depth)
420
421 @unwrap_spec(depth=int)
422 def set_coroutine_origin_tracking_depth(space, depth):
423 """set_coroutine_origin_tracking_depth(depth)
424 Enable or disable origin tracking for coroutine objects in this thread.
425
426 Coroutine objects will track 'depth' frames of traceback information
427 about where they came from, available in their cr_origin attribute.
428
429 Set a depth of 0 to disable.
430 """
431 if depth < 0:
432 raise oefmt(space.w_ValueError,
433 "depth must be >= 0")
434 ec = space.getexecutioncontext()
435 ec.coroutine_origin_tracking_depth = depth
436
437
438 class AuditHolder(object):
439 _immutable_fields_ = ['hooks_w?[:]']
440
441 def __init__(self, space):
442 self.hooks_w = None
443 self.space = space
444
445 @objectmodel.dont_inline
446 @jit.unroll_safe
447 def trigger_audit_events(self, space, event, args_w):
448 w_event = space.newtext(event)
449 w_args = space.newtuple(args_w)
450 hooks_w = self.hooks_w
451 assert hooks_w is not None
452 ec = space.getexecutioncontext()
453 # don't trace audithooks by default
454 ec.is_tracing += 1
455 try:
456 for w_hook in hooks_w:
457 w_cantrace = space.findattr(w_hook, space.newtext("__cantrace__"))
458 if w_cantrace is None:
459 cantrace = False
460 else:
461 cantrace = space.is_true(w_cantrace)
462 if cantrace:
463 ec.is_tracing -= 1
464 try:
465 space.call_function(w_hook, w_event, w_args)
466 finally:
467 if cantrace:
468 ec.is_tracing += 1
469 finally:
470 ec.is_tracing -= 1
471
472
473 @unwrap_spec(event="text")
474 def audit(space, event, args_w):
475 """
476 audit(event, *args)
477
478 Passes the event to any audit hooks that are attached.
479 """
480 holder = space.fromcache(AuditHolder)
481 if holder.hooks_w is None:
482 return
483 holder.trigger_audit_events(space, event, args_w)
484
485
486 def addaudithook(space, w_hook):
487 """
488 addaudithook(hook)
489
490 Adds a new audit hook callback.
491 """
492 holder = space.fromcache(AuditHolder)
493 try:
494 audit(space, "sys.addaudithook", [])
495 except OperationError, e:
496 if not e.match(space, space.w_RuntimeError):
497 raise
498 # RuntimeError is ignored and we don't add the new hook
499 return
500 if holder.hooks_w is None:
501 holder.hooks_w = [w_hook]
502 debug.make_sure_not_resized(holder.hooks_w)
503 else:
504 holder.hooks_w = holder.hooks_w + [w_hook]
505
506
507
508 def unraisablehook(space, w_hookargs):
509 w_type = space.getattr(w_hookargs, space.newtext("exc_type"))
510 w_value = space.getattr(w_hookargs, space.newtext("exc_value"))
511 w_tb = space.getattr(w_hookargs, space.newtext("exc_traceback"))
512 err_msg = space.text_w(space.getattr(w_hookargs, space.newtext("err_msg")))
513 w_object = space.getattr(w_hookargs, space.newtext("object"))
514 extra_line = space.text_w(space.getattr(w_hookargs, space.newtext("extra_line")))
515 OperationError.write_unraisable_default(space, w_type, w_value, w_tb, err_msg, w_object, extra_line)
516
517
518 def _pypy_prepare_shutdown(space):
519 """ prepare for interpreter shutdown by calling atexit hooks and flushing
520 file descriptors. should only be called by pypy code. """
521 try:
522 return space.newint(space.finish())
523 except OperationError as e:
524 e.write_unraisable(space, 'interpreter shutdown')
525