日期:2014-05-16  浏览次数:20741 次

分析linux上的native内存泄露

Running native profiling on Linux

Read the information provided

Introduction

Several memory profilers are available for the Linux operating system, which fit into the following categories:

Preprocessor level
These profilers require a header to be compiled with the source under test. You can recompile your own JNI libraries with one of these tools to track a native memory leak in your code. Unless you have the source code for Java itself, this recompilation cannot find a leak in the JVM. Compiling this kind of tool into a large project like a JVM would almost certainly be difficult and time-consuming. Dmalloc is an example of this kind of tool.
Linker level
These profilers require the binaries under test to be relinked with a debugging library. You can relink individual JNI libraries but it is not recommended for entire Java runtimes because the runtime vendor is unlikely to support the use of modified binaries. Ccmalloc is an example of this kind of tool.
Runtime-linker level
These profilers use the?LD_PRELOAD?environment variable to preload a library that replaces the standard memory routines with instrumented versions. These profilers do not require recompilation or relinking of source code but many of them do not work well with Java runtimes. A Java runtime is a complicated system that can use memory and threads in unusual ways. It is worth experimenting with a few to see if they work in your scenario. NJAMD is an example of this kind of tool.
Emulator-based
Valgrind is the only example of this type of memory debugger. It emulates the underlying processor in a similar way to the way that a Java runtime emulates the Java virtual machine. It is possible to run Java under Valgrind, but the heavy performance impact (25 - 50 times slower) makes it very difficult to run large, complicated Java applications in this manner. Valgrind is currently available on Linux x86, AMD64, PPC32, and PPC64. If you are intend to use Valgrind, try to narrow down the problem to the smallest possible testcase you can before using it.

For simple scenarios that can tolerate the performance overhead, Valgrind is the most simple and user-friendly of the available free tools. Valgrind can provide a full stack trace for code paths that are leaking memory.

Running a process in Valgrind

Because Valgrind is an emulation environment, the process must be run under Valgrind, and the analysis finishes when the process ends. To use Valgrind with a process that usually runs indefinitely, you must be able to stop the process.

Some Java runtimes use thread stacks and processor registers in unusual ways. This usage can confuse some debugging tools, which expect native programs to abide by standard conventions of register use and stack structure. When using Valgrind to debug leaking JNI applications, you might see many warnings about the use of memory and some unusual thread stacks. These effects ar