A quick demonstration of how one can use a debugger to interactively inspect variables in a running program…
The following C program will choose a random number between 1 and 100 and challenge you to guess it.
Let’s cheat and learn just a tiny little bit about debugging with lldb 1 along the way!
| |
Compile as follows:
$ clang -O0 -g -o guess guess.c
$ ./guess
I have chosen a number between 1 and 100.
Try to guess it!
Enter your guess: 50
Too high! Try again.
Enter your guess: 25
Too low! Try again.
Enter your guess:
Then attach a debugger to it’s pid
% lldb -p 51114
(lldb) process attach --pid 51114
Process 51114 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGSTOP
frame #0: 0x00000001834e0c98 libsystem_kernel.dylib`__read_nocancel + 8
libsystem_kernel.dylib`__read_nocancel:
-> 0x1834e0c98 <+8>: b.lo 0x1834e0cb8 ; <+40>
0x1834e0c9c <+12>: pacibsp
0x1834e0ca0 <+16>: stp x29, x30, [sp, #-0x10]!
0x1834e0ca4 <+20>: mov x29, sp
Target 0: (guess) stopped.
Executable binary set to "/Users/denis/guess".
Architecture set to: arm64-apple-macosx-.
(lldb) bt
* thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGSTOP
* frame #0: 0x00000001834e0c98 libsystem_kernel.dylib`__read_nocancel + 8
frame #1: 0x00000001833dc6e4 libsystem_c.dylib`__sread + 24
frame #2: 0x00000001833b91f8 libsystem_c.dylib`_sread + 32
frame #3: 0x00000001833b918c libsystem_c.dylib`__srefill1 + 36
frame #4: 0x00000001833b7024 libsystem_c.dylib`__svfscanf_l + 1580
frame #5: 0x000000018340e360 libsystem_c.dylib`scanf + 96
frame #6: 0x00000001003784f0 guess`main at guess.c:20:3
frame #7: 0x0000000183159d54 dyld`start + 7184
(lldb) f 6
frame #6: 0x00000001003784f0 guess`main at guess.c:20:3
17 while (guess != secretNumber)
18 {
19 printf("Enter your guess: ");
-> 20 scanf("%d", &guess);
21
22 if (guess < secretNumber) {
23 printf("Too low! Try again.\n");
(lldb) var -L secretNumber
0x000000016fa87158: (int) secretNumber = 28
(lldb) continue
Process 51114 resuming
(lldb)
Back to the shell:
Enter your guess: 28
Congratulations! You guessed the number!
like GDB, except awesome! ↩︎