> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/dolphin-emu/dolphin/llms.txt
> Use this file to discover all available pages before exploring further.

# Debugging Tools & Techniques

> Tools and techniques for debugging Dolphin Emulator

## Overview

Debugging Dolphin requires a combination of traditional debugging tools, emulator-specific features, and knowledge of GameCube/Wii hardware. This guide covers the essential debugging workflows.

## Development Builds

### Debug vs Release Builds

<Tabs>
  <Tab title="Debug Build">
    Build with debug symbols and assertions enabled:

    ```bash theme={null}
    cmake -B build -DCMAKE_BUILD_TYPE=Debug
    cmake --build build
    ```

    **Benefits:**

    * Full debug symbols
    * Assertions enabled
    * No optimization (easier to step through)
    * Better stack traces

    **Drawbacks:**

    * Significantly slower execution
    * Larger binary size
  </Tab>

  <Tab title="RelWithDebInfo">
    Build with optimizations but retain debug symbols:

    ```bash theme={null}
    cmake -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo
    cmake --build build
    ```

    **Benefits:**

    * Debug symbols available
    * Optimized performance
    * Good balance for debugging performance issues

    **Drawbacks:**

    * Harder to step through optimized code
    * Some variables may be optimized away
  </Tab>

  <Tab title="Release Build">
    Fully optimized production build:

    ```bash theme={null}
    cmake -B build -DCMAKE_BUILD_TYPE=Release
    cmake --build build
    ```

    Use this for performance testing, not debugging.
  </Tab>
</Tabs>

<Note>
  For most debugging work, use **Debug** builds. For performance profiling, use **RelWithDebInfo**.
</Note>

## Debugger Setup

### Visual Studio (Windows)

<Steps>
  <Step title="Open solution">
    Open the generated `Dolphin.sln` in Visual Studio after running CMake.
  </Step>

  <Step title="Set startup project">
    Right-click the `dolphin-emu` project and select "Set as Startup Project".
  </Step>

  <Step title="Configure debugging">
    Set breakpoints by clicking in the left margin of the code editor.
  </Step>

  <Step title="Start debugging">
    Press `F5` to start debugging, or `Ctrl+F5` to run without debugging.
  </Step>
</Steps>

**Useful shortcuts:**

* `F5`: Start/continue debugging
* `F9`: Toggle breakpoint
* `F10`: Step over
* `F11`: Step into
* `Shift+F11`: Step out

### Visual Studio Code

<Tabs>
  <Tab title="launch.json">
    Create `.vscode/launch.json`:

    ```json theme={null}
    {
      "version": "0.2.0",
      "configurations": [
        {
          "name": "Debug Dolphin",
          "type": "cppdbg",
          "request": "launch",
          "program": "${workspaceFolder}/build/Binaries/dolphin-emu",
          "args": [],
          "stopAtEntry": false,
          "cwd": "${workspaceFolder}",
          "environment": [],
          "externalConsole": false,
          "MIMode": "gdb",
          "setupCommands": [
            {
              "description": "Enable pretty-printing",
              "text": "-enable-pretty-printing",
              "ignoreFailures": true
            }
          ]
        }
      ]
    }
    ```
  </Tab>

  <Tab title="tasks.json">
    Create `.vscode/tasks.json` for building:

    ```json theme={null}
    {
      "version": "2.0.0",
      "tasks": [
        {
          "label": "Build Dolphin",
          "type": "shell",
          "command": "cmake --build build --config Debug",
          "group": {
            "kind": "build",
            "isDefault": true
          }
        }
      ]
    }
    ```
  </Tab>
</Tabs>

### GDB (Linux)

```bash theme={null}
# Start with GDB
gdb ./build/Binaries/dolphin-emu

# Common GDB commands
(gdb) break Core::RunLoop     # Set breakpoint
(gdb) run                      # Start program
(gdb) next                     # Step over (n)
(gdb) step                     # Step into (s)
(gdb) continue                 # Continue execution (c)
(gdb) print variable_name      # Print variable (p)
(gdb) backtrace               # Show stack trace (bt)
(gdb) quit                     # Exit GDB
```

**Enable pretty printing for STL containers:**

```bash theme={null}
# Add to ~/.gdbinit
set print pretty on
set print object on
set print static-members on
python
import sys
sys.path.insert(0, '/usr/share/gcc/python')
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_printers(None)
end
```

### LLDB (macOS)

```bash theme={null}
# Start with LLDB
lldb ./build/Binaries/dolphin-emu

# Common LLDB commands
(lldb) breakpoint set -n Core::RunLoop   # Set breakpoint
(lldb) run                                # Start program
(lldb) next                               # Step over (n)
(lldb) step                               # Step into (s)
(lldb) continue                           # Continue execution (c)
(lldb) frame variable variable_name       # Print variable
(lldb) bt                                 # Show stack trace
```

## Logging and Diagnostics

### Log Levels

Dolphin uses different log levels for diagnostic output:

```cpp theme={null}
#include "Common/Logging/Log.h"

// Different log levels
DEBUG_LOG_FMT(VIDEO, "Debug message: {}", value);
INFO_LOG_FMT(VIDEO, "Info message: {}", value);
NOTICE_LOG_FMT(VIDEO, "Notice message: {}", value);
WARN_LOG_FMT(VIDEO, "Warning message: {}", value);
ERROR_LOG_FMT(VIDEO, "Error message: {}", value);
```

**Log types** (first parameter):

* `VIDEO`: Video backend
* `AUDIO`: Audio processing
* `CORE`: Core emulation
* `BOOT`: Boot process
* `POWERPC`: PowerPC CPU
* `IOS`: IOS emulation
* `DSP`: DSP emulation

### Viewing Logs

<Tabs>
  <Tab title="GUI">
    In Dolphin's UI:

    1. View → Show Log
    2. View → Show Log Configuration
    3. Enable desired log types and levels
  </Tab>

  <Tab title="Console">
    Run Dolphin from terminal to see logs in real-time:

    ```bash theme={null}
    ./dolphin-emu 2>&1 | tee dolphin.log
    ```
  </Tab>

  <Tab title="Log File">
    Logs are saved to:

    * **Windows**: `%USERPROFILE%\Documents\Dolphin Emulator\Logs\`
    * **Linux**: `~/.local/share/dolphin-emu/Logs/`
    * **macOS**: `~/Library/Application Support/Dolphin/Logs/`
  </Tab>
</Tabs>

### Adding Debug Logging

When debugging issues, add temporary logging:

```cpp theme={null}
INFO_LOG_FMT(CORE, "Function called with value: {:#x}", value);
DEBUG_LOG_FMT(VIDEO, "Texture cache size: {}", texture_cache.size());

// Format multiple values
DEBUG_LOG_FMT(POWERPC, "PC: {:#010x}, LR: {:#010x}, Instr: {:#010x}",
              PC, LR, instruction);
```

<Warning>
  Remove or disable verbose debug logging before submitting pull requests.
</Warning>

## Message Handlers

### Custom Assertions

Dolphin uses a custom message handler for assertions and errors:

```cpp theme={null}
#include "Common/MsgHandler.h"

// In tests, assertions are caught
bool TestMsgHandler(const char* caption, const char* text, 
                    bool yes_no, Common::MsgType style)
{
  fmt::print(stderr, "{}\n", text);
  ADD_FAILURE();  // For test framework
  return true;     // Return yes to any question
}

Common::RegisterMsgAlertHandler(TestMsgHandler);
```

This prevents the emulator from breaking on assertions during testing.

## Common Debugging Scenarios

### Debugging Crashes

<Steps>
  <Step title="Get stack trace">
    When Dolphin crashes, capture the stack trace:

    * **Windows**: Check Event Viewer or use Visual Studio debugger
    * **Linux**: `ulimit -c unlimited && ./dolphin-emu` then `gdb dolphin-emu core`
    * **macOS**: Check Console.app for crash reports
  </Step>

  <Step title="Enable core dumps">
    Configure system to save core dumps:

    ```bash theme={null}
    # Linux
    ulimit -c unlimited
    sudo sysctl -w kernel.core_pattern=/tmp/core-%e.%p.%h.%t
    ```
  </Step>

  <Step title="Analyze with debugger">
    Load core dump:

    ```bash theme={null}
    gdb ./dolphin-emu /tmp/core-dolphin-emu.12345
    (gdb) backtrace full
    ```
  </Step>
</Steps>

### Debugging JIT Code

For JIT compiler issues:

```cpp theme={null}
// Enable JIT logging
DEBUG_LOG_FMT(DYNA_REC, "Compiling block at {:#010x}", address);

// Disable JIT for specific functions
if (address == 0x80001234)
{
  // Fall back to interpreter
  return false;
}
```

<Info>
  Use the "Enable Debugging UI" option in Dolphin settings to access JIT-related debugging features.
</Info>

### Memory Issues

<Tabs>
  <Tab title="AddressSanitizer">
    Build with ASan to detect memory errors:

    ```bash theme={null}
    cmake -B build -DCMAKE_BUILD_TYPE=Debug \
      -DCMAKE_CXX_FLAGS="-fsanitize=address -fno-omit-frame-pointer"
    cmake --build build
    ```
  </Tab>

  <Tab title="Valgrind">
    Run under Valgrind (Linux):

    ```bash theme={null}
    valgrind --leak-check=full --track-origins=yes ./dolphin-emu
    ```
  </Tab>

  <Tab title="Memory Debugger">
    Use Dolphin's built-in memory viewer:

    1. View → Memory
    2. Navigate to address
    3. Set memory breakpoints
  </Tab>
</Tabs>

### Performance Issues

<Steps>
  <Step title="Profile with built-in tools">
    Enable performance statistics:

    * View → Show Performance Monitor
    * View → Show FPS counter
  </Step>

  <Step title="Use external profilers">
    **Linux:**

    ```bash theme={null}
    perf record -g ./dolphin-emu
    perf report
    ```

    **Windows:**

    * Visual Studio Profiler
    * Intel VTune

    **macOS:**

    * Instruments (Xcode)
  </Step>

  <Step title="Identify bottlenecks">
    Look for hot paths in profiler output and optimize accordingly.
  </Step>
</Steps>

## Emulator-Specific Debugging

### Code Breakpoints

Dolphin includes a debugger for the emulated PowerPC CPU:

1. **View → Code**: Open the code debugger
2. Set breakpoints on PowerPC addresses
3. Step through emulated code instruction by instruction
4. View registers, memory, and call stack

### Memory Breakpoints

Break when emulated code accesses specific memory:

1. **View → Memory**: Open memory viewer
2. Right-click on address → Add Breakpoint
3. Choose read, write, or read/write breakpoint

### Register Tracking

Monitor PowerPC register changes:

1. **View → Registers**: Open register window
2. Watch values change as code executes
3. Edit registers to test different scenarios

## Unit Test Debugging

When debugging failing tests:

```bash theme={null}
# Run specific test under debugger
gdb --args ./Binaries/Tests/tests --gtest_filter="BitField.Storage"

# Set breakpoint in GDB
(gdb) break BitFieldTest.cpp:59
(gdb) run

# When breakpoint hits, inspect
(gdb) print object
(gdb) print object.hex
```

<Info>
  See the [Testing guide](/contributing/testing) for more information on running and writing tests.
</Info>

## Best Practices

<Steps>
  <Step title="Use assertions">
    Add assertions to catch invalid states early:

    ```cpp theme={null}
    ASSERT(pointer != nullptr);
    DEBUG_ASSERT(index < size);
    ```
  </Step>

  <Step title="Validate assumptions">
    Check preconditions and postconditions:

    ```cpp theme={null}
    void Process(const Data* data)
    {
      ASSERT(data != nullptr);
      // ... processing ...
      ASSERT(result.IsValid());
    }
    ```
  </Step>

  <Step title="Use descriptive variable names">
    Makes debugging easier when inspecting variables:

    ```cpp theme={null}
    // Good - clear in debugger
    int texture_cache_hits = 0;

    // Bad - unclear in debugger
    int tch = 0;
    ```
  </Step>

  <Step title="Isolate the problem">
    Narrow down the issue:

    * Binary search commits with `git bisect`
    * Disable features to identify culprit
    * Create minimal reproduction case
  </Step>

  <Step title="Document findings">
    Keep notes about:

    * What you tried
    * What worked/didn't work
    * Root cause analysis
  </Step>
</Steps>

## Compiler Warnings

<Warning>
  Always fix compiler warnings. They often indicate real bugs.
</Warning>

Enable additional warnings:

```bash theme={null}
cmake -B build -DCMAKE_CXX_FLAGS="-Wall -Wextra -Wpedantic"
```

Treat warnings as errors during development:

```bash theme={null}
cmake -B build -DCMAKE_CXX_FLAGS="-Werror"
```

## Getting Help

If you're stuck debugging an issue:

1. **Search existing issues**: Check GitHub for similar problems
2. **Ask on IRC**: `#dolphin-emu @ irc.libera.chat`
3. **Create detailed report**: Include:
   * Steps to reproduce
   * Expected vs actual behavior
   * Stack traces or logs
   * Build configuration
   * System information

## Next Steps

<CardGroup cols={2}>
  <Card title="Code Style" icon="code" href="/contributing/code-style">
    Review coding standards and formatting
  </Card>

  <Card title="Testing" icon="flask" href="/contributing/testing">
    Learn about unit testing practices
  </Card>
</CardGroup>
