Skip to content

fix: iteration block hook injection [backport 2.21] #13801

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 2.21
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions ddtrace/internal/injection.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from typing import Tuple # noqa:F401

from bytecode import Bytecode
from bytecode import Instr

from ddtrace.internal.assembly import Assembly

Expand Down Expand Up @@ -109,6 +110,11 @@ def _inject_hook(code: Bytecode, hook: HookType, lineno: int, arg: Any) -> None:
raise InvalidLine("Line %d does not exist or is either blank or a comment" % lineno)

for i in locs:
if isinstance(instr := code[i], Instr) and instr.name.startswith("END_"):
# This is the end of a block, e.g. a for loop. We have already
# instrumented the block on entry, so we skip instrumenting the
# end as well.
continue
code[i:i] = INJECTION_ASSEMBLY.bind(dict(hook=hook, arg=arg), lineno=lineno)


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
fixes:
- |
dynamic instrumentation: fixed an issue with the instrumentation of the
first line of an iteration block (e.g. for loops) that could have caused
undefined behavior.
15 changes: 15 additions & 0 deletions tests/internal/test_injection.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,18 @@ def test_finally():
f()

hook.assert_called_once_with(arg)


def test_for_block():
def for_loop():
a = []
for i in range(10):
a.append(i)
return a

hook, arg = mock.Mock(), mock.Mock()

with injected_hook(for_loop, hook, arg, line=for_loop.__code__.co_firstlineno + 2):
for_loop()

hook.assert_called_once_with(arg)