Monday, October 24, 2011

Linux - GDB to debug JNI with Tomcat

1. Get process ID - first you must know the Java process id for your application

ps -ef | grep java

2. Connect GDB to Java

gdb -p

or

(gdb) attach prog_port

3. If your .so is built with debug information, you should see the following when gdb load the process. To get debug information into your .so, you can use gcc or g++ with -g

Reading symbols from your_debug.so...done.

Loaded symbols for your_debug.so

4. Add your source directory for debugging

(gdb) dir /your/src/path

Below are some abstract from GNU

directory dirname ... dir dirname ...

Add directory dirname to the front of the source path. Several directory names may be given to this command, separated by `:' (`;' on MS-DOS and MS-Windows, where `:' usually appears as part of absolute file names) or whitespace. You may specify a directory that is already in the source path; this moves it forward, so GDB searches it sooner. You can use the string `$cdir' to refer to the compilation directory (if one is recorded), and `$cwd' to refer to the current working directory. `$cwd' is not the same as `.'---the former tracks the current working directory as it changes during your GDB session, while the latter is immediately expanded to the current directory at the time you add an entry to the source path. directory

Reset the source path to empty again. This requires confirmation. show directories

Print the source path: show which directories it contains.

5. Set breakpoint to gdb - the easiest way is to set break point directly to the class::method (eg, YourClass::YourMethod). gdb will locate the corresponding file and set break point to that method

6. When you attach gdb to tomcat, you may realise that the web application may hang. That is because gdb has taken over the control. To continue the application, type continue at the GDB interface
7. To check a value in your breakpoint, do the following

(gdb) p your_variable

8. - if you see this message, it means that your program is compile with gcc -03 where gcc optimizer think that the variable is redundant and had optimized away