Monday, August 13, 2012

Generating a Java Core Dump

This post demonstrates how you can generate a Java core dump manually (using JNI).

1. Create a Java class

 * A class to demonstrate core dumping.
public class CoreDumper {

  // load the library
  static {

  // native method declaration
  public native void core();

  public static void main(String[] args) {
    new CoreDumper().core();
2. Compile the Java class
$ javac
$ ls
3. Generate the header file
$ javah -jni CoreDumper
$ ls
CoreDumper.class  CoreDumper.h
4. Implement the native method
Copy the method declaration from the header file and create a new file called CoreDumper.c containing the implementation of this method:
#include "CoreDumper.h"

void bar() {
  // the following statements will produce a core
  int* p = NULL;
  *p = 5;

  // alternatively:
  // abort();

void foo() {

JNIEXPORT void JNICALL Java_CoreDumper_core
  (JNIEnv *env, jobject obj) {
5. Compile the native code
This command may vary based on your operating system. On my Red Hat Linux machine, I use the following command:
$ gcc -fPIC -o -shared \
            -I$JAVA_HOME/include/linux/ \
            -I$JAVA_HOME/include/ \
$ ls
CoreDumper.class  CoreDumper.h
6. Run the program
$ java -Djava.library.path=. CoreDumper
# A fatal error has been detected by the Java Runtime Environment:
#  SIGSEGV (0xb) at pc=0x0000002b1cecf75c, pid=18919, tid=1076017504
# JRE version: 6.0_21-b06
# Java VM: Java HotSpot(TM) 64-Bit Server VM (17.0-b16 mixed mode linux-amd64 )
# Problematic frame:
# C  []  bar+0x10
# An error report file with more information is saved as:
# /home/sharfah/tmp/jni/hs_err_pid18919.log
# If you would like to submit a bug report, please visit:
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
Aborted (core dumped)
The core file
As shown above, running the program causes it to crash and a core file is produced. On my machine, the operating system writes out core files to /var/tmp/cores. You can use the following command to see what your core file directory is configured to:
$ cat /proc/sys/kernel/core_pattern
$ ls /var/tmp/cores
In my next post, I will show you how can you perform some quick analysis on a core file to see what caused the crash.

Next Post:
Analysing a Java Core Dump

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.