Skip to content
Myr

debug.py

This file

Path

src/jinja2/debug.py

268 lines · 8.3 KiB · Python

Last changed by

Merge pull request #1163 from pallets/traceback-32-bitDavid Lordbefore adoptione1b5e50

History of this file

Take it

1import sys2from types import CodeType34from . import TemplateSyntaxError5from ._compat import PYPY6from .utils import internal_code7from .utils import missing8910def rewrite_traceback_stack(source=None):11    """Rewrite the current exception to replace any tracebacks from12    within compiled template code with tracebacks that look like they13    came from the template source.1415    This must be called within an ``except`` block.1617    :param exc_info: A :meth:`sys.exc_info` tuple. If not provided,18        the current ``exc_info`` is used.19    :param source: For ``TemplateSyntaxError``, the original source if20        known.21    :return: A :meth:`sys.exc_info` tuple that can be re-raised.22    """23    exc_type, exc_value, tb = sys.exc_info()2425    if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:26        exc_value.translated = True27        exc_value.source = source2829        try:30            # Remove the old traceback on Python 3, otherwise the frames31            # from the compiler still show up.32            exc_value.with_traceback(None)33        except AttributeError:34            pass3536        # Outside of runtime, so the frame isn't executing template37        # code, but it still needs to point at the template.38        tb = fake_traceback(39            exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno40        )41    else:42        # Skip the frame for the render function.43        tb = tb.tb_next4445    stack = []4647    # Build the stack of traceback object, replacing any in template48    # code with the source file and line information.49    while tb is not None:50        # Skip frames decorated with @internalcode. These are internal51        # calls that aren't useful in template debugging output.52        if tb.tb_frame.f_code in internal_code:53            tb = tb.tb_next54            continue5556        template = tb.tb_frame.f_globals.get("__jinja_template__")5758        if template is not None:59            lineno = template.get_corresponding_lineno(tb.tb_lineno)60            fake_tb = fake_traceback(exc_value, tb, template.filename, lineno)61            stack.append(fake_tb)62        else:63            stack.append(tb)6465        tb = tb.tb_next6667    tb_next = None6869    # Assign tb_next in reverse to avoid circular references.70    for tb in reversed(stack):71        tb_next = tb_set_next(tb, tb_next)7273    return exc_type, exc_value, tb_next747576def fake_traceback(exc_value, tb, filename, lineno):77    """Produce a new traceback object that looks like it came from the78    template source instead of the compiled code. The filename, line79    number, and location name will point to the template, and the local80    variables will be the current template context.8182    :param exc_value: The original exception to be re-raised to create83        the new traceback.84    :param tb: The original traceback to get the local variables and85        code info from.86    :param filename: The template filename.87    :param lineno: The line number in the template source.88    """89    if tb is not None:90        # Replace the real locals with the context that would be91        # available at that point in the template.92        locals = get_template_locals(tb.tb_frame.f_locals)93        locals.pop("__jinja_exception__", None)94    else:95        locals = {}9697    globals = {98        "__name__": filename,99        "__file__": filename,100        "__jinja_exception__": exc_value,101    }102    # Raise an exception at the correct line number.103    code = compile("\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec")104105    # Build a new code object that points to the template file and106    # replaces the location with a block name.107    try:108        location = "template"109110        if tb is not None:111            function = tb.tb_frame.f_code.co_name112113            if function == "root":114                location = "top-level template code"115            elif function.startswith("block_"):116                location = 'block "%s"' % function[6:]117118        # Collect arguments for the new code object. CodeType only119        # accepts positional arguments, and arguments were inserted in120        # new Python versions.121        code_args = []122123        for attr in (124            "argcount",125            "posonlyargcount",  # Python 3.8126            "kwonlyargcount",  # Python 3127            "nlocals",128            "stacksize",129            "flags",130            "code",  # codestring131            "consts",  # constants132            "names",133            "varnames",134            ("filename", filename),135            ("name", location),136            "firstlineno",137            "lnotab",138            "freevars",139            "cellvars",140        ):141            if isinstance(attr, tuple):142                # Replace with given value.143                code_args.append(attr[1])144                continue145146            try:147                # Copy original value if it exists.148                code_args.append(getattr(code, "co_" + attr))149            except AttributeError:150                # Some arguments were added later.151                continue152153        code = CodeType(*code_args)154    except Exception:155        # Some environments such as Google App Engine don't support156        # modifying code objects.157        pass158159    # Execute the new code, which is guaranteed to raise, and return160    # the new traceback without this frame.161    try:162        exec(code, globals, locals)163    except BaseException:164        return sys.exc_info()[2].tb_next165166167def get_template_locals(real_locals):168    """Based on the runtime locals, get the context that would be169    available at that point in the template.170    """171    # Start with the current template context.172    ctx = real_locals.get("context")173174    if ctx:175        data = ctx.get_all().copy()176    else:177        data = {}178179    # Might be in a derived context that only sets local variables180    # rather than pushing a context. Local variables follow the scheme181    # l_depth_name. Find the highest-depth local that has a value for182    # each name.183    local_overrides = {}184185    for name, value in real_locals.items():186        if not name.startswith("l_") or value is missing:187            # Not a template variable, or no longer relevant.188            continue189190        try:191            _, depth, name = name.split("_", 2)192            depth = int(depth)193        except ValueError:194            continue195196        cur_depth = local_overrides.get(name, (-1,))[0]197198        if cur_depth < depth:199            local_overrides[name] = (depth, value)200201    # Modify the context with any derived context.202    for name, (_, value) in local_overrides.items():203        if value is missing:204            data.pop(name, None)205        else:206            data[name] = value207208    return data209210211if sys.version_info >= (3, 7):212    # tb_next is directly assignable as of Python 3.7213    def tb_set_next(tb, tb_next):214        tb.tb_next = tb_next215        return tb216217218elif PYPY:219    # PyPy might have special support, and won't work with ctypes.220    try:221        import tputil222    except ImportError:223        # Without tproxy support, use the original traceback.224        def tb_set_next(tb, tb_next):225            return tb226227    else:228        # With tproxy support, create a proxy around the traceback that229        # returns the new tb_next.230        def tb_set_next(tb, tb_next):231            def controller(op):232                if op.opname == "__getattribute__" and op.args[0] == "tb_next":233                    return tb_next234235                return op.delegate()236237            return tputil.make_proxy(controller, obj=tb)238239240else:241    # Use ctypes to assign tb_next at the C level since it's read-only242    # from Python.243    import ctypes244245    class _CTraceback(ctypes.Structure):246        _fields_ = [247            # Extra PyObject slots when compiled with Py_TRACE_REFS.248            ("PyObject_HEAD", ctypes.c_byte * object().__sizeof__()),249            # Only care about tb_next as an object, not a traceback.250            ("tb_next", ctypes.py_object),251        ]252253    def tb_set_next(tb, tb_next):254        c_tb = _CTraceback.from_address(id(tb))255256        # Clear out the old tb_next.257        if tb.tb_next is not None:258            c_tb_next = ctypes.py_object(tb.tb_next)259            c_tb.tb_next = ctypes.py_object()260            ctypes.pythonapi.Py_DecRef(c_tb_next)261262        # Assign the new tb_next.263        if tb_next is not None:264            c_tb_next = ctypes.py_object(tb_next)265            ctypes.pythonapi.Py_IncRef(c_tb_next)266            c_tb.tb_next = c_tb_next267268        return tb