CpS 450 Language Translation Systems

Debugging Assembly in Linux

Compiling the executable

Use the following to produce an executable that can be debugged using a debugger:

gcc -g myprog.s stdlib.c -o myprog

where myprog.s is your compiler’s generated assembly file, and stdlib.c is the Dream runtime library (needed if you’re using writeint).

Using gdb

You can use gdb to step through the code (see Beej’s Quick Guide to GDB).

Suggested .gdbinit

Create a.gdbinit in your WSL home directory (ex. using $ vi ~/.gdbinit):

set extension-language .dream c
set pagination off
tui new-layout example {-horizontal src 1 regs 1} 2 status 0 cmd 1
layout example
  • The set extension-language command makes gdb treat source files with a .dream extension as if they were C source, to allow expression evaluation in the debugger
  • See info on the tui and layout commands.

Start gdb

gdb prog

Useful gdb commands

  • Start program running and stop at the beginning:
    start
    
  • Set breakpoint at line
    b 1
    

Examine memory

Show the top of the stack:

x $sp

Show the top 4 words of the stack:

x/4 $sp

Show value of global variable x:

p (int)x

Always show the top 4 words of the stack after every command (try adding this to your .gdbinit):

disp *(int **) $sp @ 4

Using vscode

  • Install VSCode C/C++ extension (Microsoft)
  • Launch VSCode from WSL
    wsl
    cd .../examples/codegen
    code .
    
  • Enable VSCode C/C++ extension for WSL
  • Setup launch.json

launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(gdb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/${relativeFileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": true,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "miDebuggerPath": "/usr/bin/gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                },
                {
                    "description": "Set Disassembly Flavor to Intel",
                    "text": "-gdb-set disassembly-flavor intel",
                    "ignoreFailures": true
                }
            ]
        }     
    ]
}