| 1 |
import sys |
| 2 |
from pypy.interpreter.error import OperationError |
| 3 |
from rpython.rlib.unroll import unrolling_iterable |
| 4 |
from rpython.rlib.objectmodel import specialize, not_rpython |
| 5 |
from rpython.rlib import jit, rgc, objectmodel |
| 6 |
from rpython.rlib.rarithmetic import r_uint |
| 7 |
|
| 8 |
TICK_COUNTER_STEP = 100 |
| 9 |
|
| 10 |
def app_profile_call(space, w_callable, frame, event, w_arg): |
| 11 |
|
| 12 |
frame = jit.hint(frame, access_directly=False) |
| 13 |
space.call_function(w_callable, |
| 14 |
frame, |
| 15 |
space.newtext(event), w_arg) |
| 16 |
|
| 17 |
class ExecutionContext(object): |
| 18 |
"""An ExecutionContext holds the state of an execution thread |
| 19 |
in the Python interpreter.""" |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
_immutable_fields_ = [ |
| 30 |
'profilefunc?', 'w_tracefunc?', |
| 31 |
'w_asyncgen_firstiter_fn?', 'w_asyncgen_finalizer_fn?'] |
| 32 |
|
| 33 |
def __init__(self, space): |
| 34 |
self.space = space |
| 35 |
self.topframeref = jit.vref_None |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
self.sys_exc_operror = None |
| 40 |
self.w_tracefunc = None |
| 41 |
self.is_tracing = 0 |
| 42 |
self.compiler = space.createcompiler() |
| 43 |
self.profilefunc = None |
| 44 |
self.w_profilefuncarg = None |
| 45 |
self.thread_disappeared = False |
| 46 |
|
| 47 |
|
| 48 |
self.w_async_exception_type = None |
| 49 |
|
| 50 |
self.w_asyncgen_firstiter_fn = None |
| 51 |
self.w_asyncgen_finalizer_fn = None |
| 52 |
self.contextvar_context = None |
| 53 |
self.coroutine_origin_tracking_depth = 0 |
| 54 |
|
| 55 |
self.current_gen_or_coroutine = None |
| 56 |
|
| 57 |
@staticmethod |
| 58 |
def _mark_thread_disappeared(space): |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
me = space.getexecutioncontext() |
| 63 |
for ec in space.threadlocals.getallvalues().values(): |
| 64 |
if ec is not me: |
| 65 |
ec.thread_disappeared = True |
| 66 |
|
| 67 |
def gettopframe(self): |
| 68 |
return self.topframeref() |
| 69 |
|
| 70 |
@jit.unroll_safe |
| 71 |
def gettopframe_nohidden(self): |
| 72 |
frame = self.topframeref() |
| 73 |
while frame and frame.hide(): |
| 74 |
frame = frame.f_backref() |
| 75 |
return frame |
| 76 |
|
| 77 |
@staticmethod |
| 78 |
@jit.unroll_safe |
| 79 |
def getnextframe_nohidden(frame): |
| 80 |
frame = frame.f_backref() |
| 81 |
while frame and frame.hide(): |
| 82 |
frame = frame.f_backref() |
| 83 |
return frame |
| 84 |
|
| 85 |
def enter(self, frame): |
| 86 |
if self.space.reverse_debugging: |
| 87 |
self._revdb_enter(frame) |
| 88 |
frame.f_backref = self.topframeref |
| 89 |
self.topframeref = jit.virtual_ref(frame) |
| 90 |
|
| 91 |
def leave(self, frame, w_exitvalue, got_exception): |
| 92 |
try: |
| 93 |
if self.profilefunc: |
| 94 |
self._trace(frame, 'leaveframe', w_exitvalue) |
| 95 |
finally: |
| 96 |
frame_vref = self.topframeref |
| 97 |
self.topframeref = frame.f_backref |
| 98 |
if frame.escaped or got_exception: |
| 99 |
|
| 100 |
|
| 101 |
f_back = frame.f_backref() |
| 102 |
if f_back: |
| 103 |
f_back.mark_as_escaped() |
| 104 |
|
| 105 |
|
| 106 |
frame_vref() |
| 107 |
jit.virtual_ref_finish(frame_vref, frame) |
| 108 |
if self.space.reverse_debugging: |
| 109 |
self._revdb_leave(got_exception) |
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
def c_call_trace(self, frame, w_func, args=None): |
| 114 |
"Profile the call of a builtin function" |
| 115 |
self._c_call_return_trace(frame, w_func, args, 'c_call') |
| 116 |
|
| 117 |
def c_return_trace(self, frame, w_func, args=None): |
| 118 |
"Profile the return from a builtin function" |
| 119 |
self._c_call_return_trace(frame, w_func, args, 'c_return') |
| 120 |
|
| 121 |
def _c_call_return_trace(self, frame, w_func, args, event): |
| 122 |
if self.profilefunc is None: |
| 123 |
frame.getorcreatedebug().is_being_profiled = False |
| 124 |
else: |
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
from pypy.interpreter.function import FunctionWithFixedCode |
| 129 |
if isinstance(w_func, FunctionWithFixedCode) and args is not None: |
| 130 |
w_firstarg = args.firstarg() |
| 131 |
if w_firstarg is not None: |
| 132 |
from pypy.interpreter.gateway import descr_function_get |
| 133 |
w_func = descr_function_get(self.space, w_func, w_firstarg, |
| 134 |
self.space.type(w_firstarg)) |
| 135 |
|
| 136 |
self._trace(frame, event, w_func) |
| 137 |
|
| 138 |
def c_exception_trace(self, frame, w_exc): |
| 139 |
"Profile function called upon OperationError." |
| 140 |
if self.profilefunc is None: |
| 141 |
frame.getorcreatedebug().is_being_profiled = False |
| 142 |
else: |
| 143 |
self._trace(frame, 'c_exception', w_exc) |
| 144 |
|
| 145 |
def call_trace(self, frame): |
| 146 |
"Trace the call of a function" |
| 147 |
if self.gettrace() is not None or self.profilefunc is not None: |
| 148 |
self._trace(frame, 'call', self.space.w_None) |
| 149 |
if self.profilefunc: |
| 150 |
frame.getorcreatedebug().is_being_profiled = True |
| 151 |
|
| 152 |
def return_trace(self, frame, w_retval): |
| 153 |
"Trace the return from a function" |
| 154 |
if self.gettrace() is not None: |
| 155 |
self._trace(frame, 'return', w_retval) |
| 156 |
|
| 157 |
@objectmodel.always_inline |
| 158 |
def bytecode_trace(self, frame, decr_by=TICK_COUNTER_STEP): |
| 159 |
"Trace function called before each bytecode." |
| 160 |
|
| 161 |
|
| 162 |
self.bytecode_only_trace(frame) |
| 163 |
actionflag = self.space.actionflag |
| 164 |
if actionflag.decrement_ticker(decr_by) < 0: |
| 165 |
actionflag.action_dispatcher(self, frame) |
| 166 |
|
| 167 |
def _run_finalizers_now(self): |
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
self.space.actionflag.action_dispatcher(self, None) |
| 172 |
|
| 173 |
@objectmodel.always_inline |
| 174 |
def bytecode_only_trace(self, frame): |
| 175 |
""" |
| 176 |
Like bytecode_trace() but doesn't invoke any other events besides the |
| 177 |
trace function. |
| 178 |
""" |
| 179 |
if self.space.reverse_debugging: |
| 180 |
self._revdb_potential_stop_point(frame) |
| 181 |
if (frame.get_w_f_trace() is None or self.is_tracing or |
| 182 |
self.gettrace() is None): |
| 183 |
return |
| 184 |
self.run_trace_func(frame) |
| 185 |
|
| 186 |
@jit.unroll_safe |
| 187 |
def run_trace_func(self, frame): |
| 188 |
code = frame.getcode() |
| 189 |
d = frame.getorcreatedebug() |
| 190 |
lastline = d.f_lineno |
| 191 |
lineno = frame.pycode._get_lineno_for_pc_tracing(frame.last_instr) |
| 192 |
if lineno != -1: |
| 193 |
d.f_lineno = lineno |
| 194 |
if d.f_trace_lines and lineno != -1: |
| 195 |
|
| 196 |
|
| 197 |
if lastline != lineno or frame.last_instr < d.instr_prev_plus_one: |
| 198 |
self._trace(frame, 'line', self.space.w_None) |
| 199 |
if d.f_trace_opcodes: |
| 200 |
self._trace(frame, 'opcode', self.space.w_None) |
| 201 |
d.instr_prev_plus_one = frame.last_instr + 1 |
| 202 |
|
| 203 |
@objectmodel.try_inline |
| 204 |
def bytecode_trace_after_exception(self, frame): |
| 205 |
"Like bytecode_trace(), but without increasing the ticker." |
| 206 |
actionflag = self.space.actionflag |
| 207 |
self.bytecode_only_trace(frame) |
| 208 |
if actionflag.get_ticker() < 0: |
| 209 |
actionflag.action_dispatcher(self, frame) |
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
def exception_trace(self, frame, operationerr): |
| 215 |
"Trace function called upon OperationError." |
| 216 |
if self.gettrace() is not None: |
| 217 |
self._trace(frame, 'exception', None, operationerr) |
| 218 |
|
| 219 |
def sys_exc_info(self): |
| 220 |
"""Implements sys.exc_info(). |
| 221 |
Return an OperationError instance or None. |
| 222 |
Returns the "top-most" exception in the stack. |
| 223 |
|
| 224 |
# NOTE: the result is not the wrapped sys.exc_info() !!! |
| 225 |
|
| 226 |
""" |
| 227 |
operr = self.sys_exc_operror |
| 228 |
if operr is not None: |
| 229 |
return operr |
| 230 |
if self.current_gen_or_coroutine: |
| 231 |
return self._get_topmost_exception() |
| 232 |
return None |
| 233 |
|
| 234 |
def current_exception(self): |
| 235 |
return self.sys_exc_operror |
| 236 |
|
| 237 |
def set_sys_exc_info(self, operror): |
| 238 |
self.sys_exc_operror = operror |
| 239 |
|
| 240 |
def set_sys_exc_info3(self, w_value): |
| 241 |
from pypy.interpreter import pytraceback |
| 242 |
from pypy.module.exceptions.interp_exceptions import W_BaseException |
| 243 |
|
| 244 |
space = self.space |
| 245 |
if space.is_none(w_value): |
| 246 |
self.sys_exc_operror = None |
| 247 |
return |
| 248 |
w_value = space.interp_w(W_BaseException, w_value) |
| 249 |
w_type = space.type(w_value) |
| 250 |
tb = w_value.w_traceback |
| 251 |
operror = OperationError(w_type, w_value, tb) |
| 252 |
self.set_sys_exc_info(operror) |
| 253 |
|
| 254 |
def push_gen_or_coroutine(self, gen): |
| 255 |
current_operr = self.sys_exc_operror |
| 256 |
self.set_sys_exc_info(gen.saved_operr) |
| 257 |
gen.saved_operr = current_operr |
| 258 |
gen.previous_gen_or_coroutine = self.current_gen_or_coroutine |
| 259 |
self.current_gen_or_coroutine = gen |
| 260 |
|
| 261 |
def pop_gen_or_coroutine(self, gen): |
| 262 |
assert self.current_gen_or_coroutine is gen |
| 263 |
saved_operr = gen.saved_operr |
| 264 |
self.current_gen_or_coroutine = gen.previous_gen_or_coroutine |
| 265 |
gen.previous_gen_or_coroutine = None |
| 266 |
gen.saved_operr = self.sys_exc_operror |
| 267 |
self.sys_exc_operror = saved_operr |
| 268 |
|
| 269 |
def save_and_reset_exc_info_state(self): |
| 270 |
res = self.sys_exc_operror, self.current_gen_or_coroutine |
| 271 |
self.sys_exc_operror = None |
| 272 |
self.current_gen_or_coroutine = None |
| 273 |
return res |
| 274 |
|
| 275 |
def restore_save_exc_info_state(self, state): |
| 276 |
self.sys_exc_operror, self.current_gen_or_coroutine = state |
| 277 |
|
| 278 |
def _get_topmost_exception(self): |
| 279 |
gen = self.current_gen_or_coroutine |
| 280 |
while gen: |
| 281 |
if gen.saved_operr: |
| 282 |
return gen.saved_operr |
| 283 |
gen = gen.previous_gen_or_coroutine |
| 284 |
return None |
| 285 |
|
| 286 |
|
| 287 |
@jit.dont_look_inside |
| 288 |
def settrace(self, w_func): |
| 289 |
"""Set the global trace function.""" |
| 290 |
|
| 291 |
if self.space.is_w(w_func, self.space.w_None): |
| 292 |
self.w_tracefunc = None |
| 293 |
else: |
| 294 |
self.force_all_frames() |
| 295 |
self.w_tracefunc = w_func |
| 296 |
|
| 297 |
|
| 298 |
jit.set_param(None, 'trace_limit', 10000) |
| 299 |
|
| 300 |
def gettrace(self): |
| 301 |
return jit.promote(self.w_tracefunc) |
| 302 |
|
| 303 |
def setprofile(self, w_func): |
| 304 |
"""Set the global trace function.""" |
| 305 |
|
| 306 |
if self.space.is_w(w_func, self.space.w_None): |
| 307 |
self.profilefunc = None |
| 308 |
self.w_profilefuncarg = None |
| 309 |
else: |
| 310 |
self.setllprofile(app_profile_call, w_func) |
| 311 |
|
| 312 |
def getprofile(self): |
| 313 |
return self.w_profilefuncarg |
| 314 |
|
| 315 |
def setllprofile(self, func, w_arg): |
| 316 |
if func is not None: |
| 317 |
if w_arg is None: |
| 318 |
raise ValueError("Cannot call setllprofile with real None") |
| 319 |
self.force_all_frames(is_being_profiled=True) |
| 320 |
self.profilefunc = func |
| 321 |
self.w_profilefuncarg = w_arg |
| 322 |
|
| 323 |
def force_all_frames(self, is_being_profiled=False): |
| 324 |
|
| 325 |
|
| 326 |
|
| 327 |
|
| 328 |
|
| 329 |
|
| 330 |
|
| 331 |
|
| 332 |
frame = self.gettopframe_nohidden() |
| 333 |
while frame: |
| 334 |
if is_being_profiled: |
| 335 |
frame.getorcreatedebug().is_being_profiled = True |
| 336 |
frame = self.getnextframe_nohidden(frame) |
| 337 |
|
| 338 |
def call_tracing(self, w_func, w_args): |
| 339 |
is_tracing = self.is_tracing |
| 340 |
self.is_tracing = 0 |
| 341 |
try: |
| 342 |
return self.space.call(w_func, w_args) |
| 343 |
finally: |
| 344 |
self.is_tracing = is_tracing |
| 345 |
|
| 346 |
def _trace(self, frame, event, w_arg, operr=None): |
| 347 |
if self.is_tracing or frame.hide(): |
| 348 |
return |
| 349 |
|
| 350 |
space = self.space |
| 351 |
|
| 352 |
|
| 353 |
if event == 'call': |
| 354 |
w_callback = self.gettrace() |
| 355 |
else: |
| 356 |
w_callback = frame.get_w_f_trace() |
| 357 |
|
| 358 |
if w_callback is not None and event != "leaveframe": |
| 359 |
if operr is not None: |
| 360 |
w_value = operr.normalize_exception(space) |
| 361 |
w_arg = space.newtuple([operr.w_type, w_value, |
| 362 |
operr.get_w_traceback(space)]) |
| 363 |
|
| 364 |
lineno = frame.pycode._get_lineno_for_pc_tracing(frame.last_instr) |
| 365 |
if frame.last_instr >= 1: |
| 366 |
init_lineno = lineno |
| 367 |
else: |
| 368 |
init_lineno = -1 |
| 369 |
d = frame.getorcreatedebug(init_lineno=init_lineno) |
| 370 |
if d.w_locals is not None: |
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
frame.fast2locals() |
| 375 |
prev_line_tracing = d.is_in_line_tracing |
| 376 |
self.is_tracing += 1 |
| 377 |
old_lineno = d.f_lineno |
| 378 |
try: |
| 379 |
if event == 'line': |
| 380 |
d.is_in_line_tracing = True |
| 381 |
try: |
| 382 |
d.f_lineno = lineno |
| 383 |
|
| 384 |
frame = jit.hint(frame, access_directly=False) |
| 385 |
w_result = space.call_function(w_callback, frame, space.newtext(event), w_arg) |
| 386 |
if space.is_w(w_result, space.w_None): |
| 387 |
|
| 388 |
|
| 389 |
pass |
| 390 |
else: |
| 391 |
d.w_f_trace = w_result |
| 392 |
except: |
| 393 |
self.settrace(space.w_None) |
| 394 |
d.w_f_trace = None |
| 395 |
raise |
| 396 |
finally: |
| 397 |
if d.f_lineno == lineno: |
| 398 |
|
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
|
| 403 |
if event != 'call' or frame.last_instr < 0: |
| 404 |
d.f_lineno = old_lineno |
| 405 |
self.is_tracing -= 1 |
| 406 |
d.is_in_line_tracing = prev_line_tracing |
| 407 |
if d.w_locals is not None: |
| 408 |
frame.locals2fast() |
| 409 |
|
| 410 |
|
| 411 |
if self.profilefunc is not None: |
| 412 |
if not (event == 'leaveframe' or |
| 413 |
event == 'call' or |
| 414 |
event == 'c_call' or |
| 415 |
event == 'c_return' or |
| 416 |
event == 'c_exception'): |
| 417 |
return |
| 418 |
|
| 419 |
if event == 'leaveframe': |
| 420 |
event = 'return' |
| 421 |
|
| 422 |
assert self.is_tracing == 0 |
| 423 |
self.is_tracing += 1 |
| 424 |
try: |
| 425 |
try: |
| 426 |
self.profilefunc(space, self.w_profilefuncarg, |
| 427 |
frame, event, w_arg) |
| 428 |
except: |
| 429 |
self.profilefunc = None |
| 430 |
self.w_profilefuncarg = None |
| 431 |
raise |
| 432 |
|
| 433 |
finally: |
| 434 |
self.is_tracing -= 1 |
| 435 |
|
| 436 |
def checksignals(self): |
| 437 |
"""Similar to PyErr_CheckSignals(). If called in the main thread, |
| 438 |
and if signals are pending for the process, deliver them now |
| 439 |
(i.e. call the signal handlers).""" |
| 440 |
if self.space.check_signal_action is not None: |
| 441 |
self.space.check_signal_action.perform(self, None) |
| 442 |
|
| 443 |
def _revdb_enter(self, frame): |
| 444 |
|
| 445 |
from pypy.interpreter.reverse_debugging import enter_call |
| 446 |
enter_call(self.topframeref(), frame) |
| 447 |
|
| 448 |
def _revdb_leave(self, got_exception): |
| 449 |
|
| 450 |
from pypy.interpreter.reverse_debugging import leave_call |
| 451 |
leave_call(self.topframeref(), got_exception) |
| 452 |
|
| 453 |
def _revdb_potential_stop_point(self, frame): |
| 454 |
|
| 455 |
from pypy.interpreter.reverse_debugging import potential_stop_point |
| 456 |
potential_stop_point(frame) |
| 457 |
|
| 458 |
def _freeze_(self): |
| 459 |
raise Exception("ExecutionContext instances should not be seen during" |
| 460 |
" translation. Now is a good time to inspect the" |
| 461 |
" traceback and see where this one comes from :-)") |
| 462 |
|
| 463 |
|
| 464 |
class AbstractActionFlag(object): |
| 465 |
"""This holds in an integer the 'ticker'. If threads are enabled, |
| 466 |
it is decremented at each bytecode; when it reaches zero, we release |
| 467 |
the GIL. And whether we have threads or not, it is forced to zero |
| 468 |
whenever we fire any of the asynchronous actions. |
| 469 |
""" |
| 470 |
|
| 471 |
_immutable_fields_ = ["checkinterval_scaled?"] |
| 472 |
|
| 473 |
def __init__(self): |
| 474 |
self._periodic_actions = [] |
| 475 |
self._nonperiodic_actions = [] |
| 476 |
|
| 477 |
|
| 478 |
self._fired_bitmask = r_uint(0) |
| 479 |
|
| 480 |
self.has_bytecode_counter = False |
| 481 |
|
| 482 |
|
| 483 |
|
| 484 |
|
| 485 |
self.checkinterval_scaled = 10000 * TICK_COUNTER_STEP |
| 486 |
self._rebuild_action_dispatcher() |
| 487 |
|
| 488 |
def fire(self, action): |
| 489 |
"""Request for the action to be run before the next opcode.""" |
| 490 |
assert action._action_index >= 0 |
| 491 |
mask = r_uint(1) << action._action_index |
| 492 |
if not self._fired_bitmask & mask: |
| 493 |
self._fired_bitmask |= mask |
| 494 |
|
| 495 |
|
| 496 |
self.reset_ticker(-1) |
| 497 |
|
| 498 |
@not_rpython |
| 499 |
def register_periodic_action(self, action, use_bytecode_counter): |
| 500 |
""" |
| 501 |
Register the PeriodicAsyncAction action to be called whenever the |
| 502 |
tick counter becomes smaller than 0. If 'use_bytecode_counter' is |
| 503 |
True, make sure that we decrease the tick counter at every bytecode. |
| 504 |
This is needed for threads. Note that 'use_bytecode_counter' can be |
| 505 |
False for signal handling, because whenever the process receives a |
| 506 |
signal, the tick counter is set to -1 by C code in signals.h. |
| 507 |
""" |
| 508 |
assert isinstance(action, PeriodicAsyncAction) |
| 509 |
|
| 510 |
|
| 511 |
if use_bytecode_counter: |
| 512 |
self._periodic_actions.append(action) |
| 513 |
self.has_bytecode_counter = True |
| 514 |
else: |
| 515 |
self._periodic_actions.insert(0, action) |
| 516 |
self._rebuild_action_dispatcher() |
| 517 |
|
| 518 |
@not_rpython |
| 519 |
def register_nonperiodic_action(self, action): |
| 520 |
self._nonperiodic_actions.append(action) |
| 521 |
assert len(self._nonperiodic_actions) < 32 |
| 522 |
self._rebuild_action_dispatcher() |
| 523 |
return len(self._nonperiodic_actions) - 1 |
| 524 |
|
| 525 |
def getcheckinterval(self): |
| 526 |
return self.checkinterval_scaled // TICK_COUNTER_STEP |
| 527 |
|
| 528 |
def setcheckinterval(self, interval): |
| 529 |
MAX = sys.maxint // TICK_COUNTER_STEP |
| 530 |
if interval < 1: |
| 531 |
interval = 1 |
| 532 |
elif interval > MAX: |
| 533 |
interval = MAX |
| 534 |
self.checkinterval_scaled = interval * TICK_COUNTER_STEP |
| 535 |
self.reset_ticker(-1) |
| 536 |
|
| 537 |
def _rebuild_action_dispatcher(self): |
| 538 |
periodic_actions = unrolling_iterable(self._periodic_actions) |
| 539 |
|
| 540 |
@jit.unroll_safe |
| 541 |
@objectmodel.dont_inline |
| 542 |
def action_dispatcher(ec, frame): |
| 543 |
|
| 544 |
self.reset_ticker(self.checkinterval_scaled) |
| 545 |
for action in periodic_actions: |
| 546 |
action.perform(ec, frame) |
| 547 |
|
| 548 |
|
| 549 |
if self._fired_bitmask: |
| 550 |
|
| 551 |
|
| 552 |
|
| 553 |
|
| 554 |
|
| 555 |
|
| 556 |
|
| 557 |
for i in range(len(self._nonperiodic_actions)): |
| 558 |
mask = r_uint(1) << i |
| 559 |
if self._fired_bitmask & mask: |
| 560 |
action = self._nonperiodic_actions[i] |
| 561 |
self._fired_bitmask &= ~mask |
| 562 |
action.perform(ec, frame) |
| 563 |
|
| 564 |
|
| 565 |
|
| 566 |
if self._fired_bitmask: |
| 567 |
self.reset_ticker(-1) |
| 568 |
|
| 569 |
self.action_dispatcher = action_dispatcher |
| 570 |
|
| 571 |
|
| 572 |
class ActionFlag(AbstractActionFlag): |
| 573 |
"""The normal class for space.actionflag. The signal module provides |
| 574 |
a different one.""" |
| 575 |
_ticker = 0 |
| 576 |
|
| 577 |
def get_ticker(self): |
| 578 |
return self._ticker |
| 579 |
|
| 580 |
def reset_ticker(self, value): |
| 581 |
self._ticker = value |
| 582 |
|
| 583 |
def decrement_ticker(self, by): |
| 584 |
value = self._ticker |
| 585 |
if self.has_bytecode_counter: |
| 586 |
if jit.isconstant(by) and by == 0: |
| 587 |
pass |
| 588 |
else: |
| 589 |
value -= by |
| 590 |
self._ticker = value |
| 591 |
return value |
| 592 |
|
| 593 |
|
| 594 |
class AsyncAction(object): |
| 595 |
"""Abstract base class for actions that must be performed |
| 596 |
asynchronously with regular bytecode execution, but that still need |
| 597 |
to occur between two opcodes, not at a completely random time. |
| 598 |
""" |
| 599 |
|
| 600 |
@not_rpython |
| 601 |
def __init__(self, space): |
| 602 |
self.space = space |
| 603 |
if not isinstance(self, PeriodicAsyncAction): |
| 604 |
self._action_index = self.space.actionflag.register_nonperiodic_action(self) |
| 605 |
else: |
| 606 |
self._action_index = -1 |
| 607 |
|
| 608 |
@rgc.no_collect |
| 609 |
def fire(self): |
| 610 |
"""Request for the action to be run before the next opcode. |
| 611 |
The action must have been registered at space initalization time.""" |
| 612 |
self.space.actionflag.fire(self) |
| 613 |
|
| 614 |
def perform(self, executioncontext, frame): |
| 615 |
"""To be overridden.""" |
| 616 |
|
| 617 |
|
| 618 |
class PeriodicAsyncAction(AsyncAction): |
| 619 |
"""Abstract base class for actions that occur automatically |
| 620 |
every sys.checkinterval bytecodes. |
| 621 |
""" |
| 622 |
|
| 623 |
|
| 624 |
class UserDelAction(AsyncAction): |
| 625 |
"""An action that invokes all pending app-level __del__() method. |
| 626 |
This is done as an action instead of immediately when the |
| 627 |
WRootFinalizerQueue is triggered, because the latter can occur more |
| 628 |
or less anywhere in the middle of code that might not be happy with |
| 629 |
random app-level code mutating data structures under its feet. |
| 630 |
""" |
| 631 |
|
| 632 |
def __init__(self, space): |
| 633 |
AsyncAction.__init__(self, space) |
| 634 |
self.finalizers_lock_count = 0 |
| 635 |
self.enabled_at_app_level = True |
| 636 |
self.pending_with_disabled_del = None |
| 637 |
|
| 638 |
def perform(self, executioncontext, frame): |
| 639 |
self._run_finalizers() |
| 640 |
|
| 641 |
@jit.dont_look_inside |
| 642 |
def _run_finalizers(self): |
| 643 |
|
| 644 |
|
| 645 |
while True: |
| 646 |
w_obj = self.space.finalizer_queue.next_dead() |
| 647 |
if w_obj is None: |
| 648 |
break |
| 649 |
self._call_finalizer(w_obj) |
| 650 |
|
| 651 |
def gc_disabled(self, w_obj): |
| 652 |
|
| 653 |
|
| 654 |
|
| 655 |
|
| 656 |
|
| 657 |
|
| 658 |
|
| 659 |
|
| 660 |
|
| 661 |
|
| 662 |
pdd = self.pending_with_disabled_del |
| 663 |
if pdd is None: |
| 664 |
return False |
| 665 |
else: |
| 666 |
pdd.append(w_obj) |
| 667 |
return True |
| 668 |
|
| 669 |
def _call_finalizer(self, w_obj): |
| 670 |
|
| 671 |
w_obj.clear_all_weakrefs() |
| 672 |
|
| 673 |
|
| 674 |
space = self.space |
| 675 |
if w_obj.typedef is None: |
| 676 |
w_del = None |
| 677 |
else: |
| 678 |
w_del = space.lookup(w_obj, '__del__') |
| 679 |
if w_del is not None: |
| 680 |
if self.gc_disabled(w_obj): |
| 681 |
return |
| 682 |
try: |
| 683 |
w_impl = space.get(w_del, w_obj) |
| 684 |
except Exception as e: |
| 685 |
report_error(space, e, "method __del__ of ", w_obj) |
| 686 |
else: |
| 687 |
try: |
| 688 |
space.call_function(w_impl) |
| 689 |
except Exception as e: |
| 690 |
report_error(space, e, '', w_del) |
| 691 |
|
| 692 |
|
| 693 |
try: |
| 694 |
w_obj._finalize_() |
| 695 |
except Exception as e: |
| 696 |
report_error(space, e, "finalizer of ", w_obj) |
| 697 |
|
| 698 |
|
| 699 |
def report_error(space, e, where, w_obj): |
| 700 |
if isinstance(e, OperationError): |
| 701 |
e.write_unraisable(space, where, w_obj) |
| 702 |
e.clear(space) |
| 703 |
else: |
| 704 |
addrstring = w_obj.getaddrstring(space) |
| 705 |
msg = ("RPython exception %s in %s<%s at 0x%s> ignored\n" % ( |
| 706 |
str(e), where, space.type(w_obj).name, addrstring)) |
| 707 |
space.call_method(space.sys.get('stderr'), 'write', |
| 708 |
space.newtext(msg)) |
| 709 |
|
| 710 |
|
| 711 |
def make_finalizer_queue(W_Root, space): |
| 712 |
"""Make a FinalizerQueue subclass which responds to GC finalizer |
| 713 |
events by 'firing' the UserDelAction class above. It does not |
| 714 |
directly fetches the objects to finalize at all; they stay in the |
| 715 |
GC-managed queue, and will only be fetched by UserDelAction |
| 716 |
(between bytecodes).""" |
| 717 |
|
| 718 |
class WRootFinalizerQueue(rgc.FinalizerQueue): |
| 719 |
Class = W_Root |
| 720 |
|
| 721 |
def finalizer_trigger(self): |
| 722 |
space.user_del_action.fire() |
| 723 |
|
| 724 |
space.user_del_action = UserDelAction(space) |
| 725 |
space.finalizer_queue = WRootFinalizerQueue() |