SXXXXXXX_CppPythonDebug/doc/English-manual.md
2025-05-27 08:16:39 +02:00

53 KiB

Cpp-Python GDB Debug Helper - User Manual

1. Introduction

1.1 What is Cpp-Python GDB Debug Helper?

The Cpp-Python GDB Debug Helper is a Graphical User Interface (GUI) designed to enhance and simplify the process of debugging C/C++ applications using the GNU Debugger (GDB). It aims to provide a more user-friendly experience compared to the GDB command-line interface, especially for tasks like inspecting complex data structures and automating repetitive debugging scenarios.

1.2 Who is it for?

This tool is primarily aimed at C/C++ developers who use GDB for debugging and would benefit from:

  • A visual interface for common GDB operations.
  • Easier inspection of complex C++ data types (structs, classes, STL containers).
  • Automation of debugging sequences through configurable profiles.
  • Structured output of variable dumps in JSON or CSV formats.

1.3 Key Features

  • Interactive Manual Debugging: Start GDB, set breakpoints, run your target program, step through code (implicitly via run/continue), and inspect variables.
  • Advanced Variable Dumping: Dump the state of C/C++ variables, including complex data structures like classes, structs, pointers, arrays, and std::string, into a structured JSON format.
  • Automated Debug Profiles: Create, manage, and execute debug profiles. Each profile can define:
    • Target executable and program parameters.
    • Multiple debug "actions", each specifying a breakpoint, variables to dump, output format (JSON/CSV), output directory, and filename patterns.
  • Symbol Analysis: Analyze your compiled executable (using GDB's Machine Interface) to extract information about functions, global variables, user-defined types, and source files. This data aids in configuring debug actions.
  • Live Scope Inspection: When configuring an action, the tool can query GDB live to list variables (locals and arguments) available at a specified breakpoint, allowing for precise selection.
  • Configurable Environment: Set paths for GDB, the custom Python dumper script, and various timeouts for GDB operations.
  • Flexible Output: Save dumped data in JSON or CSV formats with customizable filenames using placeholders for better organization.
  • GUI Logging: View application logs and raw GDB output directly within the interface.

2. System Requirements & Environment Setup

2.1 Supported Operating Systems

  • Windows: Primary development and testing platform due to the use of the wexpect library for GDB process control.
  • Linux/macOS: GDB itself is cross-platform. While wexpect is Windows-specific, the core GDB interaction logic could be adapted for pexpect on Unix-like systems (this adaptation is not currently part of the provided codebase but is a potential extension).

2.2 Python

  • Python 3.7 or newer is recommended.

2.3 Required Python Libraries

You will need to install the following Python libraries. You can typically install them using pip: pip install wexpect appdirs

  • wexpect: For controlling GDB as a child process on Windows.
    • Note: For Linux/macOS, pexpect would be the equivalent.
  • appdirs: Used for determining platform-independent user configuration and data directories.
  • Tkinter: This is usually included with standard Python installations and is used for the GUI. No separate installation is typically needed.

2.4 GDB Installation

  • A working installation of the GNU Debugger (GDB) is required.
  • Ensure that GDB is either:
    • Added to your system's PATH environment variable, so it can be invoked as gdb.
    • Or, you provide the full path to the gdb.exe (or gdb on Linux/macOS) executable in the application's configuration window.
  • GDB versions 8.x and newer are generally recommended for better Python scripting support.

2.5 Compiling Your C/C++ Target Application

  • To make the most of GDB and this tool, your C/C++ application must be compiled with debugging symbols.
  • For GCC/G++ or Clang, this is typically achieved by adding the -g flag during compilation. For example: g++ -g -o myprogram myprogram.cpp
  • Avoid high levels of optimization (e.g., -O2, -O3) if they strip too much debug information or make debugging difficult due to code reordering. Compiling with -Og (optimize for debug experience) can be a good compromise if some optimization is needed.

2.6 Tool Installation (Cpp-Python GDB Debug Helper)

Currently, the software is designed to be run from its source code:

  1. Ensure all prerequisites (Python, libraries, GDB) are met.
  2. Download or clone the source code of the Cpp-Python GDB Debug Helper.
  3. Navigate to the root directory of the project (e.g., cpp_python_debug).
  4. Run the main script using Python: python -m cpp_python_debug (This assumes __main__.py is in a package structure. If it's a simple script, python __main__.py or python main_window.py if that's the entry point might be used directly from its directory).

3. Quick Start Guide

This guide will walk you through the basic steps to get the Cpp-Python GDB Debug Helper up and running for a manual debugging session.

3.1 Launching the Application

  1. Ensure you have met all the "System Requirements & Environment Setup" (Section 2).
  2. Navigate to the root directory of the Cpp-Python GDB Debug Helper source code.
  3. Execute the main script: python -m cpp_python_debug The main application window should appear.

3.2 Initial Configuration (GDB Path)

  1. Upon first launch, or if GDB is not found, you'll likely need to configure the path to your GDB executable.
  2. In the main window, go to Options > Configure Application....
  3. In the "Configuration" window, select the Paths tab.
  4. Under "GDB Executable", click Browse... and navigate to your GDB executable file (e.g., gdb.exe on Windows, gdb on Linux/macOS).
  5. Click Save.
  6. The "Critical Configuration Status" area in the main window should now show "GDB: ... (OK)".

(Optional) Configure Dumper Script Path:

  • The tool includes a custom Python script (gdb_dumper.py) located in the core sub-directory of the application. This script enables advanced JSON dumping of variables.
  • In the Paths tab of the Configuration window, under "GDB Dumper Script", click Browse... and navigate to this gdb_dumper.py file.
  • Click Save. The status area should update to show the dumper script as "(OK)" or "(Loaded)".

3.3 Your First Manual Debug Session

  1. Select the "Manual Debug" Tab: This is typically the default tab.
  2. Target Executable:
    • Click the Browse... button next to "Target Executable".
    • Navigate to and select your C/C++ executable compiled with debug symbols (e.g., myprogram.exe).
  3. Program Parameters (Optional):
    • If your program requires command-line arguments, enter them in the "Program Parameters" field.
  4. Breakpoint Location:
    • Enter a breakpoint location in the "Breakpoint Location" field. Common examples:
      • main (to break at the start of the main function)
      • myfunction (to break at the start of myfunction)
      • myfile.cpp:42 (to break at line 42 of myfile.cpp)
      • MyClass::myMethod (to break at the C++ method)
  5. Variable/Expression to Dump:
    • Enter the name of a variable or a C/C++ expression you want to inspect when the breakpoint is hit (e.g., myLocalVar, *myPointer, myObject.member).
  6. Start GDB:
    • Click the 1. Start GDB button.
    • The "GDB Raw Output" area will show GDB's startup messages. The "Status Bar" at the bottom should indicate "GDB session active."
  7. Set Breakpoint:
    • Click the 2. Set Breakpoint button.
    • GDB's response to the breakpoint command will appear in the "GDB Raw Output". The button text should update (e.g., "BP: main (Set)") if successful.
  8. Run Program:
    • Click the 3. Run Program button.
    • The program will execute until it hits the breakpoint (or exits/crashes).
    • The "GDB Raw Output" will show program output and GDB messages. If the breakpoint is hit, the status bar will update. The "3. Run Program" button will change to "3. Continue".
  9. Dump Variable:
    • Once the breakpoint is hit, click the 4. Dump Variable button.
    • The "GDB Raw Output" will show the commands sent by the dumper script (if configured) and its output.
    • The "Parsed JSON Output" area will display the structured JSON representation of the dumped variable.
    • The "Save as JSON" and "Save as CSV" buttons will become active.
  10. Continue/Stop:
    • Click 3. Continue to resume program execution.
    • Click Stop GDB to terminate the GDB session and the program.
  11. Saving Data:
    • After dumping a variable, click Save as JSON or Save as CSV to save the displayed data to a file.

Congratulations! You've completed your first manual debug session.

4. User Interface Overview (Main Window)

The main window is the central hub for interacting with the Cpp-Python GDB Debug Helper.

(Screenshot of the main window with areas annotated would be ideal here if this were a rich document)

4.1 Menu Bar

  • Options:
    • Configure Application...: Opens the Configuration Window (see Section 5).
    • Exit: Closes the application.
  • Profiles:
    • Manage Profiles...: Opens the Profile Manager Window (see Section 7).

4.2 Critical Configuration Status Area

Located at the top, this area displays the status of:

  • GDB Executable: Shows the path to the GDB executable and whether it's found ("OK") or not.
  • Dumper Script: Shows the path to the gdb_dumper.py script and its load status ("OK", "Loaded", "Not Found", "Load Failed", or "Not Configured").
  • Configure... Button: A shortcut to open the Configuration Window.

4.3 Mode Panel (Tabs)

This section uses a tabbed interface to switch between different modes of operation:

  • Manual Debug Tab: (See Section 6)
    • Fields for setting the target executable, program parameters, breakpoint location, and variable to dump.
    • Control buttons for starting GDB, setting breakpoints, running/continuing, dumping variables, and stopping GDB.
    • Buttons to save dumped data.
  • Automated Profile Execution Tab: (See Section 9)
    • Dropdown to select a pre-configured debug profile.
    • Buttons to run or stop the selected profile.
    • Status display and progress bar for profile execution.
    • A tree view listing files produced during the profile run.
    • Button to open the output folder of the last run.

4.4 Output and Log Area (Tabs)

This area at the bottom displays various outputs:

  • GDB Raw Output Tab: Shows the raw, unfiltered command-line output from the GDB process. Useful for diagnostics and understanding GDB's behavior.
  • Parsed JSON Output Tab: Displays the pretty-printed JSON data resulting from a "Dump Variable" action (in Manual Debug mode) or from actions during a Profile Execution. If an error occurs during dumping, it might show an error structure.
  • Application Log Tab: Displays log messages generated by the Cpp-Python GDB Debug Helper application itself (e.g., status updates, warnings, errors).

4.5 Status Bar

Located at the very bottom of the window, the status bar provides brief messages about the current state of the application or the last operation performed (e.g., "Ready", "GDB session active", "Breakpoint hit", "Error...").

5. Configuration Window (Options > Configure Application...)

The Configuration Window allows you to customize various settings for the Cpp-Python GDB Debug Helper. Changes made here are saved to a JSON configuration file and persist across sessions.

(A screenshot of the Configuration Window with tabs would be beneficial here)

The window is organized into several tabs:

5.1 Paths Tab

This tab is for setting up essential file paths.

  • GDB Executable:
    • Field: Specifies the full path to the GDB executable (e.g., C:\MinGW\bin\gdb.exe or /usr/bin/gdb).
    • Browse... Button: Opens a file dialog to help you locate and select the GDB executable.
    • This path is crucial for the application to function.
  • GDB Dumper Script:
    • Field: Specifies the full path to the gdb_dumper.py script. This script is part of the Cpp-Python GDB Debug Helper distribution and is typically located in its core sub-directory.
    • Browse... Button: Opens a file dialog to select the gdb_dumper.py script.
    • This script is required for the advanced JSON dumping feature. If not configured, or if the script fails to load, the "Dump Variable" functionality (and automated profile dumping) will be limited or may report errors.

5.2 Timeouts Tab (seconds)

This tab allows you to configure timeouts for various GDB operations. Setting appropriate timeouts is important to prevent the application from hanging indefinitely if GDB becomes unresponsive or an operation takes longer than expected. All values are in seconds.

  • GDB Start: Timeout for the GDB process to start and become ready for commands. (Default: 30s)
  • GDB Command: Default timeout for general GDB commands (e.g., setting a breakpoint, internal GDB commands). (Default: 30s)
  • Program Run/Continue: Timeout for the run or continue GDB commands. This should generally be longer, as it depends on how long your program takes to reach a breakpoint or complete. (Default: 120s)
  • Dump Variable: Timeout specifically for the dump_json operation, which involves GDB executing the Python dumper script. (Default: 60s)
  • Kill Program: Timeout for GDB to confirm program termination after a kill command. (Default: 20s)
  • GDB Quit: Timeout for GDB to exit cleanly after a quit command. (Default: 10s)

Input for these fields is typically via Spinboxes, allowing easy increment/decrement of integer values.

5.3 Dumper Options Tab

These settings control the behavior of the gdb_dumper.py script when it serializes C/C++ data structures into JSON. These options help manage performance and output size for very large or complex variables.

  • Max Array Elements: The maximum number of elements to dump from arrays, std::vector, or other list-like containers. (Default: 100)
  • Max Recursion Depth: The maximum depth the dumper will traverse when serializing nested structures or pointers (e.g., linked lists, trees). This helps prevent infinite loops with cyclic data structures. (Default: 10)
  • Max String Length: The maximum number of characters to dump from a C-style string or std::string. Longer strings will be truncated. (Default: 2048)

Input for these fields is also typically via Spinboxes.

5.4 Saving and Cancelling

  • Save Button:
    • Validates the current settings in all tabs.
    • If valid, applies the changes to the application's internal settings manager.
    • Saves all settings to the JSON configuration file.
    • Closes the Configuration Window.
  • Cancel Button:
    • Discards any changes made in the Configuration Window.
    • Closes the Configuration Window.
  • Window 'X' (Close) Button: Typically behaves the same as the "Cancel" button.

6. Manual Debug Mode

The "Manual Debug" tab provides an interactive way to control a GDB session for debugging your C/C++ application.

(A screenshot of the Manual Debug tab with key elements highlighted would be useful)

6.1 Setting Target Executable and Parameters

  • Target Executable Field:
    • Enter the full path to the C/C++ executable you want to debug.
    • Alternatively, click the Browse... button to open a file dialog and select the executable.
    • The application will remember the last used executable path.
  • Program Parameters Field:
    • If your target program requires command-line arguments, enter them here.
    • These parameters will be passed to your program when GDB's run command is issued.

6.2 Setting Breakpoint Location

  • Breakpoint Location Field:
    • Specify where GDB should pause the execution of your program. Examples:
      • main (function name)
      • MyClass::myMethod (C++ class method)
      • filename.cpp:123 (file and line number)
      • 0x4005A0 (memory address, if known)
    • A small help text below the field provides common examples.

6.3 Setting Variable/Expression to Dump

  • Variable/Expression Field:
    • Enter the name of the C/C++ variable or a valid GDB expression whose value you want to inspect when a breakpoint is hit. Examples:
      • myLocalVariable
      • global_var
      • *pointer_to_struct
      • my_object.data_member
      • my_vector
      • (char*)some_address (casting an address to view memory)

6.4 Session Control Buttons

These buttons control the GDB debugging session flow:

  1. 1. Start GDB Button:
    • Action: Initializes and starts a GDB session, loading the specified "Target Executable". It also attempts to source the "GDB Dumper Script" if configured.
    • State: Enabled if GDB is configured and no session is active. Becomes disabled once a session starts.
    • Output: GDB startup messages, dumper script sourcing status, and symbol loading information appear in the "GDB Raw Output" area.
  2. 2. Set Breakpoint Button:
    • Action: Sends a command to GDB to set a breakpoint at the "Breakpoint Location" specified.
    • State: Enabled after GDB has successfully started. The button text updates to reflect the set breakpoint (e.g., "BP: main (Set)").
    • Output: GDB's confirmation or error message regarding the breakpoint is shown in "GDB Raw Output".
  3. 3. Run Program / 3. Continue Button:
    • Action (Run Program): If the program hasn't been started yet in the current session, this button sends the run command to GDB (along with any "Program Parameters").
    • Action (Continue): If the program is currently stopped (e.g., at a breakpoint), this button sends the continue command to GDB.
    • State: Enabled after a breakpoint has been successfully set (or if GDB is in a state where running is possible).
    • Output: Program output and GDB messages (like breakpoint hits or program exit status) appear in "GDB Raw Output".
  4. 4. Dump Variable Button:
    • Action: When the program is paused at a breakpoint, this button commands GDB (via the dumper script) to evaluate the "Variable/Expression" and serialize its state into JSON.
    • State: Enabled when the program is stopped at a breakpoint and the dumper script is successfully loaded.
    • Output:
      • "GDB Raw Output": Shows communication with the dumper script.
      • "Parsed JSON Output": Displays the structured JSON result of the dump.
  5. Stop GDB Button:
    • Action: Terminates the current GDB session. If the target program is running, it attempts to kill it first, then sends the quit command to GDB.
    • State: Enabled when a GDB session is active.
    • Output: GDB's responses to kill and quit commands appear in "GDB Raw Output". The GUI controls are reset to their pre-session state.

6.5 Interpreting GDB Raw Output

The "GDB Raw Output" tab displays all text-based communication with the GDB subprocess. This includes:

  • GDB's welcome messages and prompts (gdb).
  • Responses to commands (e.g., breakpoint confirmations, error messages).
  • Output from the target program (its stdout and stderr).
  • Messages from the GDB Python dumper script during its execution (these are prefixed with GDB_DUMPER_SCRIPT: or logged to gdb_dumper_debug.log).
  • Status messages like *stopped,reason="breakpoint-hit",... when in MI mode (less relevant for this tab, but might appear if GDB sends mixed output).

6.6 Interpreting Parsed JSON Output

The "Parsed JSON Output" tab shows the result of the "Dump Variable" action, formatted for readability.

  • Successful Dump: You'll see a JSON representation of the variable's structure and values.
    • Simple types (int, float, bool) appear as their JSON equivalents.
    • Pointers might be shown as their address, or if dereferenced by the dumper, the content they point to (within recursion limits). Null pointers are often null.
    • Arrays/Vectors show their elements (up to Max Array Elements).
    • Structs/Classes show their members.
    • std::string contents are shown.
    • Special strings like <optimized_out>, <max_recursion_depth_reached>, <cyclic_or_shared_ref_to_type_...> indicate limitations or specific conditions encountered by the dumper.
  • Dumper Script Error: If the gdb_dumper.py script itself encounters an issue or GDB cannot evaluate the expression, this tab will often display a JSON object with a "_gdb_tool_error" or "gdb_script_error" key, providing details about the problem. Example:
    {
      "_gdb_tool_error": "GDB evaluation error: No symbol \"non_existent_var\" in current context.",
      "expression": "non_existent_var",
      "details": "The expression could not be evaluated by GDB..."
    }
    

6.7 Saving Dumped Data (JSON/CSV)

After a successful variable dump, the last_dumped_data is stored internally.

  • Save as JSON Button:

    • Enabled if last_dumped_data is valid.
    • Opens a "Save As" dialog, allowing you to save the raw JSON data (as displayed in the "Parsed JSON Output" tab) to a .json file.
  • Save as CSV Button:

    • Enabled if last_dumped_data is valid.
    • Opens a "Save As" dialog. The tool attempts to convert the last_dumped_data into a tabular CSV format.
      • If the data is a list of dictionaries, the keys of the first dictionary become CSV headers.
      • If it's a single dictionary, it's treated as a one-row CSV.
      • If it's a list of primitive values or a single primitive, it's saved under a "value" column.
    • This is most useful for dumping arrays of simple structs or homogenous data. Complex nested JSON might not translate perfectly to a flat CSV.

    Great, let's continue with Sections 7 and 8 of the English user manual.


7. Profile Manager (Profiles > Manage Profiles...)

The Profile Manager window is where you create, configure, and organize automated debugging profiles. Each profile encapsulates settings for debugging a specific target executable with a defined set of actions.

(A screenshot of the Profile Manager window, highlighting the profiles list, details form, analysis section, and actions list, would be very helpful here.)

7.1 Profile Manager Window Overview

The window is generally divided into a few key areas:

  • Left Pane (Profiles List):
    • Profiles Listbox: Displays all saved debug profiles by name. Selecting a profile here loads its details into the right pane.
    • Control Buttons (New, Duplicate, Delete): For managing the list of profiles.
  • Right Pane (Profile Configuration):
    • Profile Details Form: Fields to edit the selected profile's name, target executable path, and program parameters.
    • Symbol Analysis Status & Control: Displays information about the last symbol analysis performed for the current target executable (if any) and allows you to trigger a new analysis.
    • Analyzed Symbols Summary: Shows counts of functions, global variables, types, and source files found in the last analysis, with "View..." buttons to inspect them.
    • Debug Actions Area: A listbox showing the sequence of debug actions defined for the selected profile, with buttons to add, edit, or remove actions.
  • Bottom Buttons (Save All Changes, Close):
    • Save All Changes: Saves all modifications made to any profile and the profile list itself to the application's settings file.
    • Close: Closes the Profile Manager window. Prompts to save if there are unsaved changes.

7.2 Managing Profiles

  • Selecting a Profile: Click on a profile name in the "Profiles Listbox" on the left. Its details and actions will load into the right pane for viewing and editing.
  • New Button:
    • Creates a new, blank profile with default settings (e.g., "New Profile", empty actions).
    • The new profile is added to the list, selected, and its name field is focused for immediate editing.
  • Duplicate Button:
    • Enabled when a profile is selected.
    • Creates a copy of the currently selected profile. The duplicated profile will have a name like "OriginalName_copy".
    • The new duplicate is added to the list and selected.
  • Delete Button:
    • Enabled when a profile is selected.
    • Prompts for confirmation, then removes the selected profile from the list.
  • Save All Changes Button:
    • This is the primary way to persist your work within the Profile Manager.
    • It validates all profiles (e.g., for unique names) and then writes the entire list of profiles (and their configurations) to the application's JSON settings file.
    • It's recommended to save frequently, especially after significant changes.

7.3 Editing Profile Details

When a profile is selected, its basic details can be edited in the "Profile Details" form:

  • Profile Name:
    • A unique name for the profile (e.g., "Debug MyLibrary FeatureX", "ReleaseMode SanityCheck").
    • This field is editable. Ensure names are unique across all profiles.
  • Target Executable:
    • The full path to the C/C++ executable that this profile will debug.
    • Use the Browse... button to select the file.
    • Changing this path might invalidate a previous symbol analysis for this profile.
  • Program Parameters:
    • Command-line arguments to pass to the target executable when it's run under this profile.

Any change to these fields marks the current profile form as modified. These changes are temporarily held in the window and are only written to the internal profile data structure when you switch profiles (after a prompt) or explicitly save the current form's state before certain operations (e.g., duplication, deletion, or triggering symbol analysis).

7.4 Symbol Analysis

This section helps you understand and manage the symbol information associated with the profile's target executable. The tool uses GDB's Machine Interface (MI) for efficient symbol extraction.

  • Symbol Analysis Status & Control Area:

    • Target in Form: Displays the name of the executable currently specified in the "Target Executable" field.
    • Last Analysis on File: Shows the name of the executable for which the stored symbol analysis was performed.
    • File Timestamp (at analysis): The modification timestamp of the executable when it was last analyzed.
    • Analysis Date: When the stored analysis was performed.
    • Saved Checksum: The MD5 checksum of the executable at the time of the last analysis.
    • Current Form Exe Checksum: The MD5 checksum of the executable currently specified in the "Target Executable" field.
    • Status Label (e.g., "Up-to-date", "TARGET CHANGED", "EXECUTABLE CHANGED", "Not performed"): Provides a quick assessment of the stored analysis's relevance to the current target executable in the form.
      • Up-to-date: The stored analysis matches the current executable.
      • TARGET CHANGED: The executable path in the form is different from the one that was analyzed. Re-analysis is highly recommended.
      • EXECUTABLE CHANGED: The executable path is the same, but its content (checksum) has changed. Re-analysis is required.
      • Not performed: No symbol analysis data is stored for this profile.
    • Analyse Target Symbols Button:
      • Enabled if a valid target executable is specified in the form and GDB is configured.
      • Triggers a new symbol analysis for the executable currently specified in the "Target Executable" field.
      • A progress dialog will appear showing the analysis steps.
      • Upon successful completion, the extracted symbol data (functions, globals, types, sources, checksum, timestamps) is stored within the currently selected profile's data in memory.
      • You must click "Save All Changes" to persist this new analysis data to the settings file.
  • Analyzed Symbols Summary Area:

    • Displays counts of Functions, Globals, Types, and Source Files found in the stored symbol analysis for the selected profile.
    • View... Buttons: Next to each count, these buttons (enabled if counts > 0 and analysis is considered relevant) open a SymbolListViewerDialog allowing you to browse the detailed list of the respective symbols.

7.5 Managing Debug Actions

For a selected profile, you can define a sequence of debug actions. These actions are executed by the ProfileExecutor when the profile is run.

  • Debug Actions Listbox:
    • Displays a summary of each action defined for the current profile (e.g., "BP: main (Vars:1,Fmt:json,Cont:Yes)").
    • Selecting an action in this listbox enables the "Edit..." and "Remove" buttons.
  • Add... Button:
    • Enabled if a profile is selected.
    • Opens the Action Editor Window (see Section 8) to define a new debug action. The new action is appended to the list for the current profile.
  • Edit... Button:
    • Enabled if an action is selected in the "Debug Actions Listbox".
    • Opens the Action Editor Window pre-filled with the data of the selected action, allowing you to modify it.
  • Remove Button:
    • Enabled if an action is selected.
    • Prompts for confirmation and then removes the selected action from the current profile.

Changes to actions (adding, editing, removing) mark the profile as modified and require using "Save All Changes" to be persisted.


8. Action Editor Window (from Profile Manager)

The Action Editor Window is a dialog used to define or modify the specifics of a single debug action within a profile.

(A screenshot of the Action Editor Window would be very useful here.)

8.1 Breakpoint Location

  • Field: Enter the location where GDB should set a breakpoint for this action (e.g., main, file.cpp:123, MyClass::myMethod).
  • Assistance Buttons:
    • Funcs... Button:
      • Opens a SymbolListViewerDialog (or FunctionSelectorDialog).
      • If symbol analysis data is available for the profile's target, it lists functions from that analysis.
      • Otherwise, it attempts a live GDB query to list functions from the current target executable (this requires GDB and the target to be valid).
      • Selecting a function populates the "Breakpoint Location" field.
    • Files... Button:
      • Enabled if symbol analysis data containing source file information is available.
      • Opens a SymbolListViewerDialog listing source files known to GDB.
      • Selecting a file populates the "Breakpoint Location" field with the file path, ready for you to append a line number (e.g., path/to/file.cpp:).

8.2 Variables to Dump

  • Scrolled Text Area: Enter the C/C++ variables or GDB expressions to be dumped when this action's breakpoint is hit.
    • Enter one variable/expression per line.
  • Assistance Buttons:
    • Globals... Button:
      • Enabled if symbol analysis data containing global variable information is available.
      • Opens a SymbolListViewerDialog allowing multiple selection of global variables.
      • Selected globals are appended to the text area.
    • Scope Vars... Button:
      • Enabled if a "Breakpoint Location" is set, GDB is configured, and a valid target executable is specified for the profile.
      • Action: This is a powerful feature. It temporarily starts a GDB session, sets the specified breakpoint, runs the program (using the profile's "Program Parameters") until the breakpoint is hit, and then lists the local variables and arguments currently in scope.
      • A progress dialog shows the status of this live inspection.
      • Once complete, a SymbolListViewerDialog appears, allowing multiple selection of these scope variables.
      • Selected scope variables are appended to the text area.
      • Results of scope inspection are cached for the session to speed up subsequent requests for the same breakpoint and parameters.
    • Test Action... Button: (Currently a placeholder, marked as disabled) Intended for future implementation to validate the action directly with GDB.

8.3 Output Format

  • Combobox (Dropdown): Choose the format for the dumped data.
    • json: Saves the data in a structured, human-readable JSON format. This is the default and generally recommended for complex data.
    • csv: Attempts to save the data in Comma Separated Values format. Best for lists of simple structures or primitive data.

8.4 Output Directory

  • Field: Specify the directory where the output files for this action will be saved.
  • Browse... Button: Opens a directory selection dialog.
  • When a profile is run, a timestamped sub-directory (e.g., ProfileName_YYYYMMDD_HHMMSS) is created within this specified directory to store all files produced by that particular run.

8.5 Filename Pattern

  • Field: Define a pattern for generating the names of the output files.
  • Available Placeholders:
    • {profile_name}: The name of the profile being executed.
    • {app_name}: The base name of the target executable.
    • {breakpoint}: The "Breakpoint Location" string for this action.
    • {variable}: The name of the variable being dumped.
    • {timestamp}: A detailed timestamp (e.g., YYYYMMDD_HHMMSS_mmm).
    • {format}: The selected output format (e.g., json, csv).
  • Example: {profile_name}_{breakpoint}_{variable}_{timestamp}.{format}
  • The file extension (.json or .csv) is automatically appended if not included via the {format} placeholder or manually.

8.6 "Continue execution after dump" Option

  • Checkbox:
    • Checked (Default): After this action's breakpoint is hit and all specified variables are dumped, GDB will automatically issue a continue command, and the program will resume execution until the next breakpoint (or it exits/crashes).
    • Unchecked: After this action's breakpoint is hit and variables are dumped, the program will remain paused in GDB. The profile execution will effectively halt at this point for this specific run path. This is useful if you want to manually inspect GDB further after a specific dump or if this is the last point of interest.

8.7 Saving and Cancelling the Action

  • OK Button: Validates the action's data. If valid, it returns the action configuration data to the Profile Manager window, which then updates its internal list of actions for the profile.
  • Cancel Button (or Window 'X'): Discards changes and closes the Action Editor Window without returning any data.

9. Automated Profile Execution Mode

The "Automated Profile Execution" tab in the main window allows you to run the debug profiles you've configured in the Profile Manager. This automates the process of setting breakpoints, running the program, and dumping specified variables.

(A screenshot of the Automated Profile Execution tab, showing profile selection, run/stop buttons, status, progress bar, and produced files log, would be very illustrative here.)

9.1 Selecting a Profile

  • Select Profile Dropdown (Combobox):
    • This dropdown lists all the profiles currently saved in your application settings (as configured via the Profile Manager).
    • Choose the profile you wish to execute from this list.
    • The "Run Profile" button will be enabled if a profile is selected and no GDB session (manual or another profile) is currently active.

9.2 Running the Profile

  • Run Profile Button:
    • Once a profile is selected, click this button to start its execution.
    • Pre-checks:
      • Ensures no other GDB session (manual or another profile) is currently running.
      • Verifies the GDB executable path is valid.
      • Verifies the target executable specified in the selected profile exists.
    • Actions during run:
      • The GUI will switch to a "running" state:
        • The "Run Profile" button and profile selection dropdown become disabled.
        • The "Stop Profile" button becomes enabled.
        • Menu items ("Options", "Profiles") and manual debug controls become disabled to prevent conflicts.
        • The "Status Display" (e.g., AVVIO PROFILO 'ProfileName' IN CORSO...) updates to show the current phase.
        • The "Progress Bar" (if visible) becomes active (indeterminate mode).
        • The "Produced Files Log" is cleared.
      • A ProfileExecutor instance is created in a separate thread to handle the GDB interaction without freezing the GUI.
      • The executor will:
        • Start GDB with the profile's target executable.
        • Source the dumper script (if configured in general settings).
        • Set all breakpoints defined in the profile's actions.
        • Run the program with the profile's specified parameters.
        • When a breakpoint is hit:
          • Identify which action(s) correspond to that breakpoint.
          • For each relevant action, dump the specified variables to the specified output format and directory, using the filename pattern.
          • Log each file production event in the "Produced Files Log" tree view.
          • Decide whether to continue execution based on the action's "Continue after dump" setting.
        • Update the "GDB Raw Output" and "Parsed JSON Output" tabs in real-time.
        • Provide status updates to the "Status Display" label.

9.3 Monitoring Execution Status and Progress Bar

  • Status Display Label (e.g., "AVVIO PROFILO 'ProfileName' IN CORSO..."):
    • This large label at the top of the "Produced Files Log" area provides textual updates on the profile's execution progress (e.g., "Starting GDB...", "Setting breakpoints...", "Running program...", "Breakpoint 'main' hit, dumping 'var1'...", "Program exited.").
  • Progress Bar:
    • Located below the status display label.
    • Runs in an indeterminate mode while the profile is active, indicating that background processing is occurring. It stops once the profile execution finishes or is stopped.

9.4 Stopping a Running Profile

  • Stop Profile Button:
    • Becomes enabled when a profile is running.
    • Clicking this button signals the ProfileExecutor to gracefully attempt to stop the current GDB session and terminate the profile execution.
    • The executor will try to kill the target program and then quit GDB.
    • The status display will update to "Requesting profile stop...".
    • The button becomes disabled again after the stop request is processed.
    • The profile execution will then conclude, and the GUI will return to an idle state.

9.5 Interpreting the "Produced Files Log"

This tree view dynamically updates as the profile executes, listing each variable dump that results in a file. Each row provides:

  • Time: Timestamp of when the dump file was produced.
  • Breakpoint Spec: The breakpoint location string as defined in the action (e.g., main, file.cpp:10).
  • Variable: The name of the variable or expression that was dumped.
  • File Produced: The base name of the output file created (e.g., ProfileX_main_varA_timestamp.json).
  • Status: "Success" if the dump and save were successful, or an error indicator (e.g., "Failed", "GDB Tool Error", "Save Error").
  • Details: Additional information, especially in case of errors (e.g., the specific error message from GDB or the dumper script).

9.6 Opening the Output Folder

  • Open Output Folder Button:
    • Becomes enabled after a profile execution has completed and if an output directory was successfully created and used during that run.
    • Clicking this button attempts to open the main output directory for the last completed profile run in your system's default file explorer. This directory usually contains a timestamped sub-folder specific to that run.

10. Troubleshooting / FAQ

Q: GDB is not found, or the "Critical Configuration Status" shows GDB path errors. A:

  1. Ensure GDB is installed on your system.
  2. Go to Options > Configure Application... > Paths tab.
  3. Use the "Browse..." button to set the correct full path to your gdb.exe (or gdb) executable.
  4. Click "Save".

Q: The dumper script status is "Not Found" or "Load Failed". A:

  1. The gdb_dumper.py script should be located in the core sub-directory of where you are running the Cpp-Python GDB Debug Helper from.
  2. Go to Options > Configure Application... > Paths tab.
  3. Set the "GDB Dumper Script" path to this gdb_dumper.py file.
  4. If it's "Load Failed" even with a correct path:
    • Check the "GDB Raw Output" when starting a GDB session (manual or profile) for any Python tracebacks or GDB errors related to sourcing the script.
    • Examine the gdb_dumper_debug.log file. This log is created by gdb_dumper.py itself. Its location is logged by gdb_dumper.py on startup (usually in your user's home directory or alongside gdb_dumper.py). This log contains detailed diagnostics from within the GDB Python environment.

Q: GDB output shows "No debugging symbols found." A:

  1. This means your target C/C++ application was not compiled with debugging information, or the symbols are stripped.
  2. Recompile your application using the -g flag (for GCC/G++ or Clang). Example: g++ -g -o myprogram myprogram.cpp.
  3. Avoid aggressive optimizations (-O2, -O3) that might interfere with debugging. Consider -Og.
  4. If symbols are still not found, ensure you are debugging the correct, newly compiled executable.
  5. The Cpp-Python GDB Debug Helper will typically abort a GDB session if no symbols are found, as debugging capabilities are severely limited.

Q: Variable dump results in "_gdb_tool_error" or "gdb_script_error" in the JSON output. A:

  1. This indicates an error occurred either within GDB while trying to evaluate the expression, or within the gdb_dumper.py script.
  2. Check the "details" field within the error JSON for a more specific message (e.g., "No symbol 'variable_name' in current context", "Cannot access memory at address...").
  3. Verify that the variable/expression is spelled correctly and is actually in scope and accessible when the breakpoint is hit.
  4. For dumper script internal errors, check the gdb_dumper_debug.log file for Python tracebacks from within GDB.

Q: Profile execution fails, hangs, or breakpoints are not hit. A:

  1. Target Executable: Ensure the target executable path in the profile is correct and the file exists.
  2. Permissions: Ensure GDB has permission to execute the target and read its symbols.
  3. Breakpoint Locations: Double-check that breakpoint locations in the profile's actions are correct (function names, file:line numbers). Use the symbol analysis feature or live scope inspection to verify.
  4. Program Logic: The program might be exiting before your breakpoints are reached, or the code path to the breakpoint is not being taken with the given "Program Parameters".
  5. Timeouts: If operations are genuinely taking a long time (e.g., on a very large project or slow machine), consider increasing the relevant timeouts in Options > Configure Application... > Timeouts.
  6. GDB Raw Output: Examine this tab for any error messages from GDB.
  7. Application Log: Check for errors reported by the Cpp-Python GDB Debug Helper itself.

Q: The GUI becomes unresponsive. A:

  1. If this happens during a GDB operation (especially "Start GDB", "Run Program", "Dump Variable"), a GDB command might be taking too long or GDB might be stuck. Check if configured timeouts are adequate.
  2. If it's a persistent issue, it might indicate a bug in the GUI's interaction logic or an unhandled exception. Check the console where you launched the Python application and the "Application Log" tab for error messages or tracebacks.

Q: How can I get more debug information from gdb_dumper.py? A:

  1. The gdb_dumper.py script logs its operations to a file named gdb_dumper_debug.log.
  2. The exact path of this log file is determined by the script:
    • If __file__ is a reliable absolute path within the GDB Python environment, the log is placed in the same directory as gdb_dumper.py.
    • As a fallback (e.g., if __file__ is not well-defined), it's placed in the user's home directory (~).
  3. When gdb_dumper.py is sourced by GDB, it attempts to write the determined log path to its own log and also tries to print a message to GDB's console indicating where it intends to log. Check the "GDB Raw Output" for lines like "GDB_DUMPER_SCRIPT: File logger setup attempted." and messages from _dumper_log_write.
  4. This log file contains detailed step-by-step messages from the dumper, including configuration values read, types encountered, and errors during serialization. It's invaluable for debugging the dumper script itself.
  5. The main application (__main__.py) attempts to delete this log file on startup to ensure a clean log for each run of the GUI tool.

11. Use Cases / Examples

11.1 Use Case: Dumping a std::vector at the entry of a function.

  • Goal: Inspect the contents of a std::vector<MyObject> myVector; as soon as a function processVector is called.
  • Steps:
    1. Manual Debug Mode:
      • Target Executable: Your program.
      • Breakpoint Location: processVector (or FileName.cpp:lineNumber of the function entry).
      • Variable/Expression: myVector.
      • Start GDB, Set BP, Run Program.
      • When processVector is hit, click "Dump Variable". The JSON output will show the elements of the vector.
    2. Automated Profile:
      • Create a new profile in the Profile Manager.
      • Set Target Executable.
      • Add an Action:
        • Breakpoint Location: processVector.
        • Variables to Dump: Add myVector.
        • Output Format: json.
        • Output Directory: e.g., ./vector_dumps.
        • Filename Pattern: {breakpoint}_{variable}_{timestamp}.json.
        • Continue after dump: Yes (if you want to see it hit multiple times) or No.
      • Save the profile.
      • Run the profile from the "Automated Profile Execution" tab. Files will be generated in ./vector_dumps/ProfileName_timestamp/.

11.2 Use Case: Tracing a global variable's value across multiple breakpoints.

  • Goal: See how a global variable int globalCounter; changes at three different points in the program: funcA, funcB, and main.cpp:150.
  • Steps (Automated Profile):
    1. Create a profile.
    2. Add Action 1:
      • Breakpoint: funcA
      • Variables: globalCounter
      • Continue: Yes
    3. Add Action 2:
      • Breakpoint: funcB
      • Variables: globalCounter
      • Continue: Yes
    4. Add Action 3:
      • Breakpoint: main.cpp:150
      • Variables: globalCounter
      • Continue: Yes (or No if this is the last point of interest for this run)
    5. Run the profile. The "Produced Files Log" will show separate dump files for globalCounter at each breakpoint, allowing you to compare its values.

11.3 Use Case: Automatically saving snapshots of a complex data structure during a long run.

  • Goal: Periodically dump a complex data structure MyStatefulObject appState; which is modified within a loop inside function longRunningTask.
  • Steps (Automated Profile):
    1. Identify a suitable line number inside the loop in longRunningTask (e.g., longRunningTask.cpp:75).
    2. Create a profile.
    3. Add an Action:
      • Breakpoint: longRunningTask.cpp:75
      • Variables: appState
      • Output Format: json
      • Output Directory: ./app_state_snapshots
      • Continue after dump: Yes
    4. Run the profile. Each time the loop iteration hits line 75, a new JSON file capturing the state of appState will be saved, creating a time-series of its evolution.

12. Advanced: The gdb_dumper.py Script

The gdb_dumper.py script is a crucial component of the Cpp-Python GDB Debug Helper, enabling the detailed inspection and JSON serialization of C/C++ variables from within an active GDB session.

12.1 Role and Interaction with GDB

  • Python within GDB: Modern GDB versions have an embedded Python interpreter, allowing for powerful scripting and automation of debugger tasks.
  • Sourcing: When you start a GDB session through this GUI (and the "GDB Dumper Script" path is correctly configured in Options > Configure Application...), the GUI instructs GDB to source the gdb_dumper.py script.
  • Custom GDB Command: The gdb_dumper.py script defines a new custom GDB command named dump_json <expression>.
  • Serialization Logic: When the GUI needs to dump a variable (either in Manual Debug mode or via an Automated Profile action), it sends this dump_json your_variable_name command to GDB. The Python code within gdb_dumper.py then:
    1. Uses GDB's Python API (gdb.parse_and_eval()) to get a Python object representing the C/C++ variable.
    2. Traverses this gdb.Value object, inspecting its type, fields, elements (for arrays/pointers), etc.
    3. Applies the configured "Dumper Options" (Max Array Elements, Max Recursion Depth, Max String Length) to manage the serialization process.
    4. Handles common C++ types like std::string, pointers, structs, classes, and arrays.
    5. Detects and marks cyclic references or shared pointers to prevent infinite recursion.
    6. Constructs a Python dictionary/list representation of the variable.
    7. Serializes this Python structure into a JSON string.
    8. Prints this JSON string to GDB's standard output, bracketed by special delimiter strings (START_JSON_OUTPUT and END_JSON_OUTPUT).
  • GUI Processing: The Cpp-Python GDB Debug Helper's main application then captures GDB's output, extracts the JSON string between the delimiters, parses it, and displays it in the "Parsed JSON Output" tab.

12.2 Dumper Log File (gdb_dumper_debug.log)

  • Purpose: The gdb_dumper.py script maintains its own detailed log file for diagnostic purposes. This log is separate from the "Application Log" visible in the GUI.
  • Content: It records:
    • Initialization messages.
    • The effective dumper configuration options being used.
    • Detailed steps during the serialization of a variable (types encountered, fields accessed, decisions made).
    • Any errors or Python exceptions that occur within the GDB Python environment while the dumper script is running.
  • Location:
    • The script attempts to create gdb_dumper_debug.log in the same directory where gdb_dumper.py itself resides.
    • If that's not possible (e.g., due to permissions or how GDB resolves paths when sourced), it falls back to creating the log in the user's home directory (~).
    • When GDB sources the script, gdb_dumper.py will attempt to print a message to its own log and to the GDB console indicating the determined log path. Look for these messages in the GDB Raw Output or the log file itself.
  • Deletion on Startup: The main Cpp-Python GDB Debug Helper application (__main__.py) attempts to delete any existing gdb_dumper_debug.log file when the GUI starts. This ensures that the log contains information relevant only to the current GUI session, making it easier to troubleshoot recent issues.
  • When to Check It: This log is invaluable if:
    • JSON dumps are failing unexpectedly.
    • The JSON output is malformed or missing expected data.
    • You suspect an error within the gdb_dumper.py script itself.

13. Appendix (Optional)

13.1 Filename Placeholder Summary

The following placeholders can be used in the "Filename Pattern" field when defining a debug action in the Profile Manager:

  • {profile_name}: The name of the profile being executed (sanitized for use in filenames).
  • {app_name}: The base name of the target executable (e.g., myprogram from /path/to/myprogram.exe).
  • {breakpoint}: The "Breakpoint Location" string specified for the action (sanitized).
  • {variable}: The name of the variable or expression being dumped (sanitized).
  • {timestamp}: A detailed timestamp in the format YYYYMMDD_HHMMSS_fff (YearMonthDay_HourMinuteSecond_Millisecond).
  • {format}: The selected output format in lowercase (e.g., json, csv).

Example Pattern: dump_{app_name}_{breakpoint}_{variable}_{timestamp}.{format} Example Output: dump_myprogram_main_myVar_20231027_143005_123.json