{"owner":"go-delve","repo":"delve","hasSkills":true,"hasMcp":false,"mcpConfig":null,"found":["CLAUDE.md"],"files":{"CLAUDE.md":"# CLAUDE.md\n\nThis file provides guidance to Claude Code (claude.ai/code) when working\nwith code in this repository.\n\n## Project Overview\n\nDelve is a debugger for the Go programming language. This is a complex,\nmulti-layered system that requires understanding of debugging internals,\nDWARF format, OS-specific process control, and Go runtime internals.\n\n## Build and Test Commands\n\n### Building\n\n```bash\nmake build          # Build dlv binary\nmake install        # Install dlv to system\nmake uninstall      # Remove dlv from system\n```\n\n### Testing\n\n```bash\nmake test                       # Run all tests with vetting\nmake vet                        # Run Go vet with architecture tags\ngo test -run TestName ./pkg/... # Run specific test by name\ngo test ./pkg/proc              # Run all pkg/proc tests\ngo test ./service/test          # Run all integration tests\n```\n\n### eBPF Backend Development\n\n```bash\nmake build-ebpf-image   # Build Docker image for eBPF compilation\nmake build-ebpf-object  # Compile eBPF C code to object files\n```\n\nThe eBPF backend uses Docker to compile C code\n(`pkg/proc/internal/ebpf/bpf/trace.bpf.c`) in a controlled environment,\nproducing architecture-specific `.o` files.\n\nThe builder image (`pkg/proc/internal/ebpf/build/ebpf-Dockerfile`) is based\non Ubuntu 26.04 with **clang-22**. The eBPF C code uses a per-CPU scratch\nbuffer with `bpf_ringbuf_output` for variable-length events, which requires\nclang 14+ for correct bounded-offset codegen on `PTR_TO_MAP_VALUE`.\n\n#### eBPF Testing\n\neBPF tests (TestTraceEBPF*) require elevated capabilities (CAP_BPF,\nCAP_PERFMON, CAP_SYS_RESOURCE) and must be run with sudo:\n\n```bash\n# Run specific eBPF test\nsudo go test -v -run TestTraceEBPF3 -count 1 ./cmd/dlv\n\n# Run all eBPF tests\nsudo go test -v -run TestTraceEBPF -count 1 ./cmd/dlv\n\n# Run eBPF tests in Docker (useful when host lacks capabilities or for CI)\ndocker run --privileged -v \"$(pwd)\":/delve -w /delve \\\n  -e GOFLAGS=\"-buildvcs=false\" golang:1.24-bookworm \\\n  go test -v -run TestTraceEBPF -count 1 ./cmd/dlv\n\n# Suppress debug output\nsudo go test -v -run TestTraceEBPF3 -count 1 ./cmd/dlv 2>&1 | \\\n  grep -v \"^DEBUG\"\n```\n\n### Running Delve\n\n```bash\ndlv debug           # Compile and debug current package\ndlv test            # Compile and debug tests\ndlv attach <pid>    # Attach to running process\ndlv exec <binary>   # Debug pre-compiled binary\ndlv dap             # Start Debug Adapter Protocol server\n```\n\n## Test-Driven Development (MANDATORY)\n\n**CRITICAL**: All code changes MUST follow test-driven development (TDD).\nThis is not optional.\n\n### Red-Green-Refactor Cycle\n\n1. **RED** - Write a failing test first (must fail for the right reason)\n2. **GREEN** - Write minimum code to pass the test\n3. **REFACTOR** - Clean up while keeping tests green\n4. **VERIFY** - Run full test suite before committing\n\n### Mandatory TDD Rules\n\n1. **NEVER write implementation code without a failing test first**\n2. **NEVER commit code without tests**\n3. **NEVER skip tests or mark them as skipped to make CI pass**\n4. **NEVER disable existing tests** - fix them or fix the code\n5. Each test should verify ONE specific behavior\n6. Test names should describe the scenario being tested\n\n### Example Workflow\n\n```bash\n# RED - Write failing test\ngo test -run TestEvaluateComplexType ./pkg/proc\n# Output: FAIL - undefined: evaluateComplexType (EXPECTED)\n\n# GREEN - Implement minimum code\ngo test -run TestEvaluateComplexType ./pkg/proc\n# Output: PASS\n\n# REFACTOR - Clean up\ngo test -run TestEvaluateComplexType ./pkg/proc\n# Output: PASS (must stay green)\n\n# VERIFY - Full suite\nmake test\n```\n\n### Where to Write Tests\n\n- **Unit tests**: Co-locate with code (e.g., `pkg/proc/variables_test.go`\n  for `variables.go`)\n- **Integration tests**: `service/test/` for end-to-end scenarios\n- **Platform-specific tests**: Use build tags (e.g., `//go:build linux`)\n- **Backend-specific tests**: Test each backend separately\n- **Test fixtures**: Source code in `_fixtures/` (compiled during tests,\n  not pre-compiled binaries)\n- **Finding fixtures directory**: Use `protest.FindFixturesDir()` from\n  `github.com/go-delve/delve/pkg/proc/test` instead of writing custom\n  fixture directory lookup code\n\n### Test Quality Standards\n\n- Test behavior, not implementation\n- One assertion per test when possible (easier diagnosis)\n- Clear naming: `Test<What>_<Scenario>_<ExpectedResult>`\n- Use existing test utilities in `*_test.go` files\n- Tests must be deterministic (no random values or race conditions)\n\n### When TDD Seems Difficult\n\nDifficulty writing tests first indicates: (1) function doing too much,\n(2) tightly coupled dependencies, or (3) unclear requirements. **DO NOT\nskip TDD** - the difficulty signals a design problem.\n\n## Architecture Overview\n\nDelve uses a **layered architecture** with clear separation of concerns:\n\n```\nCLI (cmd/dlv) → Cobra commands\n    ↓\nService Layer (service/) → RPC2, DAP protocol implementations\n    ↓\nDebugger (service/debugger) → High-level debugging operations\n    ↓\nProcess Abstraction (pkg/proc) → TargetGroup, Target, ProcessInternal\n    ↓\nBackend Implementations:\n  - pkg/proc/native/        → Direct OS debugging (ptrace, Windows APIs)\n  - pkg/proc/gdbserial/     → GDB remote protocol client\n  - pkg/proc/core/          → Core dump analysis\n  - pkg/proc/internal/ebpf/ → eBPF-based tracing (non-stop debugging)\n```\n\n### Process Abstraction (`pkg/proc`)\n\nCore of Delve's architecture with **two-level interface design**:\n\n- `Process` - Read-only public interface\n- `ProcessInternal` - Internal interface with state-modifying operations\n- `Target` - Wraps `ProcessInternal` with debugging state\n- `TargetGroup` - Manages multiple processes (for exec following)\n- `Thread` - OS thread abstraction\n- `MemoryReadWriter` - Memory access abstraction\n\nBackends are pluggable via `ProcessInternal` interface. When modifying\nbackends, changes usually apply to ALL implementations.\n\n### Service Layer (`service/`)\n\n- **`debugger/`** - `Debugger` struct wrapping `TargetGroup` with\n  high-level operations (launch, attach, breakpoints, stepping, variable\n  evaluation)\n- **`rpc2/`** - JSON-RPC 2.0 server for remote clients\n- **`dap/`** - Debug Adapter Protocol for IDE integration\n- **`api/`** - Shared type definitions\n\n### Binary Analysis\n\n- **`pkg/dwarf/`** - Custom DWARF parser with Delve-specific features\n- **`pkg/gobuild/`** - Go build system integration\n- **`pkg/proc/BinaryInfo`** - Debug symbols, function entries, line tables\n\n### Platform/Architecture Handling\n\nUses **filename-based conditional compilation**:\n\n- OS-specific: `*_linux.go`, `*_darwin.go`, `*_windows.go`, `*_freebsd.go`\n- Architecture-specific: `regs_amd64.go`, `regs_arm64.go`, etc.\n- **DO NOT put platform-specific code in generic files**\n- In most cases platform-specific code should only be added to the\n  `pkg/proc/native` and `pkg/proc/gdbserial` backends.\n\nSupported: amd64, arm64, 386, ppc64le, riscv64, loong64\n\n## Development Guidelines\n\n### Code Organization\n\n1. **OS/arch separation**: Use Go's filename-based conditional\n   compilation. Never put platform-specific code in generic files.\n\n2. **Breakpoint types**: Two kinds exist:\n   - `LogicalBreakpoint` - User-visible (set at file:line or function)\n   - `Breakpoint` - Physical per target (multiple per logical breakpoint)\n\n3. **Testing**: See \"Test-Driven Development (MANDATORY)\" section above.\n\n### Working with DWARF\n\n- Parsing in `pkg/dwarf/` with custom reader utilities\n- Operations (expressions) in `pkg/dwarf/op/`\n- Variable evaluation issues: check type reading\n  (`pkg/proc/variables.go`), DWARF expression evaluation\n  (`pkg/dwarf/op/`), and memory reading (`Process.Memory()`)\n\n### Working with eBPF Backend\n\n`pkg/proc/internal/ebpf/` is **fundamentally different**: uses **uprobes**\nto trace function calls without stopping execution. C code compiles to\neBPF bytecode using Docker for reproducible builds. Manages goroutines for\nevent processing - be careful with shutdown.\n\nModifying eBPF code:\n\n1. Edit `pkg/proc/internal/ebpf/bpf/trace.bpf.c`\n2. Run `make build-ebpf-object`\n3. Go code loads `.o` files using cilium/ebpf library\n\n**Critical - Function Prologues**: Set breakpoints/uprobes at\n`FirstPCAfterPrologue`, not `fn.Entry` (unless explicitly requested). Go's\nstack-check prologue will re-trigger if set at `fn.Entry`.\n\n**eBPF Type Support Pipeline**:\n1. `breakpoints.go` reads DWARF info, creates `UProbeArgMap` with\n   `Kind` from `dt.Common().ReflectKind`\n2. `trace.bpf.c` eBPF program captures raw bytes from regs/stack into\n   `val[0x30]`, optionally dereferences into `deref_val[0x30]`\n3. `helpers.go:parseFunctionParameterList` decodes bytes and creates\n   `godwarf.*Type` based on `reflect.Kind`\n4. `target.go:GetBufferedTracepoints` wraps in `Variable` and calls\n   `loadValue`\n\nCurrently supported types: int, uint (all sizes), bool, float, complex,\nstring, pointer (as address), slice (as address). Float/complex in XMM\nregisters (DWARF regnum >= 17) are marked unreadable since eBPF uprobes\ncannot access XMM/SSE registers. Unsupported types (map, chan, interface,\nfunc, struct, array) produce specific error messages.\n\n**eBPF Type Tests**: `TestTraceEBPFTypes` in `cmd/dlv/dlv_test.go` is the\ntest for eBPF type handling. Add new type-specific subtests there when\nextending type support. The fixture is `_fixtures/ebpf_trace_types.go`.\n\n**Tracing Test Assertions**: Tracing tests should assert on the complete\nexpected output string rather than checking for substrings. Full-output\nmatching catches regressions that substring checks would miss (e.g.,\nextra whitespace, reordered fields, format changes).\n\n### Commit Message Format\n\nUse subsystem-based format from CONTRIBUTING.md:\n\n```\n<subsystem>: <what changed>\n\n<why this change was made>\n\nFixes #<issue>\n```\n\nSubsystems: `proc`, `service`, `terminal`, `dwarf`, `native`, `dap`, `rpc2`,\n`cmd/dlv`, etc.\n\n**Subject line**: Max 70 characters, **Body**: Wrap at 80 characters\n\n**Example**:\n\n```\nproc/internal/ebpf: fix goroutine leak and shutdown sequence\n\nThe eBPF event processing goroutines were not being properly cleaned up\non debugger shutdown, causing resource leaks. This adds proper context\ncancellation and wait groups.\n\nFixes #1234\n```\n\n### Common Pitfalls\n\n1. **Don't modify Process state directly** - Use `ProcessInternal` methods\n   for locking and state consistency\n\n2. **Breakpoint insertion is backend-specific** - `native` uses software\n   breakpoints (INT3), `gdbserial` sends packets, `ebpf` uses uprobes\n\n3. **Thread vs Goroutine** - Delve tracks both OS threads (`Thread`) and\n   Go goroutines (`G` struct). Most operations work on goroutines, not\n   threads.\n\n4. **Memory safety** - Always handle errors when reading process memory.\n   Process may die, memory may be unmapped, or addresses invalid.\n\n5. **Don't reparse DWARF sections** - `loadDebugInfoMaps` already\n   iterates all compile units. Add per-CU checks there instead of\n   making separate passes over `debug_info`.\n\n## File Organization\n\n```\ndelve/\n├── cmd/dlv/                    # CLI entry point and commands\n├── pkg/\n│   ├── proc/                   # Core process abstraction\n│   │   ├── native/            # OS-level debugging backends\n│   │   ├── gdbserial/         # GDB remote protocol\n│   │   ├── core/              # Core dump support\n│   │   ├── internal/ebpf/     # eBPF tracing backend\n│   │   └── *.go               # Process interfaces and common logic\n│   ├── dwarf/                 # DWARF parsing and manipulation\n│   ├── terminal/              # Interactive CLI\n│   ├── config/                # Configuration (.delverc)\n│   └── ...                    # Other utilities\n├── service/\n│   ├── debugger/              # High-level debugger API\n│   ├── rpc2/                  # JSON-RPC 2.0 server\n│   ├── dap/                   # Debug Adapter Protocol\n│   └── api/                   # Shared type definitions\n├── _fixtures/                 # Test source files (compiled during tests)\n├── _scripts/                  # Build helper scripts\n└── Documentation/             # User and internal documentation\n```\n\n## Dependencies\n\nKey external dependencies (see `go.mod`):\n\n- `github.com/cilium/ebpf` - eBPF program loading\n- `github.com/google/go-dap` - Debug Adapter Protocol\n- `github.com/spf13/cobra` - CLI framework\n- `golang.org/x/arch` - CPU architecture utilities\n- `golang.org/x/sys` - System calls and OS interfaces\n\n## Resources\n\n- [Internal Architecture Slides](https://speakerdeck.com/aarzilli/internal-architecture-of-delve)\n- [Porting Guide](Documentation/internal/portnotes.md)\n- [API Documentation](Documentation/api)\n- [How to Write a Delve Client](Documentation/api/ClientHowto.md)\n"}}