Search code examples
debugginglldb

How to set an expression as a watchpoint in LLDB?


Here is a program:

int main(int argc, char **argv) {
    int *arr = NULL;
    arr = malloc(2 * sizeof(*arr));
    arr[0] = 1;
    arr[1] = 2;
    return 0; // break is here
} 

I want to examine the content of an arr on a break. Here is how I usually do it:

$ lldb main
(lldb) break set -l 266
(lldb) run
Process 9093 launched: '..../main' (x86_64)
Process 9093 stopped
* thread #1, name = 'main', stop reason = breakpoint 1.1
    frame #0: 0x0000555555555314 main`main(argc=1, argv=0x00007fffffffe018) at main.c:266
   263      arr = malloc(2 * sizeof(*arr));
   264      arr[0] = 1;
   265      arr[1] = 2;
-> 266      return 0;
   267  } 
(lldb) x/d -c 2 arr
0x555555757260: 1
0x555555757264: 2
(lldb) p *(int(*)[2])arr
(int [2]) $9 = ([0] = 1, [1] = 2)

Everything is good - the content is printed as expected but the problem is I want LLDB to do it for me whenever I do stepping. So how can I set a watch point (either by means of watch set var ... or watch set expr ...) to print those values automatically on each of the step?


Solution

  • I think you want to use a stop-hook here.

    target stop-hook add -o 'p *(int(*)[2])arr'
    

    If you hit return after target stop-hook add, you can enter multiple commands to do on every stop. This command takes many options for running when you stop on certain source files, functions, in certain solibs, etc., it's pretty flexible.