You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

280 lines
9.0KB

  1. import platform
  2. import sys
  3. import typing as t
  4. from types import CodeType
  5. from types import TracebackType
  6. from .exceptions import TemplateSyntaxError
  7. from .utils import internal_code
  8. from .utils import missing
  9. if t.TYPE_CHECKING:
  10. from .runtime import Context
  11. def rewrite_traceback_stack(source: t.Optional[str] = None) -> BaseException:
  12. """Rewrite the current exception to replace any tracebacks from
  13. within compiled template code with tracebacks that look like they
  14. came from the template source.
  15. This must be called within an ``except`` block.
  16. :param source: For ``TemplateSyntaxError``, the original source if
  17. known.
  18. :return: The original exception with the rewritten traceback.
  19. """
  20. _, exc_value, tb = sys.exc_info()
  21. exc_value = t.cast(BaseException, exc_value)
  22. tb = t.cast(TracebackType, tb)
  23. if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:
  24. exc_value.translated = True
  25. exc_value.source = source
  26. # Remove the old traceback, otherwise the frames from the
  27. # compiler still show up.
  28. exc_value.with_traceback(None)
  29. # Outside of runtime, so the frame isn't executing template
  30. # code, but it still needs to point at the template.
  31. tb = fake_traceback(
  32. exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno
  33. )
  34. else:
  35. # Skip the frame for the render function.
  36. tb = tb.tb_next
  37. stack = []
  38. # Build the stack of traceback object, replacing any in template
  39. # code with the source file and line information.
  40. while tb is not None:
  41. # Skip frames decorated with @internalcode. These are internal
  42. # calls that aren't useful in template debugging output.
  43. if tb.tb_frame.f_code in internal_code:
  44. tb = tb.tb_next
  45. continue
  46. template = tb.tb_frame.f_globals.get("__jinja_template__")
  47. if template is not None:
  48. lineno = template.get_corresponding_lineno(tb.tb_lineno)
  49. fake_tb = fake_traceback(exc_value, tb, template.filename, lineno)
  50. stack.append(fake_tb)
  51. else:
  52. stack.append(tb)
  53. tb = tb.tb_next
  54. tb_next = None
  55. # Assign tb_next in reverse to avoid circular references.
  56. for tb in reversed(stack):
  57. tb_next = tb_set_next(tb, tb_next)
  58. return exc_value.with_traceback(tb_next)
  59. def fake_traceback( # type: ignore
  60. exc_value: BaseException, tb: t.Optional[TracebackType], filename: str, lineno: int
  61. ) -> TracebackType:
  62. """Produce a new traceback object that looks like it came from the
  63. template source instead of the compiled code. The filename, line
  64. number, and location name will point to the template, and the local
  65. variables will be the current template context.
  66. :param exc_value: The original exception to be re-raised to create
  67. the new traceback.
  68. :param tb: The original traceback to get the local variables and
  69. code info from.
  70. :param filename: The template filename.
  71. :param lineno: The line number in the template source.
  72. """
  73. if tb is not None:
  74. # Replace the real locals with the context that would be
  75. # available at that point in the template.
  76. locals = get_template_locals(tb.tb_frame.f_locals)
  77. locals.pop("__jinja_exception__", None)
  78. else:
  79. locals = {}
  80. globals = {
  81. "__name__": filename,
  82. "__file__": filename,
  83. "__jinja_exception__": exc_value,
  84. }
  85. # Raise an exception at the correct line number.
  86. code = compile("\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec")
  87. # Build a new code object that points to the template file and
  88. # replaces the location with a block name.
  89. try:
  90. location = "template"
  91. if tb is not None:
  92. function = tb.tb_frame.f_code.co_name
  93. if function == "root":
  94. location = "top-level template code"
  95. elif function.startswith("block_"):
  96. location = f"block {function[6:]!r}"
  97. # Collect arguments for the new code object. CodeType only
  98. # accepts positional arguments, and arguments were inserted in
  99. # new Python versions.
  100. code_args = []
  101. for attr in (
  102. "argcount",
  103. "posonlyargcount", # Python 3.8
  104. "kwonlyargcount",
  105. "nlocals",
  106. "stacksize",
  107. "flags",
  108. "code", # codestring
  109. "consts", # constants
  110. "names",
  111. "varnames",
  112. ("filename", filename),
  113. ("name", location),
  114. "firstlineno",
  115. "lnotab",
  116. "freevars",
  117. "cellvars",
  118. "linetable", # Python 3.10
  119. ):
  120. if isinstance(attr, tuple):
  121. # Replace with given value.
  122. code_args.append(attr[1])
  123. continue
  124. try:
  125. # Copy original value if it exists.
  126. code_args.append(getattr(code, "co_" + t.cast(str, attr)))
  127. except AttributeError:
  128. # Some arguments were added later.
  129. continue
  130. code = CodeType(*code_args)
  131. except Exception:
  132. # Some environments such as Google App Engine don't support
  133. # modifying code objects.
  134. pass
  135. # Execute the new code, which is guaranteed to raise, and return
  136. # the new traceback without this frame.
  137. try:
  138. exec(code, globals, locals)
  139. except BaseException:
  140. return sys.exc_info()[2].tb_next # type: ignore
  141. def get_template_locals(real_locals: t.Mapping[str, t.Any]) -> t.Dict[str, t.Any]:
  142. """Based on the runtime locals, get the context that would be
  143. available at that point in the template.
  144. """
  145. # Start with the current template context.
  146. ctx: "t.Optional[Context]" = real_locals.get("context")
  147. if ctx is not None:
  148. data: t.Dict[str, t.Any] = ctx.get_all().copy()
  149. else:
  150. data = {}
  151. # Might be in a derived context that only sets local variables
  152. # rather than pushing a context. Local variables follow the scheme
  153. # l_depth_name. Find the highest-depth local that has a value for
  154. # each name.
  155. local_overrides: t.Dict[str, t.Tuple[int, t.Any]] = {}
  156. for name, value in real_locals.items():
  157. if not name.startswith("l_") or value is missing:
  158. # Not a template variable, or no longer relevant.
  159. continue
  160. try:
  161. _, depth_str, name = name.split("_", 2)
  162. depth = int(depth_str)
  163. except ValueError:
  164. continue
  165. cur_depth = local_overrides.get(name, (-1,))[0]
  166. if cur_depth < depth:
  167. local_overrides[name] = (depth, value)
  168. # Modify the context with any derived context.
  169. for name, (_, value) in local_overrides.items():
  170. if value is missing:
  171. data.pop(name, None)
  172. else:
  173. data[name] = value
  174. return data
  175. if sys.version_info >= (3, 7):
  176. # tb_next is directly assignable as of Python 3.7
  177. def tb_set_next(
  178. tb: TracebackType, tb_next: t.Optional[TracebackType]
  179. ) -> TracebackType:
  180. tb.tb_next = tb_next
  181. return tb
  182. elif platform.python_implementation() == "PyPy":
  183. # PyPy might have special support, and won't work with ctypes.
  184. try:
  185. import tputil # type: ignore
  186. except ImportError:
  187. # Without tproxy support, use the original traceback.
  188. def tb_set_next(
  189. tb: TracebackType, tb_next: t.Optional[TracebackType]
  190. ) -> TracebackType:
  191. return tb
  192. else:
  193. # With tproxy support, create a proxy around the traceback that
  194. # returns the new tb_next.
  195. def tb_set_next(
  196. tb: TracebackType, tb_next: t.Optional[TracebackType]
  197. ) -> TracebackType:
  198. def controller(op): # type: ignore
  199. if op.opname == "__getattribute__" and op.args[0] == "tb_next":
  200. return tb_next
  201. return op.delegate()
  202. return tputil.make_proxy(controller, obj=tb) # type: ignore
  203. else:
  204. # Use ctypes to assign tb_next at the C level since it's read-only
  205. # from Python.
  206. import ctypes
  207. class _CTraceback(ctypes.Structure):
  208. _fields_ = [
  209. # Extra PyObject slots when compiled with Py_TRACE_REFS.
  210. ("PyObject_HEAD", ctypes.c_byte * object().__sizeof__()),
  211. # Only care about tb_next as an object, not a traceback.
  212. ("tb_next", ctypes.py_object),
  213. ]
  214. def tb_set_next(
  215. tb: TracebackType, tb_next: t.Optional[TracebackType]
  216. ) -> TracebackType:
  217. c_tb = _CTraceback.from_address(id(tb))
  218. # Clear out the old tb_next.
  219. if tb.tb_next is not None:
  220. c_tb_next = ctypes.py_object(tb.tb_next)
  221. c_tb.tb_next = ctypes.py_object()
  222. ctypes.pythonapi.Py_DecRef(c_tb_next)
  223. # Assign the new tb_next.
  224. if tb_next is not None:
  225. c_tb_next = ctypes.py_object(tb_next)
  226. ctypes.pythonapi.Py_IncRef(c_tb_next)
  227. c_tb.tb_next = c_tb_next
  228. return tb