= *GDB Commands, Scripts and Workflow* === Breakpoints and Commands -- save time! In order to display some specific information when we reach a breakpoint, we can achieve this by `(gdb)command` command in gdb. [source,] ---- (gdb) command 1 Type commands for breakpoint(s) 1, one per line. End with a line saying just "end". >print arr >print size >end ---- Here, the argument to "command" is the index of the breakpoint to which these print commands will be associated to. === define your own commands In order to define bunch of command give it a name like a alias we can use `define `. [source,] ---- (gdb) define log Type commands for definition of "log". End with a line saying just "end". >info args >info frame >bt >end ---- [source,] ---- Temporary breakpoint 1, main () at array.c:34 34 int main () { (gdb) log No arguments. Stack level 0, frame at 0x7fffffffe230: rip = 0x555555555217 in main (array.c:34); saved rip = 0x7ffff7c2a1ca source language c. Arglist at 0x7fffffffe220, args: Locals at 0x7fffffffe220, Previous frame's sp is 0x7fffffffe230 Saved registers: rbp at 0x7fffffffe220, rip at 0x7fffffffe228 #0 main () at array.c:34 ---- To redefine the same alias like in the above example 'log' we can use the same command `define log` === gdb scripts It is like a .vimrc for gdb. It is named as *.gdbinit* and it is defined in home (~/) directory and, if we want, can be overridden by defining the *.gdbinit* in the current directory. In this script, we can `define` command to define aliases and print some message, etc. === Shell commands within GDB (shell, make and pipe) To run shell commands within GDB use keyword `shell` with respective shell command like `ls` as an argument. [source,] ---- $ gdb ./main --silent Reading symbols from ./main... (gdb) shell ls add array assertion core.14804 gcore_example.c infinite.c leak.c main.c memory.c segfault.c add.c array.c assertion.cpp gcore_example infinite leak main memory segfault ---- We can also use `make` command within GDB to compile the excutable from gdb itself. Now when you compile the executable within GDB using `make` command, there are two senario which arises. *Senario 1* _When the name of the program remain same._ In this case, we can simply start the execution of program from the beginning again. Use `start` command to do so. *Senario 2* _When the name of the program changes_ In this cae, we can load the executable to the running gdb using `file` command and start the executation again. [source,] ---- (gdb)file ./ ---- === Edit source files within GDB To edit current source in gdb without exiting out of the GDB session, we can use `edit` command to open the source file in editor to run the program. Make sure that the there is a environment variable `EDITOR=` defined and exported so that GDB can use it. [source,] ---- (gdb)edit 5 ---- Load the program again with successful compilation to see the changes made.