From 594897146984087b4d3546974050b906de41d47f Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Thu, 17 Sep 2026 15:12:56 +0530 Subject: [PATCH] Core: Shadow a @bpfglobal with a local when a write has no global statement Assigning a global's name without declaring it `global` was a compile error. Python makes it a local instead: the name is local for the whole function body, the global keeps its value, and only a `global` statement writes through to it. Do that, so the same program means the same thing in Python and in BPF. Python's scoping is function-wide and static, which the compiler gets for free: allocation runs as a pre-pass over the whole body, so a name bound anywhere is in local_sym_tab before the first statement is lowered, and reads resolve local-first. What does not come for free is the read above the binding, which Python answers with UnboundLocalError rather than the global's value. There is no runtime here in which to raise that, so the local records where its binding ends and a read above it is rejected, with the message Python would have given. Silence there would load an uninitialised stack slot through a name the author expected to be the global. `counter += 1` without `global counter` stays an error for the same reason: it binds a local and reads it in the same statement. Only its message changes, from a shadowing refusal to the UnboundLocalError it actually is. Co-Authored-By: Claude Opus 5 (1M context) --- pythonbpf/allocation_pass.py | 22 +++++++++++++------ pythonbpf/expr/expr_pass.py | 9 +++++--- pythonbpf/functions/functions_pass.py | 13 ++++++++++-- pythonbpf/symbols.py | 27 ++++++++++++++++++++++++ tests/failing_tests/globals_shadowing.py | 26 ----------------------- 5 files changed, 60 insertions(+), 37 deletions(-) delete mode 100644 tests/failing_tests/globals_shadowing.py diff --git a/pythonbpf/allocation_pass.py b/pythonbpf/allocation_pass.py index e89d658..ee37fc2 100644 --- a/pythonbpf/allocation_pass.py +++ b/pythonbpf/allocation_pass.py @@ -56,12 +56,14 @@ def handle_assign_allocation(compilation_context, builder, stmt, local_sym_tab): logger.debug(f"'{var_name}' already bound, no allocation needed") continue - # Not declared `global`, yet named like one: in real Python this would - # create a shadowing local. Refuse rather than guess which was meant. - if var_name in compilation_context.bpf_globals: - raise SyntaxError( - f"assignment to '{var_name}' shadows the BPF global of the same " - f"name — add 'global {var_name}' to write to it" + # Not declared `global`, yet named like one: Python creates a local + # that shadows the global for the whole function body, and leaves the + # global untouched. Do the same. + shadows_global = var_name in compilation_context.bpf_globals + if shadows_global: + logger.info( + f"'{var_name}' is assigned without a 'global' declaration, so it " + f"is a local shadowing the @bpfglobal of the same name" ) # Determine type and allocate based on rval @@ -86,6 +88,14 @@ def handle_assign_allocation(compilation_context, builder, stmt, local_sym_tab): f"Unsupported assignment value type for {var_name}: {type(rval).__name__}" ) + if shadows_global and var_name in local_sym_tab: + # Where the binding ends, so that a read above it is reported the + # way Python reports it. end_lineno, not lineno, so a read on a + # continuation line of a multi-line binding counts as above it too. + local_sym_tab[var_name].shadows_global_from = ( + getattr(stmt, "end_lineno", None) or target.lineno + ) + def _allocate_for_call(builder, var_name, rval, local_sym_tab, compilation_context): """Allocate memory for variable assigned from a call.""" diff --git a/pythonbpf/expr/expr_pass.py b/pythonbpf/expr/expr_pass.py index 48d5abc..1441034 100644 --- a/pythonbpf/expr/expr_pass.py +++ b/pythonbpf/expr/expr_pass.py @@ -28,9 +28,12 @@ def _handle_name_expr( ): """Handle ast.Name expressions.""" if expr.id in local_sym_tab: - var = local_sym_tab[expr.id].var - val = builder.load(var) - return val, local_sym_tab[expr.id].ir_type + sym = local_sym_tab[expr.id] + # A local that shadows a @bpfglobal is unreadable above its binding, + # exactly as in Python; for every other local this is a no-op. + sym.check_bound_at(expr.id, expr.lineno) + val = builder.load(sym.var) + return val, sym.ir_type elif expr.id in compilation_context.bpf_globals: # A @bpfglobal sym = compilation_context.bpf_globals[expr.id] diff --git a/pythonbpf/functions/functions_pass.py b/pythonbpf/functions/functions_pass.py index 1982957..7f0d124 100644 --- a/pythonbpf/functions/functions_pass.py +++ b/pythonbpf/functions/functions_pass.py @@ -208,6 +208,8 @@ def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab): # One table: a declared global is a local_sym_tab entry whose slot is # the GlobalVariable, so it needs no separate branch. if name in local_sym_tab: + # `x += v` reads x first, so it needs x to be bound already. + local_sym_tab[name].check_bound_at(name, stmt.lineno) slot = local_sym_tab[name].var slot_type = local_sym_tab[name].ir_type if slot is None: @@ -215,9 +217,16 @@ def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab): f"cannot assign to '{name}': it is the context parameter" ) elif name in compilation_context.bpf_globals: + # Binding x anywhere in the body makes it local throughout, so this + # statement reads an unbound local rather than the global. Python + # raises UnboundLocalError; there is no runtime here in which to do + # that, so the program is rejected. raise SyntaxError( - f"augmented assignment to '{name}' shadows the BPF global of " - f"the same name — add 'global {name}' to write to it" + f"local variable '{name}' referenced before assignment: " + f"'{name} += ...' binds '{name}' as a local, which shadows the " + f"@bpfglobal of the same name, and reads it in the same " + f"statement (Python raises UnboundLocalError here). Add " + f"'global {name}' to update the global." ) else: raise SyntaxError(f"augmented assignment to undefined variable '{name}'") diff --git a/pythonbpf/symbols.py b/pythonbpf/symbols.py index b6a8bd6..b942be6 100644 --- a/pythonbpf/symbols.py +++ b/pythonbpf/symbols.py @@ -30,10 +30,37 @@ class LocalSymbol(Symbol): `declared_global` marks a name bound by a `global` statement: its var is the @bpfglobal's GlobalVariable rather than an alloca. + + `shadows_global_from` is set when this local's name is also the name of a + @bpfglobal and the function did not declare it `global`: Python makes such + a name a local for the whole body, shadowing the global, and the value is + the line where its first binding ends. """ metadata: Any = None declared_global: bool = False + shadows_global_from: int | None = None + + def check_bound_at(self, name: str, lineno: int) -> None: + """Raise if `name` is read at `lineno` before its first binding. + + Python's scoping is function-wide and static: assigning a name anywhere + in a body makes it local everywhere in that body, so a read above the + assignment is an UnboundLocalError rather than a read of the global. + There is no runtime in which to raise that, so a program in this shape + is rejected at compile time. The check applies only to locals that + shadow a @bpfglobal, where staying silent would otherwise load an + uninitialised slot from a name the author expected to be the global. + """ + if self.shadows_global_from is None or lineno > self.shadows_global_from: + return + raise SyntaxError( + f"local variable '{name}' referenced before assignment: the " + f"assignment on line {self.shadows_global_from} makes '{name}' a " + f"local that shadows the @bpfglobal of the same name (Python " + f"raises UnboundLocalError here). Add 'global {name}' if you meant " + f"the global." + ) def __iter__(self): # Three fields on purpose: several call sites tuple-unpack a symbol. diff --git a/tests/failing_tests/globals_shadowing.py b/tests/failing_tests/globals_shadowing.py deleted file mode 100644 index 87e5827..0000000 --- a/tests/failing_tests/globals_shadowing.py +++ /dev/null @@ -1,26 +0,0 @@ -# Writing a global's name without `global` must be a loud compile error, not a -# silently-created shadowing local (real Python) or a silent global store. -from pythonbpf import bpf, section, bpfglobal, compile -from ctypes import c_void_p, c_int64, c_uint64 - - -@bpf -@bpfglobal -def counter() -> c_uint64: - return c_uint64(0) - - -@bpf -@section("tracepoint/raw_syscalls/sys_enter") -def prog(ctx: c_void_p) -> c_int64: - counter = 1 # noqa: F841 -- missing `global counter` on purpose - return c_int64(0) - - -@bpf -@bpfglobal -def LICENSE() -> str: - return "GPL" - - -compile()