Static analysis guidance for secure code generation by LLMsStatic Analysis Guidance for Secure LLM Code Generation
The authors propose Comment and Steering strategies for injecting static analysis warnings during the generation process; on RiskyPy, DeepSeek-V4.1-flash's Steering raised the functional-and-safe ratio from 52.5% to 64.4%, at 1.7 times the token cost.
Black-box setting: the defender runs a static analyzer (Semgrep/Bandit) during generation; when an alert appears, the code is rolled back and the alert is fed back to the model as a comment (Comment) or a user message (Steering), requiring no white-box access and applicable to API models; the victim system is the LLM generating unsafe code.
- LLM-generated code is often insecure; static analyzers are cheap and widespread, and their reports can serve as feedback signals; however, existing methods place analyzers in iterative repair loops, which is costly and cannot isolate the effect of reports on the model.
- The authors propose two black-box strategies, Comment and Steering: during generation, Semgrep is run on each line, and when an alert is triggered, the code is rolled back and the alert is given to the model as a code comment or a user message. Compared with PromSec, FDSP, Self-Refine and a no-guidance baseline on 3 models and 3 Python benchmarks, with safety measured by each benchmark's independent oracle.
- In-generation guidance is low-cost (0.9–1.9× tokens, iterative methods up to 24.1×). Only DeepSeek-V4.1-flash benefited: on RiskyPy, Steering raised the functional-and-safe proportion from 52.5% to 64.4%. On SecEvalPlus, analyzers flagged at most 5.6% of insecure programs; when warnings conflicted with the task, the model over-complied, removing the required network binding in 79/83 instances.
- The authors note: only two analyzers are tested, Python single-file, two model families, no agent scaffolding; API models are run only 3 times; Steering's fix suggestions introduce additional knowledge, a potential confound. The experiments cover 3 models, 3 benchmarks, 7 strategies, and only 11 rules ever triggered Steering.
- Evaluated models
- Qwen2.5-Coder-14B-InstructDeepSeek-V4.1-flashQwen2.5-72B-Instruct
- Benchmarks
- SecEvalPlusBaxBenchRiskyPy
- Metrics
- combined rate(功能且安全)功能通过率安全通过率analyzer flag raterecall/precision输出 token 倍数per-rule 结果(Solved/Broke/Silenced 等)
The paper proposes two strategies for providing static analysis findings to the model during generation: rolling back generation when the analyzer reports a warning, and inserting the findings as code comments (Comment) or user messages (Steering), compared against two iterative methods and a no-analyzer baseline on three models and three Python benchmarks. Generation-stage guidance uses 0.9 to 1.9 times the output tokens of the baseline, while the iterative methods reach up to 24.1 times; on RiskyPy, Steering raises the proportion of functionally correct and secure programs for DeepSeek-V4.1-flash from 52.5% to 64.4%, close to the best iterative method's 66.2%, while using less than one-fifth of its tokens. Per-rule analysis shows that rules with local fixes benefit most; on SecEvalPlus, the analyzer flags at most 5.6% of functionally correct but insecure programs, leaving limited room for guidance; when warnings conflict with the task, the model tends to follow the analyzer and break the program, and the two Qwen2.5 models often fail on fixes that require code restructuring.
Paper analysis
What problem does this paper attempt to solve?
Whether static analysis reports can serve as feedback signals for LLM secure code generation, and how to directly inject warnings at low cost during generation.
Core question: whether static analyzer alerts can effectively guide LLMs to generate safer code, and in what way alerts should be injected.
- Scenario and motivation: code written by LLMs is often unsafe; the authors state that even frontier models generate incorrect or exploitable backend applications; as generated code enters CI pipelines, automated safety checks and feeding results back to the model are needed.
- Shortcomings of existing methods: existing work (PromSec, FDSP) places static analyzers in an iterative repair loop, so alerts reach the model only through intermediate steps, which is costly and cannot isolate the effect of the report itself on generated code.
- Core observation: static analyzers are mature, cheap and widely deployed, and each alert is associated with a code line and a rule, making it convenient as feedback; but analyzers have many false positives and can only find local syntactic-level weaknesses, and whether they can serve as a feedback signal like unit tests and compiler errors is unclear.
- What the paper proposes: two black-box strategies, Comment and Steering, that inject alerts during generation, compared with iterative methods on three benchmarks spanning the "static-analysis alignment spectrum", with safety measured by an oracle independent of the guiding analyzer.
- Threat model:
- Goal: make LLM-generated code both functionally correct and safe (via each benchmark's safety oracle).
- Knowledge: black-box; the authors explicitly consider only black-box methods, also applicable to models provided via API.
- Capability: the defender runs the analyzer line by line during generation, and on alert rolls back the code and modifies the model input (comment or user message).
- Victim system: the LLM generating unsafe code (3 open-weight models).
What related research exists?
Related work is divided into two groups: static-analysis safety detection and feedback-guided code generation; the baselines are PromSec, FDSP, Self-Refine and a no-guidance baseline.
Static analysis for security (SAST)
- Bandit, Semgrep, CodeQL: Bandit builds a Python AST and runs security plugins; Semgrep uses declarative rules to match syntax and map to CWEs; CodeQL performs cross-function data-flow and taint analysis. This paper uses Semgrep (p/security-audit) and Bandit for guidance.
- Studies of analyzer limitations: Christakis and Bird (2016) and Johnson et al. (2013) note that static analysis has many false positives and developers tend to ignore them; Alecci et al. (2026) state that taint analyzers such as FlowDroid produce false positives and false negatives due to fixed source/sink lists; Firouzi and Ghafari (2026) report that Semgrep and CodeQL judgments often disagree with expert annotations.
Feedback-guided code generation
- Internal feedback: Self-Refine (Madaan et al., 2023) has the model self-criticize and revise, requiring no external tools but rewriting the whole program each round; Yan et al. (2025) report that self-generated prompts help only when the model follows instructions well, and weaker models benefit less.
- External feedback (analyzer-based): PromSec (Nazzal et al., 2024) uses a graph-guided GAN to perturb code representations and an LLM to rewrite, with Bandit only as objective and stopping condition, and the model never sees the report; FDSP (Alrashedy et al., 2024) gives Bandit reports to the model and proposes multiple candidate fixes. The paper notes that in both methods warnings pass through intermediate steps, so the effect of the reports cannot be isolated.
- Other paradigms: prefix control, instruction tuning, constrained decoding, etc. require white-box access and are excluded by this paper; methods that retrieve safety examples or secure coding guidelines (Patir et al., 2025; Saul et al., 2025) are also excluded because extra knowledge would confound the effect of analyzer feedback.
Baselines and benchmarks
- Baseline methods: PromSec, FDSP (and the authors' variant FDSP (Semgrep)), Self-Refine (analyzer-free control), and unguided Baseline.
- Benchmarks: SecEvalPlus (140 code synthesis tasks), BaxBench (84 Python backend tasks), RiskyPy (73 tasks).
Authors' positioning: this paper gives warnings directly to the model during generation with no intermediate steps, and claims this is the first systematic study spanning the alignment spectrum and measuring safety with an independent oracle (the authors say "to our knowledge, the first systematic study").
How does the paper address this problem?
Proposes Comment and Steering: run Semgrep line by line during generation, and on a triggered warning, roll back and inject the warning into code comments or the user message.
Overall approach: a harness runs the static analyzer line by line during generation; on alert it rolls back the generated code, places the alert directly into the model context, and continues generation, thereby isolating the effect of the alert itself. Comment and Steering are the two strategies proposed by the authors.
Problem setting and research questions
- RQ1 (scope): to what extent static analysis can assess the safety of LLM code (recall/precision as an upper bound on guidance).
- RQ2 (strategies): comparison of strategies on safety, functionality and cost.
- RQ3 (factors and failures): analysis of Steering's outcome per alert by model, rule and benchmark.
Comment: code-comment injection
- Intent comments as rollback points: the system prompt requires the model to write an intent comment of the form "# We will now ..." before each logical block, as a rollback location.
- Line-by-line analysis: Semgrep (p/security-audit ruleset) is run each time the model completes a line and the partial code is syntactically valid; on alert it stops and rolls back to the nearest intent comment before the flagged line; with multiple alerts, the earliest one in the code is taken.
- Injection method: a comment of the form "# I will avoid this issue: <message>" (containing the analyzer message) is inserted after the intent comment, generation continues from that point, and only code after the rollback point is regenerated.
Steering: user-message injection
- No code modification: on alert, the flagged line and all lines after it are deleted, and the alert is added to a dedicated area at the end of the user message (closest to the generated code), containing the rule identifier, CWE, analyzer message and the fix suggestion for that rule.
- Fix suggestions: before experiments, gpt-5.2-2025-12-11 generated them for each Python rule of p/security-audit; the prompt instructs the model to follow the suggestion only when it does not conflict with the task requirements.
- Rollback and stopping: when the same alert triggers again, roll back to the generation start (full rollback, letting the model revise early decisions); the dedicated area holds at most 2 alerts, with new alerts replacing the oldest; each sample rolls back at most 5 times; if a round repeats a previous prompt and code, it stops to prevent infinite loops.
Implementation and comparison settings
- Unified conditions: all strategies use the same harness, the same system prompt, greedy decoding (temperature 0), at most 5 rounds, and a maximum output of 4096 tokens.
- Analyzer configuration: Semgrep uses a frozen p/security-audit snapshot (225 rules), reporting ERROR and WARNING levels; Bandit reports medium level and above.
- Baseline adjustments: FDSP is implemented per the original authors with early stopping added, unparseable candidates discarded, and the candidate with the fewest alerts returned; an FDSP (Semgrep) variant separates the effects of analyzer and strategy. Because the authors did not release a trained generator, PromSec's gGAN is retrained per the original pipeline and hyperparameters, returning the highest-scoring round (the authors state this slightly favors PromSec).
Evaluation and result classification
- Independent oracle: SecEvalPlus uses functional/safety unit tests; BaxBench uses in-container functional tests and end-to-end exploits; RiskyPy uses an LLM review validated by human annotation (gpt-5.1-2025-11-13), avoiding the circularity of self-evaluation with the guiding analyzer.
- Per-rule result classification: each (sample × rule) pair of Steering is labeled Solved, Broke, Did nothing, Already broken, Silenced (alert cleared but still unsafe); the authors note that Broke and Silenced are upper bounds and Solved is a lower bound.
- Statistical tests: paired comparisons with the baseline use the exact McNemar test, the three rounds of API models use Cochran–Mantel–Haenszel stratification, with Holm correction within model × benchmark × metric.
What experiments did the paper conduct?
3 models × 3 benchmarks × 7 strategies; only DeepSeek-V4.1-flash benefited, analyzer coverage was narrow, and the model over-complied with conflicting warnings.
Experimental Setup
- Models tested: Qwen2.5-Coder-14B-Instruct (local), DeepSeek-V4.1-flash (official API), Qwen2.5-72B-Instruct (OpenRouter), 3 in total, from two families.
- Benchmarks: SecEvalPlus (140 code synthesis tasks, functional/security unit tests), BaxBench (84 Python single-file backend tasks, in-container functional tests + exploit), RiskyPy (73 tasks, covering 18 CWEs, LLM review).
- Strategies: Baseline (no guidance), Self-Refine, FDSP, FDSP (Semgrep), PromSec, Comment, Steering, 7 in total.
- Metrics: The main metric is combined rate (proportion of tasks that are both functional and secure); also functional rate, security rate, analyzer flag rate, recall/precision, output tokens and time multiplier.
- Review method: RiskyPy uses gpt-5.1-2025-11-13 (medium reasoning effort) to judge functionality and security; this reviewer was validated by two experts (8 and 7 years of experience) annotating 50 generated results: inter-annotator agreement 66.0% (κ=0.361), reviewer agreement with each annotator 74.0%/72.0%.
- Number of repetitions: Local model with deterministic output run 1 time; the two API models each run 3 times and averaged.
Main Results
According to Table 3 (RiskyPy, combined rate, i.e., Works + LLM safe, %):
Swipe horizontally to read the table
Method Qwen2.5-Coder-14B DeepSeek-V4.1-flash Qwen2.5-72B Baseline 31.5 52.5 34.7 Self-Refine 31.5 63.5 25.6 FDSP 27.4 66.2 30.6 FDSP (Semgrep) 27.4 61.6 30.1 PromSec 1.4 44.7 11.4 Comment (ours) 31.5 45.7 35.2 Steering (ours) 28.8 64.4 30.6 - Only DeepSeek-V4.1-flash benefits: Table 5 shows that on RiskyPy, Steering (+11.9 points), FDSP (+13.7), Self-Refine (+11.0) improve significantly relative to baseline; on SecEvalPlus, Steering and Comment reach 34.8%/34.3% (baseline 31.4%, Table 2) but not statistically significant; on BaxBench no strategy exceeds the baseline of 38.9%, and Steering drops to 28.6% (significant, Tables 4, 5).
- Neither Qwen model benefits: In Table 5 no strategy significantly improves their combined rate; PromSec is significantly negative for both Qwen models (−30.1 and −23.3 points).
- Authors' interpretation: The authors state that no strategy outperforms the baseline on all benchmarks, and that guidance is only effective for the most capable model and when the warning is consistent with the task; Self-Refine is close to Steering on DeepSeek, indicating that this portion of the gain does not depend on static analysis.
RQ1: Analyzer Coverage (Table 1)
- Recall on SecEvalPlus is extremely low: 62.0%–87.3% of functionally normal programs fail the security tests, but the analyzer flags only 4.2%–5.6% of them; the authors state that even with perfect fixing of all flagged weaknesses, over 94% of insecure programs remain unaddressed.
- Recall on RiskyPy is high but precision is low: recall 80.0%–93.8%, but the analyzer flags 75.5%–89.6% of all functional programs, and precision (47.6%–61.2%) improves by about 1.05 times relative to the insecure base rate; 39%–52% of flagged programs are judged secure.
- BaxBench: On DeepSeek, 38.6% of flagged applications are exploitable, versus 41.0% of all functional applications; the authors state that flags carry no exploitability information.
Cost (Table 6)
- Tokens: Comment and Steering are 0.9–1.9 times the baseline; FDSP is 1.9–2.3 times on SecEvalPlus and 4.9–9.8 times on BaxBench/RiskyPy; PromSec is up to 4.7–24.1 times; Self-Refine is 14.1–18.3 times on DeepSeek.
- Time: The DeepSeek baseline takes only 1.2–3.0 seconds per sample; the fixed overhead of line-by-line analysis makes Steering take 3.4–9.6 times as long, slower than FDSP (Semgrep) on all three benchmarks; the authors state that real-time guidance tokens are the cheapest, but with fast API models line-by-line analysis may offset the time advantage.
Per-rule and Overcompliance (Tables 7, 8)
- At the rule level: Only 11/225 rules ever triggered Steering. use-defused-xml (local replacement fix) is net positive on two models (DeepSeek +28.3, n=99; 72B +3.0, n=99); eval-detected is +63.6 on DeepSeek (n=33), and −31.6/−33.3 on the two Qwen models; subprocess-shell-true is negative on all three models.
- Overcompliance: BaxBench requires the service to listen on 0.0.0.0, while the Semgrep rule avoid_app_run_with_bad_host flags this binding; although the prompt requires task priority, only 4 of the 83 baseline-functional pairs retain the binding (79/83 removed), this rule is never resolved, and Broke accounts for 15.9%–25.9%.
- Analyzer criteria overestimate gains: On RiskyPy, the 4 analyzer-guidance strategies show significant improvement in 12/12 comparisons under the "functionally normal and unflagged by both analyzers" criterion (+12.3 to +48.4 points), but with an independent security oracle only 2/12 are significant (Table 5); the authors state that evaluating with the guiding analyzer itself exaggerates security gains.
Other Ablations and Analyses
- Model scale: Within the Qwen2.5 family, 14B→72B (5 times the parameters) does not change the result pattern; on RiskyPy, Solved is 1.5%/6.5% respectively, Broke 21.2%/16.9%, and DeepSeek is Solved 25.0%/Broke 5.5% (Section 4.3.1).
- Rule severity: Among the 6 rules with n≥10, 2 ERROR-level rules have opposite results; the authors state that severity does not appear to predict effectiveness (Section 4.3.2).
- Functional cost: Each analyzer-guidance strategy reduces the RiskyPy functional rate by 2.7–71.2 percentage points; FDSP (Semgrep) on Qwen2.5-Coder-14B lowers the flag rate from 74.0% to 1.4%, but 52.0% of programs are already broken without being flagged (Section 4.2.1).
- Silenced: On RiskyPy, 8.6%–12.1% of Steering pairs clear the warning but remain insecure (Section 5).
What are some points that can be further explored?
The authors list validity threats from analyzers, languages, and model families, and point to two directions: having models question warnings, and improving analyzer precision.
Limitations and future directions noted by the authors
- Construct validity (Section 6): RiskyPy uses LLM review to measure functionality and safety; safety tests in other benchmarks may have coverage gaps; cost counts only output tokens, and counting input tokens would further increase the relative cost of iterative strategies.
- Internal validity (Section 6): the reimplementations of FDSP and PromSec deviate from the original methods (documented, with trade-offs favoring the reproduced method); Steering's repair suggestions introduce extra knowledge beyond the analyzer messages, a potential confound (the Comment condition controls for this); no pure prompt-based safety baseline was included; Qwen2.5 and DeepSeek differ in family, release time, and scale, so capability factors cannot be isolated; API models were run only 3 times on average.
- External validity (Section 6): only two analyzers, Semgrep and Bandit, were used, with frozen, untuned rule sets; real-time guidance requires line-by-line analysis to be fast enough, excluding database analyzers like CodeQL, and more precise data-flow analysis could change results; benchmarks are Python only; only two model families were tested; only 11 rules ever triggered Steering; only single code snippets with small-to-medium models without agent scaffolding were studied, and the authors note agents may react differently to warnings.
- Conclusion validity (Section 6): per-rule samples are small, and pairs from the same task and merged runs are not independent.
- Future directions (Section 7): first, make analyzers trigger less often and more precisely, reducing false positives reaching the model; second, help models respond to warnings in context, e.g., having the model either fix the warning or argue against the specification why the flagged behavior is necessary (same as Section 5 Outlook).
Experimental coverage
- Models tested: Qwen2.5-Coder-14B-Instruct, DeepSeek-V4.1-flash, Qwen2.5-72B-Instruct, 3 in total (Section 3.4).
- Benchmarks: SecEvalPlus (140 tasks), BaxBench (84 tasks), RiskyPy (73 tasks), all Python (Section 3.3).
- 7 comparison strategies: Baseline, Self-Refine, FDSP, FDSP (Semgrep), PromSec, Comment, Steering (Section 3.2).
- Local models ran once per experiment, API models 3 times; RiskyPy review validation used 50 generated samples and 2 annotators (Sections 3.4, 3.6).
- The paper does not report iteration budget details beyond the query count cap for each strategy (uniformly 5 rounds, Steering at most 5 rollbacks), nor how item-by-item agreement between human annotation and final safety conclusions was applied.
Summarize the main content of the paper
Directly injecting static analysis warnings during generation is cheap and effective under specific conditions: the model is capable, the rules can be locally fixed, and the warnings do not conflict with the task.
An empirical study on using static analysis to guide LLM safe code generation. The authors propose two black-box strategies, Comment (alerts as code comments) and Steering (alerts placed in the user message), running Semgrep line by line during generation, rolling back and injecting on alert, compared with PromSec, FDSP, Self-Refine and a no-guidance baseline on 3 models and 3 Python benchmarks, with safety measured by each benchmark's independent oracle.
- Low cost: Comment and Steering output tokens are 0.9–1.9× the baseline, and iterative methods up to 24.1× (PromSec, Table 6a).
- Only the strong model benefits: on RiskyPy, Steering with DeepSeek-V4.1-flash raises the functional-and-safe proportion from 52.5% to 64.4% (significant), close to FDSP's 66.2% with less than one-fifth of its tokens; no strategy significantly improves either Qwen model (Tables 3, 5).
- Narrow analyzer coverage: on SecEvalPlus the analyzer flags at most 5.6% of functionally correct but unsafe programs; on RiskyPy precision improves over the base rate by only about 1.05× (Table 1).
- Overcompliance is a failure mode: when alerts conflict with the task, the model tends to follow the analyzer—on BaxBench, 79/83 times the spec-required network binding was removed, although the prompt requires task priority (Section 4.3.3).
- Rule level: local-replacement fixes (use-defused-xml) are net positive on two models; fixes requiring refactoring are only completed by DeepSeek; evaluated with the guiding analyzer itself, 12/12 comparisons are significant, but under the independent oracle only 2/12, which the authors state exaggerates gains.
The authors' conclusion: static-analysis guidance is worth using with sufficiently capable models, on rules that can be fixed locally, and after filtering out alerts that conflict with the task; future directions are making analyzers more precise and enabling models to fix alerts or justify their behavior against the spec.