Re: debugging a dynamically loaded library

Kevin Buettner
2001-08-29T15:41:00Z

On Aug 29, 4:44pm, Mike Krogh wrote:

> Can someone explain how to debug subroutines that are loaded via
> dlopen()/dlsym()?

Sure. Read on...

> Specifically I'd like to compile and link dso.c
> into dso.so and then compile main.c and have it dynamically load
> dso.so. Once that is done, I'd like to get gdb to stop in
> dso_init(int i) from ./dso.so.
>
> I'm compiling with the following:
>
> cc -g -c dso.c
> cc -shared -g -o dso.so dso.o
> cc -rdynamic -o main main.c -ldl

You'll have an easier time of it if you compile main.c with -g.

[...]

> int
> main(int argc, char *argv[]) {
>
> void *handle;
> void (*init)(int);
> void (*incr)(int);
> char *error;
> int i;
>
>
> if (!(handle = dlopen("./dso.so", RTLD_NOW|RTLD_GLOBAL))) {
> fputs(dlerror(), stderr);
> exit(1);
> }
>
> init = dlsym(handle, "dso_init");

Once you're running gdb, place a breakpoint on the above line. The
point of doing this is that it's after the call to dlopen(). GDB
will automatically read dso.so's symbols after the dlopen() call and
then you'll be able to place breakpoints in your dynamically loaded
library.

Here's a test run using your example:

saguaro:dynlib$ /saguaro1/sourceware/bld-saguaro/gdb/gdb main
GNU gdb 2001-08-21-cvs (MI_OUT)
Copyright 2001 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i686-pc-linux-gnu"...
(gdb) b main.c:23
Breakpoint 1 at 0x80487fc: file main.c, line 23.
(gdb) r
Starting program: /home/kev/ctests/dynlib/main

Breakpoint 1, main (argc=1, argv=0xbffffa2c) at main.c:23
23 init = dlsym(handle, "dso_init");
(gdb) b dso_init
Breakpoint 2 at 0x400188a2: file dso.c, line 10.
(gdb) b dso_increment
Breakpoint 3 at 0x400188ce: file dso.c, line 19.
(gdb) c
Continuing.
Do `add-symbol-file dso.so 0x4001889c`
Breakpoint 2, dso_init (i=5) at dso.c:10
10 value = i;
(gdb) c
Continuing.
dso_init: initialized with 5

Breakpoint 3, dso_increment (i=2) at dso.c:19
19 value += i;
(gdb) c
Continuing.
dso_increment: i = 2 value = 7

Breakpoint 3, dso_increment (i=2) at dso.c:19
19 value += i;

etc...