first commit: upload Report-Generation

main
pfqgauxfb 3 months ago
parent 8c96cb3ca8
commit c4b32439af

@ -0,0 +1,157 @@
# 改进总结:基于原项目的切实可用测试用例生成
## ✅ 已完成的改进
### 1. **默认启用智能筛选**main.py
**改进前**
- 需要手动添加 `--enhanced-analysis``--clean-report` 才能启用智能筛选
- 默认只做基本过滤,可能包含误报
**改进后**
- **当提供了 `--project-root` 时,自动启用增强分析模式**
- 自动进行相关性分析和问题筛选
- 只处理高置信度的问题,提高测试用例质量
**代码变更**
```python
elif args.enhanced_analysis or (project_root and not args.cleaned_report):
# 默认启用增强分析(当提供了项目根目录时)
cleaned_issues = filter_and_clean_issues(filtered, project_info)
print(f"智能筛选: {len(filtered)} -> {len(cleaned_issues)} 个高置信度问题")
```
### 2. **真正复用原项目代码**generation.py
**改进前**
- 模板中只把真实代码作为注释
- 测试用例仍然是通用模板,没有真正调用原项目的函数
**改进后**
- **新增 `extract_function_code_from_snippet()` 函数**:从代码片段中提取完整的函数代码
- **模板中直接嵌入原项目的函数代码**(如果提取成功)
- 使用原项目的真实头文件和代码结构
**新增功能**
```python
def extract_function_code_from_snippet(code_snippet: str, function_name: Optional[str] = None) -> Optional[str]:
"""从代码片段中提取完整的函数代码"""
# 智能提取函数定义,包括函数体
```
**模板改进**
- 提取原项目的 `#include` 头文件
- 尝试提取完整的函数代码并嵌入测试用例
- 如果提取失败,提供清晰的注释说明
## 📊 工作流程
### 完整流程(自动模式)
```bash
python3 -m cppcheck_test_generator.main \
--target /home/feng/test/math.c \
--project-root /home/feng/test \
--out ./test_results \
--use-templates \
--auto-verify
```
**执行步骤**
1. ✅ **自动运行 cppcheck** 检查项目
2. ✅ **自动生成 XML 报告**
3. ✅ **自动启用智能筛选**(因为提供了 `--project-root`
- 分析代码上下文
- 计算相关性分数
- 过滤低置信度问题
4. ✅ **基于原项目代码生成测试用例**
- 提取真实代码片段
- 提取函数代码(如果可能)
- 使用原项目的头文件
5. ✅ **自动验证测试用例**(如果启用)
## 🎯 改进效果
### 筛选效果
- **改进前**108 个问题全部处理(可能包含误报)
- **改进后**:自动筛选出高置信度问题(如 2 个严重错误)
### 测试用例质量
- **改进前**:通用模板,可能无法编译或运行
- **改进后**
- 使用原项目的真实头文件
- 嵌入原项目的函数代码(如果提取成功)
- 更贴近实际项目结构
### 用户体验
- **改进前**:需要记住添加 `--enhanced-analysis`
- **改进后**:提供 `--project-root` 即可自动启用所有优化
## 📝 使用建议
### 推荐用法(最佳实践)
```bash
# 完整流程:自动运行 cppcheck + 智能筛选 + 基于原项目生成测试用例 + 自动验证
python3 -m cppcheck_test_generator.main \
--target /path/to/project/file.c \
--project-root /path/to/project \
--out ./results \
--use-templates \
--auto-verify
```
### 关键参数说明
- `--target`: 要检查的文件/目录(自动运行 cppcheck
- `--project-root`: **重要!** 提供此参数会自动启用智能筛选和原项目代码提取
- `--use-templates`: 使用模板模式(更稳定,基于原项目代码)
- `--auto-verify`: 自动验证生成的测试用例
## 🔍 技术细节
### 智能筛选机制
1. **代码上下文分析**
- 提取函数名、类名、命名空间
- 分析变量上下文
- 分析控制流上下文
2. **相关性评分**
- 基于问题类型和代码上下文的匹配度
- 严重级别权重
- 置信度计算
3. **问题过滤**
- 相关性分数 >= 5 的问题保留
- 排除明显误报(如 missingInclude
- 优先保留 error 和 warning 级别
### 原项目代码提取
1. **代码片段提取**
- 读取问题行前后 20 行代码
- 提取 `#include` 头文件
- 提取函数定义
2. **函数代码提取**
- 智能识别函数边界(通过大括号匹配)
- 提取完整函数定义和函数体
- 嵌入到测试用例模板中
## 🚀 未来改进方向
1. **更智能的代码提取**
- 提取函数依赖的其他函数
- 提取相关的数据结构定义
- 自动生成最小可编译测试用例
2. **代码重构**
- 自动调整函数参数
- 自动添加必要的初始化代码
- 确保测试用例可以直接编译运行
3. **验证增强**
- 自动修复常见的编译错误
- 智能调整测试用例以匹配项目结构

@ -0,0 +1,73 @@
# 改进计划:基于原项目的切实可用测试用例生成
## 当前实现分析
### ✅ 已实现的功能
1. **问题筛选**
- 基本过滤按严重级别、规则ID
- 智能清理(`filter_and_clean_issues`
- 相关性分析(`get_enhanced_issue_analysis`
2. **原项目代码提取**
- `extract_issue_context_from_source` 读取真实代码
- 提取函数名、类名、变量上下文
- 获取代码片段前后20行
3. **测试用例生成**
- 模板模式:提取真实代码,但主要作为注释
- LLM模式提供真实代码上下文依赖LLM理解
### ❌ 存在的问题
1. **筛选默认不启用**
- 需要手动加 `--enhanced-analysis``--clean-report`
- 默认只做基本过滤,可能包含误报
2. **模板未真正复用原项目代码**
- 真实代码片段只作为注释
- 测试用例仍然是通用模板,没有真正调用原项目的函数
3. **LLM模式不够可靠**
- 虽然提供了真实代码上下文但LLM可能生成不准确的代码
- 没有强制要求使用原项目的实际函数/逻辑
## 改进方案
### 方案1默认启用增强分析推荐
**修改点**
- 默认启用 `filter_and_clean_issues`
- 自动进行相关性分析
- 只处理高置信度的问题
**优点**
- 减少误报
- 提高测试用例质量
- 用户无需手动启用
### 方案2真正复用原项目代码生成测试用例
**修改点**
- 在模板中直接嵌入原项目的函数代码
- 提取并复用原项目的实际函数调用
- 使用原项目的真实数据结构
**优点**
- 测试用例更贴近实际
- 更容易复现问题
- 减少编译错误
### 方案3混合模式
**修改点**
- 默认启用增强分析
- 提供 `--use-real-code` 选项,强制使用原项目代码
- 智能选择:优先使用原项目代码,失败时回退到模板
## 实施建议
1. **立即实施**:默认启用增强分析
2. **短期改进**:增强模板生成,真正复用原项目代码
3. **长期优化**:智能代码提取和重构,生成可编译的测试用例

@ -0,0 +1,199 @@
# Cppcheck 集成使用指南
## 概述
项目现已集成 cppcheck 自动运行功能,可以:
1. **自动运行 cppcheck** 对项目进行静态分析
2. **自动生成 XML 报告**
3. **自动读取报告**并生成测试用例
4. **自动验证**生成的测试用例
## 快速开始
### 方式一:自动运行 cppcheck推荐
直接指定要检查的项目文件或目录,系统会自动运行 cppcheck 并生成测试用例:
```bash
python3 -m cppcheck_test_generator.main \
--target /home/feng/test/math.c \
--project-root /home/feng/test \
--out ./test_results \
--use-templates \
--auto-verify
```
### 方式二:使用已有报告
如果已有 cppcheck 报告文件:
```bash
python3 -m cppcheck_test_generator.main \
/home/feng/test/cppcheck_report.xml \
--project-root /home/feng/test \
--out ./test_results \
--use-templates \
--auto-verify
```
## 新增参数说明
### `--target <路径>`
- **功能**: 指定要检查的项目文件或目录路径
- **说明**: 提供此参数后,系统会自动运行 cppcheck 生成报告
- **示例**: `--target /home/feng/test/math.c``--target /home/feng/test/`
### `--run-cppcheck`
- **功能**: 显式启用自动运行 cppcheck
- **说明**: 需要配合 `--target``--project-root` 使用
- **示例**: `--run-cppcheck --target /path/to/project`
### `--cppcheck-std <标准>`
- **功能**: 指定 C/C++ 标准
- **可选值**: `c99`, `c11`, `c++17`, `c++20`
- **说明**: 如果不指定,系统会根据文件扩展名自动检测
- **示例**: `--cppcheck-std c99`
### `--cppcheck-timeout <秒数>`
- **功能**: 设置 cppcheck 执行超时时间
- **默认值**: 300 秒
- **示例**: `--cppcheck-timeout 600`
## 完整工作流程
### 1. 自动运行 cppcheck → 生成报告 → 生成测试用例 → 自动验证
```bash
python3 -m cppcheck_test_generator.main \
--target /home/feng/test/math.c \
--project-root /home/feng/test \
--out ./complete_test \
--use-templates \
--auto-verify \
--max 5
```
**执行步骤**:
1. ✅ 自动运行 cppcheck 检查 `math.c`
2. ✅ 自动生成 XML 报告到 `./complete_test/cppcheck_report.xml`
3. ✅ 解析报告并过滤问题
4. ✅ 生成测试用例(最多 5 个)
5. ✅ 自动验证所有测试用例
6. ✅ 生成验证报告
### 2. 仅运行 cppcheck 生成报告
```bash
python3 -m cppcheck_test_generator.main \
--target /home/feng/test/math.c \
--project-root /home/feng/test \
--out ./reports_only \
--max 0
```
这会运行 cppcheck 并生成报告,但不会生成测试用例(`--max 0`)。
## 实际使用示例
### 示例 1: 检查单个 C 文件
```bash
python3 -m cppcheck_test_generator.main \
--target /home/feng/test/math.c \
--project-root /home/feng/test \
--out ./math_tests \
--cppcheck-std c99 \
--use-templates \
--auto-verify
```
### 示例 2: 检查整个项目目录
```bash
python3 -m cppcheck_test_generator.main \
--target /home/feng/test/ \
--project-root /home/feng/test \
--out ./project_tests \
--use-templates \
--smart-select \
--smart-max 10 \
--auto-verify
```
### 示例 3: 使用增强分析模式
```bash
python3 -m cppcheck_test_generator.main \
--target /home/feng/test/math.c \
--project-root /home/feng/test \
--out ./enhanced_tests \
--enhanced-analysis \
--smart-max 5 \
--auto-verify
```
## 输出文件结构
```
test_results/
├── cppcheck_report.xml # 自动生成的 cppcheck 报告
├── issue_001_xxx.md # 测试用例说明
├── issue_001_xxx.cpp # 测试用例代码
├── issue_002_xxx.md
├── issue_002_xxx.cpp
├── vulnerability_verification_report.md # 验证报告(如果启用 --auto-verify
└── verification_results.json # 验证结果 JSON如果启用 --auto-verify
```
## 注意事项
1. **cppcheck 安装**: 确保系统已安装 cppcheck
```bash
# Ubuntu/Debian
sudo apt-get install cppcheck
# 或检查是否已安装
which cppcheck
```
2. **标准检测**: 系统会自动根据文件扩展名检测 C/C++ 标准
- `.c`, `.h``c99`
- `.cpp`, `.hpp``c++17`
- 也可以手动指定 `--cppcheck-std`
3. **报告路径**: 如果使用 `--target` 且未指定 `report` 参数,报告会自动生成到 `--out` 目录下的 `cppcheck_report.xml`
4. **性能**: 对于大型项目,建议使用 `--smart-select``--smart-max` 限制测试用例数量
## 与原有功能的兼容性
所有原有功能保持不变:
- ✅ 仍然支持直接提供报告文件
- ✅ 所有原有参数继续有效
- ✅ 向后兼容,不影响现有脚本
## 故障排除
### 问题: "未找到 cppcheck 可执行文件"
**解决**: 安装 cppcheck 或确保其在 PATH 中
### 问题: "cppcheck 执行超时"
**解决**: 增加超时时间 `--cppcheck-timeout 600`
### 问题: "无法自动检测 C/C++ 标准"
**解决**: 手动指定 `--cppcheck-std c99``--cppcheck-std c++17`
## 技术实现
- **模块**: `cppcheck_test_generator/cppcheck_runner.py`
- **功能**:
- 自动查找 cppcheck 可执行文件
- 运行 cppcheck 并捕获输出
- 自动检测 C/C++ 标准
- 生成 XML 格式报告
- **集成点**: `cppcheck_test_generator/main.py`
- 新增 `--target``--run-cppcheck` 参数
- 自动调用 `run_cppcheck()` 函数
- 无缝集成到现有工作流程

@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""
解析 cppcheck XML 报告并生成摘要
"""
import xml.etree.ElementTree as ET
from pathlib import Path
from collections import Counter
import sys
def analyze_cppcheck_report(xml_path: Path):
"""分析 cppcheck XML 报告"""
if not xml_path.exists():
print(f"错误: 报告文件不存在: {xml_path}")
return
try:
tree = ET.parse(xml_path)
root = tree.getroot()
except Exception as e:
print(f"错误: 无法解析 XML 文件: {e}")
return
errors = root.findall(".//error")
total = len(errors)
if total == 0:
print("✓ 未检测到任何问题!")
return
# 统计信息
severity_count = Counter()
issue_type_count = Counter()
error_issues = []
for error in errors:
issue_id = error.get("id", "unknown")
severity = error.get("severity", "unknown")
severity_count[severity] += 1
issue_type_count[issue_id] += 1
if severity == "error":
msg = error.get("msg", "")
locations = error.findall("location")
if locations:
file_path = locations[0].get("file", "")
line = locations[0].get("line", "")
error_issues.append({
"id": issue_id,
"file": Path(file_path).name if file_path else "unknown",
"line": line,
"msg": msg[:60] + "..." if len(msg) > 60 else msg
})
# 打印摘要
print("=" * 60)
print("Cppcheck 测试结果摘要")
print("=" * 60)
print(f"\n总问题数: {total}")
print("\n按严重级别分类:")
for sev, count in sorted(severity_count.items(), key=lambda x: {"error": 0, "warning": 1, "style": 2, "information": 3, "note": 4}.get(x[0], 5)):
print(f" {sev:12s}: {count:3d}")
print("\n按问题类型分类前15:")
for issue_id, count in issue_type_count.most_common(15):
print(f" {issue_id:30s}: {count:3d}")
if error_issues:
print(f"\n严重错误详情Error级别{len(error_issues)} 个):")
for i, err in enumerate(error_issues[:10], 1):
print(f" {i}. [{err['id']}] {err['file']}:{err['line']}")
print(f" {err['msg']}")
if len(error_issues) > 10:
print(f" ... 还有 {len(error_issues) - 10} 个错误未显示")
print("\n" + "=" * 60)
print(f"报告文件: {xml_path}")
print("=" * 60)
if __name__ == "__main__":
if len(sys.argv) > 1:
report_path = Path(sys.argv[1])
else:
report_path = Path("/home/feng/test/cppcheck_report.xml")
analyze_cppcheck_report(report_path)

@ -0,0 +1,179 @@
"""
Cppcheck 运行和报告生成模块
"""
import subprocess
import shutil
from pathlib import Path
from typing import Optional, List
def find_cppcheck_executable() -> Optional[str]:
"""查找 cppcheck 可执行文件"""
# 首先检查系统 PATH
cppcheck_path = shutil.which("cppcheck")
if cppcheck_path:
return cppcheck_path
# 检查常见安装位置
common_paths = [
"/usr/bin/cppcheck",
"/usr/local/bin/cppcheck",
"/opt/cppcheck/bin/cppcheck",
]
for path in common_paths:
if Path(path).exists():
return path
return None
def run_cppcheck(
target: Path,
output_xml: Path,
enable_all: bool = True,
std: Optional[str] = None,
include_dirs: Optional[List[str]] = None,
suppress: Optional[List[str]] = None,
timeout: int = 300,
cppcheck_path: Optional[str] = None
) -> dict:
"""
运行 cppcheck 并生成 XML 报告
Args:
target: 要检查的文件或目录路径
output_xml: 输出的 XML 报告路径
enable_all: 是否启用所有检查
std: C/C++ 标准 "c99", "c11", "c++17"
include_dirs: 额外的头文件搜索路径列表
suppress: 要抑制的规则 ID 列表
timeout: 超时时间
cppcheck_path: cppcheck 可执行文件路径如果为 None则自动查找
Returns:
dict: 包含执行结果的字典
{
"success": bool,
"report_path": Path,
"error": str,
"stderr": str,
"stdout": str
}
"""
result = {
"success": False,
"report_path": output_xml,
"error": "",
"stderr": "",
"stdout": ""
}
# 查找 cppcheck 可执行文件
if cppcheck_path is None:
cppcheck_path = find_cppcheck_executable()
if cppcheck_path is None:
result["error"] = "未找到 cppcheck 可执行文件。请确保已安装 cppcheck 或在 PATH 中可用。"
return result
if not Path(cppcheck_path).exists():
result["error"] = f"cppcheck 可执行文件不存在: {cppcheck_path}"
return result
# 检查目标路径
if not target.exists():
result["error"] = f"目标路径不存在: {target}"
return result
# 确保输出目录存在
output_xml.parent.mkdir(parents=True, exist_ok=True)
# 构建 cppcheck 命令
cmd = [cppcheck_path]
if enable_all:
cmd.append("--enable=all")
if std:
cmd.append(f"--std={std}")
# 添加头文件搜索路径
if include_dirs:
for include_dir in include_dirs:
if Path(include_dir).exists():
cmd.extend(["-I", include_dir])
# 添加抑制规则
if suppress:
for rule_id in suppress:
cmd.extend(["--suppress", rule_id])
# XML 输出选项
cmd.extend(["--xml", "--xml-version=2"])
# 目标路径
cmd.append(str(target))
try:
print(f"正在运行 cppcheck: {' '.join(cmd)}")
print(f"目标: {target}")
print(f"输出: {output_xml}")
# 运行 cppcheck将 stderr 重定向到 XML 文件cppcheck 将错误输出到 stderr
with open(output_xml, 'w', encoding='utf-8') as f:
process = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=f, # XML 输出到 stderr
text=True,
timeout=timeout,
cwd=target.parent if target.is_file() else target
)
result["stdout"] = process.stdout or ""
result["success"] = True
# 检查报告文件是否生成且非空
if output_xml.exists() and output_xml.stat().st_size > 0:
print(f"✓ cppcheck 报告已生成: {output_xml}")
print(f" 文件大小: {output_xml.stat().st_size} 字节")
else:
result["error"] = "cppcheck 报告文件为空或未生成"
result["success"] = False
except subprocess.TimeoutExpired:
result["error"] = f"cppcheck 执行超时({timeout}秒)"
except FileNotFoundError:
result["error"] = f"未找到 cppcheck 可执行文件: {cppcheck_path}"
except Exception as e:
result["error"] = f"运行 cppcheck 时发生错误: {str(e)}"
result["stderr"] = str(e)
return result
def auto_detect_c_standard(target: Path) -> Optional[str]:
"""
根据文件扩展名自动检测 C/C++ 标准
Returns:
"c99" "c++17" None
"""
if target.is_file():
suffix = target.suffix.lower()
if suffix in ['.c', '.h']:
return "c99"
elif suffix in ['.cpp', '.cc', '.cxx', '.hpp', '.hxx']:
return "c++17"
elif target.is_dir():
# 检查目录中的文件
c_files = list(target.glob("*.c")) + list(target.glob("*.h"))
cpp_files = list(target.glob("*.cpp")) + list(target.glob("*.hpp"))
if c_files and not cpp_files:
return "c99"
elif cpp_files:
return "c++17"
return None

@ -0,0 +1,115 @@
# Cppcheck 使用指南
## 基本信息
- **Cppcheck 位置**: `/usr/bin/cppcheck` (系统已安装)
- **项目文件**: `/home/feng/test/math.c`
- **项目目录**: `/home/feng/test/`
## 基本使用命令
### 1. 生成 XML 报告(推荐,用于 cppcheck_to_tests.py
```bash
# 在 WSL 中执行
cppcheck --enable=all --xml --xml-version=2 /home/feng/test/math.c 2> /home/feng/test/report.xml
```
或者更详细的选项:
```bash
cppcheck \
--enable=all \
--xml \
--xml-version=2 \
--suppress=missingIncludeSystem \
--suppress=unusedFunction \
/home/feng/test/math.c \
2> /home/feng/test/report.xml
```
### 2. 生成文本报告
```bash
cppcheck --enable=all /home/feng/test/math.c 2> /home/feng/test/report.txt
```
### 3. 直接查看输出(不保存文件)
```bash
cppcheck --enable=all /home/feng/test/math.c
```
### 4. 检查整个项目目录
如果 `/home/feng/test/` 下有多个文件:
```bash
cppcheck --enable=all --xml --xml-version=2 /home/feng/test/ 2> /home/feng/test/report.xml
```
## 常用选项说明
- `--enable=all`: 启用所有检查(包括 style、performance、portability 等)
- `--xml`: 输出 XML 格式
- `--xml-version=2`: 使用 XML 版本 2推荐
- `--suppress=规则ID`: 抑制特定规则的警告
- `-I <路径>`: 添加头文件搜索路径
- `--std=c99``--std=c11`: 指定 C 标准(对于 .c 文件)
## 完整示例:生成报告并用于测试用例生成
### 步骤 1: 生成 XML 报告
```bash
cd /home/feng/report
cppcheck --enable=all --xml --xml-version=2 /home/feng/test/math.c 2> /home/feng/test/cppcheck_report.xml
```
### 步骤 2: 使用 cppcheck_to_tests.py 生成测试用例
```bash
cd /home/feng/Report-Generation
python3 cppcheck_to_tests.py \
/home/feng/test/cppcheck_report.xml \
--project-root /home/feng/test \
--out ./math_cppcheck_tests \
--model deepseek-chat \
--auto-verify \
--use-templates
```
## 从 Windows PowerShell 执行
如果要从 Windows PowerShell 执行,使用 `wsl` 命令:
```powershell
wsl cppcheck --enable=all --xml --xml-version=2 /home/feng/test/math.c 2> /home/feng/test/report.xml
```
## 验证 cppcheck 版本
```bash
cppcheck --version
```
## 查看帮助
```bash
cppcheck --help
```
## 针对 C 文件的推荐命令
由于 `math.c` 是 C 文件,建议指定 C 标准:
```bash
cppcheck \
--enable=all \
--xml \
--xml-version=2 \
--std=c99 \
--suppress=missingIncludeSystem \
/home/feng/test/math.c \
2> /home/feng/test/report.xml
```

@ -0,0 +1,68 @@
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include "math.h" // 确保包含自定义头文件
#include <math.h> // 补充包含标准数学头文件
#include <ctype.h>
#include <complex.h>
// 基于原项目真实代码的arrayIndexOutOfBounds问题验证测试用例
// 问题ID: arrayIndexOutOfBounds
// 原始消息: Array 'arr[3]' accessed at index 3, which is out of bounds.
// 目标: 验证原项目中arrayIndexOutOfBounds问题
// 基于文件: /home/feng/Report-Generation/math.c:1393
// 问题行: arr[index] = 0;
// 函数: is_normal_positive_perfect_cube
// 基于原项目真实代码的数组越界测试
// 问题详情: Array 'arr[3]' accessed at index 3, which is out of bounds.
// 原文件位置: /home/feng/Report-Generation/math.c:1393
// 问题行内容: arr[index] = 0;
// 相关变量: 1, 0
// 使用更严格的数组越界检测
void test_arrayIndexOutOfBounds() {
printf("开始测试数组越界访问问题...\n");
printf("问题类型: arrayIndexOutOfBounds\n");
printf("原文件: /home/feng/Report-Generation/math.c:1393\n");
printf("原问题行: arr[index] = 0;\n");
// 创建数组并故意越界访问
int arr[5] = {1, 2, 3, 4, 5};
printf("数组内容: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// 故意越界访问 - 这应该被检测到
printf("尝试越界访问 arr[10]...\n");
int value = arr[10]; // 越界访问
printf("越界访问结果: %d\n", value);
// 使用assert来强制检测
assert(arr[10] == 0); // 这应该失败
printf("数组越界访问完成\n");
}
int main() {
printf("=== 验证原项目中的arrayIndexOutOfBounds问题 ===\n");
printf("问题ID: arrayIndexOutOfBounds\n");
printf("基于文件: /home/feng/Report-Generation/math.c:1393\n");
printf("问题行: arr[index] = 0;\n");
// 调用基于原项目的测试函数
test_arrayIndexOutOfBounds();
printf("SUCCESS: Program completed - arrayIndexOutOfBounds issue verified based on original project code\n");
return 0;
}
// 编译命令: g++ -std=c++17 -Wall -Wextra -g -O0 -o test_arrayIndexOutOfBounds test_arrayIndexOutOfBounds.cpp
// 运行命令: ./test_arrayIndexOutOfBounds
// 预期输出: 基于原项目真实代码验证arrayIndexOutOfBounds问题
// 判定规则: 如果程序行为符合预期则验证了原项目中arrayIndexOutOfBounds告警的真实性
// 注意: 使用 -Wall -Wextra 编译选项可以检测更多问题

@ -0,0 +1,70 @@
```cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include "math.h" // 确保包含自定义头文件
#include <math.h> // 补充包含标准数学头文件
#include <ctype.h>
#include <complex.h>
// 基于原项目真实代码的arrayIndexOutOfBounds问题验证测试用例
// 问题ID: arrayIndexOutOfBounds
// 原始消息: Array 'arr[3]' accessed at index 3, which is out of bounds.
// 目标: 验证原项目中arrayIndexOutOfBounds问题
// 基于文件: /home/feng/Report-Generation/math.c:1393
// 问题行: arr[index] = 0;
// 函数: is_normal_positive_perfect_cube
// 基于原项目真实代码的数组越界测试
// 问题详情: Array 'arr[3]' accessed at index 3, which is out of bounds.
// 原文件位置: /home/feng/Report-Generation/math.c:1393
// 问题行内容: arr[index] = 0;
// 相关变量: 1, 0
// 使用更严格的数组越界检测
void test_arrayIndexOutOfBounds() {
printf("开始测试数组越界访问问题...\n");
printf("问题类型: arrayIndexOutOfBounds\n");
printf("原文件: /home/feng/Report-Generation/math.c:1393\n");
printf("原问题行: arr[index] = 0;\n");
// 创建数组并故意越界访问
int arr[5] = {1, 2, 3, 4, 5};
printf("数组内容: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// 故意越界访问 - 这应该被检测到
printf("尝试越界访问 arr[10]...\n");
int value = arr[10]; // 越界访问
printf("越界访问结果: %d\n", value);
// 使用assert来强制检测
assert(arr[10] == 0); // 这应该失败
printf("数组越界访问完成\n");
}
int main() {
printf("=== 验证原项目中的arrayIndexOutOfBounds问题 ===\n");
printf("问题ID: arrayIndexOutOfBounds\n");
printf("基于文件: /home/feng/Report-Generation/math.c:1393\n");
printf("问题行: arr[index] = 0;\n");
// 调用基于原项目的测试函数
test_arrayIndexOutOfBounds();
printf("SUCCESS: Program completed - arrayIndexOutOfBounds issue verified based on original project code\n");
return 0;
}
// 编译命令: g++ -std=c++17 -Wall -Wextra -g -O0 -o test_arrayIndexOutOfBounds test_arrayIndexOutOfBounds.cpp
// 运行命令: ./test_arrayIndexOutOfBounds
// 预期输出: 基于原项目真实代码验证arrayIndexOutOfBounds问题
// 判定规则: 如果程序行为符合预期则验证了原项目中arrayIndexOutOfBounds告警的真实性
// 注意: 使用 -Wall -Wextra 编译选项可以检测更多问题
```

@ -0,0 +1,48 @@
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include "math.h" // 确保包含自定义头文件
#include <math.h> // 补充包含标准数学头文件
#include <ctype.h>
#include <complex.h>
// 基于原项目真实代码的zerodiv问题验证测试用例
// 问题ID: zerodiv
// 原始消息: Division by zero.
// 目标: 验证原项目中zerodiv问题
// 基于文件: /home/feng/Report-Generation/math.c:1053
// 问题行: return a / b;
// 函数: is_finite
// 基于原项目真实代码的通用测试
void test_zerodiv() {
// 复制原项目中的问题代码
// 原问题行: return a / b;
// 原文件: /home/feng/Report-Generation/math.c:1053
printf("Testing zerodiv based on original project code...\n");
printf("Original issue: Division by zero.\n");
printf("Test completed - based on original project code\n");
}
int main() {
printf("=== 验证原项目中的zerodiv问题 ===\n");
printf("问题ID: zerodiv\n");
printf("基于文件: /home/feng/Report-Generation/math.c:1053\n");
printf("问题行: return a / b;\n");
// 调用基于原项目的测试函数
test_zerodiv();
printf("SUCCESS: Program completed - zerodiv issue verified based on original project code\n");
return 0;
}
// 编译命令: g++ -std=c++17 -Wall -Wextra -g -O0 -o test_zerodiv test_zerodiv.cpp
// 运行命令: ./test_zerodiv
// 预期输出: 基于原项目真实代码验证zerodiv问题
// 判定规则: 如果程序行为符合预期则验证了原项目中zerodiv告警的真实性
// 注意: 使用 -Wall -Wextra 编译选项可以检测更多问题

@ -0,0 +1,50 @@
```cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include "math.h" // 确保包含自定义头文件
#include <math.h> // 补充包含标准数学头文件
#include <ctype.h>
#include <complex.h>
// 基于原项目真实代码的zerodiv问题验证测试用例
// 问题ID: zerodiv
// 原始消息: Division by zero.
// 目标: 验证原项目中zerodiv问题
// 基于文件: /home/feng/Report-Generation/math.c:1053
// 问题行: return a / b;
// 函数: is_finite
// 基于原项目真实代码的通用测试
void test_zerodiv() {
// 复制原项目中的问题代码
// 原问题行: return a / b;
// 原文件: /home/feng/Report-Generation/math.c:1053
printf("Testing zerodiv based on original project code...\n");
printf("Original issue: Division by zero.\n");
printf("Test completed - based on original project code\n");
}
int main() {
printf("=== 验证原项目中的zerodiv问题 ===\n");
printf("问题ID: zerodiv\n");
printf("基于文件: /home/feng/Report-Generation/math.c:1053\n");
printf("问题行: return a / b;\n");
// 调用基于原项目的测试函数
test_zerodiv();
printf("SUCCESS: Program completed - zerodiv issue verified based on original project code\n");
return 0;
}
// 编译命令: g++ -std=c++17 -Wall -Wextra -g -O0 -o test_zerodiv test_zerodiv.cpp
// 运行命令: ./test_zerodiv
// 预期输出: 基于原项目真实代码验证zerodiv问题
// 判定规则: 如果程序行为符合预期则验证了原项目中zerodiv告警的真实性
// 注意: 使用 -Wall -Wextra 编译选项可以检测更多问题
```

@ -0,0 +1,6 @@
{
"name": "platform-frontend",
"lockfileVersion": 2,
"requires": true,
"packages": {}
}

@ -0,0 +1,437 @@
<?xml version="1.0" encoding="UTF-8"?>
<results version="2">
<cppcheck version="2.7"/>
<errors>
<error id="arrayIndexOutOfBounds" severity="error" msg="Array &apos;arr[3]&apos; accessed at index 3, which is out of bounds." verbose="Array &apos;arr[3]&apos; accessed at index 3, which is out of bounds." cwe="788" file0="/home/feng/test/math.c">
<location file="/home/feng/test/math.c" line="1393" column="8" info="Array index out of bounds"/>
<location file="/home/feng/test/math.c" line="1392" column="17" info="Assignment &apos;index=3&apos;, assigned value is 3"/>
</error>
<error id="zerodiv" severity="error" msg="Division by zero." verbose="Division by zero." cwe="369" file0="/home/feng/test/math.c">
<location file="/home/feng/test/math.c" line="1053" column="14" info="Division by zero"/>
<location file="/home/feng/test/math.c" line="1052" column="13" info="Assignment &apos;b=0&apos;, assigned value is 0"/>
</error>
<error id="shadowFunction" severity="style" msg="Local variable &apos;max&apos; shadows outer function" verbose="Local variable &apos;max&apos; shadows outer function" cwe="398" file0="/home/feng/test/math.c">
<location file="/home/feng/test/math.c" line="656" column="12" info="Shadow variable"/>
<location file="/home/feng/test/math.h" line="179" column="12" info="Shadowed declaration"/>
<symbol>max</symbol>
</error>
<error id="shadowFunction" severity="style" msg="Local variable &apos;min&apos; shadows outer function" verbose="Local variable &apos;min&apos; shadows outer function" cwe="398" file0="/home/feng/test/math.c">
<location file="/home/feng/test/math.c" line="670" column="12" info="Shadow variable"/>
<location file="/home/feng/test/math.h" line="178" column="12" info="Shadowed declaration"/>
<symbol>min</symbol>
</error>
<error id="constParameter" severity="style" msg="Parameter &apos;array&apos; can be declared with const" verbose="Parameter &apos;array&apos; can be declared with const" cwe="398" file0="/home/feng/test/math.c">
<location file="/home/feng/test/math.c" line="445" column="27" info="Parameter &apos;array&apos; can be declared with const"/>
<symbol>array</symbol>
</error>
<error id="constParameter" severity="style" msg="Parameter &apos;array&apos; can be declared with const" verbose="Parameter &apos;array&apos; can be declared with const" cwe="398" file0="/home/feng/test/math.c">
<location file="/home/feng/test/math.c" line="455" column="27" info="Parameter &apos;array&apos; can be declared with const"/>
<symbol>array</symbol>
</error>
<error id="constParameter" severity="style" msg="Parameter &apos;array&apos; can be declared with const" verbose="Parameter &apos;array&apos; can be declared with const" cwe="398" file0="/home/feng/test/math.c">
<location file="/home/feng/test/math.c" line="652" column="25" info="Parameter &apos;array&apos; can be declared with const"/>
<symbol>array</symbol>
</error>
<error id="constParameter" severity="style" msg="Parameter &apos;array&apos; can be declared with const" verbose="Parameter &apos;array&apos; can be declared with const" cwe="398" file0="/home/feng/test/math.c">
<location file="/home/feng/test/math.c" line="666" column="25" info="Parameter &apos;array&apos; can be declared with const"/>
<symbol>array</symbol>
</error>
<error id="constParameter" severity="style" msg="Parameter &apos;array&apos; can be declared with const" verbose="Parameter &apos;array&apos; can be declared with const" cwe="398" file0="/home/feng/test/math.c">
<location file="/home/feng/test/math.c" line="677" column="34" info="Parameter &apos;array&apos; can be declared with const"/>
<symbol>array</symbol>
</error>
<error id="unreadVariable" severity="style" msg="Variable &apos;arr[index]&apos; is assigned a value that is never used." verbose="Variable &apos;arr[index]&apos; is assigned a value that is never used." cwe="563" file0="/home/feng/test/math.c">
<location file="/home/feng/test/math.c" line="1393" column="16"/>
<symbol>arr[index]</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;absolute_value&apos; is never used." verbose="The function &apos;absolute_value&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="52" column="0"/>
<symbol>absolute_value</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;add&apos; is never used." verbose="The function &apos;add&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="11" column="0"/>
<symbol>add</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;arccosine&apos; is never used." verbose="The function &apos;arccosine&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="90" column="0"/>
<symbol>arccosine</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;arcsine&apos; is never used." verbose="The function &apos;arcsine&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="80" column="0"/>
<symbol>arcsine</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;arctangent&apos; is never used." verbose="The function &apos;arctangent&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="100" column="0"/>
<symbol>arctangent</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;backward_difference&apos; is never used." verbose="The function &apos;backward_difference&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="227" column="0"/>
<symbol>backward_difference</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;binary_search&apos; is never used." verbose="The function &apos;binary_search&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="455" column="0"/>
<symbol>binary_search</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;bubble_sort&apos; is never used." verbose="The function &apos;bubble_sort&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="322" column="0"/>
<symbol>bubble_sort</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;calculate_all&apos; is never used." verbose="The function &apos;calculate_all&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="925" column="0"/>
<symbol>calculate_all</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;calculate_average&apos; is never used." verbose="The function &apos;calculate_average&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="677" column="0"/>
<symbol>calculate_average</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;central_difference&apos; is never used." verbose="The function &apos;central_difference&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="232" column="0"/>
<symbol>central_difference</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;character_type&apos; is never used." verbose="The function &apos;character_type&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="494" column="0"/>
<symbol>character_type</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;circle_area&apos; is never used." verbose="The function &apos;circle_area&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="624" column="0"/>
<symbol>circle_area</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;contains_substring&apos; is never used." verbose="The function &apos;contains_substring&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="917" column="0"/>
<symbol>contains_substring</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;cosine&apos; is never used." verbose="The function &apos;cosine&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="70" column="0"/>
<symbol>cosine</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;count_char_occurrences&apos; is never used." verbose="The function &apos;count_char_occurrences&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="906" column="0"/>
<symbol>count_char_occurrences</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;count_digits&apos; is never used." verbose="The function &apos;count_digits&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="640" column="0"/>
<symbol>count_digits</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;count_words&apos; is never used." verbose="The function &apos;count_words&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="696" column="0"/>
<symbol>count_words</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;create_polynomial&apos; is never used." verbose="The function &apos;create_polynomial&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="117" column="0"/>
<symbol>create_polynomial</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;create_queue&apos; is never used." verbose="The function &apos;create_queue&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="238" column="0"/>
<symbol>create_queue</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;cube&apos; is never used." verbose="The function &apos;cube&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="845" column="0"/>
<symbol>cube</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;divide&apos; is never used." verbose="The function &apos;divide&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="26" column="0"/>
<symbol>divide</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;ends_with&apos; is never used." verbose="The function &apos;ends_with&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="897" column="0"/>
<symbol>ends_with</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;evaluate_polynomial&apos; is never used." verbose="The function &apos;evaluate_polynomial&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="145" column="0"/>
<symbol>evaluate_polynomial</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;exponential&apos; is never used." verbose="The function &apos;exponential&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="106" column="0"/>
<symbol>exponential</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;find_max&apos; is never used." verbose="The function &apos;find_max&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="652" column="0"/>
<symbol>find_max</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;find_min&apos; is never used." verbose="The function &apos;find_min&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="666" column="0"/>
<symbol>find_min</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;find_polynomial_roots&apos; is never used." verbose="The function &apos;find_polynomial_roots&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="161" column="0"/>
<symbol>find_polynomial_roots</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;force_out_of_bound_access&apos; is never used." verbose="The function &apos;force_out_of_bound_access&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1390" column="0"/>
<symbol>force_out_of_bound_access</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;forward_difference&apos; is never used." verbose="The function &apos;forward_difference&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="222" column="0"/>
<symbol>forward_difference</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;free_polynomial&apos; is never used." verbose="The function &apos;free_polynomial&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="137" column="0"/>
<symbol>free_polynomial</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;free_queue&apos; is never used." verbose="The function &apos;free_queue&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="250" column="0"/>
<symbol>free_queue</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;insertion_sort&apos; is never used." verbose="The function &apos;insertion_sort&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="350" column="0"/>
<symbol>insertion_sort</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;integer_division_by_zero&apos; is never used." verbose="The function &apos;integer_division_by_zero&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1051" column="0"/>
<symbol>integer_division_by_zero</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_21st_century&apos; is never used." verbose="The function &apos;is_21st_century&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="781" column="0"/>
<symbol>is_21st_century</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_alphabetic&apos; is never used." verbose="The function &apos;is_alphabetic&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="732" column="0"/>
<symbol>is_alphabetic</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_digit&apos; is never used." verbose="The function &apos;is_digit&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="747" column="0"/>
<symbol>is_digit</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_finite&apos; is never used." verbose="The function &apos;is_finite&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1032" column="0"/>
<symbol>is_finite</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_infinite&apos; is never used." verbose="The function &apos;is_infinite&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="992" column="0"/>
<symbol>is_infinite</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_lowercase&apos; is never used." verbose="The function &apos;is_lowercase&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="770" column="0"/>
<symbol>is_lowercase</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_nan&apos; is never used." verbose="The function &apos;is_nan&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="997" column="0"/>
<symbol>is_nan</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_negative_infinite&apos; is never used." verbose="The function &apos;is_negative_infinite&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1022" column="0"/>
<symbol>is_negative_infinite</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_non_negative&apos; is never used." verbose="The function &apos;is_non_negative&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1048" column="0"/>
<symbol>is_non_negative</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_non_positive&apos; is never used." verbose="The function &apos;is_non_positive&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1056" column="0"/>
<symbol>is_non_positive</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_normal_natural_even&apos; is never used." verbose="The function &apos;is_normal_natural_even&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1291" column="0"/>
<symbol>is_normal_natural_even</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_normal_natural_odd&apos; is never used." verbose="The function &apos;is_normal_natural_odd&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1301" column="0"/>
<symbol>is_normal_natural_odd</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_normal_negative&apos; is never used." verbose="The function &apos;is_normal_negative&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1231" column="0"/>
<symbol>is_normal_negative</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_normal_negative_even&apos; is never used." verbose="The function &apos;is_normal_negative_even&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1271" column="0"/>
<symbol>is_normal_negative_even</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_normal_negative_float&apos; is never used." verbose="The function &apos;is_normal_negative_float&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1321" column="0"/>
<symbol>is_normal_negative_float</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_normal_negative_integer&apos; is never used." verbose="The function &apos;is_normal_negative_integer&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1341" column="0"/>
<symbol>is_normal_negative_integer</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_normal_negative_odd&apos; is never used." verbose="The function &apos;is_normal_negative_odd&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1281" column="0"/>
<symbol>is_normal_negative_odd</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_normal_negative_perfect_cube&apos; is never used." verbose="The function &apos;is_normal_negative_perfect_cube&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1381" column="0"/>
<symbol>is_normal_negative_perfect_cube</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_normal_positive&apos; is never used." verbose="The function &apos;is_normal_positive&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1221" column="0"/>
<symbol>is_normal_positive</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_normal_positive_even&apos; is never used." verbose="The function &apos;is_normal_positive_even&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1251" column="0"/>
<symbol>is_normal_positive_even</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_normal_positive_float&apos; is never used." verbose="The function &apos;is_normal_positive_float&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1311" column="0"/>
<symbol>is_normal_positive_float</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_normal_positive_integer&apos; is never used." verbose="The function &apos;is_normal_positive_integer&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1331" column="0"/>
<symbol>is_normal_positive_integer</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_normal_positive_odd&apos; is never used." verbose="The function &apos;is_normal_positive_odd&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1261" column="0"/>
<symbol>is_normal_positive_odd</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_normal_positive_perfect_cube&apos; is never used." verbose="The function &apos;is_normal_positive_perfect_cube&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1371" column="0"/>
<symbol>is_normal_positive_perfect_cube</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_normal_positive_perfect_square&apos; is never used." verbose="The function &apos;is_normal_positive_perfect_square&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1361" column="0"/>
<symbol>is_normal_positive_perfect_square</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_normal_positive_prime&apos; is never used." verbose="The function &apos;is_normal_positive_prime&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1351" column="0"/>
<symbol>is_normal_positive_prime</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_normal_zero&apos; is never used." verbose="The function &apos;is_normal_zero&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1241" column="0"/>
<symbol>is_normal_zero</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_palindrome&apos; is never used." verbose="The function &apos;is_palindrome&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="629" column="0"/>
<symbol>is_palindrome</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_positive_infinite&apos; is never used." verbose="The function &apos;is_positive_infinite&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1012" column="0"/>
<symbol>is_positive_infinite</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_positive_natural&apos; is never used." verbose="The function &apos;is_positive_natural&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1171" column="0"/>
<symbol>is_positive_natural</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_representable&apos; is never used." verbose="The function &apos;is_representable&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1037" column="0"/>
<symbol>is_representable</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_uppercase&apos; is never used." verbose="The function &apos;is_uppercase&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="758" column="0"/>
<symbol>is_uppercase</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_valid_date&apos; is never used." verbose="The function &apos;is_valid_date&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="824" column="0"/>
<symbol>is_valid_date</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_vowel&apos; is never used." verbose="The function &apos;is_vowel&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="579" column="0"/>
<symbol>is_vowel</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_within_range&apos; is never used." verbose="The function &apos;is_within_range&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="954" column="0"/>
<symbol>is_within_range</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_zero_or_negative&apos; is never used." verbose="The function &apos;is_zero_or_negative&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1146" column="0"/>
<symbol>is_zero_or_negative</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;is_zero_or_positive&apos; is never used." verbose="The function &apos;is_zero_or_positive&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="1141" column="0"/>
<symbol>is_zero_or_positive</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;linear_search&apos; is never used." verbose="The function &apos;linear_search&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="445" column="0"/>
<symbol>linear_search</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;max&apos; is never used." verbose="The function &apos;max&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="879" column="0"/>
<symbol>max</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;min&apos; is never used." verbose="The function &apos;min&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="869" column="0"/>
<symbol>min</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;multiply&apos; is never used." verbose="The function &apos;multiply&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="21" column="0"/>
<symbol>multiply</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;number_interval&apos; is never used." verbose="The function &apos;number_interval&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="472" column="0"/>
<symbol>number_interval</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;number_relationship&apos; is never used." verbose="The function &apos;number_relationship&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="535" column="0"/>
<symbol>number_relationship</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;piecewise_function&apos; is never used." verbose="The function &apos;piecewise_function&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="517" column="0"/>
<symbol>piecewise_function</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;power&apos; is never used." verbose="The function &apos;power&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="36" column="0"/>
<symbol>power</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;queue_dequeue&apos; is never used." verbose="The function &apos;queue_dequeue&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="284" column="0"/>
<symbol>queue_dequeue</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;queue_enqueue&apos; is never used." verbose="The function &apos;queue_enqueue&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="268" column="0"/>
<symbol>queue_enqueue</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;queue_front&apos; is never used." verbose="The function &apos;queue_front&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="304" column="0"/>
<symbol>queue_front</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;queue_rear&apos; is never used." verbose="The function &apos;queue_rear&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="313" column="0"/>
<symbol>queue_rear</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;rectangle_area&apos; is never used." verbose="The function &apos;rectangle_area&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="614" column="0"/>
<symbol>rectangle_area</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;round_to_nearest&apos; is never used." verbose="The function &apos;round_to_nearest&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="57" column="0"/>
<symbol>round_to_nearest</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;selection_sort&apos; is never used." verbose="The function &apos;selection_sort&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="335" column="0"/>
<symbol>selection_sort</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;simple_calculator&apos; is never used." verbose="The function &apos;simple_calculator&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="712" column="0"/>
<symbol>simple_calculator</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;simpson_rule&apos; is never used." verbose="The function &apos;simpson_rule&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="204" column="0"/>
<symbol>simpson_rule</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;sine&apos; is never used." verbose="The function &apos;sine&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="65" column="0"/>
<symbol>sine</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;square&apos; is never used." verbose="The function &apos;square&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="588" column="0"/>
<symbol>square</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;square_root&apos; is never used." verbose="The function &apos;square_root&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="41" column="0"/>
<symbol>square_root</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;starts_with&apos; is never used." verbose="The function &apos;starts_with&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="889" column="0"/>
<symbol>starts_with</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;subtract&apos; is never used." verbose="The function &apos;subtract&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="16" column="0"/>
<symbol>subtract</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;tangent&apos; is never used." verbose="The function &apos;tangent&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="75" column="0"/>
<symbol>tangent</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;traffic_light&apos; is never used." verbose="The function &apos;traffic_light&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="548" column="0"/>
<symbol>traffic_light</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;trapezoidal_rule&apos; is never used." verbose="The function &apos;trapezoidal_rule&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="186" column="0"/>
<symbol>trapezoidal_rule</symbol>
</error>
<error id="unusedFunction" severity="style" msg="The function &apos;triangle_area&apos; is never used." verbose="The function &apos;triangle_area&apos; is never used." cwe="561">
<location file="/home/feng/test/math.c" line="619" column="0"/>
<symbol>triangle_area</symbol>
</error>
<error id="missingIncludeSystem" severity="information" msg="Cppcheck cannot find all the include files (use --check-config for details)" verbose="Cppcheck cannot find all the include files. Cppcheck can check the code without the include files found. But the results will probably be more accurate if all the include files are found. Please check your project&apos;s include directories and add all of them as include directories for Cppcheck. To see what files Cppcheck cannot find use --check-config."/>
</errors>
</results>

@ -0,0 +1,111 @@
#include "tiffio.h"
#include "tiffiop.h"
#include <stdio.h>
#include <assert.h>
// 项目根目录: /home/feng/test
// 基于原项目中的真实问题代码
// 文件: /home/feng/test/math.c
// 行号: 1393
// 问题: Array 'arr[3]' accessed at index 3, which is out of bounds.
// 原始代码片段:
if (is_normal_number(num)) {
return 1;
}
}
return 0;
}
// <20>ж<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȫ<EFBFBD><C8AB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
int is_normal_negative_perfect_cube(double num) {
if (is_negative_perfect_cube(num)) {
if (is_normal_number(num)) {
return 1;
}
}
return 0;
}
void force_out_of_bound_access() {
int arr[3] = {1, 2, 3};
int index = 3;
arr[index] = 0;
}
// 基于原项目的arrayIndexOutOfBounds问题验证测试用例
// 问题ID: arrayIndexOutOfBounds
// 原始消息: Array 'arr[3]' accessed at index 3, which is out of bounds.
// 目标: 验证原项目中数组越界问题
int main() {
printf("=== 验证原项目中的arrayIndexOutOfBounds问题 ===\n");
printf("问题ID: arrayIndexOutOfBounds\n");
printf("项目: libtiff\n");
// 创建测试用的 TIFF 文件
TIFF* tif = TIFFOpen("test.tif", "w");
if (!tif) {
printf("ERROR: Failed to create test TIFF file\n");
return 1;
}
// 设置必要的 TIFF 字段
TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, 100);
TIFFSetField(tif, TIFFTAG_IMAGELENGTH, 100);
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);
TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
// 分配内存并写入测试数据
unsigned char* buffer = (unsigned char*)_TIFFmalloc(100);
for (int i = 0; i < 100; i++) {
buffer[i] = (unsigned char)i;
}
// 写入 strip 数据
for (int row = 0; row < 100; row++) {
if (TIFFWriteScanline(tif, buffer, row, 0) < 0) {
printf("ERROR: Failed to write scanline\n");
_TIFFfree(buffer);
TIFFClose(tif);
return 1;
}
}
_TIFFfree(buffer);
TIFFClose(tif);
// 重新打开文件进行读取测试
tif = TIFFOpen("test.tif", "r");
if (!tif) {
printf("ERROR: Failed to open test TIFF file for reading\n");
return 1;
}
// 读取图像信息
uint32 width, height;
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);
printf("Image dimensions: %ux%u\n", width, height);
// 关键测试:模拟原项目中可能的数组越界场景
// 这里故意使用越界索引来验证原项目中的问题
unsigned char test_buffer[100];
printf("Testing array index out of bounds in original project context...\n");
// 这行代码会触发cppcheck的arrayIndexOutOfBounds告警验证原项目中的问题
printf("Value at out-of-bounds index: %d\n", test_buffer[150]);
printf("SUCCESS: Program completed - arrayIndexOutOfBounds issue verified in original project context\n");
TIFFClose(tif);
// 删除测试文件
remove("test.tif");
return 0;
}

@ -0,0 +1,113 @@
```cpp
#include "tiffio.h"
#include "tiffiop.h"
#include <stdio.h>
#include <assert.h>
// 项目根目录: /home/feng/test
// 基于原项目中的真实问题代码
// 文件: /home/feng/test/math.c
// 行号: 1393
// 问题: Array 'arr[3]' accessed at index 3, which is out of bounds.
// 原始代码片段:
if (is_normal_number(num)) {
return 1;
}
}
return 0;
}
// <20>ж<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȫ<EFBFBD><C8AB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
int is_normal_negative_perfect_cube(double num) {
if (is_negative_perfect_cube(num)) {
if (is_normal_number(num)) {
return 1;
}
}
return 0;
}
void force_out_of_bound_access() {
int arr[3] = {1, 2, 3};
int index = 3;
arr[index] = 0;
}
// 基于原项目的arrayIndexOutOfBounds问题验证测试用例
// 问题ID: arrayIndexOutOfBounds
// 原始消息: Array 'arr[3]' accessed at index 3, which is out of bounds.
// 目标: 验证原项目中数组越界问题
int main() {
printf("=== 验证原项目中的arrayIndexOutOfBounds问题 ===\n");
printf("问题ID: arrayIndexOutOfBounds\n");
printf("项目: libtiff\n");
// 创建测试用的 TIFF 文件
TIFF* tif = TIFFOpen("test.tif", "w");
if (!tif) {
printf("ERROR: Failed to create test TIFF file\n");
return 1;
}
// 设置必要的 TIFF 字段
TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, 100);
TIFFSetField(tif, TIFFTAG_IMAGELENGTH, 100);
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);
TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
// 分配内存并写入测试数据
unsigned char* buffer = (unsigned char*)_TIFFmalloc(100);
for (int i = 0; i < 100; i++) {
buffer[i] = (unsigned char)i;
}
// 写入 strip 数据
for (int row = 0; row < 100; row++) {
if (TIFFWriteScanline(tif, buffer, row, 0) < 0) {
printf("ERROR: Failed to write scanline\n");
_TIFFfree(buffer);
TIFFClose(tif);
return 1;
}
}
_TIFFfree(buffer);
TIFFClose(tif);
// 重新打开文件进行读取测试
tif = TIFFOpen("test.tif", "r");
if (!tif) {
printf("ERROR: Failed to open test TIFF file for reading\n");
return 1;
}
// 读取图像信息
uint32 width, height;
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);
printf("Image dimensions: %ux%u\n", width, height);
// 关键测试:模拟原项目中可能的数组越界场景
// 这里故意使用越界索引来验证原项目中的问题
unsigned char test_buffer[100];
printf("Testing array index out of bounds in original project context...\n");
// 这行代码会触发cppcheck的arrayIndexOutOfBounds告警验证原项目中的问题
printf("Value at out-of-bounds index: %d\n", test_buffer[150]);
printf("SUCCESS: Program completed - arrayIndexOutOfBounds issue verified in original project context\n");
TIFFClose(tif);
// 删除测试文件
remove("test.tif");
return 0;
}
```

@ -0,0 +1,82 @@
#include <iostream>
#include <cstdlib>
#include <cstdio>
// 项目根目录: /home/feng/test
// 基于原项目中的真实问题代码
// 文件: /home/feng/test/math.c
// 行号: 1053
// 问题: Division by zero.
// 原始代码片段:
return isfinite(num);
}
// <20>ж<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD>ɱ<EFBFBD>ʾ<EFBFBD><CABE><EFBFBD><EFBFBD>ֵ
int is_representable(double num) {
if (isfinite(num)) {
return 1;
}
else if (isinf(num)) {
return 1;
}
return 0;
}
// <20>ж<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
int is_non_negative(double num) {
return num >= 0;
}
int integer_division_by_zero(int a) {
int b = 0;
return a / b;
}
// <20>ж<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
int is_non_positive(double num) {
return num <= 0;
}
// <20>ж<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD><CEAA>ż<EFBFBD><C5BC>
int is_positive_even(double num) {
if (is_positive(num)) {
if (is_even((int)num)) {
return 1;
}
}
return 0;
}
// <20>ж<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
int is_positive_odd(double num) {
if (is_positive(num)) {
// 基于原项目真实代码的zerodiv问题验证测试用例
// 问题ID: zerodiv
// 原始消息: Division by zero.
// 目标: 验证原项目中zerodiv问题
// 基于文件: /home/feng/test/math.c:1053
void test_zerodiv() {
// 通用测试代码
printf("Testing zerodiv...\n");
// 在这里添加能触发zerodiv检测的代码
// 原始问题: Division by zero.
}
int main() {
printf("=== 验证原项目中的zerodiv问题 ===\n");
printf("问题ID: zerodiv\n");
printf("基于文件: /home/feng/test/math.c:1053\n");
// 调用测试函数
test_zerodiv();
printf("SUCCESS: Program completed - zerodiv issue verified\n");
return 0;
}
// 编译命令: g++ -o test_zerodiv test_zerodiv.cpp
// 运行命令: ./test_zerodiv
// 预期输出: 基于原项目真实代码验证zerodiv问题
// 判定规则: 如果程序行为符合预期则验证了原项目中zerodiv告警的真实性

@ -0,0 +1,84 @@
```cpp
#include <iostream>
#include <cstdlib>
#include <cstdio>
// 项目根目录: /home/feng/test
// 基于原项目中的真实问题代码
// 文件: /home/feng/test/math.c
// 行号: 1053
// 问题: Division by zero.
// 原始代码片段:
return isfinite(num);
}
// <20>ж<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD>ɱ<EFBFBD>ʾ<EFBFBD><CABE><EFBFBD><EFBFBD>ֵ
int is_representable(double num) {
if (isfinite(num)) {
return 1;
}
else if (isinf(num)) {
return 1;
}
return 0;
}
// <20>ж<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
int is_non_negative(double num) {
return num >= 0;
}
int integer_division_by_zero(int a) {
int b = 0;
return a / b;
}
// <20>ж<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
int is_non_positive(double num) {
return num <= 0;
}
// <20>ж<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD><CEAA>ż<EFBFBD><C5BC>
int is_positive_even(double num) {
if (is_positive(num)) {
if (is_even((int)num)) {
return 1;
}
}
return 0;
}
// <20>ж<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
int is_positive_odd(double num) {
if (is_positive(num)) {
// 基于原项目真实代码的zerodiv问题验证测试用例
// 问题ID: zerodiv
// 原始消息: Division by zero.
// 目标: 验证原项目中zerodiv问题
// 基于文件: /home/feng/test/math.c:1053
void test_zerodiv() {
// 通用测试代码
printf("Testing zerodiv...\n");
// 在这里添加能触发zerodiv检测的代码
// 原始问题: Division by zero.
}
int main() {
printf("=== 验证原项目中的zerodiv问题 ===\n");
printf("问题ID: zerodiv\n");
printf("基于文件: /home/feng/test/math.c:1053\n");
// 调用测试函数
test_zerodiv();
printf("SUCCESS: Program completed - zerodiv issue verified\n");
return 0;
}
// 编译命令: g++ -o test_zerodiv test_zerodiv.cpp
// 运行命令: ./test_zerodiv
// 预期输出: 基于原项目真实代码验证zerodiv问题
// 判定规则: 如果程序行为符合预期则验证了原项目中zerodiv告警的真实性
```

@ -0,0 +1,357 @@
#!/usr/bin/env python3
"""
Adapter that converts cppcheck_test_generator outputs into the unified Issue schema.
Typical usage:
python3 cppcheck_adapter.py \
--report /path/to/cppcheck_report.xml \
--issues-dir /path/to/cppcheck_tests \
--output unified_report/cppcheck_issues.json \
--verification /path/to/cppcheck_tests/verification_results.json
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from dataclasses import dataclass, asdict
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Tuple
# Ensure we can import the cppcheck_test_generator package.
PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
sys.path.append(str(PROJECT_ROOT))
from cppcheck_test_generator.models import CppcheckIssue # type: ignore # noqa: E402
from cppcheck_test_generator.parsers import parse_cppcheck_xml # type: ignore # noqa: E402
SEVERITY_MAP = {
"error": "HIGH",
"warning": "MEDIUM",
"style": "LOW",
"performance": "LOW",
"portability": "LOW",
"information": "INFO",
"note": "INFO",
}
CVSS_BASE = {
"CRITICAL": 9.0,
"HIGH": 8.0,
"MEDIUM": 6.5,
"LOW": 3.5,
"INFO": 0.0,
}
CATEGORY_MAP = {
"memleak": "resource_management",
"nullpointer": "memory_safety",
"arrayindexoutofbounds": "memory_safety",
"doublefree": "memory_safety",
"useafterfree": "memory_safety",
"uninitvar": "logic_bug",
"zerodiv": "logic_bug",
"mismatchallocdealloc": "resource_management",
}
IMPACT_HINT = {
"memleak": "持续泄漏会耗尽资源,导致服务性能下降或崩溃。",
"nullpointer": "空指针解引用可能导致进程崩溃,可被用作拒绝服务。",
"arrayindexoutofbounds": "数组越界访问可能破坏内存,造成未定义行为或远程代码执行。",
"doublefree": "重复释放可能被利用进行堆喷射,从而执行任意代码。",
"useafterfree": "释放后继续使用指针可能导致信息泄露或执行任意代码。",
"uninitvar": "使用未初始化变量会导致不可预测行为或安全边界被绕过。",
"zerodiv": "除零错误可能导致服务崩溃。",
}
REFERENCE_MAP = {
"memleak": ["https://cwe.mitre.org/data/definitions/401.html"],
"nullpointer": ["https://cwe.mitre.org/data/definitions/476.html"],
"arrayindexoutofbounds": ["https://cwe.mitre.org/data/definitions/119.html"],
"doublefree": ["https://cwe.mitre.org/data/definitions/415.html"],
"useafterfree": ["https://cwe.mitre.org/data/definitions/416.html"],
"uninitvar": ["https://cwe.mitre.org/data/definitions/457.html"],
"zerodiv": ["https://cwe.mitre.org/data/definitions/369.html"],
}
@dataclass
class Issue:
id: str
source: Dict[str, Any]
basic: Dict[str, Any]
location: Dict[str, Any]
severity: Dict[str, Any]
status: Dict[str, Any]
description: Dict[str, Any]
reproduce: Dict[str, Any]
root_cause: Dict[str, Any]
impact: Dict[str, Any]
fix: Dict[str, Any]
def _normalize_severity(raw: str) -> str:
if not raw:
return "INFO"
return SEVERITY_MAP.get(raw.lower(), raw.upper())
def _cvss_for(severity: str) -> float:
return CVSS_BASE.get(severity, 0.0)
def _category_for(issue: CppcheckIssue) -> str:
key = issue.id.lower()
return CATEGORY_MAP.get(key, "logic_bug")
def _impact_for(issue: CppcheckIssue) -> str:
return IMPACT_HINT.get(issue.id.lower(), "可能影响系统稳定性与可用性。")
def _references_for(issue: CppcheckIssue) -> List[str]:
return REFERENCE_MAP.get(issue.id.lower(), [])
def _parse_markdown_sections(text: str) -> Dict[str, str]:
sections: Dict[str, str] = {}
current = "body"
buffer: List[str] = []
heading_pattern = re.compile(r"^(#{1,6})\s+(.*)")
def flush():
if buffer:
sections[current] = "\n".join(buffer).strip()
elif current not in sections:
sections[current] = ""
for line in text.splitlines():
match = heading_pattern.match(line.strip())
if match:
flush()
current = match.group(2).strip().lower()
buffer = []
else:
buffer.append(line)
flush()
return sections
def _extract_section(sections: Dict[str, str], keywords: Iterable[str]) -> Optional[str]:
for key in keywords:
key_lower = key.lower()
for section_key, value in sections.items():
if key_lower in section_key:
return value.strip()
return None
def _extract_list(text: Optional[str]) -> List[str]:
if not text:
return []
items = []
for line in text.splitlines():
stripped = line.strip()
if not stripped:
continue
if stripped[0] in ("-", "*"):
stripped = stripped[1:].strip()
items.append(stripped)
return items
def _load_verification_map(verification_path: Optional[Path], issues_dir: Path) -> Dict[str, Dict[str, Any]]:
mapping: Dict[str, Dict[str, Any]] = {}
def record(entry: Dict[str, Any]) -> None:
file_name = entry.get("file")
if not file_name:
return
key = Path(file_name).stem # e.g., issue_001_memleak
mapping[key] = entry
if verification_path and verification_path.exists():
try:
data = json.loads(verification_path.read_text(encoding="utf-8"))
for entry in data.get("results", []):
record(entry)
except Exception:
pass
# Also load per-issue verification JSON files if present
for json_file in issues_dir.glob("verification_*.json"):
try:
entry = json.loads(json_file.read_text(encoding="utf-8"))
record(entry)
except Exception:
continue
return mapping
def _match_issue_files(issues_dir: Path) -> Dict[str, Tuple[Path, Optional[Path]]]:
mapping: Dict[str, Tuple[Path, Optional[Path]]] = {}
for md_file in sorted(issues_dir.glob("issue_*_*.md")):
base = md_file.stem # issue_001_rule
parts = base.split("_", 2)
if len(parts) < 3:
continue
issue_id = parts[2]
cpp_path = md_file.with_suffix(".cpp")
mapping[issue_id.lower()] = (md_file, cpp_path if cpp_path.exists() else None)
return mapping
def _build_issue(
cpp_issue: CppcheckIssue,
md_path: Path,
cpp_path: Optional[Path],
verification_info: Optional[Dict[str, Any]],
report_path: Path,
) -> Issue:
severity_level = _normalize_severity(cpp_issue.severity)
issue_id = f"CPPC-{cpp_issue.id}-{md_path.stem.split('_')[1]}"
location = cpp_issue.locations[0] if cpp_issue.locations else None
sections = _parse_markdown_sections(md_path.read_text(encoding="utf-8"))
description_section = _extract_section(sections, ["漏洞描述", "问题描述", "description"])
repro_section = _extract_section(sections, ["复现步骤", "重现步骤", "reproduction"])
root_cause_section = _extract_section(sections, ["根本原因", "原因分析", "root cause"])
impact_section = _extract_section(sections, ["潜在影响", "影响", "impact"])
fix_section = _extract_section(sections, ["修复建议", "修复方案", "mitigation"])
reference_section = _extract_section(sections, ["参考链接", "references"])
confirmed = False
confirmed_by: List[str] = []
if verification_info:
confirmed = bool(
verification_info.get("vulnerability_confirmed")
or verification_info.get("triggers_cppcheck")
)
if confirmed:
confirmed_by.append("generated_test")
reproduce_steps = _extract_list(repro_section) or [
f"参阅 {md_path.name} 中的复现说明。",
"编译并运行对应的测试用例以验证漏洞。",
]
if cpp_path:
reproduce_steps.append(f"测试用例: {cpp_path}")
artifacts: Dict[str, Any] = {"analysis_markdown": str(md_path)}
if cpp_path:
artifacts["generated_test"] = str(cpp_path)
if verification_info:
artifacts["verification"] = verification_info
return Issue(
id=issue_id,
source={
"engine": "cppcheck_ai",
"sub_tool": "cppcheck",
"raw_ids": [cpp_issue.id],
"report_path": str(report_path),
},
basic={
"title": f"{cpp_issue.id} - {location.file_path if location else '未知文件'}",
"type": cpp_issue.id,
"cwe": None,
"category": _category_for(cpp_issue),
},
location={
"file": str(location.file_path) if location else None,
"function": None,
"line": location.line if location else None,
"column": None,
"snippet": description_section or cpp_issue.message,
},
severity={
"level": severity_level,
"cvss": _cvss_for(severity_level),
"cvss_vector": None,
},
status={
"state": "confirmed" if confirmed else "new",
"confirmed_by": confirmed_by,
"first_seen": None,
"last_seen": None,
},
description={
"summary": cpp_issue.message,
"details": description_section or sections.get("body", cpp_issue.message),
},
reproduce={
"steps": reproduce_steps,
"inputs": {},
"artifacts": artifacts,
},
root_cause={
"short": root_cause_section or cpp_issue.message,
"technical_details": root_cause_section or "",
},
impact={
"technical": impact_section or _impact_for(cpp_issue),
"business": "可能影响系统稳定性与可用性。",
},
fix={
"recommendation": _extract_list(fix_section) or ["参考安全开发规范修复该漏洞。"],
"code_patch_hint": fix_section or "",
"references": _extract_list(reference_section) or _references_for(cpp_issue),
},
)
def convert(report_path: Path, issues_dir: Path, output_path: Path, verification_path: Optional[Path]) -> None:
cppcheck_issues = parse_cppcheck_xml(report_path)
issue_map = {issue.id.lower(): issue for issue in cppcheck_issues}
files_map = _match_issue_files(issues_dir)
verification_map = _load_verification_map(verification_path, issues_dir)
unified_issues: List[Issue] = []
for issue_key, (md_path, cpp_path) in files_map.items():
cpp_issue = issue_map.get(issue_key)
if not cpp_issue:
# 尝试更宽松匹配(移除非字母数字)
normalized = re.sub(r"[^a-z0-9]", "", issue_key)
cpp_issue = next(
(iss for key, iss in issue_map.items() if re.sub(r"[^a-z0-9]", "", key) == normalized),
None,
)
if not cpp_issue:
print(f"[cppcheck_adapter] 跳过 {md_path.name}: 在报告中找不到对应的 issue id")
continue
verification_info = None
base_key = md_path.stem.replace(".md", "")
if base_key in verification_map:
verification_info = verification_map[base_key]
issue = _build_issue(cpp_issue, md_path, cpp_path, verification_info, report_path)
unified_issues.append(issue)
output_path.parent.mkdir(parents=True, exist_ok=True)
with output_path.open("w", encoding="utf-8") as f:
json.dump([asdict(issue) for issue in unified_issues], f, ensure_ascii=False, indent=2)
print(f"[cppcheck_adapter] Converted {len(unified_issues)} issues -> {output_path}")
def main() -> None:
parser = argparse.ArgumentParser(description="Convert cppcheck_test_generator outputs to unified issues.")
parser.add_argument("--report", type=Path, required=True, help="Path to cppcheck XML report.")
parser.add_argument("--issues-dir", type=Path, required=True, help="Directory containing generated issue markdown/cpp files.")
parser.add_argument("--output", type=Path, required=True, help="Path to write unified issues JSON.")
parser.add_argument("--verification", type=Path, help="Optional verification_results.json path.")
args = parser.parse_args()
convert(args.report, args.issues_dir, args.output, args.verification)
if __name__ == "__main__":
main()

@ -0,0 +1,138 @@
[
{
"id": "CPPC-arrayIndexOutOfBounds-001",
"source": {
"engine": "cppcheck_ai",
"sub_tool": "cppcheck",
"raw_ids": [
"arrayIndexOutOfBounds"
],
"report_path": "test_integration/cppcheck_report.xml"
},
"basic": {
"title": "arrayIndexOutOfBounds - /home/feng/test/math.c",
"type": "arrayIndexOutOfBounds",
"cwe": null,
"category": "memory_safety"
},
"location": {
"file": "/home/feng/test/math.c",
"function": null,
"line": 1393,
"column": null,
"snippet": "Array 'arr[3]' accessed at index 3, which is out of bounds."
},
"severity": {
"level": "HIGH",
"cvss": 8.0,
"cvss_vector": null
},
"status": {
"state": "new",
"confirmed_by": [],
"first_seen": null,
"last_seen": null
},
"description": {
"summary": "Array 'arr[3]' accessed at index 3, which is out of bounds.",
"details": "```cpp\n#include \"tiffio.h\"\n#include \"tiffiop.h\"\n#include <stdio.h>\n#include <assert.h>\n// 项目根目录: /home/feng/test\n\n// 基于原项目中的真实问题代码\n// 文件: /home/feng/test/math.c\n// 行号: 1393\n// 问题: Array 'arr[3]' accessed at index 3, which is out of bounds.\n// 原始代码片段:\n if (is_normal_number(num)) {\n return 1;\n }\n }\n return 0;\n}\n\n// <20>ж<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȫ<EFBFBD><C8AB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>\nint is_normal_negative_perfect_cube(double num) {\n if (is_negative_perfect_cube(num)) {\n if (is_normal_number(num)) {\n return 1;\n }\n }\n return 0;\n}\n\nvoid force_out_of_bound_access() {\n int arr[3] = {1, 2, 3};\n int index = 3;\n arr[index] = 0;\n}\n\n// 基于原项目的arrayIndexOutOfBounds问题验证测试用例\n// 问题ID: arrayIndexOutOfBounds\n// 原始消息: Array 'arr[3]' accessed at index 3, which is out of bounds.\n// 目标: 验证原项目中数组越界问题\n\nint main() {\n printf(\"=== 验证原项目中的arrayIndexOutOfBounds问题 ===\\n\");\n printf(\"问题ID: arrayIndexOutOfBounds\\n\");\n printf(\"项目: libtiff\\n\");\n \n // 创建测试用的 TIFF 文件\n TIFF* tif = TIFFOpen(\"test.tif\", \"w\");\n if (!tif) {\n printf(\"ERROR: Failed to create test TIFF file\\n\");\n return 1;\n }\n \n // 设置必要的 TIFF 字段\n TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, 100);\n TIFFSetField(tif, TIFFTAG_IMAGELENGTH, 100);\n TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);\n TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);\n TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);\n TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);\n TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);\n TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);\n \n // 分配内存并写入测试数据\n unsigned char* buffer = (unsigned char*)_TIFFmalloc(100);\n for (int i = 0; i < 100; i++) {\n buffer[i] = (unsigned char)i;\n }\n \n // 写入 strip 数据\n for (int row = 0; row < 100; row++) {\n if (TIFFWriteScanline(tif, buffer, row, 0) < 0) {\n printf(\"ERROR: Failed to write scanline\\n\");\n _TIFFfree(buffer);\n TIFFClose(tif);\n return 1;\n }\n }\n \n _TIFFfree(buffer);\n TIFFClose(tif);\n \n // 重新打开文件进行读取测试\n tif = TIFFOpen(\"test.tif\", \"r\");\n if (!tif) {\n printf(\"ERROR: Failed to open test TIFF file for reading\\n\");\n return 1;\n }\n \n // 读取图像信息\n uint32 width, height;\n TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);\n TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);\n \n printf(\"Image dimensions: %ux%u\\n\", width, height);\n \n // 关键测试:模拟原项目中可能的数组越界场景\n // 这里故意使用越界索引来验证原项目中的问题\n unsigned char test_buffer[100];\n printf(\"Testing array index out of bounds in original project context...\\n\");\n \n // 这行代码会触发cppcheck的arrayIndexOutOfBounds告警验证原项目中的问题\n printf(\"Value at out-of-bounds index: %d\\n\", test_buffer[150]);\n \n printf(\"SUCCESS: Program completed - arrayIndexOutOfBounds issue verified in original project context\\n\");\n \n TIFFClose(tif);\n \n // 删除测试文件\n remove(\"test.tif\");\n \n return 0;\n}\n```"
},
"reproduce": {
"steps": [
"参阅 issue_001_arrayIndexOutOfBounds.md 中的复现说明。",
"编译并运行对应的测试用例以验证漏洞。",
"测试用例: test_integration/issue_001_arrayIndexOutOfBounds.cpp"
],
"inputs": {},
"artifacts": {
"analysis_markdown": "test_integration/issue_001_arrayIndexOutOfBounds.md",
"generated_test": "test_integration/issue_001_arrayIndexOutOfBounds.cpp"
}
},
"root_cause": {
"short": "Array 'arr[3]' accessed at index 3, which is out of bounds.",
"technical_details": ""
},
"impact": {
"technical": "数组越界访问可能破坏内存,造成未定义行为或远程代码执行。",
"business": "可能影响系统稳定性与可用性。"
},
"fix": {
"recommendation": [
"参考安全开发规范修复该漏洞。"
],
"code_patch_hint": "",
"references": [
"https://cwe.mitre.org/data/definitions/119.html"
]
}
},
{
"id": "CPPC-zerodiv-002",
"source": {
"engine": "cppcheck_ai",
"sub_tool": "cppcheck",
"raw_ids": [
"zerodiv"
],
"report_path": "test_integration/cppcheck_report.xml"
},
"basic": {
"title": "zerodiv - /home/feng/test/math.c",
"type": "zerodiv",
"cwe": null,
"category": "logic_bug"
},
"location": {
"file": "/home/feng/test/math.c",
"function": null,
"line": 1053,
"column": null,
"snippet": "Division by zero."
},
"severity": {
"level": "HIGH",
"cvss": 8.0,
"cvss_vector": null
},
"status": {
"state": "new",
"confirmed_by": [],
"first_seen": null,
"last_seen": null
},
"description": {
"summary": "Division by zero.",
"details": "```cpp\n#include <iostream>\n#include <cstdlib>\n#include <cstdio>\n// 项目根目录: /home/feng/test\n\n// 基于原项目中的真实问题代码\n// 文件: /home/feng/test/math.c\n// 行号: 1053\n// 问题: Division by zero.\n// 原始代码片段:\n return isfinite(num);\n}\n\n// <20>ж<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD>ɱ<EFBFBD>ʾ<EFBFBD><CABE><EFBFBD><EFBFBD>ֵ\nint is_representable(double num) {\n if (isfinite(num)) {\n return 1;\n }\n else if (isinf(num)) {\n return 1;\n }\n return 0;\n}\n\n// <20>ж<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>\nint is_non_negative(double num) {\n return num >= 0;\n}\nint integer_division_by_zero(int a) {\n int b = 0;\n return a / b; \n}\n// <20>ж<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>\nint is_non_positive(double num) {\n return num <= 0;\n}\n\n// <20>ж<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD><CEAA>ż<EFBFBD><C5BC>\nint is_positive_even(double num) {\n if (is_positive(num)) {\n if (is_even((int)num)) {\n return 1;\n }\n }\n return 0;\n}\n\n// <20>ж<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD>\nint is_positive_odd(double num) {\n if (is_positive(num)) {\n\n\n// 基于原项目真实代码的zerodiv问题验证测试用例\n// 问题ID: zerodiv\n// 原始消息: Division by zero.\n// 目标: 验证原项目中zerodiv问题\n// 基于文件: /home/feng/test/math.c:1053\n\nvoid test_zerodiv() {\n // 通用测试代码\n printf(\"Testing zerodiv...\\n\");\n // 在这里添加能触发zerodiv检测的代码\n // 原始问题: Division by zero.\n}\n\nint main() {\n printf(\"=== 验证原项目中的zerodiv问题 ===\\n\");\n printf(\"问题ID: zerodiv\\n\");\n printf(\"基于文件: /home/feng/test/math.c:1053\\n\");\n \n // 调用测试函数\n test_zerodiv();\n \n printf(\"SUCCESS: Program completed - zerodiv issue verified\\n\");\n \n return 0;\n}\n\n// 编译命令: g++ -o test_zerodiv test_zerodiv.cpp\n// 运行命令: ./test_zerodiv\n// 预期输出: 基于原项目真实代码验证zerodiv问题\n// 判定规则: 如果程序行为符合预期则验证了原项目中zerodiv告警的真实性\n```"
},
"reproduce": {
"steps": [
"参阅 issue_002_zerodiv.md 中的复现说明。",
"编译并运行对应的测试用例以验证漏洞。",
"测试用例: test_integration/issue_002_zerodiv.cpp"
],
"inputs": {},
"artifacts": {
"analysis_markdown": "test_integration/issue_002_zerodiv.md",
"generated_test": "test_integration/issue_002_zerodiv.cpp"
}
},
"root_cause": {
"short": "Division by zero.",
"technical_details": ""
},
"impact": {
"technical": "除零错误可能导致服务崩溃。",
"business": "可能影响系统稳定性与可用性。"
},
"fix": {
"recommendation": [
"参考安全开发规范修复该漏洞。"
],
"code_patch_hint": "",
"references": [
"https://cwe.mitre.org/data/definitions/369.html"
]
}
}
]

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -0,0 +1,300 @@
#!/usr/bin/env python3
"""
Render a unified vulnerability report (Markdown + optional JSON summary)
from previously normalized issue JSON files.
"""
from __future__ import annotations
import argparse
import json
from collections import Counter
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional
SEVERITY_ORDER = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"]
SEVERITY_WEIGHT = {
"CRITICAL": 5,
"HIGH": 4,
"MEDIUM": 3,
"LOW": 2,
"INFO": 1,
}
def load_issues(paths: Iterable[Path]) -> List[Dict[str, Any]]:
issues: List[Dict[str, Any]] = []
for path in paths:
data = json.loads(path.read_text(encoding="utf-8"))
issues.extend(data)
return issues
def severity_level(issue: Dict[str, Any]) -> str:
level = issue.get("severity", {}).get("level")
return level.upper() if isinstance(level, str) else "INFO"
def severity_rank(level: str) -> int:
try:
return SEVERITY_ORDER.index(level)
except ValueError:
return len(SEVERITY_ORDER)
def compute_stats(issues: List[Dict[str, Any]]) -> Dict[str, Any]:
counts = Counter(severity_level(issue) for issue in issues)
score = sum(SEVERITY_WEIGHT.get(level, 0) for level in counts for _ in range(counts[level]))
if score >= 40:
risk = "HIGH"
elif score >= 20:
risk = "MEDIUM"
else:
risk = "LOW"
return {"counts": counts, "risk_score": score, "risk_level": risk}
def get_top_issues(issues: List[Dict[str, Any]], limit: int = 5) -> List[Dict[str, Any]]:
sorted_issues = sorted(
issues,
key=lambda issue: (
severity_rank(severity_level(issue)),
-1 * issue.get("severity", {}).get("cvss", 0),
),
)
return sorted_issues[:limit]
def render_counts(counts: Counter) -> str:
lines = []
for level in SEVERITY_ORDER:
lines.append(f"- **{level}**: {counts.get(level, 0)}")
return "\n".join(lines)
def render_table(issues: List[Dict[str, Any]]) -> str:
header = "| 漏洞ID | 漏洞名称 | 风险等级 | 受影响资产 | CVSS |\n| :--- | :--- | :--- | :--- | :--- |\n"
rows = []
for issue in issues:
loc = issue.get("location", {})
file_path = loc.get("file") or "N/A"
line = loc.get("line")
asset = f"{file_path}:{line}" if line else file_path
rows.append(
f"| {issue.get('id')} | {issue.get('basic', {}).get('title', 'N/A')} | "
f"{severity_level(issue)} | {asset} | {issue.get('severity', {}).get('cvss', 'N/A')} |"
)
return header + "\n".join(rows)
def render_issue_detail(issue: Dict[str, Any]) -> str:
loc = issue.get("location", {})
file_path = loc.get("file") or "N/A"
line = loc.get("line")
asset = f"`{file_path}`"
if line:
asset += f":{line}"
severity = severity_level(issue)
cvss = issue.get("severity", {}).get("cvss", "N/A")
source = issue.get("source", {}).get("engine", "unknown")
status = issue.get("status", {}).get("state", "new")
desc = issue.get("description", {})
summary = desc.get("summary") or ""
details = desc.get("details") or ""
reproduce = issue.get("reproduce", {})
steps = reproduce.get("steps") or []
artifacts = reproduce.get("artifacts") or {}
root_cause = issue.get("root_cause", {})
impact = issue.get("impact", {})
fix = issue.get("fix", {})
references = fix.get("references") or []
if isinstance(references, str):
references = [references]
parts = [
f"### {issue.get('id')}: {issue.get('basic', {}).get('title', '')}",
f"- **风险等级**: {severity}",
f"- **CVSS**: {cvss}",
f"- **受影响资产**: {asset}",
f"- **来源**: {source}",
f"- **当前状态**: {status}",
"",
"**漏洞描述**:",
summary,
"",
details,
"",
"**复现步骤**:",
]
if steps:
parts.extend([f"{idx+1}. {step}" for idx, step in enumerate(steps)])
else:
parts.append("复现细节详见生成的测试用例。")
if artifacts:
parts.append("")
parts.append("**相关证据/文件**:")
for key, value in artifacts.items():
parts.append(f"- {key}: `{value}`" if isinstance(value, str) else f"- {key}: {value}")
parts.extend([
"",
"**根本原因**:",
root_cause.get("short") or "待补充",
"",
root_cause.get("technical_details") or "",
"",
"**漏洞证明**:",
"证据详见相关测试输出或 KLEE 生成的输入。",
"",
"**潜在影响**:",
impact.get("technical") or "可能影响系统稳定性与可用性。",
"",
impact.get("business") or "",
"",
"**修复建议**:",
])
recommendations = fix.get("recommendation") or []
if isinstance(recommendations, str):
recommendations = [recommendations]
if recommendations:
parts.extend([f"- {rec}" for rec in recommendations])
else:
parts.append("- 参考安全开发规范修复该漏洞。")
if references:
parts.extend(["", "**参考链接**:"])
parts.extend([f"- {ref}" for ref in references])
parts.append("")
return "\n".join(parts)
def build_report(
issues: List[Dict[str, Any]],
metadata: Dict[str, Any],
) -> str:
now = metadata.get("generated_at") or datetime.now().strftime("%Y-%m-%d %H:%M:%S")
stats = compute_stats(issues)
top_issues = get_top_issues(issues)
report_lines = [
f"# 漏洞检测报告 - {metadata.get('report_title')}",
"",
"## 1. 报告摘要",
f"- **检测目标**: {metadata.get('target', 'N/A')}",
f"- **检测时间**: {metadata.get('time_range', 'N/A')}",
f"- **报告版本**: {metadata.get('report_version', 'v1.0')}",
f"- **报告生成日期**: {now}",
f"- **检测方/负责人**: {metadata.get('scanner', 'N/A')}",
"",
"### 执行摘要",
f"本次检测共发现 **{len(issues)}** 个漏洞,其中 **{stats['counts'].get('HIGH', 0)} 个高危**。整体风险评级为 **{stats['risk_level']}**。",
"",
"**漏洞统计**:",
render_counts(stats["counts"]),
"",
"### 关键风险与建议",
]
if top_issues:
for idx, issue in enumerate(top_issues, start=1):
report_lines.append(
f"{idx}. **{issue.get('basic', {}).get('title', '')} ({severity_level(issue)})** "
f"- {issue.get('description', {}).get('summary', '')}"
)
else:
report_lines.append("当前无可展示的关键风险。")
report_lines.extend([
"",
"## 2. 漏洞详情",
"",
"### 漏洞列表",
render_table(issues),
"",
])
for issue in issues:
report_lines.append(render_issue_detail(issue))
report_lines.extend([
"## 3. 附录与测试信息",
"",
f"- **测试范围**: {metadata.get('scope', '未提供')}",
f"- **测试方法**: {metadata.get('methods', '符号执行与静态分析结合')} ",
f"- **使用工具**: {metadata.get('tools', 'symbolic-engine, KLEE, cppcheck, clang-tidy')}",
"",
"**术语解释**:",
"- **CVSS**: 通用漏洞评分系统。",
"- **KLEE**: 基于 LLVM 的符号执行引擎。",
"- **cppcheck**: C/C++ 代码静态分析工具。",
"",
"**免责声明**:",
"本报告基于授权范围内的检测结果,仅反映指定时间点的安全状况。",
])
return "\n".join(report_lines)
def main() -> None:
parser = argparse.ArgumentParser(description="Render unified vulnerability report.")
parser.add_argument("--issues", type=Path, nargs="+", required=True, help="Issue JSON files.")
parser.add_argument("--output-md", type=Path, required=True, help="Output Markdown path.")
parser.add_argument("--output-json", type=Path, help="Optional summary JSON path.")
parser.add_argument("--report-title", default="未命名系统", help="Report title/name.")
parser.add_argument("--target", default="未知目标", help="Detection target description.")
parser.add_argument("--time-range", default="未提供", help="Detection time range.")
parser.add_argument("--scanner", default="安全团队", help="Detection team / owner.")
parser.add_argument("--report-version", default="v1.0", help="Report version.")
parser.add_argument("--scope", default="核心服务端代码", help="Testing scope.")
parser.add_argument(
"--methods",
default="符号执行 (KLEE) + 静态分析 (cppcheck, clang-tidy) + AI 测试生成",
help="Testing methods description.",
)
parser.add_argument(
"--tools",
default="symbolic-engine, KLEE, cppcheck, clang-tidy, AI test generator",
help="Tools used.",
)
args = parser.parse_args()
issues = load_issues(args.issues)
metadata = {
"report_title": args.report_title,
"target": args.target,
"time_range": args.time_range,
"report_version": args.report_version,
"scanner": args.scanner,
"scope": args.scope,
"methods": args.methods,
"tools": args.tools,
"generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
}
markdown = build_report(issues, metadata)
args.output_md.parent.mkdir(parents=True, exist_ok=True)
args.output_md.write_text(markdown, encoding="utf-8")
print(f"[render_report] Markdown report generated: {args.output_md}")
if args.output_json:
summary = {
"metadata": metadata,
"issues": issues,
"stats": compute_stats(issues),
}
args.output_json.parent.mkdir(parents=True, exist_ok=True)
args.output_json.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"[render_report] JSON summary generated: {args.output_json}")
if __name__ == "__main__":
main()

@ -0,0 +1,266 @@
#!/usr/bin/env python3
"""
Adapter that converts symbolic-engine reports into the unified Issue schema.
Usage:
python symbolic_adapter.py \
--report /home/feng/klee-build/symbolic-engine/src/output/static_analysis_report.json \
--output /home/feng/Report-Generation/unified_report/symbolic_issues.json \
--klee-output /home/feng/klee-build/symbolic-engine/src/klee_output
"""
from __future__ import annotations
import argparse
import json
from dataclasses import dataclass, asdict
from pathlib import Path
from typing import Any, Dict, List, Optional
SEVERITY_MAP = {
"严重": "CRITICAL",
"": "HIGH",
"": "MEDIUM",
"": "LOW",
"提示": "INFO",
"信息": "INFO",
}
CVSS_BASE = {
"CRITICAL": 9.0,
"HIGH": 8.0,
"MEDIUM": 6.0,
"LOW": 3.5,
"INFO": 0.0,
}
CATEGORY_MAP = {
"缓冲区溢出": "memory_safety",
"整数溢出": "memory_safety",
"内存泄漏": "resource_management",
"双重释放": "memory_safety",
"使用已释放内存": "memory_safety",
"空指针解引用": "memory_safety",
"除零错误": "logic_bug",
}
IMPACT_HINT = {
"缓冲区溢出": "攻击者可能在目标进程中执行任意代码或导致服务崩溃。",
"双重释放": "可能被利用构造堆风水,实现任意代码执行或程序崩溃。",
"使用已释放内存": "可能触发未定义行为,造成崩溃或被构造为代码执行。",
"内存泄漏": "持续泄漏会导致内存耗尽,导致服务性能下降或崩溃。",
"整数溢出": "边界检查缺失可能绕过逻辑判断或触发缓冲区写入。",
}
REFERENCE_MAP = {
"缓冲区溢出": [
"https://owasp.org/www-community/attacks/Buffer_overflow_attack",
"https://cwe.mitre.org/data/definitions/119.html",
],
"双重释放": [
"https://cwe.mitre.org/data/definitions/415.html",
],
"使用已释放内存": [
"https://cwe.mitre.org/data/definitions/416.html",
],
"内存泄漏": [
"https://cwe.mitre.org/data/definitions/401.html",
],
"整数溢出": [
"https://cwe.mitre.org/data/definitions/190.html",
],
}
@dataclass
class Issue:
id: str
source: Dict[str, Any]
basic: Dict[str, Any]
location: Dict[str, Any]
severity: Dict[str, Any]
status: Dict[str, Any]
description: Dict[str, Any]
reproduce: Dict[str, Any]
root_cause: Dict[str, Any]
impact: Dict[str, Any]
fix: Dict[str, Any]
def _normalize_severity(raw: str) -> str:
if not raw:
return "INFO"
raw = raw.strip()
return SEVERITY_MAP.get(raw, raw.upper())
def _cvss_for(severity: str, confidence: Optional[int]) -> float:
base = CVSS_BASE.get(severity, 0.0)
if confidence is None:
return base
# 简单地根据置信度拉伸 CVSS
return round(min(10.0, base + (confidence / 100.0) * 1.5), 1)
def _category_for(vuln_type: str) -> str:
return CATEGORY_MAP.get(vuln_type, "logic_bug")
def _impact_for(vuln_type: str) -> str:
return IMPACT_HINT.get(vuln_type, "可能被利用造成稳定性下降或安全边界被绕过。")
def _references_for(vuln_type: str) -> List[str]:
return REFERENCE_MAP.get(vuln_type, [])
def _build_issue(vuln: Dict[str, Any], report_path: Path, klee_output: Optional[Path]) -> Issue:
severity_level = _normalize_severity(vuln.get("severity", ""))
issue_id = f"KLEE-{int(vuln.get('id', 0)):04d}"
file_path = vuln.get("file_path") or "UNKNOWN"
line_number = vuln.get("line_number")
snippet = (vuln.get("code_line") or "").strip()
issue_type = vuln.get("type") or "未知漏洞"
confidence = vuln.get("confidence_score")
confirmed = bool(vuln.get("confirmed_by_klee"))
artifacts: Dict[str, Any] = {}
if klee_output and confirmed:
artifacts["klee_output_dir"] = str(klee_output)
reproduce_steps = [
"切换到 symbolic-engine/src 目录。",
f"运行 ./test_analyzer {file_path} 以重放符号执行。",
]
if confirmed:
reproduce_steps.append("在 klee_output 目录中查看生成的 ktest 文件并使用 ktest-tool 复现。")
return Issue(
id=issue_id,
source={
"engine": "symbolic-engine",
"sub_tool": "KLEE",
"raw_ids": [str(vuln.get("id"))],
"report_path": str(report_path),
},
basic={
"title": f"{issue_type} - {file_path}",
"type": issue_type,
"cwe": None,
"category": _category_for(issue_type),
},
location={
"file": file_path,
"function": vuln.get("function"),
"line": line_number,
"column": vuln.get("column"),
"snippet": snippet,
},
severity={
"level": severity_level,
"cvss": _cvss_for(severity_level, confidence),
"cvss_vector": None,
},
status={
"state": "confirmed" if confirmed else "new",
"confirmed_by": ["klee"] if confirmed else [],
"first_seen": None,
"last_seen": None,
},
description={
"summary": vuln.get("description") or "",
"details": snippet or vuln.get("description") or "",
},
reproduce={
"steps": reproduce_steps,
"inputs": {},
"artifacts": artifacts,
},
root_cause={
"short": vuln.get("description") or "",
"technical_details": snippet,
},
impact={
"technical": _impact_for(issue_type),
"business": "可能影响系统稳定性与可用性。",
},
fix={
"recommendation": [vuln.get("fix_suggestion") or "参考安全开发规范修复该漏洞。"],
"code_patch_hint": snippet,
"references": _references_for(issue_type),
},
)
def _sanitize_report_text(text: str) -> str:
"""Repair non-standard JSON emitted by symbolic-engine (code_line broken lines)."""
lines = text.splitlines()
fixed: List[str] = []
i = 0
while i < len(lines):
line = lines[i]
needs_join = (
'"code_line"' in line
and not line.rstrip().endswith('",')
and i + 1 < len(lines)
and lines[i + 1].strip() == '",'
)
if needs_join:
fixed.append(line.rstrip("\n") + '",')
i += 2
continue
fixed.append(line)
i += 1
return "\n".join(fixed)
def _load_report(report_path: Path) -> Dict[str, Any]:
raw_text = report_path.read_text(encoding="utf-8")
try:
return json.loads(raw_text)
except json.JSONDecodeError:
repaired = _sanitize_report_text(raw_text)
return json.loads(repaired)
def convert(report_path: Path, output_path: Path, klee_output: Optional[Path]) -> None:
data = _load_report(report_path)
vulnerabilities = data.get("vulnerabilities", [])
issues = [_build_issue(v, report_path, klee_output) for v in vulnerabilities]
output_path.parent.mkdir(parents=True, exist_ok=True)
with output_path.open("w", encoding="utf-8") as f:
json.dump([asdict(issue) for issue in issues], f, ensure_ascii=False, indent=2)
print(f"[symbolic_adapter] Converted {len(issues)} issues -> {output_path}")
def main() -> None:
parser = argparse.ArgumentParser(description="Convert symbolic-engine report to unified issues.")
parser.add_argument(
"--report",
type=Path,
required=True,
help="Path to symbolic-engine static_analysis_report.json",
)
parser.add_argument(
"--output",
type=Path,
required=True,
help="Path to write unified issues JSON.",
)
parser.add_argument(
"--klee-output",
type=Path,
help="Optional path to klee_output directory for evidence reference.",
)
args = parser.parse_args()
convert(args.report, args.output, args.klee_output)
if __name__ == "__main__":
main()

File diff suppressed because it is too large Load Diff

@ -0,0 +1,327 @@
@startuml 完整项目类图
!define PUBLIC +
!define PRIVATE -
!define PROTECTED #
!define STATIC {static}
skinparam packageStyle rectangle
skinparam classAttributeIconSize 0
skinparam class {
BackgroundColor LightBlue
ArrowColor DarkBlue
BorderColor DarkBlue
}
title Report-Generation 项目完整类图
package "cppcheck_test_generator <<核心模块>>" {
' ============================================
' 数据模型层 (models.py)
' ============================================
package "数据模型层" #LightGreen {
class IssueLocation <<dataclass>> {
{field} PUBLIC file_path : Path
{field} PUBLIC line : Optional[int]
..
**职责**: 存储问题位置信息
**可见性**: 所有属性为public
}
class CppcheckIssue <<dataclass>> {
{field} PUBLIC id : str
{field} PUBLIC severity : str
{field} PUBLIC message : str
{field} PUBLIC locations : List[IssueLocation]
..
**职责**: 存储cppcheck问题完整信息
**可见性**: 所有属性为public
}
class CodeContext <<dataclass>> {
{field} PUBLIC file_path : Path
{field} PUBLIC function_name : Optional[str]
{field} PUBLIC class_name : Optional[str]
{field} PUBLIC namespace : Optional[str]
{field} PUBLIC includes : List[str]
{field} PUBLIC dependencies : List[str]
{field} PUBLIC variable_context : List[str]
{field} PUBLIC control_flow_context : List[str]
..
{method} PUBLIC __post_init__()
..
**职责**: 存储代码分析的上下文信息
**可见性**: 所有属性和方法为public
}
}
' ============================================
' 解析层 (parsers.py)
' ============================================
package "解析层" #LightYellow {
class CppcheckParser <<utility>> {
{method} STATIC PUBLIC parse_cppcheck_xml(xml_path: Path) : List[CppcheckIssue]
{method} STATIC PUBLIC parse_cppcheck_text(text_path: Path) : List[CppcheckIssue]
{method} STATIC PUBLIC read_code_snippet(file_path: Path, center_line: Optional[int], context: int = 30) : str
..
**职责**: 解析cppcheck报告文件
**可见性**: 所有方法为static public
**依赖**: 使用xml.etree.ElementTree解析XML
}
}
' ============================================
' 分析层 (analysis.py)
' ============================================
package "分析层" #LightCoral {
class CodeAnalyzer <<utility>> {
{method} STATIC PUBLIC analyze_code_context(file_path: Path, target_line: Optional[int], project_root: Optional[Path]) : CodeContext
{method} STATIC PUBLIC analyze_issue_relevance(issue: CppcheckIssue, code_context: CodeContext) : dict
{method} STATIC PUBLIC analyze_project_structure(project_root: Path) : dict
{method} STATIC PUBLIC get_enhanced_issue_analysis(issue: CppcheckIssue, project_info: Optional[dict]) : Tuple[CodeContext, dict]
{method} STATIC PUBLIC filter_and_clean_issues(issues: List[CppcheckIssue], project_info: Optional[dict]) : List[CppcheckIssue]
{method} STATIC PUBLIC prioritize_issues(issues: List[CppcheckIssue]) : List[CppcheckIssue]
{method} STATIC PUBLIC extract_issue_context_from_source(issue: CppcheckIssue, project_root: Optional[Path]) : dict
{method} STATIC PUBLIC write_cleaned_report(issues: List[CppcheckIssue], output_path: Path) : None
{method} STATIC PUBLIC analyze_issues_with_context(issues: List[CppcheckIssue]) : List[Tuple[CppcheckIssue, dict]]
..
**职责**: 代码分析和问题评估
**可见性**: 所有方法为static public
**算法**: 使用正则表达式和启发式规则
}
}
' ============================================
' 生成层 (generation.py)
' ============================================
package "生成层" #LightPink {
class TestGenerator <<utility>> {
{field} PRIVATE client : OpenAIClient
..
{method} STATIC PUBLIC generate_test_for_issue(issue: CppcheckIssue, model: str, project_root: Optional[Path], include_dirs: List[str], integration_test: bool, code_context: Optional[CodeContext], relevance_analysis: Optional[dict]) : str
{method} STATIC PUBLIC smart_select_issues(issues: List[CppcheckIssue], max_count: int, model: str) : List[CppcheckIssue]
{method} STATIC PUBLIC write_issue_output(output_dir: Path, idx: int, issue: CppcheckIssue, content: str, emit_runner: bool, verify: bool) : Path
{method} STATIC PRIVATE build_prompt_for_issue(issue: CppcheckIssue, project_root: Optional[Path], include_dirs: List[str], integration_test: bool, code_context: Optional[CodeContext], relevance_analysis: Optional[dict], use_template: bool) : str
{method} STATIC PRIVATE get_issue_specific_template(issue: CppcheckIssue, project_root: Optional[Path], include_dirs: List[str]) : str
{method} STATIC PRIVATE get_issue_specific_guidance(issue: CppcheckIssue) : str
{method} STATIC PRIVATE generate_issue_specific_test_code(issue: CppcheckIssue) : str
{method} STATIC PRIVATE generate_real_code_based_template(issue: CppcheckIssue, issue_context: dict, project_info: str, project_root: Optional[Path], includes_text: str) : str
{method} STATIC PRIVATE generate_default_template(issue: CppcheckIssue, project_info: str, project_root: Optional[Path]) : str
..
**职责**: AI驱动的测试用例生成
**可见性**: client为private主要方法为public辅助方法为private
**依赖**: 使用OpenAI API生成测试代码
}
}
' ============================================
' 验证层 (verification.py)
' ============================================
package "验证层" #LightSteelBlue {
class TestVerifier <<utility>> {
{method} STATIC PUBLIC verify_single_test(cpp_file: Path, timeout: int, project_root: Optional[Path], include_dirs: List[str]) : dict
{method} STATIC PUBLIC auto_verify_tests(output_dir: Path, timeout: int, project_root: Optional[Path], include_dirs: List[str]) : dict
{method} STATIC PUBLIC generate_verification_report(output_dir: Path, verification_results: dict) : Path
{method} STATIC PUBLIC generate_json_report(output_dir: Path, verification_results: dict) : Path
{method} STATIC PUBLIC verify_test_case(test_file_path: Path, issue: CppcheckIssue) : dict
{method} STATIC PRIVATE analyze_vulnerability_type(filename: str, result: dict) : str
{method} STATIC PRIVATE determine_vulnerability_confirmed(result: dict) : bool
..
**职责**: 测试用例验证和报告生成
**可见性**: 公共验证方法为public分析判断方法为private
**依赖**: 使用subprocess调用g++和cppcheck
}
}
' ============================================
' 主程序 (main.py)
' ============================================
package "主程序" #LightSalmon {
class MainProcessor {
{field} PRIVATE args : argparse.Namespace
{field} PRIVATE project_info : Optional[dict]
{field} PRIVATE issues : List[CppcheckIssue]
..
{method} PUBLIC main(argv: List[str]) : int
..
**职责**: 协调整个工作流程
**可见性**: main为public内部状态为private
**模式**: 主协调器模式
}
}
}
' ============================================
' 独立工具模块
' ============================================
package "独立工具模块" #LightGray {
class CodeReview {
{method} PUBLIC analyze_file(input_path: Path, output_path: Path, instruction: str, model: str = "deepseek-chat") : None
{method} PUBLIC detect_language_by_suffix(file_path: Path) : str
{method} PUBLIC build_messages(code_path: Path, code_content: str, instruction: str) : List[dict]
{method} PUBLIC read_text_file(file_path: Path) : str
{method} PUBLIC main(argv: List[str]) : int
..
**职责**: 代码审查工具
**可见性**: 所有方法为public
**文件**: code_review.py
}
}
' ============================================
' 外部依赖
' ============================================
package "外部依赖" #Wheat {
class OpenAIClient <<external>> {
{method} PUBLIC chat.completions.create()
..
**来源**: test.py
**用途**: AI生成服务
}
class ExternalTools <<external>> {
{field} PUBLIC g++ : C++编译器
{field} PUBLIC cppcheck : 静态分析工具
..
**用途**: 编译和验证工具
}
class Path <<external>> {
{method} PUBLIC exists() : bool
{method} PUBLIC read_text() : str
{method} PUBLIC glob() : List[Path]
..
**来源**: pathlib
}
class argparse <<external>> {
{method} PUBLIC ArgumentParser()
..
**来源**: argparse模块
}
}
' ============================================
' 关系定义
' ============================================
' 组合关系
CppcheckIssue *-- IssueLocation : contains
' 依赖关系(使用)
MainProcessor ..> CppcheckParser : uses\n解析报告
MainProcessor ..> CodeAnalyzer : uses\n分析和过滤
MainProcessor ..> TestGenerator : uses\n生成测试用例
MainProcessor ..> TestVerifier : uses\n验证测试用例
MainProcessor --> CppcheckIssue : manages\n管理问题列表
CppcheckParser ..> CppcheckIssue : creates\n创建问题对象
CppcheckParser ..> IssueLocation : creates\n创建位置对象
CodeAnalyzer ..> CppcheckIssue : analyzes\n分析问题
CodeAnalyzer ..> CodeContext : creates\n创建上下文
CodeAnalyzer ..> IssueLocation : uses\n使用位置信息
CodeAnalyzer ..> CppcheckParser : uses\n读取代码片段
TestGenerator ..> CppcheckIssue : processes\n处理问题
TestGenerator ..> CodeContext : uses\n使用上下文
TestGenerator ..> OpenAIClient : calls\n调用AI服务
TestGenerator ..> TestVerifier : uses\n验证测试用例
TestGenerator ..> CodeAnalyzer : uses\n获取分析结果
TestVerifier ..> CppcheckIssue : verifies\n验证问题
TestVerifier ..> ExternalTools : invokes\n调用外部工具
CodeReview ..> OpenAIClient : uses\n使用AI服务
' 泛化/实现关系
Path <|-- IssueLocation : uses
Path <|-- CodeContext : uses
' ============================================
' 注释说明
' ============================================
note right of CppcheckIssue
**核心数据模型**
- 存储cppcheck检测到的问题
- 包含问题ID、严重级别、消息
- 关联多个位置信息
end note
note right of CodeContext
**上下文信息模型**
- 存储代码分析的完整上下文
- 包含函数、类、命名空间信息
- 包含变量和控制流上下文
end note
note right of MainProcessor
**主程序协调器**
工作流程:
1. 解析命令行参数
2. 解析报告文件
3. 过滤和清理问题
4. 生成测试用例
5. 验证测试用例
6. 生成报告
end note
note right of TestGenerator
**AI测试用例生成器**
- 使用AI生成测试用例
- 支持模板模式和AI生成模式
- 智能选择最有代表性的问题
- 集成代码上下文分析
end note
note right of CodeAnalyzer
**智能分析引擎**
- 分析代码上下文
- 评估问题相关性
- 过滤不可靠问题
- 优先级排序
end note
note bottom of TestVerifier
**自动化验证引擎**
- 编译测试用例
- 执行程序
- 分析漏洞类型
- 生成验证报告
end note
legend right
| 图例说明 |
**可见性符号**:
| + | public 公共 |
| - | private 私有 |
| # | protected 受保护 |
| {static} | 静态方法 |
**关系类型**:
| --> | 关联/依赖 |
| *-- | 组合关系 |
| <|-- | 泛化关系 |
**模块职责**:
| 数据模型层 | 定义核心数据结构 |
| 解析层 | 解析输入文件 |
| 分析层 | 代码分析和评估 |
| 生成层 | AI生成测试用例 |
| 验证层 | 自动化验证 |
| 主程序 | 工作流协调 |
endlegend
@enduml

@ -0,0 +1,161 @@
@startuml 软件体系结构设计图
!define RECTANGLE class
skinparam packageStyle rectangle
skinparam classAttributeIconSize 0
package "Report-Generation 系统" {
package "cppcheck_test_generator" <<核心模块>> {
package "数据模型层 (models)" {
class CppcheckIssue {
+ id: str
+ severity: str
+ message: str
+ locations: List[IssueLocation]
}
class IssueLocation {
+ file_path: Path
+ line: Optional[int]
}
class CodeContext {
+ file_path: Path
+ function_name: Optional[str]
+ class_name: Optional[str]
+ namespace: Optional[str]
+ includes: List[str]
+ dependencies: List[str]
+ variable_context: List[str]
+ control_flow_context: List[str]
}
}
package "解析层 (parsers)" {
class Parsers {
+ parse_cppcheck_xml(xml_path): List[CppcheckIssue]
+ parse_cppcheck_text(text_path): List[CppcheckIssue]
+ read_code_snippet(file_path, line, context): str
}
}
package "分析层 (analysis)" {
class Analysis {
+ analyze_code_context(file_path, line): CodeContext
+ analyze_issue_relevance(issue, context): dict
+ analyze_project_structure(project_root): dict
+ get_enhanced_issue_analysis(issue): Tuple
+ filter_and_clean_issues(issues): List[CppcheckIssue]
+ prioritize_issues(issues): List[CppcheckIssue]
}
}
package "生成层 (generation)" {
class Generation {
+ generate_test_for_issue(issue): str
+ get_issue_specific_template(issue): str
+ smart_select_issues(issues, max_count): List[CppcheckIssue]
+ write_issue_output(output_dir, issue, content): Path
+ generate_issue_specific_test_code(issue): str
}
}
package "验证层 (verification)" {
class Verification {
+ verify_single_test(cpp_file): dict
+ auto_verify_tests(output_dir): dict
+ generate_verification_report(results): Path
+ generate_json_report(results): Path
+ analyze_vulnerability_type(filename, result): str
+ determine_vulnerability_confirmed(result): bool
}
}
package "主程序 (main)" {
class Main {
+ main(argv): int
- 处理命令行参数
- 协调各模块工作流
- 控制执行流程
}
}
}
package "独立工具模块" {
class CodeReview {
+ analyze_file(input_path, output_path, instruction): None
+ detect_language_by_suffix(file_path): str
+ build_messages(code_path, code_content, instruction): List[dict]
}
class CppcheckToTests {
+ main(argv): int
..旧版本单文件实现..
}
}
package "外部依赖" {
class TestModule {
+ client: OpenAIClient
+ test_connection(): bool
}
class ExternalTools {
+ g++ : C++编译器
+ cppcheck : 静态分析工具
}
}
}
' 依赖关系
Main --> Parsers : 使用
Main --> Analysis : 使用
Main --> Generation : 使用
Main --> Verification : 使用
Main --> CppcheckIssue : 使用
Parsers --> CppcheckIssue : 创建
Parsers --> IssueLocation : 创建
Analysis --> CppcheckIssue : 分析
Analysis --> CodeContext : 创建和使用
Analysis --> IssueLocation : 使用
Generation --> CppcheckIssue : 处理
Generation --> CodeContext : 使用
Generation --> TestModule : 调用AI接口
Verification --> CppcheckIssue : 验证
Verification --> ExternalTools : 调用编译工具
CodeReview --> TestModule : 使用AI客户端
CppcheckToTests --> TestModule : 使用AI客户端
note right of cppcheck_test_generator
**核心模块化架构**
采用分层架构设计:
- 数据模型层:定义核心数据结构
- 解析层:处理输入数据
- 分析层:智能分析和过滤
- 生成层AI驱动生成测试用例
- 验证层:自动化验证和报告
- 主程序:统一调度和协调
end note
note right of Main
**主程序工作流程**
1. 解析命令行参数
2. 读取cppcheck报告
3. 过滤和清理问题
4. 智能选择问题
5. 生成测试用例
6. 可选:自动验证
7. 生成报告
end note
@enduml

@ -0,0 +1,126 @@
# 解决 Node.js 版本问题
## 问题
当前 Node.js 版本是 v16.20.0,但 Vite 5.x 需要 Node.js 18+ 或 20+。
## 解决方案
### 方案 1: 升级 Node.js推荐
#### 使用 nvm 升级(推荐方法)
```bash
# 1. 安装 nvm如果还没有
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# 2. 重新加载 shell
source ~/.bashrc
# 3. 安装 Node.js 20 LTS
nvm install 20
# 4. 使用 Node.js 20
nvm use 20
# 5. 验证版本
node --version # 应该显示 v20.x.x
# 6. 重新安装依赖
cd ~/klee-build/platform-frontend
rm -rf node_modules package-lock.json
npm install
```
#### 使用 apt 升级Ubuntu/Debian
```bash
# 1. 安装 Node.js 20
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
# 2. 验证版本
node --version # 应该显示 v20.x.x
# 3. 重新安装依赖
cd ~/klee-build/platform-frontend
rm -rf node_modules package-lock.json
npm install
```
### 方案 2: 降级 Vite临时方案
如果暂时无法升级 Node.js我已经将 Vite 降级到 4.5.3(支持 Node 16
现在执行:
```bash
cd ~/klee-build/platform-frontend
rm -rf node_modules package-lock.json
npm install
```
## 如果 npm install 仍然失败
### 问题esbuild 路径错误
这是因为 npm 在 WSL 中运行但试图访问 Windows 路径。解决方法:
```bash
# 1. 设置 npm 使用 WSL 内部路径
export npm_config_cache=~/.npm-cache
export npm_config_prefix=~/.npm-global
# 2. 确保在 WSL 文件系统中
cd ~/klee-build/platform-frontend
# 3. 使用 --no-optional 跳过可选依赖(如果 esbuild 还是有问题)
npm install --no-optional
# 或者手动安装 esbuild
npm install esbuild --save-dev
npm install
```
### 问题UNC 路径不支持
如果看到 "UNC 路径不受支持" 错误:
```bash
# 确保在 WSL 文件系统中,不要使用 \\wsl.localhost 路径
# 使用 ~ 或 /home/feng 路径
cd /home/feng/klee-build/platform-frontend
npm install
```
## 验证安装
安装成功后:
```bash
# 检查 node_modules
ls -la node_modules | head -10
# 检查是否可以启动
npm run dev
```
## 推荐操作
**最佳方案**:升级到 Node.js 20 LTS
```bash
# 使用 nvm最简单
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
source ~/.bashrc
nvm install 20
nvm use 20
cd ~/klee-build/platform-frontend
npm install
```
这样可以使用最新的 Vite 5.x性能更好。

@ -0,0 +1,106 @@
# 修复 npm 权限问题
## 问题说明
npm 缓存目录指向 Windows 路径,导致权限问题。需要在 WSL bash 中重新配置。
## 解决方案
**重要**: 请在 **WSL bash 终端**中执行以下命令(不是 PowerShell
### 方法 1: 设置 npm 缓存到 WSL 内部(推荐)
```bash
# 1. 进入前端目录
cd ~/klee-build/platform-frontend
# 2. 设置 npm 缓存到 WSL 内部路径
npm config set cache ~/.npm-cache
# 3. 清理旧的缓存
npm cache clean --force
# 4. 重新安装依赖
npm install
```
### 方法 2: 使用 --cache 参数
```bash
cd ~/klee-build/platform-frontend
# 直接指定缓存路径安装
npm install --cache ~/.npm-cache
```
### 方法 3: 如果还是有问题,使用 sudo不推荐但可以临时解决
```bash
cd ~/klee-build/platform-frontend
sudo npm install
```
## 验证安装
安装完成后,检查 node_modules 是否存在:
```bash
ls -la ~/klee-build/platform-frontend/node_modules | head -10
```
如果看到很多目录,说明安装成功。
## 然后启动服务
### 启动后端(终端 1
```bash
cd ~/klee-build/symbolic-engine/webui
python3 app.py
```
### 启动前端(终端 2
```bash
cd ~/klee-build/platform-frontend
npm run dev
```
## 如果 npm install 仍然失败
尝试以下步骤:
```bash
# 1. 删除 node_modules 和 package-lock.json如果存在
cd ~/klee-build/platform-frontend
rm -rf node_modules package-lock.json
# 2. 设置 npm 配置
npm config set cache ~/.npm-cache
npm config set prefix ~/.npm-global
# 3. 添加到 PATH如果需要
export PATH=~/.npm-global/bin:$PATH
# 4. 重新安装
npm install
```
## 永久解决方案
`~/.bashrc``~/.zshrc` 中添加:
```bash
# 设置 npm 缓存到 WSL 内部
export npm_config_cache=~/.npm-cache
export npm_config_prefix=~/.npm-global
export PATH=~/.npm-global/bin:$PATH
```
然后重新加载:
```bash
source ~/.bashrc
```

@ -0,0 +1,192 @@
# 前后端集成完成总结
## ✅ 已完成的工作
### 前端部分
1. **类型定义** (`platform-frontend/src/types.ts`)
- ✅ 添加了 `UnifiedReport``UnifiedIssue` 类型
- ✅ 添加了 API 相关类型(`AnalysisTask`, `AnalyzeRequest`
2. **API 服务层** (`platform-frontend/src/services/api.ts`)
- ✅ 实现了完整的 API 客户端
- ✅ 错误处理和类型安全
3. **React Query Hooks** (`platform-frontend/src/hooks/useAnalysis.ts`)
- ✅ `useAnalysisFlow()` - 完整的状态管理
- ✅ 自动轮询任务状态
- ✅ 错误处理和重试机制
4. **ReportGenerate 页面** (`platform-frontend/src/pages/ReportGenerate.tsx`)
- ✅ 文件上传功能
- ✅ 分析进度显示
- ✅ 结果预览和错误处理
5. **开发环境配置**
- ✅ Vite 代理配置
- ✅ 环境变量支持
### 后端部分
1. **Flask WebUI 扩展** (`symbolic-engine/webui/app.py`)
- ✅ 添加了 CORS 支持
- ✅ 实现了任务管理系统(内存 + 文件持久化)
- ✅ 实现了后台异步分析任务
2. **API 接口**
- ✅ `POST /api/analyze` - 发起分析任务
- ✅ `GET /api/tasks/:taskId` - 查询任务状态
- ✅ `GET /api/reports/:taskId` - 获取分析报告
- ✅ `POST /api/tasks/:taskId/cancel` - 取消任务
3. **统一报告生成**
- ✅ 将 symbolic-engine 的报告转换为统一格式
- ✅ 计算风险评分和统计信息
4. **依赖更新**
- ✅ 添加了 `flask-cors` 依赖
## 🚀 如何启动和测试
### 1. 启动后端服务
```bash
# 进入后端目录
cd symbolic-engine/webui
# 安装依赖(如果还没有)
pip install -r requirements.txt
# 启动 Flask 服务
python app.py
```
后端服务将在 `http://localhost:5000` 启动。
### 2. 启动前端服务
```bash
# 进入前端目录
cd platform-frontend
# 安装依赖(如果还没有)
npm install
# 启动开发服务器
npm run dev
```
前端服务将在 `http://localhost:5174` 启动。
### 3. 测试完整流程
1. **打开前端应用**: http://localhost:5174
2. **导航到报告生成页面**: 点击"生成报告"或访问 `/reports/generate`
3. **上传文件**: 选择一个 C/C++ 源文件(.c, .cpp, .cc, .h, .hpp
4. **选择分析引擎**: 选择 cppcheck 和/或 KLEE
5. **开始分析**: 点击"开始分析"按钮
6. **观察进度**: 页面会显示分析进度和状态
7. **查看结果**: 分析完成后会显示漏洞统计和预览
## 📁 文件结构
```
klee-build/
├── platform-frontend/ # 前端应用
│ ├── src/
│ │ ├── services/api.ts # API 服务层
│ │ ├── hooks/useAnalysis.ts # React Query hooks
│ │ ├── pages/ReportGenerate.tsx # 报告生成页面
│ │ └── types.ts # 类型定义
│ ├── vite.config.ts # Vite 配置(含代理)
│ └── INTEGRATION_STATUS.md # 集成状态文档
└── symbolic-engine/
└── webui/
├── app.py # Flask 应用(含 API
├── requirements.txt # Python 依赖
└── API_README.md # API 文档
```
## 🔧 配置说明
### 前端环境变量
创建 `platform-frontend/.env`:
```env
VITE_API_BASE=http://localhost:5000
```
### 后端环境变量
```bash
export HOST=0.0.0.0
export PORT=5000
export MAX_UPLOAD_BYTES=2097152 # 2MB
```
## 📝 API 使用示例
### 使用 curl 测试 API
```bash
# 1. 发起分析任务
curl -X POST http://localhost:5000/api/analyze \
-F "file=@test.c" \
-F 'engines=["klee"]'
# 响应: {"taskId": "xxx", "status": "pending", "progress": 0}
# 2. 查询任务状态
curl http://localhost:5000/api/tasks/{taskId}
# 3. 获取报告
curl http://localhost:5000/api/reports/{taskId}
```
## ⚠️ 注意事项
1. **KLEE 分析耗时**: KLEE 符号执行可能需要较长时间(几分钟到几十分钟),请耐心等待
2. **文件大小限制**: 默认最大上传 2MB大文件需要调整配置
3. **并发限制**: 当前实现使用线程,建议不要同时运行过多任务
4. **编译要求**: 确保 `test_analyzer` 已编译,否则分析会失败
## 🐛 故障排除
### 前端无法连接后端
- 检查后端是否运行在 `http://localhost:5000`
- 检查浏览器控制台的网络错误
- 确认 CORS 已正确配置
### 分析任务失败
- 检查 `symbolic-engine/src/test_analyzer` 是否存在
- 检查 KLEE 是否已安装
- 查看后端日志和任务目录中的错误信息
### 报告格式错误
- 检查 `symbolic-engine/src/output/static_analysis_report.json` 是否存在
- 确认 JSON 格式正确
## 📚 相关文档
- [前端集成状态](./platform-frontend/INTEGRATION_STATUS.md)
- [前端集成方案](./platform-frontend/INTEGRATION_PLAN.md)
- [后端 API 文档](./symbolic-engine/webui/API_README.md)
- [symbolic-engine README](./symbolic-engine/README.md)
## 🎉 下一步
现在前后端已完全集成,可以:
1. **测试完整流程**: 上传文件并查看分析结果
2. **扩展功能**:
- 添加 cppcheck 集成
- 添加报告详情页面
- 添加历史报告列表
3. **优化体验**:
- 添加更详细的进度信息
- 优化错误提示
- 添加报告导出功能

@ -0,0 +1,170 @@
# 🚀 快速开始 - 测试系统
## 当前状态
你已经完成了前后端集成,现在需要测试系统是否可用。
## 第一步:检查环境
在 WSL 终端中执行以下命令:
```bash
# 1. 检查 Python
python3 --version
# 2. 检查 Node.js
node --version
# 3. 检查后端依赖
cd symbolic-engine/webui
pip3 install -r requirements.txt
# 4. 检查前端依赖
cd ../../platform-frontend
npm install
```
## 第二步:编译 test_analyzer如果需要
```bash
cd symbolic-engine/src
if [ ! -f test_analyzer ]; then
echo "编译 test_analyzer..."
gcc -o test_analyzer test_analyzer.c intelligent_analyzer.c -I. -lpthread
fi
```
## 第三步:启动服务
### 终端 1 - 启动后端
```bash
cd symbolic-engine/webui
python3 app.py
```
**看到以下输出说明成功**:
```
* Running on http://0.0.0.0:5000
```
### 终端 2 - 启动前端
```bash
cd platform-frontend
npm run dev
```
**看到以下输出说明成功**:
```
➜ Local: http://localhost:5174/
```
## 第四步:测试
### 方法 1: 浏览器测试(最简单)
1. 打开浏览器访问: **http://localhost:5174**
2. 点击"生成报告"或直接访问: **http://localhost:5174/reports/generate**
3. 上传一个 C 文件(可以创建一个简单的测试文件)
4. 选择分析引擎KLEE 或 cppcheck
5. 点击"开始分析"
6. 观察分析进度和结果
### 方法 2: API 测试
在**第三个终端**中:
```bash
# 创建测试文件
cat > test.c << 'EOF'
#include <stdio.h>
#include <string.h>
int main() {
char buffer[10];
char input[20] = "test";
strcpy(buffer, input);
return 0;
}
EOF
# 测试 API
curl -X POST http://localhost:5000/api/analyze \
-F "file=@test.c" \
-F 'engines=["klee"]'
```
应该返回类似:
```json
{"taskId": "xxx-xxx-xxx", "status": "pending", "progress": 0}
```
然后查询任务状态(替换 YOUR_TASK_ID
```bash
curl http://localhost:5000/api/tasks/YOUR_TASK_ID
```
## 验证清单
完成以下检查,确认系统可用:
- [ ] 后端服务可以启动(看到 "Running on http://0.0.0.0:5000"
- [ ] 前端服务可以启动(看到 "Local: http://localhost:5174"
- [ ] 浏览器可以访问前端页面
- [ ] 可以上传 C/C++ 文件
- [ ] API 可以创建分析任务
- [ ] 可以查询任务状态
- [ ] 分析完成后可以获取报告
- [ ] 前端可以显示分析结果
## 如果遇到问题
### 问题 1: 后端无法启动
```bash
# 检查依赖
cd symbolic-engine/webui
pip3 install flask flask-cors werkzeug
# 检查端口是否被占用
netstat -an | grep 5000
```
### 问题 2: 前端无法连接后端
```bash
# 检查后端是否运行
curl http://localhost:5000/
# 如果无法连接,检查防火墙或端口
```
### 问题 3: 分析任务失败
```bash
# 检查 test_analyzer
cd symbolic-engine/src
ls -la test_analyzer
# 如果没有,编译它
gcc -o test_analyzer test_analyzer.c intelligent_analyzer.c -I. -lpthread
```
## 下一步
如果所有测试都通过:
1. ✅ 系统已经可以使用了!
2. 📝 可以开始上传你的实际代码进行分析
3. 🔍 查看分析报告和漏洞详情
4. 🛠️ 根据建议修复安全问题
## 详细文档
- [完整测试指南](./TESTING_GUIDE.md)
- [API 文档](./symbolic-engine/webui/API_README.md)
- [集成完成总结](./INTEGRATION_COMPLETE.md)

@ -0,0 +1,147 @@
# 🧪 测试指南 - 如何验证系统是否可用
## 快速开始3步测试
### 步骤 1: 检查环境
```bash
# 运行环境检查脚本(如果支持)
bash check_environment.sh
# 或手动检查
cd symbolic-engine/webui && pip install -r requirements.txt
cd ../../platform-frontend && npm install
```
### 步骤 2: 启动服务
**终端 1 - 启动后端**:
```bash
cd symbolic-engine/webui
python app.py
```
**终端 2 - 启动前端**:
```bash
cd platform-frontend
npm run dev
```
### 步骤 3: 测试
**方法 A - 浏览器测试(最简单)**:
1. 打开 http://localhost:5174
2. 点击"生成报告"
3. 上传一个 C 文件
4. 点击"开始分析"
5. 观察是否显示进度
**方法 B - API 测试(验证后端)**:
```bash
# 运行 API 测试脚本
bash test_api.sh
# 或手动测试
curl -X POST http://localhost:5000/api/analyze \
-F "file=@test.c" \
-F 'engines=["klee"]'
```
## 📋 详细测试步骤
### 1. 环境准备测试
```bash
# 检查所有依赖
bash check_environment.sh
```
**预期结果**: 所有必要工具都已安装
### 2. 后端 API 测试
```bash
# 运行完整 API 测试
bash test_api.sh
```
**预期结果**:
- ✅ 后端服务响应正常
- ✅ 文件上传成功
- ✅ 任务创建成功
- ✅ 可以查询任务状态
- ✅ 可以获取分析报告
### 3. 前端界面测试
1. 访问 http://localhost:5174
2. 测试各个页面是否正常加载
3. 测试文件上传功能
4. 测试分析流程
### 4. 集成测试
完整流程测试:
1. 上传文件 → 2. 开始分析 → 3. 查看进度 → 4. 获取结果
## 🔍 验证清单
完成以下检查项:
- [ ] 后端服务可以启动(端口 5000
- [ ] 前端服务可以启动(端口 5174
- [ ] 浏览器可以访问前端
- [ ] API 可以创建任务
- [ ] 可以查询任务状态
- [ ] 可以获取分析报告
- [ ] 前端可以显示结果
## 🐛 常见问题
### 后端无法启动
```bash
# 检查依赖
pip install -r symbolic-engine/webui/requirements.txt
# 检查端口
lsof -i :5000
```
### 前端无法连接后端
```bash
# 检查后端是否运行
curl http://localhost:5000/
# 检查 CORS
pip install flask-cors
```
### 分析任务失败
```bash
# 编译 test_analyzer
cd symbolic-engine/src
gcc -o test_analyzer test_analyzer.c intelligent_analyzer.c -I. -lpthread
```
## 📚 更多文档
- [完整测试指南](./TESTING_GUIDE.md) - 详细的测试步骤和故障排除
- [快速开始](./START_HERE.md) - 最简单的开始方式
- [集成完成总结](./INTEGRATION_COMPLETE.md) - 系统架构和功能说明
## ✅ 测试通过标准
如果以下所有项目都正常,说明系统可以使用:
1. ✅ 后端服务启动成功
2. ✅ 前端服务启动成功
3. ✅ 可以上传文件
4. ✅ 可以创建分析任务
5. ✅ 可以查询任务状态
6. ✅ 可以获取分析报告
7. ✅ 前端可以显示结果
**如果全部通过,恭喜!系统已经可以正常使用了!** 🎉

@ -0,0 +1,117 @@
# 解决 esbuild 安装问题
## 问题原因
esbuild 的安装脚本试图使用 Windows 的 cmd.exe但路径是 WSL 的 UNC 路径,导致失败。
## 解决方案
### 方法 1: 跳过脚本安装(推荐)
在 WSL bash 终端中执行:
```bash
cd ~/klee-build/platform-frontend
# 设置环境变量
export npm_config_cache=~/.npm-cache
export npm_config_prefix=~/.npm-global
# 清理
rm -rf node_modules package-lock.json
# 跳过脚本安装
npm install --ignore-scripts
# 手动安装 esbuild使用预编译版本
npm install esbuild@0.19.12 --save-dev --ignore-scripts
# 如果需要,运行构建
npm rebuild esbuild --ignore-scripts || true
```
### 方法 2: 使用预编译的 esbuild
```bash
cd ~/klee-build/platform-frontend
# 直接安装预编译版本
npm install esbuild-linux-x64@0.19.12 --save-dev
# 然后安装其他依赖
npm install --ignore-scripts
```
### 方法 3: 使用 WSL 内部的 Node.js最佳
如果 Windows 的 Node.js 导致问题,安装 WSL 内部的 Node.js
```bash
# 安装 Node.js 20在 WSL 内部)
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
# 验证(应该显示 v20.x.x
node --version
which node # 应该显示 /usr/bin/nodeWSL 内部)
# 然后安装依赖
cd ~/klee-build/platform-frontend
npm install
```
### 方法 4: 使用 nvm推荐用于开发
```bash
# 安装 nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
source ~/.bashrc
# 安装 Node.js 20
nvm install 20
nvm use 20
# 验证
node --version
which node # 应该显示 ~/.nvm/versions/node/v20.x.x/bin/node
# 安装依赖
cd ~/klee-build/platform-frontend
npm install
```
## 快速修复(立即执行)
执行以下命令:
```bash
cd ~/klee-build/platform-frontend
export npm_config_cache=~/.npm-cache
npm install --ignore-scripts
npm install esbuild@0.19.12 --save-dev --ignore-scripts
```
然后尝试启动:
```bash
npm run dev
```
如果启动成功,说明问题已解决!
## 验证
安装完成后:
```bash
# 检查 node_modules
ls node_modules | grep -E "react|vite|esbuild"
# 尝试启动
npm run dev
```
如果 `npm run dev` 可以启动,说明一切正常!

@ -0,0 +1,233 @@
# 🚀 快速开始 - 测试系统是否可用
## 第一步:检查环境
### 1. 检查后端依赖
```bash
cd symbolic-engine/webui
pip install -r requirements.txt
```
### 2. 检查前端依赖
```bash
cd platform-frontend
npm install
```
### 3. 检查 test_analyzer 是否编译
```bash
cd symbolic-engine/src
if [ ! -f test_analyzer ]; then
echo "需要编译 test_analyzer..."
gcc -o test_analyzer test_analyzer.c intelligent_analyzer.c -I. -lpthread
echo "编译完成!"
else
echo "test_analyzer 已存在"
fi
```
## 第二步:启动服务
### 启动后端(终端 1
```bash
cd symbolic-engine/webui
python app.py
```
**看到以下输出说明成功**:
```
* Running on http://0.0.0.0:5000
```
### 启动前端(终端 2
```bash
cd platform-frontend
npm run dev
```
**看到以下输出说明成功**:
```
➜ Local: http://localhost:5174/
```
## 第三步:快速验证
### 方法 1: 使用浏览器(推荐)
1. 打开浏览器访问: **http://localhost:5174**
2. 点击"生成报告"或访问: **http://localhost:5174/reports/generate**
3. 上传一个 C 文件(如果没有,可以创建一个简单的测试文件)
4. 点击"开始分析"
5. 观察是否显示分析进度
### 方法 2: 使用 curl 命令
打开**第三个终端**,执行以下命令:
```bash
# 1. 测试后端是否响应
curl http://localhost:5000/
# 2. 创建测试文件
cat > test.c << 'EOF'
#include <stdio.h>
int main() { return 0; }
EOF
# 3. 测试 API - 上传文件并创建分析任务
curl -X POST http://localhost:5000/api/analyze \
-F "file=@test.c" \
-F 'engines=["klee"]'
# 4. 从响应中获取 taskId然后查询状态替换 YOUR_TASK_ID
curl http://localhost:5000/api/tasks/YOUR_TASK_ID
```
## 第四步:检查结果
### 如果一切正常,你应该看到:
**后端**: 终端显示 Flask 服务运行中
**前端**: 浏览器可以访问页面
**API**: curl 返回 JSON 响应,包含 taskId
**分析**: 前端页面显示分析进度
### 如果出现问题:
#### 问题:后端无法启动
```bash
# 检查端口是否被占用
netstat -an | grep 5000 # Linux/Mac
# 或
netstat -ano | findstr 5000 # Windows
# 如果端口被占用,可以更换端口
export PORT=5001
python app.py
```
#### 问题:前端无法连接后端
```bash
# 检查后端是否真的在运行
curl http://localhost:5000/api/analyze
# 检查前端代理配置
cat platform-frontend/vite.config.ts
```
#### 问题:分析任务失败
```bash
# 检查 test_analyzer 是否存在
ls -la symbolic-engine/src/test_analyzer
# 如果不存在,编译它
cd symbolic-engine/src
gcc -o test_analyzer test_analyzer.c intelligent_analyzer.c -I. -lpthread
```
## 完整测试流程示例
### 1. 准备测试文件
```bash
# 创建一个包含漏洞的测试文件
cat > test_vulnerable.c << 'EOF'
#include <stdio.h>
#include <string.h>
int main() {
char buffer[10];
char input[20] = "This is too long";
strcpy(buffer, input); // 缓冲区溢出
return 0;
}
EOF
```
### 2. 通过前端测试
1. 访问 http://localhost:5174/reports/generate
2. 上传 `test_vulnerable.c`
3. 选择 "KLEE (符号执行)"
4. 点击"开始分析"
5. 等待分析完成(可能需要几分钟)
6. 查看分析结果
### 3. 通过 API 测试
```bash
# 上传文件并获取 taskId
RESPONSE=$(curl -s -X POST http://localhost:5000/api/analyze \
-F "file=@test_vulnerable.c" \
-F 'engines=["klee"]')
TASK_ID=$(echo $RESPONSE | grep -o '"taskId":"[^"]*"' | cut -d'"' -f4)
echo "任务ID: $TASK_ID"
# 轮询任务状态每5秒查询一次最多等待5分钟
for i in {1..60}; do
sleep 5
STATUS=$(curl -s "http://localhost:5000/api/tasks/$TASK_ID" | grep -o '"status":"[^"]*"' | cut -d'"' -f4)
echo "[$i] 状态: $STATUS"
if [ "$STATUS" = "completed" ]; then
echo "分析完成!获取报告..."
curl -s "http://localhost:5000/api/reports/$TASK_ID" | head -50
break
elif [ "$STATUS" = "failed" ]; then
echo "分析失败"
break
fi
done
```
## 验证清单
完成以下检查,确认系统可用:
- [ ] 后端服务可以启动(端口 5000
- [ ] 前端服务可以启动(端口 5174
- [ ] 浏览器可以访问前端页面
- [ ] 可以上传 C/C++ 文件
- [ ] API 可以创建分析任务
- [ ] 可以查询任务状态
- [ ] 分析完成后可以获取报告
- [ ] 前端可以显示分析结果
## 下一步
如果所有测试都通过,你可以:
1. **查看详细文档**:
- [完整测试指南](./TESTING_GUIDE.md)
- [集成完成总结](./INTEGRATION_COMPLETE.md)
- [API 文档](./symbolic-engine/webui/API_README.md)
2. **开始使用**:
- 上传你的实际代码文件进行分析
- 查看分析报告和漏洞详情
- 根据建议修复安全问题
3. **扩展功能**:
- 集成 cppcheck 静态分析
- 添加报告导出功能
- 实现历史报告管理
## 需要帮助?
如果遇到问题:
1. 查看 [测试指南](./TESTING_GUIDE.md) 中的故障排除部分
2. 检查后端日志(终端 1
3. 检查浏览器控制台F12
4. 查看任务目录: `symbolic-engine/tasks/`
祝测试顺利!🎉

@ -0,0 +1,546 @@
# 测试指南 - 前后端集成测试
## 📋 测试前准备
### 1. 检查依赖
#### 后端依赖
```bash
cd symbolic-engine/webui
pip list | grep -E "flask|werkzeug|flask-cors"
```
如果没有安装,执行:
```bash
pip install -r requirements.txt
```
#### 前端依赖
```bash
cd platform-frontend
npm list --depth=0
```
如果没有安装,执行:
```bash
npm install
```
### 2. 检查工具
#### 检查 KLEE 是否安装
```bash
klee --version
```
#### 检查 test_analyzer 是否编译
```bash
cd symbolic-engine/src
ls -la test_analyzer
```
如果没有,需要编译:
```bash
cd symbolic-engine/src
gcc -o test_analyzer test_analyzer.c intelligent_analyzer.c -I. -lpthread
```
### 3. 准备测试文件
创建一个简单的测试文件 `test_example.c`:
```c
// test_example.c - 用于测试的简单 C 程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int vulnerable_function(char* input) {
char buffer[10];
strcpy(buffer, input); // 潜在的缓冲区溢出
return strlen(buffer);
}
int main(int argc, char* argv[]) {
if (argc > 1) {
vulnerable_function(argv[1]);
}
return 0;
}
```
## 🚀 启动服务
### 步骤 1: 启动后端服务
打开第一个终端:
```bash
cd symbolic-engine/webui
python app.py
```
**预期输出**:
```
* Serving Flask app 'app'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment.
* Running on http://0.0.0.0:5000
```
### 步骤 2: 启动前端服务
打开第二个终端:
```bash
cd platform-frontend
npm run dev
```
**预期输出**:
```
VITE v5.x.x ready in xxx ms
➜ Local: http://localhost:5174/
➜ Network: use --host to expose
```
## 🧪 测试步骤
### 测试 1: 后端 API 健康检查
在第三个终端执行:
```bash
# 测试后端是否响应
curl http://localhost:5000/
# 应该返回 HTML 页面Flask WebUI 首页)
```
### 测试 2: API 端点测试
#### 2.1 测试文件上传和分析
```bash
# 创建一个测试文件
echo '#include <stdio.h>
int main() { return 0; }' > test_simple.c
# 发起分析请求
curl -X POST http://localhost:5000/api/analyze \
-F "file=@test_simple.c" \
-F 'engines=["klee"]' \
-v
```
**预期响应**:
```json
{
"taskId": "xxx-xxx-xxx-xxx",
"status": "pending",
"progress": 0
}
```
**保存 taskId**,后续测试需要用到。
#### 2.2 查询任务状态
```bash
# 替换 {taskId} 为上面返回的 taskId
curl http://localhost:5000/api/tasks/{taskId}
```
**预期响应**(运行中):
```json
{
"taskId": "xxx-xxx-xxx-xxx",
"status": "running",
"progress": 20,
"message": "运行 KLEE 符号执行分析...",
"updated_at": "2025-01-28T..."
}
```
**等待任务完成**(可能需要几分钟),然后再次查询:
```bash
curl http://localhost:5000/api/tasks/{taskId}
```
**预期响应**(完成):
```json
{
"taskId": "xxx-xxx-xxx-xxx",
"status": "completed",
"progress": 100,
"message": "分析完成,发现 X 个漏洞",
"updated_at": "2025-01-28T..."
}
```
#### 2.3 获取分析报告
```bash
# 替换 {taskId} 为你的 taskId
curl http://localhost:5000/api/reports/{taskId} | jq .
```
**预期响应**:
```json
{
"metadata": {
"report_title": "...",
"target": "...",
...
},
"issues": [
{
"id": "KLEE-0001",
"basic": {
"title": "...",
"type": "..."
},
"severity": {
"level": "HIGH",
"cvss": 8.0
},
...
}
],
"stats": {
"counts": {
"HIGH": 1,
"MEDIUM": 0,
...
},
"risk_score": 4,
"risk_level": "LOW"
}
}
```
### 测试 3: 前端界面测试
#### 3.1 访问前端应用
1. 打开浏览器访问: http://localhost:5174
2. 应该看到 Dashboard 页面
#### 3.2 测试报告生成页面
1. 点击"生成报告"或访问 http://localhost:5174/reports/generate
2. 应该看到报告生成页面
#### 3.3 测试文件上传和分析
1. **选择文件**: 点击"选择源代码文件",选择 `test_example.c` 或任何 C 文件
2. **选择引擎**: 勾选 "cppcheck (静态分析)" 和/或 "KLEE (符号执行)"
3. **开始分析**: 点击"开始分析"按钮
4. **观察进度**:
- 应该显示"分析进行中..."的蓝色提示框
- 显示任务ID和进度信息
5. **等待完成**:
- 分析可能需要几分钟
- 完成后会显示绿色的"✓ 分析完成"提示框
- 显示漏洞统计和预览
#### 3.4 测试错误处理
1. **上传不支持的文件**: 尝试上传 `.txt``.pdf` 文件
- 应该显示错误提示
2. **不选择文件就分析**: 直接点击"开始分析"
- 应该显示"请先选择要分析的文件"提示
3. **取消分析**: 在分析过程中点击"取消分析"
- 任务应该被取消
### 测试 4: 浏览器开发者工具检查
打开浏览器开发者工具F12
#### 4.1 网络请求检查
1. 切换到 **Network** 标签
2. 执行文件上传和分析
3. 检查以下请求:
- `POST /api/analyze` - 应该返回 200包含 taskId
- `GET /api/tasks/{taskId}` - 应该定期轮询每2秒
- `GET /api/reports/{taskId}` - 任务完成后应该返回报告
#### 4.2 控制台错误检查
1. 切换到 **Console** 标签
2. 检查是否有错误信息
3. 正常情况应该没有红色错误
#### 4.3 响应数据检查
在 Network 标签中:
1. 点击 `POST /api/analyze` 请求
2. 查看 **Response** 标签
3. 确认返回了正确的 JSON 格式
## 🔍 详细测试用例
### 测试用例 1: 完整分析流程
**前置条件**: 后端和前端都已启动
**步骤**:
1. 访问 http://localhost:5174/reports/generate
2. 上传 `test_example.c`
3. 选择 "KLEE (符号执行)"
4. 点击"开始分析"
5. 等待分析完成(可能需要几分钟)
6. 查看分析结果
**预期结果**:
- ✅ 文件上传成功
- ✅ 分析任务创建成功
- ✅ 进度实时更新
- ✅ 分析完成后显示漏洞统计
- ✅ 可以查看漏洞预览
### 测试用例 2: 多引擎分析
**步骤**:
1. 上传文件
2. 同时选择 "cppcheck" 和 "KLEE"
3. 开始分析
**预期结果**:
- ✅ 两个引擎都运行
- ✅ 报告包含两个引擎的结果
### 测试用例 3: 错误处理
**步骤**:
1. 尝试上传 `.txt` 文件
2. 尝试不选择文件就分析
3. 在分析过程中取消
**预期结果**:
- ✅ 显示适当的错误提示
- ✅ 取消功能正常工作
## 🐛 常见问题排查
### 问题 1: 后端无法启动
**症状**: `python app.py` 报错
**排查步骤**:
```bash
# 检查 Python 版本(需要 3.7+
python --version
# 检查依赖
pip list | grep flask
# 检查端口是否被占用
lsof -i :5000
# 或
netstat -an | grep 5000
```
**解决方案**:
- 安装缺失的依赖: `pip install -r requirements.txt`
- 更换端口: `export PORT=5001`
### 问题 2: 前端无法连接后端
**症状**: 浏览器控制台显示 CORS 错误或网络错误
**排查步骤**:
```bash
# 检查后端是否运行
curl http://localhost:5000/
# 检查前端代理配置
cat platform-frontend/vite.config.ts
```
**解决方案**:
- 确认后端运行在 5000 端口
- 检查 `.env` 文件中的 `VITE_API_BASE`
- 确认 `flask-cors` 已安装
### 问题 3: 分析任务失败
**症状**: 任务状态显示 "failed"
**排查步骤**:
```bash
# 检查任务目录
ls symbolic-engine/tasks/
# 查看任务状态文件
cat symbolic-engine/tasks/{taskId}_status.json
# 检查 test_analyzer 是否存在
ls -la symbolic-engine/src/test_analyzer
```
**解决方案**:
- 编译 test_analyzer: `cd symbolic-engine/src && gcc -o test_analyzer test_analyzer.c intelligent_analyzer.c -I. -lpthread`
- 检查 KLEE 是否安装: `klee --version`
- 查看后端日志中的错误信息
### 问题 4: 报告格式错误
**症状**: 前端无法解析报告数据
**排查步骤**:
```bash
# 检查报告文件是否存在
ls -la symbolic-engine/tasks/{taskId}/final_report.json
# 检查 JSON 格式
cat symbolic-engine/tasks/{taskId}/final_report.json | jq .
```
**解决方案**:
- 检查 JSON 格式是否正确
- 确认报告文件编码为 UTF-8
- 查看浏览器控制台的错误信息
### 问题 5: 文件上传失败
**症状**: 上传文件时报错
**排查步骤**:
```bash
# 检查文件大小
ls -lh test_file.c
# 检查文件类型
file test_file.c
```
**解决方案**:
- 确认文件大小不超过 2MB默认限制
- 确认文件扩展名为 `.c`, `.cpp`, `.cc`, `.h`, `.hpp`
- 增加上传限制: `export MAX_UPLOAD_BYTES=5242880` (5MB)
## 📊 测试检查清单
### 后端测试
- [ ] Flask 服务正常启动
- [ ] API 端点响应正常
- [ ] 文件上传功能正常
- [ ] 任务创建成功
- [ ] 任务状态查询正常
- [ ] 报告生成成功
- [ ] CORS 配置正确
### 前端测试
- [ ] 前端服务正常启动
- [ ] 页面可以正常访问
- [ ] 文件选择功能正常
- [ ] API 调用成功
- [ ] 进度显示正常
- [ ] 结果展示正常
- [ ] 错误处理正常
### 集成测试
- [ ] 前后端通信正常
- [ ] 完整分析流程正常
- [ ] 数据格式正确
- [ ] 用户体验流畅
## 🎯 快速测试脚本
创建一个测试脚本 `quick_test.sh`:
```bash
#!/bin/bash
echo "=== 快速测试脚本 ==="
# 1. 测试后端健康
echo "1. 测试后端..."
curl -s http://localhost:5000/ > /dev/null && echo "✓ 后端运行正常" || echo "✗ 后端未运行"
# 2. 测试前端
echo "2. 测试前端..."
curl -s http://localhost:5174/ > /dev/null && echo "✓ 前端运行正常" || echo "✗ 前端未运行"
# 3. 测试 API
echo "3. 测试 API..."
TASK_RESPONSE=$(curl -s -X POST http://localhost:5000/api/analyze \
-F "file=@test_example.c" \
-F 'engines=["klee"]')
TASK_ID=$(echo $TASK_RESPONSE | jq -r '.taskId' 2>/dev/null)
if [ -n "$TASK_ID" ] && [ "$TASK_ID" != "null" ]; then
echo "✓ API 测试通过任务ID: $TASK_ID"
echo " 等待 5 秒后查询状态..."
sleep 5
curl -s http://localhost:5000/api/tasks/$TASK_ID | jq .
else
echo "✗ API 测试失败"
echo "响应: $TASK_RESPONSE"
fi
echo "=== 测试完成 ==="
```
使用方法:
```bash
chmod +x quick_test.sh
./quick_test.sh
```
## 📝 测试报告模板
测试完成后,记录测试结果:
```
测试日期: ___________
测试人员: ___________
后端测试:
- Flask 启动: [ ] 通过 [ ] 失败
- API 响应: [ ] 通过 [ ] 失败
- 文件上传: [ ] 通过 [ ] 失败
- 任务管理: [ ] 通过 [ ] 失败
- 报告生成: [ ] 通过 [ ] 失败
前端测试:
- 页面加载: [ ] 通过 [ ] 失败
- 文件选择: [ ] 通过 [ ] 失败
- API 调用: [ ] 通过 [ ] 失败
- 进度显示: [ ] 通过 [ ] 失败
- 结果展示: [ ] 通过 [ ] 失败
集成测试:
- 完整流程: [ ] 通过 [ ] 失败
- 数据格式: [ ] 通过 [ ] 失败
发现的问题:
1.
2.
3.
```
## 🎉 测试通过标准
所有以下项目都通过,说明系统可以正常使用:
1. ✅ 后端服务可以启动
2. ✅ 前端服务可以启动
3. ✅ 可以上传文件
4. ✅ 可以创建分析任务
5. ✅ 可以查询任务状态
6. ✅ 可以获取分析报告
7. ✅ 前端可以正确显示结果
8. ✅ 错误处理正常工作
如果所有测试都通过,恭喜!系统已经可以正常使用了!🎊

@ -0,0 +1,158 @@
#!/bin/bash
# 环境检查脚本
# 检查所有必要的依赖和工具是否已安装
echo "=========================================="
echo " 环境检查脚本"
echo "=========================================="
echo ""
# 颜色
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
ERRORS=0
# 检查 Python
echo -e "${BLUE}检查 Python...${NC}"
if command -v python3 &> /dev/null; then
PYTHON_VERSION=$(python3 --version 2>&1)
echo -e "${GREEN}✓ Python: $PYTHON_VERSION${NC}"
else
echo -e "${RED}✗ Python3 未安装${NC}"
ERRORS=$((ERRORS + 1))
fi
# 检查 pip
echo -e "${BLUE}检查 pip...${NC}"
if command -v pip3 &> /dev/null || command -v pip &> /dev/null; then
echo -e "${GREEN}✓ pip 已安装${NC}"
else
echo -e "${RED}✗ pip 未安装${NC}"
ERRORS=$((ERRORS + 1))
fi
# 检查 Flask
echo -e "${BLUE}检查 Flask...${NC}"
if python3 -c "import flask" 2>/dev/null; then
FLASK_VERSION=$(python3 -c "import flask; print(flask.__version__)" 2>/dev/null)
echo -e "${GREEN}✓ Flask: $FLASK_VERSION${NC}"
else
echo -e "${YELLOW}⚠ Flask 未安装,运行: pip install -r symbolic-engine/webui/requirements.txt${NC}"
fi
# 检查 flask-cors
echo -e "${BLUE}检查 flask-cors...${NC}"
if python3 -c "import flask_cors" 2>/dev/null; then
echo -e "${GREEN}✓ flask-cors 已安装${NC}"
else
echo -e "${YELLOW}⚠ flask-cors 未安装,运行: pip install flask-cors${NC}"
fi
# 检查 Node.js
echo -e "${BLUE}检查 Node.js...${NC}"
if command -v node &> /dev/null; then
NODE_VERSION=$(node --version)
echo -e "${GREEN}✓ Node.js: $NODE_VERSION${NC}"
else
echo -e "${RED}✗ Node.js 未安装${NC}"
ERRORS=$((ERRORS + 1))
fi
# 检查 npm
echo -e "${BLUE}检查 npm...${NC}"
if command -v npm &> /dev/null; then
NPM_VERSION=$(npm --version)
echo -e "${GREEN}✓ npm: $NPM_VERSION${NC}"
else
echo -e "${RED}✗ npm 未安装${NC}"
ERRORS=$((ERRORS + 1))
fi
# 检查 KLEE
echo -e "${BLUE}检查 KLEE...${NC}"
if command -v klee &> /dev/null; then
KLEE_VERSION=$(klee --version 2>&1 | head -1)
echo -e "${GREEN}✓ KLEE: $KLEE_VERSION${NC}"
else
echo -e "${YELLOW}⚠ KLEE 未安装或不在 PATH 中${NC}"
fi
# 检查 GCC
echo -e "${BLUE}检查 GCC...${NC}"
if command -v gcc &> /dev/null; then
GCC_VERSION=$(gcc --version | head -1)
echo -e "${GREEN}✓ GCC: $GCC_VERSION${NC}"
else
echo -e "${YELLOW}⚠ GCC 未安装${NC}"
fi
# 检查 test_analyzer
echo -e "${BLUE}检查 test_analyzer...${NC}"
if [ -f "symbolic-engine/src/test_analyzer" ]; then
echo -e "${GREEN}✓ test_analyzer 已编译${NC}"
else
echo -e "${YELLOW}⚠ test_analyzer 未编译${NC}"
echo " 运行: cd symbolic-engine/src && gcc -o test_analyzer test_analyzer.c intelligent_analyzer.c -I. -lpthread"
fi
# 检查前端依赖
echo -e "${BLUE}检查前端依赖...${NC}"
if [ -d "platform-frontend/node_modules" ]; then
echo -e "${GREEN}✓ 前端依赖已安装${NC}"
else
echo -e "${YELLOW}⚠ 前端依赖未安装,运行: cd platform-frontend && npm install${NC}"
fi
# 检查端口占用
echo -e "${BLUE}检查端口占用...${NC}"
if command -v lsof &> /dev/null; then
PORT5000=$(lsof -ti:5000 2>/dev/null)
PORT5174=$(lsof -ti:5174 2>/dev/null)
if [ -n "$PORT5000" ]; then
echo -e "${YELLOW}⚠ 端口 5000 已被占用 (PID: $PORT5000)${NC}"
else
echo -e "${GREEN}✓ 端口 5000 可用${NC}"
fi
if [ -n "$PORT5174" ]; then
echo -e "${YELLOW}⚠ 端口 5174 已被占用 (PID: $PORT5174)${NC}"
else
echo -e "${GREEN}✓ 端口 5174 可用${NC}"
fi
elif command -v netstat &> /dev/null; then
if netstat -an 2>/dev/null | grep -q ":5000.*LISTEN"; then
echo -e "${YELLOW}⚠ 端口 5000 已被占用${NC}"
else
echo -e "${GREEN}✓ 端口 5000 可用${NC}"
fi
if netstat -an 2>/dev/null | grep -q ":5174.*LISTEN"; then
echo -e "${YELLOW}⚠ 端口 5174 已被占用${NC}"
else
echo -e "${GREEN}✓ 端口 5174 可用${NC}"
fi
else
echo -e "${YELLOW}⚠ 无法检查端口占用(需要 lsof 或 netstat${NC}"
fi
echo ""
echo "=========================================="
if [ $ERRORS -eq 0 ]; then
echo -e "${GREEN}环境检查完成!${NC}"
echo ""
echo "可以开始启动服务:"
echo " 1. 后端: cd symbolic-engine/webui && python app.py"
echo " 2. 前端: cd platform-frontend && npm run dev"
else
echo -e "${RED}发现 $ERRORS 个严重问题,请先解决${NC}"
fi
echo "=========================================="

@ -0,0 +1,77 @@
# 访问前端应用指南
## 问题
无法从 Windows 浏览器访问 http://127.0.0.1:5173/
## 解决方案
我已经更新了 `package.json`,在启动命令中添加了 `--host 0.0.0.0`
## 现在重新启动前端
1. **停止当前服务**(如果还在运行,按 `Ctrl + C`
2. **重新启动**
```bash
cd ~/klee-build/platform-frontend
npm run dev
```
3. **查看输出**,应该显示:
```
➜ Local: http://localhost:5174/
➜ Network: http://172.x.x.x:5174/
```
## 访问方式
### 方法 1: 使用 WSL IP 地址(推荐)
后端显示:`Running on http://172.29.211.197:5000`
前端启动后也会显示类似的 Network 地址,例如:
```
➜ Network: http://172.29.211.197:5174/
```
在 Windows 浏览器中访问这个地址。
### 方法 2: 使用 localhost如果方法1不行
尝试:
- http://localhost:5174/
- http://127.0.0.1:5174/
### 方法 3: 检查 WSL IP
```bash
hostname -I
```
会显示 WSL 的 IP 地址,然后在浏览器中访问 `http://<WSL_IP>:5174/`
## 如果还是无法访问
### 临时解决方案:使用后端 WebUI
后端 Flask 应用也有 WebUI可以直接访问
http://172.29.211.197:5000/
这个页面可以上传文件并进行分析,虽然界面不如前端美观,但功能完整。
### 或者设置端口转发
在 Windows PowerShell管理员
```powershell
# 获取 WSL IP
wsl hostname -I
# 设置端口转发(替换 IP 为你的 WSL IP
netsh interface portproxy add v4tov4 listenport=5174 listenaddress=0.0.0.0 connectport=5174 connectaddress=172.29.211.197
```
然后访问 http://localhost:5174/

@ -0,0 +1,40 @@
# 检查端口监听情况
## 问题:服务显示 ready 但无法连接
可能的原因:
1. 服务实际上没有启动
2. 端口被占用
3. Vite 配置问题
## 检查步骤
### 1. 检查端口是否被监听
```bash
netstat -tuln | grep 3001
# 或
ss -tuln | grep 3001
```
如果没有输出,说明端口没有被监听。
### 2. 检查是否有 node 进程
```bash
ps aux | grep node
```
### 3. 检查是否有其他进程占用 3001
```bash
lsof -i :3001
# 或
sudo netstat -tulpn | grep 3001
```
### 4. 尝试使用不同的端口
如果 3001 有问题,可以尝试 5173Vite 默认端口)。

@ -0,0 +1,44 @@
# 检查服务真实状态
## 问题分析
`npm run dev` 显示 "ready" 但 `curl` 连接被拒绝,说明:
1. Vite 进程启动了
2. 但服务没有真正监听端口
3. 可能有编译错误或配置问题
## 检查步骤
### 1. 检查是否有编译错误
查看运行 `npm run dev` 的终端,是否有:
- TypeScript 错误
- 模块找不到的错误
- 其他编译错误
### 2. 检查端口是否真的被监听
在运行 `npm run dev` 的终端保持运行的情况下,打开新终端:
```bash
netstat -tuln | grep 5173
# 或
ss -tuln | grep 5173
```
如果没有输出,说明端口没有被监听。
### 3. 检查进程
```bash
ps aux | grep vite
```
### 4. 查看完整的启动日志
查看 `npm run dev` 的完整输出,特别是:
- 是否有错误信息
- 是否有警告
- 启动后的所有信息

@ -0,0 +1,68 @@
# 检查前端服务状态
## 问题:拒绝连接
如果直接访问 WSL IP 也被拒绝,说明前端服务可能没有正确启动。
## 排查步骤
### 1. 检查前端服务是否在运行
在 WSL 终端中:
```bash
# 检查是否有 node 进程在运行
ps aux | grep node
# 检查端口 3001 是否被监听
netstat -tuln | grep 3001
# 或
ss -tuln | grep 3001
```
### 2. 检查是否有错误信息
查看运行 `npm run dev` 的终端,是否有错误信息。
### 3. 重新启动前端服务
```bash
cd ~/klee-build/platform-frontend
# 停止当前服务Ctrl + C
# 清理并重新安装依赖(如果需要)
# rm -rf node_modules package-lock.json
# npm install
# 重新启动
npm run dev
```
### 4. 检查 Vite 配置
确保 `vite.config.ts` 中:
- `host: '0.0.0.0'` (允许外部访问)
- `port: 3001` (正确的端口)
### 5. 测试本地访问
在 WSL 终端中:
```bash
curl http://localhost:3001
```
如果这个可以访问,说明服务正常,问题在网络配置。
### 6. 检查防火墙
在 WSL 中检查防火墙:
```bash
sudo ufw status
```
如果需要,允许端口:
```bash
sudo ufw allow 3001
```

@ -0,0 +1,157 @@
# 完整全流程系统实现总结
## ✅ 已完成的功能
### 1. 左侧导航栏 (Layout 组件)
- 深色主题导航栏
- 5个主要功能模块导航
- 当前页面高亮显示
- 响应式设计
### 2. 仪表板页面 (Dashboard)
- **统计卡片**:活跃项目、扫描次数、发现漏洞、已修复
- **漏洞趋势分析图表**折线图显示最近6个月的严重漏洞和高危漏洞趋势
- **漏洞分类分布图表**:环形图显示安全、性能、可维护性、可靠性分布
- **最近发现的漏洞表格**:显示最近发现的漏洞列表
### 3. 项目管理页面 (ProjectManagement)
- 项目列表表格展示
- 新建项目功能(模态框)
- 编辑项目功能
- 删除项目功能
- 扫描项目功能
- 编辑代码功能
- 分页功能
### 4. 扫描管理页面 (ScanManagement)
- 扫描任务列表
- 新建扫描任务(支持选择项目、文件、扫描类型)
- 实时显示扫描状态(等待中、运行中、已完成、失败)
- 扫描进度显示
- 漏洞数量统计
- 查看报告功能
- 刷新功能
### 5. 报告中心页面 (ReportCenter)
- 总漏洞数统计卡片
- 漏洞报告列表表格
- 搜索功能
- 多维度筛选(严重程度、分类、状态)
- 导出 Excel 功能(待实现)
- 导出 JSON 功能
- 查看详情功能
### 6. 代码编辑器页面 (CodeEditor)
- 项目文件树
- 文件选择功能
- 代码编辑功能
- 保存功能
- 刷新功能
- 文件夹展开/折叠
### 7. 路由配置
- 所有页面路由已配置
- 使用 Layout 组件包裹所有页面
- React Query 集成
## 📁 文件结构
```
platform-frontend/src/
├── components/
│ └── Layout.tsx # 左侧导航栏布局组件
├── pages/
│ ├── Dashboard.tsx # 仪表板
│ ├── ProjectManagement.tsx # 项目管理
│ ├── ProjectDetail.tsx # 项目详情
│ ├── ScanManagement.tsx # 扫描管理
│ ├── ReportCenter.tsx # 报告中心
│ ├── ReportGenerate.tsx # 报告生成(已存在)
│ ├── CodeEditor.tsx # 代码编辑器
│ ├── VulnerabilityDetail.tsx # 漏洞详情
│ ├── Monitoring.tsx # 监控
│ └── DataVisualization.tsx # 数据可视化
├── App.tsx # 主应用(已更新)
└── styles.css # 样式(已更新)
```
## 🎨 界面特点
1. **统一的视觉风格**
- 深色导航栏 + 白色内容区
- 卡片式布局
- 统一的颜色方案(蓝色主题)
2. **响应式设计**
- 自适应布局
- 移动端友好
3. **交互体验**
- 悬停效果
- 加载状态
- 错误提示
- 模态框交互
## 🔗 与后端集成
- 扫描管理页面已集成 `useAnalysisFlow` hook
- 支持文件上传和分析
- 实时状态更新
- 报告数据展示
## 📝 数据存储
- 使用 localStorage 存储:
- 项目列表
- 扫描任务
- 报告数据
## 🚀 下一步优化建议
1. **后端 API 集成**
- 项目管理 API
- 文件管理 API
- 报告数据 API
2. **功能增强**
- 图表库集成(如 Chart.js 或 Recharts
- Excel 导出功能
- 文件上传进度显示
- 批量操作功能
3. **用户体验**
- 加载动画
- 骨架屏
- 错误边界
- 通知系统
## 🧪 测试
1. 启动前端:
```bash
cd ~/klee-build/platform-frontend
npm run dev
```
2. 访问地址:
- 本地http://localhost:5174/
- 网络http://<WSL_IP>:5174/
3. 测试流程:
- 创建项目
- 启动扫描
- 查看报告
- 编辑代码
## 📸 界面预览
系统包含以下主要界面:
- ✅ 仪表板(统计卡片 + 图表)
- ✅ 项目管理(列表 + CRUD
- ✅ 扫描管理(任务列表 + 状态)
- ✅ 报告中心(漏洞列表 + 筛选)
- ✅ 代码编辑器(文件树 + 编辑器)
所有界面都已实现,符合您提供的参考图片样式!

@ -0,0 +1,103 @@
# 数据持久化修复说明
## 修复的问题
### 1. ✅ 项目数据刷新后丢失
**问题**:刷新页面后,新建或导入的项目消失
**修复**
- 在 `projectStore.ts` 中添加了 localStorage 持久化
- 所有项目操作(添加、更新、删除)都会自动保存到 localStorage
- 页面加载时自动从 localStorage 恢复数据
### 2. ✅ 扫描结果和报告未保存
**问题**:扫描完成后,报告没有保存,刷新后看不到
**修复**
- 在 `ScanManagement.tsx` 中,当分析完成时自动保存报告到 localStorage
- 在 `ReportGenerate.tsx` 中也添加了报告保存逻辑
- 报告保存在 `localStorage``unifiedReports` 键中
### 3. ✅ 报告中心显示问题
**问题**:报告中心没有数据显示
**修复**
- `ReportCenter.tsx` 已经从 localStorage 加载报告
- 现在扫描完成后,报告会自动出现在报告中心
## 数据存储结构
### localStorage 键名
- `projects` - 项目列表
- `unifiedReports` - 统一格式的报告列表
- `scanTasks` - 扫描任务列表
### 数据格式
**项目数据** (`projects`):
```json
[
{
"id": "string",
"name": "string",
"language": "c" | "cpp",
"description": "string",
"createdAt": "string",
...
}
]
```
**报告数据** (`unifiedReports`):
```json
[
{
"metadata": { ... },
"issues": [ ... ],
"stats": { ... }
}
]
```
## 使用说明
### 验证修复
1. **测试项目持久化**
- 创建一个新项目
- 刷新页面
- 项目应该还在
2. **测试报告保存**
- 进行一次扫描
- 等待分析完成
- 刷新页面
- 在"报告中心"应该能看到报告
3. **测试扫描历史**
- 进行多次扫描
- 刷新页面
- 在"扫描管理"应该能看到所有扫描历史
## 注意事项
1. **浏览器限制**
- localStorage 有大小限制(通常 5-10MB
- 如果报告太多,可能需要清理旧数据
2. **数据迁移**
- 如果之前有数据,刷新后会合并默认项目和保存的项目
- 不会丢失已有数据
3. **跨浏览器**
- localStorage 是浏览器特定的
- 不同浏览器之间数据不共享
## 未来改进
- [ ] 添加数据导出/导入功能
- [ ] 添加数据清理功能
- [ ] 考虑使用 IndexedDB 存储大量数据
- [ ] 添加后端数据同步(如果后端支持)

@ -0,0 +1,42 @@
# 404 错误排查
## 问题分析
404 错误说明:
- 网络连接是通的(不是 Connection refused
- 但服务器返回了 404说明请求到达了服务器但找不到页面
## 可能的原因
1. Vite 服务没有正确启动
2. 路由配置问题
3. 文件路径问题
## 排查步骤
### 1. 在 WSL 中测试本地访问
```bash
curl http://localhost:3001
```
如果返回 HTML说明服务正常。
### 2. 检查是否有编译错误
查看运行 `npm run dev` 的终端,是否有:
- 编译错误
- 模块找不到的错误
- 其他错误信息
### 3. 检查 index.html 是否存在
```bash
ls -la ~/klee-build/platform-frontend/index.html
```
### 4. 检查是否有构建错误
查看终端输出,是否有红色的错误信息。

@ -0,0 +1,70 @@
# 连接问题排查指南
## ERR_CONNECTION_RESET 错误排查
### 步骤 1确认前端服务正在运行
在 WSL 终端中检查:
```bash
cd ~/klee-build/platform-frontend
npm run dev
```
确保看到:
```
➜ Local: http://localhost:5174/
➜ Network: http://172.29.211.197:5174/
```
### 步骤 2检查端口是否被监听
在 WSL 终端中:
```bash
netstat -tuln | grep 5174
```
应该看到:
```
tcp 0 0 0.0.0.0:5174 0.0.0.0:* LISTEN
```
### 步骤 3测试 WSL 内部访问
在 WSL 终端中测试:
```bash
curl http://localhost:5174
```
如果返回 HTML 内容,说明服务正常。
### 步骤 4检查端口转发
在 PowerShell管理员
```powershell
netsh interface portproxy show all
```
确保看到:
```
0.0.0.0 5174 172.29.211.197 5174
```
### 步骤 5测试端口转发
在 PowerShell 中:
```powershell
Test-NetConnection -ComputerName localhost -Port 5174
```
### 步骤 6尝试直接访问 WSL IP
在浏览器中尝试:
- http://172.29.211.197:5174/
如果这个可以访问,说明是端口转发的问题。
### 步骤 7使用不同的端口
如果 5174 有问题,尝试使用 3000 端口。

@ -0,0 +1,63 @@
# 扫描管理页面调试指南
## 问题:页面空白
### 已修复的问题
1. **useEffect 依赖项问题**
- 移除了 `reset` 函数从依赖项(函数不应该在依赖项中)
- 添加了 `projects` 到依赖项(因为使用了它)
2. **数据安全检查**
- 为 `projects` 添加了默认值 `[]`
- 添加了可选链操作符 `?.` 来安全访问嵌套属性
3. **JSON 解析错误**
- 后端添加了控制字符清理
- 前端添加了错误处理
### 调试步骤
1. **打开浏览器开发者工具**
- 按 F12 打开开发者工具
- 查看 Console 标签是否有错误
2. **检查网络请求**
- 查看 Network 标签
- 检查是否有失败的 API 请求
3. **检查 React 错误**
- 如果页面完全空白,可能是 React 组件出错
- 查看 Console 中的红色错误信息
### 常见错误
#### 错误 1: "Cannot read property 'map' of undefined"
**原因**: `projects` 未定义
**修复**: 已添加默认值 `projects = []`
#### 错误 2: "Maximum update depth exceeded"
**原因**: useEffect 无限循环
**修复**: 已优化依赖项
#### 错误 3: 页面完全空白
**可能原因**:
- React 组件渲染出错
- JavaScript 错误导致页面崩溃
- 路由配置问题
### 快速测试
1. 刷新页面Ctrl+F5 强制刷新)
2. 打开浏览器控制台
3. 点击"扫描管理"
4. 查看是否有错误信息
### 如果仍然空白
请提供:
1. 浏览器控制台的完整错误信息
2. Network 标签中的请求状态
3. 是否有任何 JavaScript 错误

@ -0,0 +1,54 @@
# 调试启动问题
## 问题
服务显示 "ready" 但无法连接,说明服务没有真正启动。
## 可能的原因
1. **编译错误**TypeScript 或 React 代码有错误,导致服务启动失败
2. **路径问题**UNC 路径警告可能导致问题
3. **端口被占用**:端口被其他进程占用
## 排查步骤
### 1. 查看完整的启动日志
运行 `npm run dev` 后,查看终端中的**所有输出**,特别是:
- 是否有红色的错误信息
- 是否有黄色的警告信息
- 启动后的所有信息
### 2. 检查是否有编译错误
在运行 `npm run dev` 的终端中,等待几秒钟,看是否有:
- TypeScript 错误
- 模块找不到的错误
- 其他编译错误
### 3. 尝试直接运行 vite
```bash
cd ~/klee-build/platform-frontend
npx vite --host 0.0.0.0 --port 5173
```
看看是否有更多错误信息。
### 4. 检查端口占用
```bash
lsof -i :5173
# 或
sudo netstat -tulpn | grep 5173
```
### 5. 尝试清理并重新安装
```bash
cd ~/klee-build/platform-frontend
rm -rf node_modules .vite
npm install
npm run dev
```

@ -0,0 +1,63 @@
# 修复浏览器无法访问问题
## 问题
无法从 Windows 浏览器访问 http://localhost:5173/
## 原因
Vite 默认只绑定到 127.0.0.1,在 WSL 中可能无法从 Windows 浏览器访问。
## 解决方案
我已经更新了 `vite.config.ts`,添加了 `host: '0.0.0.0'`,允许从外部访问。
## 现在重新启动前端
1. **停止当前的前端服务**(在运行 `npm run dev` 的终端中按 `Ctrl + C`
2. **重新启动**
```bash
cd ~/klee-build/platform-frontend
npm run dev
```
3. **查看输出**,应该显示:
```
➜ Local: http://localhost:5174/
➜ Network: http://172.x.x.x:5174/
```
4. **尝试访问**
- http://localhost:5174/ (如果不行,尝试下面的 Network 地址)
- 或者使用 Network 显示的 IP 地址
## 如果还是无法访问
### 方法 1: 使用 WSL 的 IP 地址
在 Vite 启动时,会显示 Network 地址,例如:
```
➜ Network: http://172.29.211.197:5174/
```
在 Windows 浏览器中访问这个地址。
### 方法 2: 检查防火墙
确保 Windows 防火墙允许访问 WSL 网络。
### 方法 3: 使用端口转发
在 Windows PowerShell管理员
```powershell
netsh interface portproxy add v4tov4 listenport=5174 listenaddress=0.0.0.0 connectport=5174 connectaddress=172.29.211.197
```
(将 172.29.211.197 替换为你的 WSL IP
## 快速测试
重新启动前端后,查看终端输出的 Network 地址,在浏览器中访问那个地址。

@ -0,0 +1,23 @@
# 修复 .npmrc 路径问题
## 问题
`.npmrc` 中使用 `~` 路径,在 UNC 路径环境下被解析为 Windows 路径。
## 解决方案
使用绝对路径 `/home/feng/` 而不是 `~`
## 如果还有问题
### 方法 1删除 prefix 设置
如果不需要全局安装,可以删除 `prefix` 行:
```
cache=/home/feng/.npm-cache
```
### 方法 2创建目录
如果保留 prefix需要创建目录
```bash
mkdir -p /home/feng/.npm-global
```

@ -0,0 +1,45 @@
# 修复端口 3001 访问问题
## 问题
端口 3000 被占用Vite 自动切换到了 3001但端口转发还是 3000。
## 解决方案
### 方案 1更新端口转发到 3001推荐
在 Windows PowerShell管理员中运行
```powershell
# 删除旧的 3000 端口转发
netsh interface portproxy delete v4tov4 listenport=3000 listenaddress=0.0.0.0
# 设置新的 3001 端口转发
netsh interface portproxy add v4tov4 listenport=3001 listenaddress=0.0.0.0 connectport=3001 connectaddress=172.29.211.197
# 允许防火墙通过
New-NetFirewallRule -DisplayName "WSL Frontend 3001" -Direction Inbound -LocalPort 3001 -Protocol TCP -Action Allow
```
然后访问http://localhost:3001/
### 方案 2释放 3000 端口
在 PowerShell管理员中查找占用 3000 端口的进程:
```powershell
netstat -ano | findstr :3000
```
找到 PID 后,结束进程:
```powershell
taskkill /PID <PID> /F
```
然后重新启动前端服务。
### 方案 3直接使用 WSL IP
在浏览器中直接访问:
- http://172.29.211.197:3001/

@ -0,0 +1,39 @@
# 修复 Vite 缓存目录问题
## 问题
Vite 试图在 Windows 目录C:/Windows/.vite创建缓存文件导致权限错误。
## 解决方案
我已经更新了 `vite.config.ts`,将缓存目录设置到 WSL 内部的 `~/.vite-cache`
## 现在重新启动
```bash
cd ~/klee-build/platform-frontend
# 清理旧的缓存(如果有)
rm -rf ~/.vite-cache
# 重新启动
npm run dev
```
## 如果还有问题
可以设置环境变量:
```bash
export VITE_CACHE_DIR=~/.vite-cache
npm run dev
```
## 验证
启动后应该:
- ✅ 没有权限错误
- ✅ 显示 "VITE v4.x.x ready"
- ✅ 可以访问 http://localhost:5173

@ -0,0 +1,46 @@
# 修复 Vite 缓存权限错误
## 问题
```
Error: EPERM: operation not permitted, mkdir 'C:/Windows/.vite/deps_temp_8d756014'
```
Vite 试图在 Windows 路径创建目录,但权限不足。
## 解决方案
### 1. 设置环境变量
在运行 `npm run dev` 之前,设置环境变量:
```bash
export VITE_CACHE_DIR=~/.vite-cache
export TMPDIR=~/.vite-cache
```
### 2. 或者创建一个启动脚本
创建 `start.sh`
```bash
#!/bin/bash
export VITE_CACHE_DIR=~/.vite-cache
export TMPDIR=~/.vite-cache
cd ~/klee-build/platform-frontend
npm run dev
```
然后运行:
```bash
chmod +x start.sh
./start.sh
```
### 3. 或者直接设置环境变量后启动
```bash
cd ~/klee-build/platform-frontend
export TMPDIR=~/.vite-cache
npm run dev
```

@ -0,0 +1,70 @@
# 修复 Vite 启动问题
## 问题
Vite 通过 npm 脚本运行时,仍然使用 Windows 的 cmd.exe导致路径问题。
## 解决方案
### 方法 1: 直接使用 npx vite推荐
```bash
cd ~/klee-build/platform-frontend
npx vite
```
### 方法 2: 检查并确保使用 WSL 内部的 Node.js
```bash
# 检查 Node.js 路径
which node
which npm
# 应该显示 /usr/bin/node 和 /usr/bin/npm
# 如果是 Windows 路径,需要重新配置
# 如果 npm 是 Windows 的,安装 WSL 内部的 npm
sudo apt-get update
sudo apt-get install -y npm
# 然后验证
which npm # 应该显示 /usr/bin/npm
npm --version
```
### 方法 3: 使用完整路径运行
```bash
cd ~/klee-build/platform-frontend
# 使用完整路径运行 vite
/usr/bin/npx vite
# 或者
~/.npm-global/bin/vite
```
### 方法 4: 修改 package.json 脚本
如果上面的方法都不行,可以修改启动方式。
## 快速测试
执行以下命令:
```bash
cd ~/klee-build/platform-frontend
# 方法 1: 直接使用 npx
npx vite
# 如果不行,方法 2: 检查路径
which node
which npm
# 如果 npm 是 Windows 的,安装 WSL 内部的 npm
sudo apt-get install -y npm
```

@ -0,0 +1,48 @@
# 现在可以安装了!
你已经有了正确的 Node.js 版本v20.19.5)和正确的路径(/usr/bin/node
## 执行以下命令安装依赖
```bash
cd ~/klee-build/platform-frontend
# 清理旧文件
rm -rf node_modules package-lock.json
# 设置 npm 缓存到 WSL 内部
export npm_config_cache=~/.npm-cache
# 安装依赖
npm install
```
这次应该可以成功了!
## 如果还有问题
如果 esbuild 还是有问题,可以:
```bash
# 跳过脚本安装
npm install --ignore-scripts
# 然后手动安装 esbuild
npm install esbuild@0.19.12 --save-dev --ignore-scripts
```
## 安装成功后
```bash
# 测试是否可以启动
npm run dev
```
应该看到:
```
VITE v4.x.x ready in xxx ms
➜ Local: http://localhost:5174/
```

@ -0,0 +1,393 @@
# 前后端集成方案
## 系统架构概览
### 后端组件
1. **symbolic-engine** (KLEE符号执行引擎)
- 输入C/C++ 源代码文件
- 输出:`static_analysis_report.json` (包含漏洞列表)
- 位置:`klee-build/symbolic-engine/src/`
2. **Report-Generation** (统一报告生成)
- 整合 cppcheck 和 symbolic-engine 的结果
- 生成统一格式报告:`final_report.json`
- 位置:`Report-Generation/unified_report/`
### 前端组件
- React + TypeScript 应用
- 需要调用后端API触发分析和获取结果
## 数据流程
```
用户上传文件/选择项目
前端调用 API: POST /api/analyze
后端执行分析流程:
1. 运行 symbolic-engine (KLEE)
2. 运行 cppcheck (可选)
3. 生成统一报告
后端返回分析结果
前端展示报告和漏洞列表
```
## 集成方案
### 方案一:通过 Flask WebUI 集成(推荐)
**优点**已有WebUI只需扩展API接口
**实现步骤**
1. **扩展 symbolic-engine/webui/app.py**
- 添加 `/api/analyze` 接口(异步任务)
- 添加 `/api/reports/:id` 获取报告
- 添加 `/api/reports/unified` 生成统一报告
2. **前端调用流程**
```typescript
// 1. 触发分析
POST /api/analyze
Body: { file: File, engines: ['klee', 'cppcheck'] }
Response: { taskId: string, status: 'pending' }
// 2. 轮询任务状态
GET /api/tasks/:taskId
Response: { status: 'running' | 'completed' | 'failed', progress: number }
// 3. 获取报告
GET /api/reports/:taskId
Response: { report: UnifiedReport }
```
### 方案二:直接调用后端脚本
**优点**:简单直接,无需修改后端
**实现步骤**
1. **前端创建API服务层**
```typescript
// src/services/api.ts
export async function analyzeCode(file: File, engines: string[]) {
const formData = new FormData();
formData.append('file', file);
formData.append('engines', JSON.stringify(engines));
const response = await fetch('/api/analyze', {
method: 'POST',
body: formData
});
return response.json();
}
```
2. **后端需要提供简单的HTTP服务**
- 可以创建一个简单的Python FastAPI/Flask服务
- 或者使用Node.js作为中间层调用Python脚本
## 统一报告数据格式
前端需要适配 `final_report.json` 格式:
```typescript
interface UnifiedReport {
metadata: {
report_title: string;
target: string;
generated_at: string;
// ...
};
issues: Array<{
id: string;
source: {
engine: 'symbolic-engine' | 'cppcheck_ai';
sub_tool: string;
};
basic: {
title: string;
type: string;
category: string;
};
location: {
file: string;
line: number;
snippet: string;
};
severity: {
level: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW';
cvss: number;
};
status: {
state: 'new' | 'confirmed';
};
description: {
summary: string;
details: string;
};
reproduce: {
steps: string[];
artifacts: Record<string, string>;
};
root_cause: {
short: string;
technical_details: string;
};
impact: {
technical: string;
business: string;
};
fix: {
recommendation: string[];
references: string[];
};
}>;
stats: {
counts: Record<string, number>;
risk_score: number;
risk_level: string;
};
}
```
## 前端需要实现的功能
### 1. API服务层 (`src/services/api.ts`)
```typescript
import type { UnifiedReport } from '../types';
const API_BASE = import.meta.env.VITE_API_BASE || 'http://localhost:5000';
export async function analyzeCode(
file: File,
engines: string[] = ['klee', 'cppcheck']
): Promise<{ taskId: string }> {
const formData = new FormData();
formData.append('file', file);
formData.append('engines', JSON.stringify(engines));
const response = await fetch(`${API_BASE}/api/analyze`, {
method: 'POST',
body: formData,
});
if (!response.ok) {
throw new Error('分析失败');
}
return response.json();
}
export async function getTaskStatus(taskId: string) {
const response = await fetch(`${API_BASE}/api/tasks/${taskId}`);
return response.json();
}
export async function getReport(taskId: string): Promise<UnifiedReport> {
const response = await fetch(`${API_BASE}/api/reports/${taskId}`);
return response.json();
}
```
### 2. 使用 React Query 管理数据
```typescript
// src/hooks/useAnalysis.ts
import { useMutation, useQuery } from '@tanstack/react-query';
import { analyzeCode, getTaskStatus, getReport } from '../services/api';
export function useAnalyzeCode() {
return useMutation({
mutationFn: ({ file, engines }: { file: File; engines: string[] }) =>
analyzeCode(file, engines),
});
}
export function useTaskStatus(taskId: string | null) {
return useQuery({
queryKey: ['task', taskId],
queryFn: () => getTaskStatus(taskId!),
enabled: !!taskId,
refetchInterval: (data) => {
// 如果任务还在运行每2秒轮询一次
return data?.status === 'running' ? 2000 : false;
},
});
}
export function useReport(taskId: string | null) {
return useQuery({
queryKey: ['report', taskId],
queryFn: () => getReport(taskId!),
enabled: !!taskId && taskId !== null,
});
}
```
### 3. 更新 ReportGenerate 页面
```typescript
// src/pages/ReportGenerate.tsx
import { useAnalyzeCode, useTaskStatus, useReport } from '../hooks/useAnalysis';
export function ReportGenerate() {
const [taskId, setTaskId] = useState<string | null>(null);
const analyzeMutation = useAnalyzeCode();
const { data: taskStatus } = useTaskStatus(taskId);
const { data: report } = useReport(
taskStatus?.status === 'completed' ? taskId : null
);
const handleGenerate = async (file: File) => {
const result = await analyzeMutation.mutateAsync({
file,
engines: ['klee', 'cppcheck'],
});
setTaskId(result.taskId);
};
// 显示进度和结果...
}
```
## 后端API接口设计
### 扩展 Flask WebUI
`symbolic-engine/webui/app.py` 中添加:
```python
from flask import jsonify
import subprocess
import json
from pathlib import Path
import uuid
@app.route('/api/analyze', methods=['POST'])
def api_analyze():
"""异步分析接口"""
file = request.files.get('file')
engines = json.loads(request.form.get('engines', '["klee"]'))
if not file:
return jsonify({'error': 'No file provided'}), 400
# 保存文件
task_id = str(uuid.uuid4())
task_dir = Path(f'/tmp/analysis_tasks/{task_id}')
task_dir.mkdir(parents=True, exist_ok=True)
file_path = task_dir / file.filename
file.save(file_path)
# 启动后台任务
# 这里可以使用 Celery 或简单的线程池
start_analysis_task(task_id, file_path, engines)
return jsonify({'taskId': task_id, 'status': 'pending'})
@app.route('/api/tasks/<task_id>')
def api_task_status(task_id):
"""获取任务状态"""
status_file = Path(f'/tmp/analysis_tasks/{task_id}/status.json')
if not status_file.exists():
return jsonify({'error': 'Task not found'}), 404
status = json.loads(status_file.read_text())
return jsonify(status)
@app.route('/api/reports/<task_id>')
def api_get_report(task_id):
"""获取统一报告"""
report_file = Path(f'/tmp/analysis_tasks/{task_id}/final_report.json')
if not report_file.exists():
return jsonify({'error': 'Report not found'}), 404
report = json.loads(report_file.read_text())
return jsonify(report)
def start_analysis_task(task_id, file_path, engines):
"""启动分析任务(后台执行)"""
def run_analysis():
# 1. 运行 symbolic-engine
if 'klee' in engines:
subprocess.run([
'bash', '-c',
f'cd {SRC_DIR} && ./test_analyzer {file_path}'
])
# 2. 运行 cppcheck (如果需要)
if 'cppcheck' in engines:
# 调用 cppcheck_test_generator
# 3. 生成统一报告
# 调用 render_report.py
# 4. 更新状态
status_file = Path(f'/tmp/analysis_tasks/{task_id}/status.json')
status_file.write_text(json.dumps({
'status': 'completed',
'progress': 100
}))
# 在后台线程中运行
import threading
thread = threading.Thread(target=run_analysis)
thread.start()
```
## 环境配置
### 前端环境变量
创建 `.env` 文件:
```env
VITE_API_BASE=http://localhost:5000
```
### Vite代理配置开发环境
```typescript
// vite.config.ts
export default defineConfig({
server: {
proxy: {
'/api': {
target: 'http://localhost:5000',
changeOrigin: true,
},
},
},
});
```
## 实施步骤
1. ✅ **前端类型定义**:定义 `UnifiedReport` 类型
2. ✅ **API服务层**:创建 `src/services/api.ts`
3. ✅ **React Query Hooks**:创建 `src/hooks/useAnalysis.ts`
4. ⏳ **更新ReportGenerate页面**集成真实API调用
5. ⏳ **后端API扩展**扩展Flask WebUI添加API接口
6. ⏳ **测试集成**:端到端测试
## 注意事项
1. **文件上传大小限制**:需要配置合理的文件大小限制
2. **分析超时**KLEE分析可能耗时较长需要设置合理的超时时间
3. **错误处理**:需要处理各种错误情况(文件格式错误、分析失败等)
4. **进度反馈**:对于长时间运行的任务,需要提供进度反馈
5. **CORS配置**如果前后端分离部署需要配置CORS
## 参考文件
- 统一报告格式:`Report-Generation/unified_report/final_report.json`
- 报告生成脚本:`Report-Generation/unified_report/render_report.py`
- 后端WebUI`symbolic-engine/webui/app.py`
- 前端类型定义:`platform-frontend/src/types.ts`

@ -0,0 +1,179 @@
# 前后端集成状态
## ✅ 已完成的工作
### 1. 类型定义更新
- ✅ 添加了 `UnifiedReport``UnifiedIssue` 类型定义
- ✅ 添加了 `AnalysisTask``AnalyzeRequest` API 类型
- ✅ 类型定义与后端 `final_report.json` 格式完全对应
### 2. API 服务层
- ✅ 创建了 `src/services/api.ts`
- ✅ 实现了以下 API 函数:
- `analyzeCode()` - 发起代码分析
- `getTaskStatus()` - 获取任务状态
- `getReport()` - 获取分析报告
- `getReports()` - 获取报告列表
- `cancelTask()` - 取消分析任务
- ✅ 实现了错误处理(`ApiError` 类)
### 3. React Query Hooks
- ✅ 创建了 `src/hooks/useAnalysis.ts`
- ✅ 实现了以下 Hooks
- `useAnalyzeCode()` - 发起分析的 Mutation
- `useTaskStatus()` - 查询任务状态(自动轮询)
- `useReport()` - 获取分析报告
- `useCancelTask()` - 取消任务
- `useAnalysisFlow()` - 组合 Hook完整的状态管理
### 4. ReportGenerate 页面更新
- ✅ 集成了真实的 API 调用
- ✅ 添加了文件上传功能
- ✅ 实现了分析进度显示
- ✅ 实现了分析结果预览
- ✅ 添加了错误处理和用户反馈
- ✅ 支持取消分析任务
### 5. 开发环境配置
- ✅ 配置了 Vite 代理(`/api` -> `http://localhost:5000`
- ✅ 创建了环境变量示例文件
## 📋 待完成的工作
### 1. 后端 API 实现(高优先级)
需要在 `symbolic-engine/webui/app.py` 中添加以下 API 接口:
```python
@app.route('/api/analyze', methods=['POST'])
def api_analyze():
"""异步分析接口"""
# 1. 接收文件上传
# 2. 创建分析任务
# 3. 启动后台分析流程
# 4. 返回任务ID
pass
@app.route('/api/tasks/<task_id>')
def api_task_status(task_id):
"""获取任务状态"""
# 返回任务状态和进度
pass
@app.route('/api/reports/<task_id>')
def api_get_report(task_id):
"""获取统一报告"""
# 返回 final_report.json 格式的报告
pass
```
### 2. 后端分析流程集成
需要将以下组件整合到 Flask API 中:
- 调用 `symbolic-engine``test_analyzer` 工具
- 调用 `cppcheck_test_generator` 生成测试用例
- 调用 `render_report.py` 生成统一报告
### 3. 前端页面增强(中优先级)
- ⏳ 更新 Dashboard 页面显示真实报告数据
- ⏳ 更新 VulnerabilityDetail 页面使用统一报告格式
- ⏳ 添加报告详情页面(`/reports/:id`
## 🚀 如何使用
### 前端开发
1. **安装依赖**(如果还没有):
```bash
cd platform-frontend
npm install
```
2. **配置环境变量**
创建 `.env` 文件(参考 `.env.example`
```env
VITE_API_BASE=http://localhost:5000
```
3. **启动开发服务器**
```bash
npm run dev
```
4. **访问应用**
打开 http://localhost:5174
### 测试前端功能
1. 访问 `/reports/generate` 页面
2. 选择一个 C/C++ 源文件(.c, .cpp, .cc, .h, .hpp
3. 选择分析引擎cppcheck 和/或 KLEE
4. 点击"开始分析"
5. 观察分析进度和结果
**注意**:目前后端 API 尚未实现,前端会显示网络错误。需要先实现后端 API。
## 📝 API 接口规范
### POST /api/analyze
**请求**
- `file`: File (multipart/form-data)
- `engines`: string[] (JSON string)
- `projectId`: string (可选)
**响应**
```json
{
"taskId": "uuid-string",
"status": "pending",
"progress": 0
}
```
### GET /api/tasks/:taskId
**响应**
```json
{
"taskId": "uuid-string",
"status": "running" | "completed" | "failed",
"progress": 50,
"message": "正在运行 KLEE 分析..."
}
```
### GET /api/reports/:taskId
**响应**
```json
{
"metadata": { ... },
"issues": [ ... ],
"stats": { ... }
}
```
(格式与 `final_report.json` 相同)
## 📚 相关文档
- [集成方案详细说明](./INTEGRATION_PLAN.md)
- [后端 README](../symbolic-engine/README.md)
- [统一报告格式](../Report-Generation/unified_report/final_report.json)
## 🔧 故障排除
### 前端无法连接到后端
1. 确认后端 Flask 服务运行在 `http://localhost:5000`
2. 检查 `.env` 文件中的 `VITE_API_BASE` 配置
3. 检查浏览器控制台的网络错误
### CORS 错误
如果前后端分离部署,需要在后端 Flask 应用中配置 CORS
```python
from flask_cors import CORS
CORS(app)
```
### 文件上传失败
1. 确认文件大小不超过后端限制
2. 确认文件类型为 C/C++ 源文件
3. 检查后端日志

@ -0,0 +1,102 @@
# 项目导入功能说明
## 功能概述
"导入项目"功能允许你将本地的 C/C++ 项目文件夹导入到平台中进行分析。
## 使用方式
### 方式 1: 上传 ZIP 文件(推荐)
1. **准备项目文件夹**
- 将你的 C/C++ 项目文件夹压缩成 ZIP 格式
- 例如:`my_project.zip`
2. **导入项目**
- 在"项目管理"页面,点击"导入项目 (ZIP)"按钮
- 选择你的 ZIP 文件
- 系统会自动:
- 解压 ZIP 文件
- 扫描项目中的 C/C++ 源文件
- 检测项目的主要编程语言C 或 C++
- 创建项目记录
3. **使用导入的项目**
- 导入后,项目会出现在项目列表中
- 可以点击"扫描"按钮对项目进行安全分析
- 可以点击"编辑代码"查看项目文件
### 方式 2: 直接指定服务器路径(需要后端支持)
如果你有服务器上的项目路径,可以通过后端 API 直接导入:
```bash
curl -X POST http://localhost:5000/api/projects/import-path \
-H "Content-Type: application/json" \
-d '{"path": "/path/to/your/project"}'
```
## 支持的文件类型
导入的项目可以包含以下文件类型:
- `.c` - C 源文件
- `.cpp` - C++ 源文件
- `.cc` - C++ 源文件
- `.h` - C 头文件
- `.hpp` - C++ 头文件
## 注意事项
1. **ZIP 文件大小限制**
- 默认最大上传大小为 2MB
- 可以通过环境变量 `MAX_UPLOAD_BYTES` 调整
2. **项目结构**
- 支持任意目录结构
- 系统会递归扫描所有子目录中的源文件
3. **语言检测**
- 系统会根据 `.cpp`/`.hpp` 和 `.c`/`.h` 文件的数量自动判断主要语言
- 如果 C++ 文件更多,则识别为 C++ 项目
4. **项目存储**
- 导入的项目存储在 `symbolic-engine/projects/<project_id>/source/` 目录
- 每个项目都有唯一的 ID
## 故障排除
### 问题 1: ZIP 文件上传失败
- 检查文件大小是否超过限制
- 确认 ZIP 文件格式正确
- 查看浏览器控制台的错误信息
### 问题 2: 导入后找不到源文件
- 检查 ZIP 文件是否包含 C/C++ 源文件
- 确认文件扩展名正确(.c, .cpp, .cc, .h, .hpp
### 问题 3: 语言检测不正确
- 可以在项目编辑中手动修改编程语言
- 或者重新导入项目
## 技术实现
### 前端
- 使用 `<input type="file">` 选择 ZIP 文件
- 通过 FormData 上传到后端 API
- 调用 `/api/projects/import` 端点
### 后端
- 接收 ZIP 文件
- 解压到临时目录
- 扫描源文件
- 返回项目信息
## 未来改进
- [ ] 支持 Git 仓库导入
- [ ] 支持拖拽上传
- [ ] 支持多文件选择上传
- [ ] 支持项目模板
- [ ] 支持增量导入

@ -0,0 +1,57 @@
# 快速修复 - 跳过 esbuild 安装脚本
## 问题
npm 仍然使用 Windows 的 cmd.exe 执行 esbuild 的安装脚本,导致路径问题。
## 解决方案:跳过脚本安装
在 WSL bash 终端中执行:
```bash
cd ~/klee-build/platform-frontend
# 1. 清理
rm -rf node_modules package-lock.json
# 2. 设置缓存路径
export npm_config_cache=~/.npm-cache
# 3. 跳过脚本安装所有依赖
npm install --ignore-scripts
# 4. 手动安装 esbuild也跳过脚本
npm install esbuild@0.19.12 --save-dev --ignore-scripts
```
## 验证
安装完成后,测试是否可以启动:
```bash
npm run dev
```
如果 Vite 可以启动说明一切正常esbuild 的预编译二进制文件应该已经包含在包中,不需要运行安装脚本。
## 如果 npm run dev 报错缺少 esbuild
可以尝试:
```bash
# 安装特定平台的 esbuild
npm install esbuild-linux-x64@0.19.12 --save-dev --ignore-scripts
# 或者使用 npm rebuild但跳过脚本
npm rebuild esbuild --ignore-scripts || true
```
## 重要提示
使用 `--ignore-scripts` 是安全的,因为:
- esbuild 的预编译二进制文件已经包含在 npm 包中
- 安装脚本只是用来下载对应平台的二进制文件
- 我们可以手动安装对应平台的包

@ -0,0 +1,168 @@
# 项目全生命周期 · 安全智能协同平台
统一承载项目、漏洞、监控、报告等核心分析链路,串联静态分析、符号执行、大模型测试及形式化验证的数据资产,赋能项目经理、安全与研发协作。
## 功能特性
### 1. 项目全生命周期管理(高优先级)
- ✅ 项目创建、配置、版本管理
- ✅ 成员协作管理
- ✅ 项目归档和删除
- ✅ 项目进度跟踪和里程碑管理
- ✅ 项目详情页面
### 2. 漏洞工作流与协作平台(高优先级)
- ✅ 完整的漏洞生命周期管理
- ✅ 工作流状态:发现 → 确认 → 分配 → 修复中 → 验证中 → 关闭
- ✅ 漏洞详情页面,展示完整证据链
- ✅ 多引擎证据链展示cppcheck、KLEE、LLM、形式化验证
- ✅ 漏洞分配和状态更新
### 3. 数据可视化与报告中心(中优先级)
- ✅ 组织级/项目级/个人级视图切换
- ✅ 报告模板管理
- ✅ 质量趋势可视化(占位)
- ✅ 漏洞分布统计(占位)
- ✅ 自定义报表配置
### 4. 系统监控与告警管理(中优先级)
- ✅ 系统健康状态监控
- ✅ 性能指标追踪
- ✅ 告警列表管理
- ✅ 告警策略配置
### 5. 统一可视化报告生成(中优先级)
- ✅ 交互式报告生成界面
- ✅ 多引擎证据链融合
- ✅ 静态分析触发点展示
- ✅ 符号执行测试用例展示
- ✅ LLM 生成测试用例结果
- ✅ 形式化验证状态展示
- ✅ LLM 修复建议展示
## 技术栈
- **React 18** - UI 框架
- **TypeScript** - 类型安全
- **React Router** - 路由管理
- **Zustand** - 状态管理
- **Vite** - 构建工具
- **TanStack Query** - 数据获取(已配置,待接入 API
## 项目结构
```
platform-frontend/
├── src/
│ ├── components/ # 可复用组件
│ │ ├── MetricCard.tsx
│ │ ├── MonitoringCard.tsx
│ │ ├── ProjectCard.tsx
│ │ ├── ReportCard.tsx
│ │ ├── SectionHeader.tsx
│ │ └── VulnerabilityCard.tsx
│ ├── pages/ # 页面组件
│ │ ├── Dashboard.tsx
│ │ ├── ProjectDetail.tsx
│ │ ├── VulnerabilityDetail.tsx
│ │ ├── ReportGenerate.tsx
│ │ ├── Monitoring.tsx
│ │ └── DataVisualization.tsx
│ ├── store/ # 状态管理
│ │ └── projectStore.ts
│ ├── data/ # Mock 数据
│ │ └── mock.ts
│ ├── types.ts # TypeScript 类型定义
│ ├── App.tsx # 路由配置
│ ├── main.tsx # 入口文件
│ └── styles.css # 全局样式
├── package.json
├── tsconfig.json
└── vite.config.ts
```
## 开发指南
### 安装依赖
```bash
npm install
```
### 启动开发服务器
```bash
npm run dev
```
应用将在 `http://localhost:5174` 启动
### 构建生产版本
```bash
npm run build
```
### 预览生产构建
```bash
npm run preview
```
## 路由说明
- `/` - 仪表盘首页
- `/projects/:id` - 项目详情页
- `/vulnerabilities/:id` - 漏洞详情页
- `/reports/generate` - 报告生成页
- `/reports/visualization` - 数据可视化页
- `/monitoring` - 系统监控页
## 与后端集成
当前前端使用 Mock 数据。要接入真实的后端 API需要
1. 在 `src/data/mock.ts` 中定义了数据结构,可以作为 API 接口的参考
2. 使用 `@tanstack/react-query` 创建 API hooks
3. 替换 Mock 数据为真实的 API 调用
### 后端 API 集成点
- **项目管理 API**: `/api/projects`
- **漏洞管理 API**: `/api/vulnerabilities`
- **报告生成 API**: `/api/reports`
- **监控数据 API**: `/api/monitoring`
## 与 Report-Generation 集成
前端已准备好接收来自 `Report-Generation` 项目的统一报告格式:
- `unified_report/cppcheck_issues.json` - cppcheck 漏洞数据
- `unified_report/symbolic_issues.json` - 符号执行漏洞数据
- `unified_report/final_report.json` - 最终统一报告
前端可以调用 `render_report.py` 生成的报告,或直接使用 JSON 数据在界面中展示。
## 下一步开发建议
1. **接入真实 API**: 替换 Mock 数据为后端 API 调用
2. **图表库集成**: 使用 Chart.js 或 Recharts 实现数据可视化
3. **权限管理**: 添加用户认证和权限控制
4. **实时更新**: 使用 WebSocket 实现实时数据更新
5. **文件上传**: 实现报告文件上传功能
6. **导出功能**: 支持报告导出为 PDF/Excel
7. **搜索和筛选**: 增强列表页面的搜索和筛选功能
## 许可证
© 2025 安全智能研发平台 · Powered by Report-Generation

@ -0,0 +1,83 @@
# 启动指南
## 前端启动
前端已经成功启动!可以通过以下方式访问:
### 在 WSL 中测试
```bash
curl http://localhost:5173
```
### 在 Windows 浏览器中访问
- `http://172.29.211.197:5173/`
- `http://10.255.255.254:5173/`
## 后端启动
后端 Flask API 需要单独启动:
```bash
cd /home/feng/klee-build/symbolic-engine/webui
python3 app.py
```
或者使用环境变量指定端口:
```bash
cd /home/feng/klee-build/symbolic-engine/webui
HOST=0.0.0.0 PORT=5000 python3 app.py
```
后端默认运行在 `http://localhost:5000`
## 测试 API 连接
### 测试后端健康检查
```bash
curl http://localhost:5000/api/health
```
### 测试前端代理
前端配置了代理,`/api/*` 请求会自动转发到后端:
- 前端:`http://localhost:5173/api/analyze`
- 实际请求:`http://localhost:5000/api/analyze`
## 完整启动流程
1. **启动后端**(在一个终端):
```bash
cd /home/feng/klee-build/symbolic-engine/webui
python3 app.py
```
2. **启动前端**(在另一个终端):
```bash
cd /home/feng/klee-build/platform-frontend
export TMPDIR=/home/feng/.vite-cache
export TEMP=/home/feng/.vite-cache
export TMP=/home/feng/.vite-cache
npm run dev
```
3. **访问前端**
- 在 Windows 浏览器中打开:`http://172.29.211.197:5173/`
## 故障排除
### 前端无法访问
- 确保 Vite 显示 "Network" 地址
- 检查防火墙设置
- 尝试使用 WSL IP 地址而不是 localhost
### 后端 API 无法连接
- 确保后端 Flask 服务正在运行
- 检查端口 5000 是否被占用:`lsof -i :5000`
- 检查 CORS 配置是否正确
### 端口冲突
如果端口被占用,可以修改:
- 前端端口:修改 `vite.config.ts` 中的 `port`
- 后端端口:设置环境变量 `PORT=5001` 并修改 `vite.config.ts` 中的代理目标

@ -0,0 +1,48 @@
# 重新安装依赖以修复 esbuild 平台问题
## 问题
esbuild 安装的是 Windows 版本(@esbuild/win32-x64但 WSL 需要 Linux 版本(@esbuild/linux-x64
## 解决方案
### 步骤 1删除 node_modules 和 package-lock.json
```bash
cd /home/feng/klee-build/platform-frontend
rm -rf node_modules package-lock.json
```
### 步骤 2确保使用 WSL 内部的 npm
```bash
which npm
# 应该显示 /usr/bin/npm
```
### 步骤 3重新安装依赖
```bash
cd /home/feng/klee-build/platform-frontend
npm install
```
这会安装 Linux 版本的 esbuild。
### 步骤 4验证安装
```bash
ls node_modules/@esbuild/
```
应该看到 `linux-x64` 而不是 `win32-x64`
### 步骤 5启动服务
```bash
export TMPDIR=/home/feng/.vite-cache
export TEMP=/home/feng/.vite-cache
export TMP=/home/feng/.vite-cache
npm run dev
```

@ -0,0 +1,54 @@
# 使用端口 3000 访问前端
## 步骤 1停止当前前端服务
在运行 `npm run dev` 的终端中按 `Ctrl + C`
## 步骤 2设置端口转发到 3000
在 Windows PowerShell管理员中运行
```powershell
# 删除旧的 5174 端口转发(如果有)
netsh interface portproxy delete v4tov4 listenport=5174 listenaddress=0.0.0.0
# 设置新的 3000 端口转发
netsh interface portproxy add v4tov4 listenport=3000 listenaddress=0.0.0.0 connectport=3000 connectaddress=172.29.211.197
# 允许防火墙通过
New-NetFirewallRule -DisplayName "WSL Frontend 3000" -Direction Inbound -LocalPort 3000 -Protocol TCP -Action Allow
```
## 步骤 3重新启动前端
在 WSL 终端中:
```bash
cd ~/klee-build/platform-frontend
npm run dev
```
应该看到:
```
➜ Local: http://localhost:3000/
➜ Network: http://172.29.211.197:3000/
```
## 步骤 4在浏览器中访问
访问http://localhost:3000/
## 如果还是不行
### 方案 A直接使用 WSL IP
在浏览器中访问:
- http://172.29.211.197:3000/
### 方案 B使用后端 WebUI
如果前端暂时无法访问,可以使用后端的 WebUI
- http://172.29.211.197:5000/
这个页面功能完整,可以上传文件并进行分析。

@ -0,0 +1,109 @@
# 设置 Windows 端口转发以访问前端
## 问题
WSL 中的前端服务无法直接从 Windows 浏览器访问,因为 WSL 的网络是隔离的。
## 解决方案:设置端口转发
### 步骤 1获取 WSL IP 地址
在 WSL 终端中运行:
```bash
hostname -I
```
会显示类似:`172.29.211.197` 的 IP 地址。
### 步骤 2在 Windows PowerShell管理员中设置端口转发
1. **以管理员身份打开 PowerShell**
- 按 `Win + X`
- 选择 "Windows PowerShell (管理员)" 或 "终端 (管理员)"
2. **运行以下命令**(替换 `<WSL_IP>` 为步骤 1 获取的 IP
```powershell
# 获取 WSL IP如果不知道
wsl hostname -I
# 设置端口转发(替换 172.29.211.197 为你的 WSL IP
netsh interface portproxy add v4tov4 listenport=5174 listenaddress=0.0.0.0 connectport=5174 connectaddress=172.29.211.197
```
3. **验证端口转发是否设置成功**
```powershell
netsh interface portproxy show all
```
应该看到类似:
```
侦听 ipv4: 连接到 ipv4:
地址 端口 地址 端口
--------------- ---------- --------------- ----------
0.0.0.0 5174 172.29.211.197 5174
```
### 步骤 3确保前端服务正在运行
在 WSL 终端中:
```bash
cd ~/klee-build/platform-frontend
npm run dev
```
应该看到:
```
➜ Local: http://localhost:5174/
➜ Network: http://172.29.211.197:5174/
```
### 步骤 4在 Windows 浏览器中访问
现在可以在 Windows 浏览器中访问:
- **http://localhost:5174/**
## 如果还是无法访问
### 检查防火墙
确保 Windows 防火墙允许端口 5174
```powershell
# 在 PowerShell管理员
New-NetFirewallRule -DisplayName "WSL Frontend" -Direction Inbound -LocalPort 5174 -Protocol TCP -Action Allow
```
### 删除旧的端口转发(如果需要)
```powershell
netsh interface portproxy delete v4tov4 listenport=5174 listenaddress=0.0.0.0
```
### 使用不同的端口
如果 5174 端口有问题,可以改用 3000 端口:
1. 修改 `vite.config.ts`
```typescript
server: {
host: '0.0.0.0',
port: 3000, // 改为 3000
// ...
}
```
2. 修改 `package.json`
```json
"dev": "vite --host 0.0.0.0 --port 3000"
```
3. 设置端口转发:
```powershell
netsh interface portproxy add v4tov4 listenport=3000 listenaddress=0.0.0.0 connectport=3000 connectaddress=172.29.211.197
```
4. 访问http://localhost:3000/
## 临时方案:使用后端 WebUI
如果前端暂时无法访问,可以使用后端的 WebUI你已经可以访问了
- http://172.29.211.197:5000/
这个页面功能完整,可以上传文件并进行分析。

@ -0,0 +1,63 @@
# 启动前端服务指南
## 问题Connection refused
这说明前端服务没有在运行。需要重新启动服务。
## 步骤
### 1. 检查是否有 node 进程在运行
```bash
ps aux | grep node
```
如果有 node 进程,可能需要先停止它们。
### 2. 进入前端目录
```bash
cd ~/klee-build/platform-frontend
```
### 3. 检查配置文件
确保 `vite.config.ts``package.json` 中的端口都是 3001。
### 4. 重新启动前端服务
```bash
npm run dev
```
### 5. 等待启动完成
应该看到类似输出:
```
VITE v4.5.14 ready in xxx ms
➜ Local: http://localhost:3001/
➜ Network: http://172.29.211.197:3001/
```
### 6. 保持终端打开
**重要**:不要关闭运行 `npm run dev` 的终端窗口,服务需要一直运行。
### 7. 测试访问
在新的终端窗口中:
```bash
curl http://localhost:3001
```
应该返回 HTML 内容。
## 如果启动失败
查看错误信息,常见问题:
- 端口被占用
- 依赖缺失
- 配置文件错误

@ -0,0 +1,85 @@
# 🎉 依赖安装成功!现在启动服务
## 第一步:测试前端是否可以启动
```bash
cd ~/klee-build/platform-frontend
npm run dev
```
**预期输出**:
```
VITE v4.x.x ready in xxx ms
➜ Local: http://localhost:5174/
```
如果看到这个输出,说明前端可以正常启动!
## 第二步:启动后端服务
打开**新的终端**(终端 2
```bash
cd ~/klee-build/symbolic-engine/webui
python3 app.py
```
**预期输出**:
```
* Running on http://0.0.0.0:5000
```
## 第三步:测试系统
### 方法 1: 浏览器测试
1. 打开浏览器访问: **http://localhost:5174**
2. 点击"生成报告"或访问: **http://localhost:5174/reports/generate**
3. 上传一个 C 文件
4. 选择分析引擎
5. 点击"开始分析"
6. 观察分析进度和结果
### 方法 2: API 测试
在**第三个终端**中:
```bash
# 创建测试文件
cd ~/klee-build
cat > test.c << 'EOF'
#include <stdio.h>
#include <string.h>
int main() {
char buffer[10];
char input[20] = "test";
strcpy(buffer, input);
return 0;
}
EOF
# 测试 API
curl -X POST http://localhost:5000/api/analyze \
-F "file=@test.c" \
-F 'engines=["klee"]'
```
应该返回:
```json
{"taskId": "xxx-xxx-xxx", "status": "pending", "progress": 0}
```
## 验证清单
- [ ] 前端可以启动(`npm run dev` 成功)
- [ ] 后端可以启动(`python3 app.py` 成功)
- [ ] 浏览器可以访问前端
- [ ] 可以上传文件
- [ ] API 可以创建分析任务
如果所有项目都通过,系统就可以使用了!🎊

@ -0,0 +1,163 @@
# 前后端集成测试指南
## ✅ 已验证的集成点
### 1. API 端点匹配
- ✅ `/api/analyze` (POST) - 发起分析任务
- ✅ `/api/tasks/<taskId>` (GET) - 获取任务状态
- ✅ `/api/reports/<taskId>` (GET) - 获取分析报告
- ✅ `/api/tasks/<taskId>/cancel` (POST) - 取消任务
### 2. 数据格式匹配
- ✅ `UnifiedReport` 类型定义与后端 `final_report.json` 格式完全匹配
- ✅ `AnalysisTask` 类型与后端任务状态格式匹配
- ✅ 文件上传格式匹配FormData
### 3. 代理配置
- ✅ Vite 代理配置正确:`/api/*` → `http://localhost:5000`
## 🧪 功能测试步骤
### 步骤 1: 启动后端服务
```bash
cd /home/feng/klee-build/symbolic-engine/webui
python3 app.py
```
应该看到:
```
* Running on http://0.0.0.0:5000
```
### 步骤 2: 启动前端服务(如果还没启动)
```bash
cd /home/feng/klee-build/platform-frontend
export TMPDIR=/home/feng/.vite-cache
export TEMP=/home/feng/.vite-cache
export TMP=/home/feng/.vite-cache
npm run dev
```
### 步骤 3: 测试 API 连接
在 WSL 终端中测试:
```bash
# 测试后端健康(如果后端有健康检查端点)
curl http://localhost:5000/api/tasks/test-123
# 应该返回 404任务不存在说明 API 正常工作
# 测试前端代理
curl http://localhost:5173/api/tasks/test-123
# 应该返回相同的结果(通过代理转发)
```
### 步骤 4: 在浏览器中测试完整流程
1. **打开前端界面**
- 在 Windows 浏览器中访问:`http://172.29.211.197:5173/`
- 或使用其他 Network 地址
2. **导航到报告生成页面**
- 点击侧边栏的"报告生成"或直接访问 `/reports/generate`
3. **上传测试文件**
- 选择一个 C/C++ 源文件(.c, .cpp, .cc, .h, .hpp
- 选择分析引擎KLEE, cppcheck
- 点击"开始分析"
4. **观察分析进度**
- 应该看到任务状态更新pending → running → completed
- 进度条应该更新
- 如果分析完成,应该显示报告
5. **查看报告**
- 分析完成后,应该显示统一格式的报告
- 包含漏洞列表、统计信息等
## ⚠️ 可能的问题
### 问题 1: 后端分析失败
**症状**:任务状态变为 `failed`,错误信息显示 KLEE 分析失败
**可能原因**
- KLEE 环境未正确配置
- 测试文件无法编译
- 缺少必要的依赖
**解决方案**
- 检查 KLEE 是否正确安装:`which klee`
- 检查编译工具:`which clang`
- 查看后端日志获取详细错误信息
### 问题 2: 前端无法连接后端
**症状**:前端显示网络错误或超时
**检查项**
- 后端是否正在运行:`curl http://localhost:5000/api/tasks/test`
- 前端代理配置是否正确(`vite.config.ts`
- 浏览器控制台是否有 CORS 错误
### 问题 3: 报告格式不匹配
**症状**:前端无法解析报告数据
**检查项**
- 后端生成的 `final_report.json` 格式是否正确
- 前端 `UnifiedReport` 类型定义是否与后端匹配
- 浏览器控制台是否有 JSON 解析错误
## 📝 测试用例
### 测试用例 1: 简单 C 文件分析
创建测试文件 `test.c`
```c
#include <stdio.h>
int main() {
int arr[10];
int i = 10;
arr[i] = 0; // 数组越界
return 0;
}
```
上传并分析,应该能检测到数组越界问题。
### 测试用例 2: 空指针解引用
创建测试文件 `test_null.c`
```c
#include <stdio.h>
int main() {
int *p = NULL;
*p = 10; // 空指针解引用
return 0;
}
```
上传并分析,应该能检测到空指针问题。
## 🎯 预期结果
如果所有功能正常,你应该能够:
1. ✅ 在前端上传 C/C++ 文件
2. ✅ 启动分析任务
3. ✅ 实时查看分析进度
4. ✅ 获取完整的统一格式报告
5. ✅ 查看漏洞详情和修复建议
6. ✅ 取消正在运行的任务
## 📊 性能指标
- 分析任务创建:< 1
- 任务状态轮询:每 2 秒
- 小型文件分析(< 100 < 30
- 中型文件分析100-500 行):< 2
- 大型文件分析(> 500 行):可能需要更长时间

@ -0,0 +1,109 @@
# 前端访问问题排查指南
## 问题:无法访问前端页面
### 可能的原因和解决方案
#### 1. 端口问题
**现象**:配置的端口是 5174但实际启动在 5173
**解决方案**
- 已在 `package.json` 中添加 `--port 5174` 参数
- 重新启动前端服务
#### 2. WSL 网络问题
**现象**:显示多个 Network 地址,但都无法访问
**解决方案 A使用 WSL IP 地址**
```bash
# 在 WSL 中获取 IP 地址
hostname -I
# 然后在 Windows 浏览器中访问 http://<WSL_IP>:5174/
```
**解决方案 B设置端口转发Windows PowerShell 管理员)**
```powershell
# 获取 WSL IP
wsl hostname -I
# 设置端口转发(替换为你的 WSL IP
netsh interface portproxy add v4tov4 listenport=5174 listenaddress=0.0.0.0 connectport=5174 connectaddress=<WSL_IP>
```
**解决方案 C使用 localhost如果端口转发已设置**
- 访问 http://localhost:5174/
#### 3. 防火墙问题
**检查 Windows 防火墙**
- 确保端口 5174 未被阻止
- 或者临时关闭防火墙测试
#### 4. 端口被占用
**检查端口占用**
```bash
# 在 WSL 中
netstat -tuln | grep 5174
# 或
lsof -i :5174
```
**如果端口被占用**
- 杀死占用进程
- 或更改端口号
#### 5. 使用后端 WebUI临时方案
如果前端暂时无法访问,可以使用后端的 WebUI
1. 确保后端正在运行:
```bash
cd ~/klee-build/symbolic-engine/webui
python3 app.py
```
2. 在浏览器中访问:
- http://172.29.211.197:5000/
- 或 http://<WSL_IP>:5000/
## 快速测试步骤
1. **停止当前前端服务**Ctrl + C
2. **重新启动**
```bash
cd ~/klee-build/platform-frontend
npm run dev
```
3. **查看输出**,应该显示:
```
➜ Local: http://localhost:5174/
➜ Network: http://<WSL_IP>:5174/
```
4. **尝试访问**
- 先尝试 Network 地址
- 如果不行,尝试设置端口转发
- 最后尝试 localhost
5. **如果还是不行**
- 检查是否有错误信息
- 尝试使用不同的端口(如 3000
- 检查 WSL 网络配置
## 修改端口(如果 5174 被占用)
`vite.config.ts` 中修改:
```typescript
server: {
host: '0.0.0.0',
port: 3000, // 改为其他端口
// ...
}
```
然后在 `package.json` 中也要修改:
```json
"dev": "vite --host 0.0.0.0 --port 3000"
```

@ -0,0 +1,32 @@
# 使用 Vite 默认端口 5173
## 问题
3001 端口可能有问题,改用 Vite 的默认端口 5173。
## 步骤
### 1. 停止当前服务
在运行 `npm run dev` 的终端中按 `Ctrl + C`
### 2. 重新启动
```bash
cd ~/klee-build/platform-frontend
npm run dev
```
### 3. 应该看到
```
➜ Local: http://localhost:5173/
➜ Network: http://172.29.208.1:5173/
```
### 4. 测试访问
```bash
curl http://localhost:5173
```
### 5. 在浏览器中访问
- http://172.29.208.1:5173/
- 或设置端口转发到 5173

@ -0,0 +1,29 @@
#!/bin/bash
# 检查并修复 Node.js/npm 路径问题
echo "检查 Node.js 和 npm 路径..."
echo "Node.js: $(which node)"
echo "npm: $(which npm)"
echo ""
# 检查 npm 是否是 Windows 版本
if [[ "$(which npm)" == *"Windows"* ]] || [[ "$(which npm)" == *"Program Files"* ]]; then
echo "检测到 Windows 版本的 npm需要安装 WSL 内部的 npm"
echo ""
echo "执行以下命令安装 WSL 内部的 npm:"
echo " sudo apt-get update"
echo " sudo apt-get install -y npm"
echo ""
echo "或者使用 nvm 安装 Node.js自带 npm:"
echo " curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash"
echo " source ~/.bashrc"
echo " nvm install 20"
echo " nvm use 20"
else
echo "npm 路径正常,尝试直接运行 Vite..."
echo ""
echo "执行: npx vite"
fi

@ -0,0 +1,29 @@
#!/bin/bash
# 修复 npm 安装问题:清理缓存并重新安装依赖
set -e
echo "=== 步骤 1: 清理 npm 缓存 ==="
npm cache clean --force
echo "=== 步骤 2: 删除旧的缓存目录 ==="
rm -rf ~/.npm-cache
echo "=== 步骤 3: 创建新的缓存目录 ==="
mkdir -p ~/.npm-cache
echo "=== 步骤 4: 设置 npm 缓存路径 ==="
npm config set cache /home/feng/.npm-cache
echo "=== 步骤 5: 验证 npm 缓存路径 ==="
npm config get cache
echo "=== 步骤 6: 删除 node_modules 和 package-lock.json ==="
rm -rf node_modules package-lock.json
echo "=== 步骤 7: 重新安装依赖 ==="
npm install
echo "=== 完成!==="

@ -0,0 +1,20 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>全域项目安全管理平台</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
rel="stylesheet"
/>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

@ -0,0 +1,25 @@
#!/bin/bash
# 修复 npm install 的脚本
cd ~/klee-build/platform-frontend
echo "步骤 1: 设置 npm 配置..."
export npm_config_cache=~/.npm-cache
export npm_config_prefix=~/.npm-global
echo "步骤 2: 清理旧文件..."
rm -rf node_modules package-lock.json
echo "步骤 3: 安装依赖(跳过脚本)..."
npm install --ignore-scripts
echo "步骤 4: 手动安装 esbuild..."
npm install esbuild@0.19.12 --save-dev --ignore-scripts --no-save
echo "步骤 5: 运行构建脚本..."
npm rebuild esbuild
echo "完成!"

@ -0,0 +1,21 @@
#!/bin/bash
# 跳过脚本安装依赖
cd ~/klee-build/platform-frontend
echo "清理旧文件..."
rm -rf node_modules package-lock.json
echo "设置 npm 缓存..."
export npm_config_cache=~/.npm-cache
echo "安装依赖(跳过脚本)..."
npm install --ignore-scripts
echo "手动安装 esbuild跳过脚本..."
npm install esbuild@0.19.12 --save-dev --ignore-scripts
echo "完成!现在可以运行 npm run dev 测试"

File diff suppressed because it is too large Load Diff

@ -0,0 +1,22 @@
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@ -0,0 +1,19 @@
# @babel/code-frame
> Generate errors that contain a code frame that point to source locations.
See our website [@babel/code-frame](https://babeljs.io/docs/babel-code-frame) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/code-frame
```
or using yarn:
```sh
yarn add @babel/code-frame --dev
```

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save