vscode-bug-hunter
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseVS Code Bug Hunter
VS Code Bug 排查工具
Overview
概述
This skill enables systematic discovery and detection of bugs in VS Code extensions before they cause problems in production. It provides structured workflows for proactively finding issues through static analysis, pattern matching, code auditing, and systematic investigation techniques.
该Skill可在VS Code扩展引发生产环境问题前,系统化地发现和检测其中的bug。它提供结构化工作流,通过静态分析、模式匹配、代码审计和系统化排查技术主动发现问题。
When to Use This Skill
适用场景
- Proactively searching for bugs in extension code
- Auditing code for potential issues before release
- Investigating suspicious behavior patterns
- Analyzing code for memory leaks, race conditions, or security vulnerabilities
- Performing systematic code reviews
- Finding bugs that haven't manifested yet
- Preparing for release by identifying hidden issues
- 主动排查扩展代码中的bug
- 发布前审计代码以发现潜在问题
- 排查可疑行为模式
- 分析代码中的内存泄漏、竞态条件或安全漏洞
- 执行系统化代码审查
- 查找尚未显现的bug
- 通过识别隐藏问题为发布做准备
Bug Hunting vs Debugging
排查Bug vs 调试
| Bug Hunting (This Skill) | Debugging (vscode-extension-debugger) |
|---|---|
| Proactive discovery | Reactive fixing |
| Find bugs before they manifest | Fix bugs after they occur |
| Static and dynamic analysis | Error investigation |
| Code auditing | Stack trace analysis |
| Pattern-based detection | Reproduction-based fixing |
| Bug排查(本Skill) | 调试(vscode-extension-debugger) |
|---|---|
| 主动发现 | 被动修复 |
| 在bug显现前查找 | 问题出现后修复 |
| 静态与动态分析 | 错误排查 |
| 代码审计 | 堆栈跟踪分析 |
| 基于模式的检测 | 基于复现的修复 |
Bug Detection Workflow
Bug 排查工作流
Phase 1: Reconnaissance
第一阶段:信息收集
Gather intelligence about the codebase before hunting.
在开始排查前,先收集代码库的相关信息。
1.1 Map the Codebase Structure
1.1 梳理代码库结构
bash
undefinedbash
undefinedFind all TypeScript files
Find all TypeScript files
find src -name "*.ts" | head -20
find src -name "*.ts" | head -20
Identify key components
Identify key components
grep -r "export class" src/ --include="*.ts" | head -20
grep -r "export class" src/ --include="*.ts" | head -20
Find entry points
Find entry points
grep -r "activate|deactivate" src/ --include="*.ts"
undefinedgrep -r "activate|deactivate" src/ --include="*.ts"
undefined1.2 Identify High-Risk Areas
1.2 识别高风险区域
High-risk areas are more likely to contain bugs:
| Area | Risk Level | Reason |
|---|---|---|
| Async operations | High | Race conditions, unhandled rejections |
| Event handlers | High | Memory leaks, missing dispose |
| WebView communication | High | Message timing, state sync |
| File I/O | Medium | Error handling, permissions |
| User input processing | Medium | Validation, injection |
| Configuration handling | Medium | Type mismatches, defaults |
| UI rendering | Low | Visual issues, layout |
高风险区域更可能存在bug:
| 区域 | 风险等级 | 原因 |
|---|---|---|
| 异步操作 | 高 | 竞态条件、未处理的拒绝 |
| 事件处理器 | 高 | 内存泄漏、未执行销毁操作 |
| WebView 通信 | 高 | 消息时序、状态同步问题 |
| 文件I/O | 中 | 错误处理、权限问题 |
| 用户输入处理 | 中 | 验证、注入风险 |
| 配置处理 | 中 | 类型不匹配、默认值问题 |
| UI渲染 | 低 | 视觉问题、布局异常 |
1.3 Review Recent Changes
1.3 查看近期变更
bash
undefinedbash
undefinedRecent commits - often contain fresh bugs
Recent commits - often contain fresh bugs
git log --oneline -20
git log --oneline -20
Files changed recently
Files changed recently
git diff --name-only HEAD~10
git diff --name-only HEAD~10
Diff for specific file
Diff for specific file
git diff HEAD~5 -- src/path/to/suspicious/file.ts
undefinedgit diff HEAD~5 -- src/path/to/suspicious/file.ts
undefinedPhase 2: Static Analysis
第二阶段:静态分析
Analyze code without executing it.
无需执行代码即可进行分析。
2.1 Pattern-Based Bug Detection
2.1 基于模式的bug检测
Search for known bug patterns:
Memory Leak Patterns
typescript
// Pattern: Event listener without dispose
// Search: addEventListener|on\w+\s*\(
// Risk: Memory leak if listener not removed
// Pattern: setInterval/setTimeout without clear
// Search: setInterval|setTimeout
// Risk: Timer continues after disposal
// Pattern: Missing dispose registration
// Search: vscode\.\w+\.on\w+\(
// Risk: Event handler leaksRace Condition Patterns
typescript
// Pattern: Shared mutable state without lock
// Search: private \w+ = (?!readonly)
// Risk: Concurrent modification
// Pattern: Check-then-act without atomicity
// Search: if \(.*\)\s*\{[^}]*await
// Risk: State may change between check and act
// Pattern: Promise without await in loop
// Search: for.*\{[^}]*(?<!await)\s+\w+\([^)]*\)
// Risk: Uncontrolled concurrencyNull/Undefined Patterns
typescript
// Pattern: Optional chaining missing
// Search: \.\w+\.\w+\.\w+(?!\?)
// Risk: Null reference in chain
// Pattern: Type assertion without check
// Search: as \w+(?!\s*\|)
// Risk: Runtime type mismatch
// Pattern: Array access without bounds check
// Search: \[\d+\]|\[.*\](?!\?)
// Risk: Index out of bounds搜索已知的bug模式:
内存泄漏模式
typescript
// Pattern: Event listener without dispose
// Search: addEventListener|on\w+\s*\(
// Risk: Memory leak if listener not removed
// Pattern: setInterval/setTimeout without clear
// Search: setInterval|setTimeout
// Risk: Timer continues after disposal
// Pattern: Missing dispose registration
// Search: vscode\.\w+\.on\w+\(
// Risk: Event handler leaks竞态条件模式
typescript
// Pattern: Shared mutable state without lock
// Search: private \w+ = (?!readonly)
// Risk: Concurrent modification
// Pattern: Check-then-act without atomicity
// Search: if \(.*\)\s*\{[^}]*await
// Risk: State may change between check and act
// Pattern: Promise without await in loop
// Search: for.*\{[^}]*(?<!await)\s+\w+\([^)]*\)
// Risk: Uncontrolled concurrency空值/未定义模式
typescript
// Pattern: Optional chaining missing
// Search: \.\w+\.\w+\.\w+(?!\?)
// Risk: Null reference in chain
// Pattern: Type assertion without check
// Search: as \w+(?!\s*\|)
// Risk: Runtime type mismatch
// Pattern: Array access without bounds check
// Search: \[\d+\]|\[.*\](?!\?)
// Risk: Index out of bounds2.2 Automated Search Commands
2.2 自动化搜索命令
bash
undefinedbash
undefinedFind potential memory leaks
Find potential memory leaks
grep -rn "addEventListener|setInterval|setTimeout" src/ --include="*.ts"
grep -rn "addEventListener|setInterval|setTimeout" src/ --include="*.ts"
Find missing error handling
Find missing error handling
grep -rn "catch\s*{\s*}" src/ --include="*.ts"
grep -rn "catch\s*{\s*}" src/ --include="*.ts"
Find TODO/FIXME comments (often mark known issues)
Find TODO/FIXME comments (often mark known issues)
grep -rn "TODO|FIXME|HACK|BUG|XXX" src/ --include="*.ts"
grep -rn "TODO|FIXME|HACK|BUG|XXX" src/ --include="*.ts"
Find console.log (should be removed in production)
Find console.log (should be removed in production)
grep -rn "console.(log|debug|info)" src/ --include="*.ts"
grep -rn "console.(log|debug|info)" src/ --include="*.ts"
Find async functions without try-catch
Find async functions without try-catch
grep -rn "async.{" src/ --include=".ts" | head -20
undefinedgrep -rn "async.{" src/ --include=".ts" | head -20
undefined2.3 TypeScript Compiler Analysis
2.3 TypeScript 编译器分析
bash
undefinedbash
undefinedStrict type checking
Strict type checking
npx tsc --noEmit --strict
npx tsc --noEmit --strict
Find implicit any
Find implicit any
npx tsc --noEmit --noImplicitAny
npx tsc --noEmit --noImplicitAny
Check for unused variables
Check for unused variables
npx tsc --noEmit --noUnusedLocals --noUnusedParameters
undefinednpx tsc --noEmit --noUnusedLocals --noUnusedParameters
undefinedPhase 3: Semantic Analysis
第三阶段:语义分析
Understand code behavior beyond syntax.
理解代码语法之外的行为逻辑。
3.1 Control Flow Analysis
3.1 控制流分析
Trace execution paths to find issues:
typescript
// Identify all entry points to a function
// Search for: functionName(
// Trace data flow through function
// What inputs can reach this code path?
// What state can this code modify?
// Find unreachable code
// Code after return/throw/break/continue追踪执行路径以发现问题:
typescript
// Identify all entry points to a function
// Search for: functionName(
// Trace data flow through function
// What inputs can reach this code path?
// What state can this code modify?
// Find unreachable code
// Code after return/throw/break/continue3.2 State Analysis
3.2 状态分析
Track state changes:
typescript
// Questions to ask:
// 1. What state does this component manage?
// 2. What operations modify this state?
// 3. Can state become inconsistent?
// 4. Is state properly initialized?
// 5. Is state properly cleaned up?跟踪状态变化:
typescript
// Questions to ask:
// 1. What state does this component manage?
// 2. What operations modify this state?
// 3. Can state become inconsistent?
// 4. Is state properly initialized?
// 5. Is state properly cleaned up?3.3 Lifecycle Analysis
3.3 生命周期分析
Verify proper lifecycle management:
typescript
// For each resource:
// 1. Where is it created?
// 2. Where is it disposed?
// 3. Can disposal be skipped?
// 4. Is disposal order correct?
// 5. Are references cleared after disposal?验证生命周期管理是否正确:
typescript
// For each resource:
// 1. Where is it created?
// 2. Where is it disposed?
// 3. Can disposal be skipped?
// 4. Is disposal order correct?
// 5. Are references cleared after disposal?Phase 4: Dynamic Analysis
第四阶段:动态分析
Analyze code behavior during execution.
在代码执行过程中分析其行为。
4.1 Runtime Monitoring
4.1 运行时监控
Add temporary instrumentation:
typescript
// Wrap suspicious function to monitor calls
const original = object.suspiciousMethod;
object.suspiciousMethod = function(...args) {
console.log('[MONITOR] suspiciousMethod called with:', args);
const result = original.apply(this, args);
console.log('[MONITOR] suspiciousMethod returned:', result);
return result;
};添加临时监控代码:
typescript
// Wrap suspicious function to monitor calls
const original = object.suspiciousMethod;
object.suspiciousMethod = function(...args) {
console.log('[MONITOR] suspiciousMethod called with:', args);
const result = original.apply(this, args);
console.log('[MONITOR] suspiciousMethod returned:', result);
return result;
};4.2 Memory Profiling
4.2 内存分析
typescript
// Track object creation
const instances = new WeakSet();
const originalConstructor = SuspiciousClass;
SuspiciousClass = class extends originalConstructor {
constructor(...args) {
super(...args);
instances.add(this);
console.log('[MEMORY] New instance created, count:', instances.size);
}
};typescript
// Track object creation
const instances = new WeakSet();
const originalConstructor = SuspiciousClass;
SuspiciousClass = class extends originalConstructor {
constructor(...args) {
super(...args);
instances.add(this);
console.log('[MEMORY] New instance created, count:', instances.size);
}
};4.3 Performance Profiling
4.3 性能分析
typescript
// Measure function execution time
const start = performance.now();
await suspiciousOperation();
const duration = performance.now() - start;
console.log(`[PERF] Operation took ${duration}ms`);typescript
// Measure function execution time
const start = performance.now();
await suspiciousOperation();
const duration = performance.now() - start;
console.log(`[PERF] Operation took ${duration}ms`);Phase 5: Hypothesis Testing
第五阶段:假设验证
Form and test hypotheses about potential bugs.
构建并验证关于潜在bug的假设。
5.1 Hypothesis Formation
5.1 假设构建
Template:
IF [condition/action]
THEN [expected buggy behavior]
BECAUSE [root cause theory]
Example:
IF rapid terminal creation requests are made
THEN duplicate terminals may be created
BECAUSE there is no atomic lock on the creation operation模板:
如果 [条件/操作]
那么 [预期的bug行为]
因为 [根因推测]
示例:
如果 频繁触发终端创建请求
那么 可能会创建重复终端
因为 创建操作没有原子锁5.2 Test Design
5.2 测试设计
typescript
// Design test to confirm hypothesis
describe('Bug Hypothesis: Rapid terminal creation causes duplicates', () => {
it('should handle concurrent creation requests', async () => {
const manager = new TerminalManager();
// Trigger the suspected bug condition
const results = await Promise.all([
manager.createTerminal(),
manager.createTerminal(),
manager.createTerminal()
]);
// Verify expected behavior
const uniqueIds = new Set(results.map(t => t.id));
expect(uniqueIds.size).toBe(results.length);
});
});typescript
// Design test to confirm hypothesis
describe('Bug Hypothesis: Rapid terminal creation causes duplicates', () => {
it('should handle concurrent creation requests', async () => {
const manager = new TerminalManager();
// Trigger the suspected bug condition
const results = await Promise.all([
manager.createTerminal(),
manager.createTerminal(),
manager.createTerminal()
]);
// Verify expected behavior
const uniqueIds = new Set(results.map(t => t.id));
expect(uniqueIds.size).toBe(results.length);
});
});Bug Categories Reference
Bug 类别参考
Category 1: Resource Leaks
类别1:资源泄漏
Memory Leaks
- Event listeners not removed
- Timers not cleared
- References not nullified
- Closures capturing large objects
Handle Leaks
- File handles not closed
- WebView panels not disposed
- Terminal processes not killed
- Watchers not stopped
内存泄漏
- 事件监听器未移除
- 定时器未清除
- 引用未置空
- 闭包捕获大型对象
句柄泄漏
- 文件句柄未关闭
- WebView 面板未销毁
- 终端进程未终止
- 监视器未停止
Category 2: Concurrency Issues
类别2:并发问题
Race Conditions
- Check-then-act patterns
- Shared mutable state
- Non-atomic operations
- Missing synchronization
Deadlocks
- Circular dependencies
- Nested locks
- Resource contention
竞态条件
- 检查后执行模式
- 共享可变状态
- 非原子操作
- 缺少同步机制
死锁
- 循环依赖
- 嵌套锁
- 资源竞争
Category 3: State Issues
类别3:状态问题
Invalid State
- Uninitialized variables
- Stale state references
- Inconsistent state transitions
- Missing state validation
State Corruption
- Concurrent modification
- Partial updates
- Missing rollback on failure
无效状态
- 未初始化变量
- 陈旧状态引用
- 不一致的状态转换
- 缺少状态验证
状态损坏
- 并发修改
- 部分更新
- 失败时缺少回滚
Category 4: Error Handling Issues
类别4:错误处理问题
Missing Error Handling
- Uncaught exceptions
- Unhandled promise rejections
- Silent failures
- Missing validation
Incorrect Error Handling
- Swallowed errors
- Wrong error type caught
- Incomplete cleanup on error
缺少错误处理
- 未捕获异常
- 未处理的Promise拒绝
- 静默失败
- 缺少验证
错误处理不当
- 错误被吞掉
- 捕获了错误的类型
- 错误发生时清理不完整
Category 5: Security Issues
类别5:安全问题
Injection Vulnerabilities
- Command injection
- Path traversal
- XSS in WebView
Information Disclosure
- Sensitive data in logs
- Error messages revealing internals
- Debug information in production
注入漏洞
- 命令注入
- 路径遍历
- WebView 中的XSS
信息泄露
- 日志中包含敏感数据
- 错误信息暴露内部细节
- 生产环境中存在调试信息
Quick Reference Commands
快速参考命令
Find Memory Leaks
查找内存泄漏
bash
grep -rn "addEventListener\|on.*=.*function" src/ --include="*.ts" | grep -v "dispose\|remove"bash
grep -rn "addEventListener\|on.*=.*function" src/ --include="*.ts" | grep -v "dispose\|remove"Find Missing Error Handling
查找缺失的错误处理
bash
grep -rn "\.then\(" src/ --include="*.ts" | grep -v "\.catch\("bash
grep -rn "\.then\(" src/ --include="*.ts" | grep -v "\.catch\("Find Potential Race Conditions
查找潜在竞态条件
bash
grep -rn "async.*{" src/ --include="*.ts" -A 5 | grep -E "if.*\{|while.*\{"bash
grep -rn "async.*{" src/ --include="*.ts" -A 5 | grep -E "if.*\{|while.*\{"Find Security Issues
查找安全问题
bash
grep -rn "eval\|innerHTML\|child_process\|exec\(" src/ --include="*.ts"bash
grep -rn "eval\|innerHTML\|child_process\|exec\(" src/ --include="*.ts"Find Code Smells
查找代码异味
bash
grep -rn "any\|@ts-ignore\|@ts-nocheck" src/ --include="*.ts"bash
grep -rn "any\|@ts-ignore\|@ts-nocheck" src/ --include="*.ts"Investigation Workflow Summary
排查工作流总结
- Reconnaissance: Map codebase, identify high-risk areas
- Static Analysis: Search for known bug patterns
- Semantic Analysis: Understand control flow and state
- Dynamic Analysis: Monitor runtime behavior
- Hypothesis Testing: Form and test bug theories
- Documentation: Record findings for fixing
- 信息收集:梳理代码库结构,识别高风险区域
- 静态分析:搜索已知bug模式
- 语义分析:理解控制流与状态
- 动态分析:监控运行时行为
- 假设验证:构建并验证bug假设
- 文档记录:记录发现的问题以便修复
Resources
参考资源
For detailed reference documentation:
- - Comprehensive bug pattern catalog
references/detection-patterns.md - - Static and dynamic analysis tool guide
references/analysis-tools.md - - Systematic investigation procedures
references/investigation-checklist.md
如需详细参考文档:
- - 全面的bug模式目录
references/detection-patterns.md - - 静态与动态分析工具指南
references/analysis-tools.md - - 系统化排查流程
references/investigation-checklist.md