pwnlib.atexception — Callbacks on unhandled exception

Analogous to atexit, this module allows the programmer to register functions to be run if an unhandled exception occurs.

pwnlib.atexception.register(func, *args, **kwargs)[source]

Registers a function to be called when an unhandled exception occurs. The function will be called with positional arguments args and keyword arguments kwargs, i.e. func(*args, **kwargs). The current context is recorded and will be the one used when the handler is run.

E.g. to suppress logging output from an exception-handler one could write:

with context.local(log_level = 'error'):
  atexception.register(handler)

An identifier is returned which can be used to unregister the exception-handler.

This function can be used as a decorator:

@atexception.register
def handler():
  ...

Notice however that this will bind handler to the identifier and not the actual exception-handler. The exception-handler can then be unregistered with:

ident = atexception.register(handler)
atexception.unregister(ident)

This function is thread safe.

>>> def handler(a, b):
...     print("Exception handler", a, b)
>>> ident = atexception.register(handler, 13, 37)
>>> raise Exception("Unexpected error")
Traceback (most recent call last):
...
Exception: Unexpected error
Exception handler 13 37
>>> atexception.unregister(ident)
>>> raise Exception("Unexpected error")
Traceback (most recent call last):
...
Exception: Unexpected error
pwnlib.atexception.unregister(ident)[source]

Remove the exception-handler identified by ident from the list of registered handlers. If ident isn’t registered this is a no-op.