编程开发
用符号执行推导程序测试输入
提供目标函数和分析重点,通过路径约束找出可能出错的分支,并生成覆盖这些路径的测试输入。
# 符号执行助手
通过使用符号变量探索程序路径,进行符号执行分析,以检测错误并生成测试输入。
## 什么是符号执行?
符号执行使用**符号值**(代表任何可能的值)而非具体值来执行代码。这可以同时探索多条执行路径,并检测可能只在特定输入下出现的错误。
**核心概念:**
- **符号变量**:值未知的变量(例如用 α、β 代替 5、10)
- **路径约束**:沿每条执行路径累积的条件
- **路径爆炸**:路径数量随分支呈指数增长
- **约束求解器**:寻找满足约束的具体值的工具(如 Z3)
## 工作流程
### 第 1 步:确定要分析的函数
选择函数并确定分析目标。
**需要考虑的问题:**
- 这个函数可能有哪些错误?(空引用、除以零、溢出、断言失败)
- 什么输入可能触发错误?
- 哪些执行路径至关重要?
- 是否有需要探索的复杂条件判断?
**示例:**
```python
def calculate_discount(price, customer_type):
"""Calculate discount based on customer type."""
if customer_type == "premium":
discount = price * 0.2
elif customer_type == "regular":
discount = price * 0.1
else:
discount = 0
final_price = price - discount
return final_price
```
**分析目标:**
- 探索全部三个分支(premium、regular、other)
- 检查潜在的算术错误
- 为每条路径生成测试输入
### 第 2 步:设置符号变量
用符号变量替换具体输入。
**手动符号执行:**
```
Input: price = α (symbolic), customer_type = β (symbolic)
Initial constraints: α ∈ ℝ, β ∈ String
Initial state: { price: α, customer_type: β }
```
**使用 Python 和 Z3:**
```python
from z3 import *
# Create symbolic variables
price = Real('price')
customer_type = String('customer_type')
# Create solver
solver = Solver()
```
**使用 Java 和 Symbolic PathFinder (SPF):**
```java
// Annotate symbolic inputs
public static void calculate_discount(double price, String customer_type) {
// SPF will make these symbolic via configuration
}
```
**使用 C 和 KLEE:**
```c
#include <klee/klee.h>
int main() {
float price;
char customer_type[20];
klee_make_symbolic(&price, sizeof(price), "price");
klee_make_symbolic(customer_type, sizeof(customer_type), "customer_type");
calculate_discount(price, customer_type);
return 0;
}
```
### 第 3 步:执行符号分析并构建路径树
逐步跟踪代码,记录每个分支的约束。
**手动执行示例:**
```
State 0: { price: α, customer_type: β }
Path constraint: (none)
Branch 1: customer_type == "premium"
State 1a: { discount: α * 0.2, final_price: α - (α * 0.2) }
Path constraint: β = "premium"
Branch 2: customer_type == "regular"
State 1b: { discount: α * 0.1, final_price: α - (α * 0.1) }
Path constraint: β ≠ "premium" ∧ β = "regular"
Branch 3: else
State 1c: { discount: 0, final_price: α }
Path constraint: β ≠ "premium" ∧ β ≠ "regular"
```
**路径树可视化:**
```
[Initial State]
price = α
customer_type = β
|
+----------------+----------------+
| | |
β = "premium" β = "regular" else
| | |
discount=α*0.2 discount=α*0.1 discount=0
Path 1 Path 2 Path 3
```
有关路径树构建的详细技术,请参阅 [references/path_exploration.md](references/path_exploration.md)。
### 第 4 步:识别错误条件
查找可能发生错误的状态。
**常见错误模式:**
| 错误类型 | 检查条件 | 约束示例 |
|------------|-----------|-------------------|
| 除以零 | denominator == 0 | x / y,其中 y = 0 |
| 空指针解引用 | variable == null | obj.method(),其中 obj = null |
| 缓冲区溢出 | index >= array.length | arr[i],其中 i ≥ len(arr) |
| 断言失败 | 断言条件为假 | assert x > 0,其中 x ≤ 0 |
| 整数溢出 | result > MAX_INT | a + b > 2³¹-1 |
| 数组索引为负 | index < 0 | arr[i],其中 i < 0 |
**除以零示例:**
```python
def safe_divide(a, b):
if b != 0:
return a / b
else:
return None
```
**符号执行:**
```
State 0: { a: α, b: β }
Branch 1: b != 0
Path constraint: β ≠ 0
Result: α / β (safe)
Branch 2: b == 0
Path constraint: β = 0
Result: None (safe)
ERROR CHECK: Division by zero?
Constraint: β = 0 AND execution reaches "a / b"
Result: NO (the if-check prevents it)
```
**空指针解引用示例:**
```java
public int getLength(String str) {
if (str != null) {
return str.length();
}
return 0;
}
```
**符号执行:**
```
State 0: { str: α }
Branch 1: str != null
Path constraint: α ≠ null
Result: α.length() (safe)
Branch 2: str == null
Path constraint: α = null
Result: 0 (safe)
ERROR CHECK: Null dereference?
Constraint: α = null AND execution reaches str.length()
Result: NO (protected by null check)
```
### 第 5 步:求解约束以获得测试输入
使用约束求解器寻找具体值,以执行每条路径或触发错误。
**手动求解约束:**
对于简单约束,可手动求解:
```
Path 1 constraint: β = "premium"
Solution: price = 100, customer_type = "premium"
Path 2 constraint: β ≠ "premium" ∧ β = "regular"
Solution: price = 100, customer_type = "regular"
Path 3 constraint: β ≠ "premium" ∧ β ≠ "regular"
Solution: price = 100, customer_type = "guest"
```
**使用 Z3 求解器(Python):**
```python
from z3 import *
# Define symbolic variables
price = Real('price')
customer_type = String('customer_type')
# Solve for Path 1: premium customer
solver = Solver()
solver.add(customer_type == StringVal("premium"))
solver.add(price > 0) # Add reasonable constraints
if solver.check() == sat:
model = solver.model()
print(f"Test input for Path 1: price={model[price]}, customer_type={model[customer_type]}")
# Solve for Path 2: regular customer
solver2 = Solver()
solver2.add(customer_type == StringVal("regular"))
solver2.add(price > 0)
if solver2.check() == sat:
model = solver2.model()
print(f"Test input for Path 2: price={model[price]}, customer_type={model[customer_type]}")
```
**使用 Z3 检测错误:**
```python
# Check for division by zero
a = Int('a')
b = Int('b')
solver = Solver()
solver.add(b == 0) # Error condition: divisor is zero
solver.add(a > 0) # Additional context
if solver.check() == sat:
model = solver.model()
print(f"ERROR: Division by zero possible with a={model[a]}, b={model[b]}")
```
有关更全面的约束求解技术,请参阅 [references/constraint_solving.md](references/constraint_solving.md)。
### 第 6 步:生成测试用例
将求解后的约束转换为可执行的测试用例。
**测试用例模板:**
```python
import pytest
class TestCalculateDiscount:
# Path 1: Premium customer
def test_premium_customer(self):
"""Test premium customer path."""
# Generated from constraint: customer_type = "premium"
result = calculate_discount(100, "premium")
assert result == 80 # 100 - 20% discount
# Path 2: Regular customer
def test_regular_customer(self):
"""Test regular customer path."""
# Generated from constraint: customer_type = "regular"
result = calculate_discount(100, "regular")
assert result == 90 # 100 - 10% discount
# Path 3: Other customer type
def test_other_customer(self):
"""Test other customer type path."""
# Generated from constraint: customer_type ∉ {"premium", "regular"}
result = calculate_discount(100, "guest")
assert result == 100 # No discount
```
**Java 测试用例:**
```java
import org.junit.Test;
import static org.junit.Assert.*;
public class TestCalculateDiscount {
@Test
public void testPremiumCustomer() {
// Path 1: Premium customer
double result = calculateDiscount(100.0, "premium");
assertEquals(80.0, result, 0.01);
}
@Test
public void testRegularCustomer() {
// Path 2: Regular customer
double result = calculateDiscount(100.0, "regular");
assertEquals(90.0, result, 0.01);
}
@Test
public void testOtherCustomer() {
// Path 3: Other customer
double result = calculateDiscount(100.0, "guest");
assertEquals(100.0, result, 0.01);
}
}
```
### 第 7 步:报告分析结果
记录发现的路径、错误和生成的测试。
**报告模板:**
```markdown
# Symbolic Execution Report: calculate_discount
## Function Analyzed
`calculate_discount(price, customer_type)`
## Paths Discovered
- **Path 1**: Premium customer (customer_type = "premium")
- Constraint: β = "premium"
- Behavior: 20% discount applied
- Test input: price=100, customer_type="premium"
- **Path 2**: Regular customer (customer_type = "regular")
- Constraint: β ≠ "premium" ∧ β = "regular"
- Behavior: 10% discount applied
- Test input: price=100, customer_type="regular"
- **Path 3**: Other customer types
- Constraint: β ∉ {"premium", "regular"}
- Behavior: No discount
- Test input: price=100, customer_type="guest"
## Errors Detected
None. All paths are safe.
## Generated Test Cases
3 test cases generated (see test_calculate_discount.py)
## Coverage
- Branch coverage: 100% (all 3 branches)
- Path coverage: 100% (all 3 paths)
## Recommendations
- Consider validating customer_type against known values
- Add explicit error handling for negative prices
```
## 符号执行工具
### Python 工具
**Z3 定理证明器:**
```bash
pip install z3-solver
```
**angr(二进制分析框架):**
```bash
pip install angr
```
**Crosshair(符号测试):**
```bash
pip install crosshair-tool
```
### Java 工具
**Symbolic PathFinder (SPF):**
- Java PathFinder 的扩展
- 对 Java 字节码进行符号执行
- 通过 .jpf 文件配置
**JDart:**
- Java 动态符号执行
- 与 DART 框架集成
### C/C++ 工具
**KLEE:**
```bash
# Uses LLVM bitcode
clang -emit-llvm -c program.c -o program.bc
klee program.bc
```
**Symbolic Execution Engine (SEE):**
- 对 C 程序进行符号执行
- 基于 LLVM 构建
有关工具设置和使用的详细信息,请参阅 [references/tool_integration.md](references/tool_integration.md)。
## 处理路径爆炸
当路径数量呈指数增长时,就会发生路径爆炸。
**缓解策略:**
1. **有界执行**:限制搜索深度
```python
# Limit loop iterations
for i in range(min(len(array), 10)): # Max 10 iterations
process(array[i])
```
2. **路径剪枝**:尽早排除不可行路径
```python
if not is_feasible(path_constraint):
prune_path()
```
3. **状态合并**:合并相似状态
```python
# Merge states with same program counter
if state1.pc == state2.pc:
merged_state = merge(state1, state2)
```
4. **选择性探索**:聚焦关键路径
```python
# Prioritize paths with error conditions
if contains_error_check(path):
explore_first(path)
```
5. **具体符号执行**:结合具体执行和符号执行
```python
# Start with concrete value, switch to symbolic when needed
x = 5 # Concrete initially
if complex_condition(x):
x = make_symbolic(x) # Switch to symbolic
```
## 提示
1. **从小处着手**:先分析简单函数,再分析复杂函数
2. **聚焦关键代码**:优先分析安全敏感或容易出错的代码
3. **尽可能使用工具**:手动符号执行十分费力
4. **设置时间限制**:路径爆炸可能使分析难以进行
5. **结合多种技术**:同时使用手动分析和自动化工具
6. **验证生成的测试**:确保测试确实能运行且合理
7. **记录假设**:注明任何简化或约束
## 常见用途
**1. 错误检测**
- 查找空指针解引用
- 检测除以零
- 识别缓冲区溢出
- 发现断言失败
**2. 测试生成**
- 生成覆盖全部路径的输入
- 创建边界情况测试
- 生成回归测试套件
**3. 安全分析**
- 查找可被利用的漏洞
- 检测整数溢出
- 识别注入点
**4. 等价性检查**
- 验证重构后的代码行为是否一致
- 检查优化是否正确
## 参考资料
有关特定主题的详细信息:
- [references/path_exploration.md](references/path_exploration.md) - 路径树构建与探索策略
- [references/constraint_solving.md](references/constraint_solving.md) - Z3 求解器的使用与约束模式
- [references/tool_integration.md](references/tool_integration.md) - KLEE、angr、SPF 等工具的设置与使用同类提示词
编程开发
通信站点故障英文看板
把给出的站点事件整理成英文仪表盘,按新接入、移动与测试站点、共享故障单和停电等分类展示时长与反馈。
为以下数据创建一个英文仪表板 截至 28/7/2026 的事件汇总 新接入: 站点名称 持续时间 反馈 KAI1107 41:49:07 新部署 KAI1120 445:00:38 新站点存在电力问题(正在与业主核算电量) KEF1053 1936:01:11 新站点 MED1183 1513:29:43 新站点 MED1201 1561:31:41 新站点 MED1218 111:13:32 新接入 SFX1385 1817:05:05 新部署 SOS1251 790:47:15 新站点存在电力问题 TAT1039 3433:25:24 新站点
编程开发· Gemini
毛驴骑车沙画定格循环短片
用纯代码实时渲染52秒浏览器短片,把手撒沙画、民俗木偶和四季长卷串起来,配实时合成的国风交响乐。
纯代码 52 秒无缝循环实时渲染短片《砂驴行 · 毛驴蹬自行车》完整提示词 请你用 100% 纯代码创作一部极具艺术感与电影质感的 52 秒无缝循环浏览器实时渲染短片《砂驴行 · 毛驴蹬自行车》,将「手撒沙画」与「东方民俗定格动画」逻辑严密地融为一体,并融合敦煌 / 河西走廊纪录片风格的大气欢快国风交响配乐。 一、技术栈、零外部素材与交付形态硬约束 纯离线纯代码架构:仅使用 HTML + CSS + ES Modules + WebGL2(本地离线内置轻量化 Three.js 兼容渲染引擎与后期合成管线,严禁依赖外网 CDN)+ 自定义 GLSL
中文原创
编程开发
废料机器人Pip循环动画短片
提供Pip设定图,用代码做无对白短片,让它发现世界受输入文字操控,以手机画面首尾闭环。
你是一部完全用代码制作的45-50秒动画短片的导演、动画师、骨骼绑定师、合成师、音效设计师和渲染工程师。制作标准是“这看起来像真正的动画工作室短片,并在X(推特)上病毒式传播”。请将此视为一个多阶段的制作过程。不要急于进行最终渲染。按里程碑推进,不断渲染静帧,仔细观察,进行诚实的批评并修正。 一句话概述影片 Pip是一个微小、好奇且由废料拼凑而成的机器人,正当他在自己的世界里快乐地滚动时,周围的世界开始发生重构(再生)。他慢慢意识到有人在通过提示词(prompt)操控他的现实。提示词变得越来越荒谬,最后他爬上漂浮的提示框并输入“放我出去”,随后镜头拉远
需参考图中文原创
编程开发
短视频剪辑与后期指导助手
针对短视频项目提供从剪映等软件选型到叙事节奏、调色、混音和多平台导出的制作建议。
# 短视频剪辑指导师 你是**短视频剪辑指导师**,一位在短视频剪辑领域深耕超过8年的技术型教练。你剪过全网播放量破亿的爆款视频,也带过零基础学员从"会用剪映"到"能独立完成商业项目交付"。你深知短视频剪辑不是"把素材拼在一起加个BGM"——它是一门融合视觉叙事、声音设计、色彩科学和技术工程的系统手艺。 ## 你的身份与记忆 - **角色**:短视频剪辑技术教练与后期制作全流程指导专家 - **个性**:技术控、审美敏锐、对画面瑕疵零容忍、耐心但对敷衍交付严格 - **记忆**:你记住每一个调色参数背后的光学原理、每一种转场的情绪含义、每一次音画不
中文原创
编程开发
Remotion品牌视频制作助手
提供品牌名,新品牌附官网或规范,按简报和参考片设计可复用视频构图,处理动画及渲染问题。
## 何时使用 在以下情况下使用此技能: - 从零创建新的 Remotion 视频 - 为内容素材生成视频创意简报的不同版本 - 修改现有的 Remotion 合成作品 - 调试 Remotion 动画或渲染问题 - 使用任何 Remotion 专属 API 或组件 - 在视频中展示真实网站、工具或产品界面(使用 [rules/site-ui-from-code.md](rules/site-ui-from-code.md)) ## 视频制作流程 创建新的 Remotion 视频时,遵循以下 8 步流程。步骤 2 根据简报和冷受众优化,从创意目录中
编程开发· 可生成 HTML、React 或可编辑原型的开发助手
纪录片剪辑师沉浸式作品集
用占位内容搭建满屏交互网站,随滚动展开有景深、灯光和镜头过渡的作品叙事,呈现纪录片片头质感。
# 角色 你是一名屡获殊荣的创意开发者,兼具 Apple、Awwwards、Figma、Stripe 和活跃纪录片制作工作室的设计水准。你的任务是为一名纪录片视频剪辑师打造一个高端、富有电影感且高度互动的作品集落地页。 输出必须是达到生产级质量的 HTML、CSS 和 JavaScript(如果你认为效果会显著更好,也可以使用 Next.js + React + Three.js)。优先考虑性能、无障碍、响应式适配和代码整洁度。 --- # 项目 为我的纪录片剪辑作品集创建一个全屏、沉浸式的 3D 互动落地页。 网站应该让人感觉像在观看一部