Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/tools/jmap/JMap.java
38918 views
/*1* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.tools.jmap;2627import java.lang.reflect.Method;28import java.io.File;29import java.io.IOException;30import java.io.InputStream;3132import com.sun.tools.attach.VirtualMachine;33import com.sun.tools.attach.AttachNotSupportedException;34import sun.tools.attach.HotSpotVirtualMachine;3536/*37* This class is the main class for the JMap utility. It parses its arguments38* and decides if the command should be satisfied using the VM attach mechanism39* or an SA tool. At this time the only option that uses the VM attach mechanism40* is the -dump option to get a heap dump of a running application. All other41* options are mapped to SA tools.42*/43public class JMap {4445// Options handled by the attach mechanism46private static String HISTO_OPTION = "-histo";47private static String LIVE_HISTO_OPTION = "-histo:live";48private static String DUMP_OPTION_PREFIX = "-dump:";4950// These options imply the use of a SA tool51private static String SA_TOOL_OPTIONS =52"-heap|-heap:format=b|-clstats|-finalizerinfo";5354// The -F (force) option is currently not passed through to SA55private static String FORCE_SA_OPTION = "-F";5657// Default option (if nothing provided)58private static String DEFAULT_OPTION = "-pmap";5960public static void main(String[] args) throws Exception {61if (args.length == 0) {62usage(1); // no arguments63}6465// used to indicate if we should use SA66boolean useSA = false;6768// the chosen option (-heap, -dump:*, ... )69String option = null;7071// First iterate over the options (arguments starting with -). There should be72// one (but maybe two if -F is also used).73int optionCount = 0;74while (optionCount < args.length) {75String arg = args[optionCount];76if (!arg.startsWith("-")) {77break;78}79if (arg.equals("-help") || arg.equals("-h")) {80usage(0);81} else if (arg.equals(FORCE_SA_OPTION)) {82useSA = true;83} else {84if (option != null) {85usage(1); // option already specified86}87option = arg;88}89optionCount++;90}9192// if no option provided then use default.93if (option == null) {94option = DEFAULT_OPTION;95}96if (option.matches(SA_TOOL_OPTIONS)) {97useSA = true;98}99100// Next we check the parameter count. For the SA tools there are101// one or two parameters. For the built-in -dump option there is102// only one parameter (the process-id)103int paramCount = args.length - optionCount;104if (paramCount == 0 || paramCount > 2) {105usage(1);106}107108if (optionCount == 0 || paramCount != 1) {109useSA = true;110} else {111// the parameter for the -dump option is a process-id.112// If it doesn't parse to a number then it must be SA113// debug server114if (!args[optionCount].matches("[0-9]+")) {115useSA = true;116}117}118119120// at this point we know if we are executing an SA tool or a built-in121// option.122123if (useSA) {124// parameters (<pid> or <exe> <core>)125String params[] = new String[paramCount];126for (int i=optionCount; i<args.length; i++ ){127params[i-optionCount] = args[i];128}129runTool(option, params);130131} else {132String pid = args[1];133// Here we handle the built-in options134// As more options are added we should create an abstract tool class and135// have a table to map the options136if (option.equals(HISTO_OPTION)) {137histo(pid, false);138} else if (option.equals(LIVE_HISTO_OPTION)) {139histo(pid, true);140} else if (option.startsWith(DUMP_OPTION_PREFIX)) {141dump(pid, option);142} else {143usage(1);144}145}146}147148// Invoke SA tool with the given arguments149private static void runTool(String option, String args[]) throws Exception {150String[][] tools = {151{ "-pmap", "sun.jvm.hotspot.tools.PMap" },152{ "-heap", "sun.jvm.hotspot.tools.HeapSummary" },153{ "-heap:format=b", "sun.jvm.hotspot.tools.HeapDumper" },154{ "-histo", "sun.jvm.hotspot.tools.ObjectHistogram" },155{ "-clstats", "sun.jvm.hotspot.tools.ClassLoaderStats" },156{ "-finalizerinfo", "sun.jvm.hotspot.tools.FinalizerInfo" },157};158159String tool = null;160161// -dump option needs to be handled in a special way162if (option.startsWith(DUMP_OPTION_PREFIX)) {163// first check that the option can be parsed164String fn = parseDumpOptions(option);165if (fn == null) {166usage(1);167}168169// tool for heap dumping170tool = "sun.jvm.hotspot.tools.HeapDumper";171172// HeapDumper -f <file>173args = prepend(fn, args);174args = prepend("-f", args);175} else {176int i=0;177while (i < tools.length) {178if (option.equals(tools[i][0])) {179tool = tools[i][1];180break;181}182i++;183}184}185if (tool == null) {186usage(1); // no mapping to tool187}188189// Tool not available on this platform.190Class<?> c = loadClass(tool);191if (c == null) {192usage(1);193}194195// invoke the main method with the arguments196Class[] argTypes = { String[].class } ;197Method m = c.getDeclaredMethod("main", argTypes);198199Object[] invokeArgs = { args };200m.invoke(null, invokeArgs);201}202203// loads the given class using the system class loader204private static Class<?> loadClass(String name) {205//206// We specify the system clas loader so as to cater for development207// environments where this class is on the boot class path but sa-jdi.jar208// is on the system class path. Once the JDK is deployed then both209// tools.jar and sa-jdi.jar are on the system class path.210//211try {212return Class.forName(name, true,213ClassLoader.getSystemClassLoader());214} catch (Exception x) { }215return null;216}217218private static final String LIVE_OBJECTS_OPTION = "-live";219private static final String ALL_OBJECTS_OPTION = "-all";220private static void histo(String pid, boolean live) throws IOException {221VirtualMachine vm = attach(pid);222InputStream in = ((HotSpotVirtualMachine)vm).223heapHisto(live ? LIVE_OBJECTS_OPTION : ALL_OBJECTS_OPTION);224drain(vm, in);225}226227private static void dump(String pid, String options) throws IOException {228// parse the options to get the dump filename229String filename = parseDumpOptions(options);230if (filename == null) {231usage(1); // invalid options or no filename232}233234// get the canonical path - important to avoid just passing235// a "heap.bin" and having the dump created in the target VM236// working directory rather than the directory where jmap237// is executed.238filename = new File(filename).getCanonicalPath();239240// dump live objects only or not241boolean live = isDumpLiveObjects(options);242243VirtualMachine vm = attach(pid);244System.out.println("Dumping heap to " + filename + " ...");245InputStream in = ((HotSpotVirtualMachine)vm).246dumpHeap((Object)filename,247(live ? LIVE_OBJECTS_OPTION : ALL_OBJECTS_OPTION));248drain(vm, in);249}250251// Parse the options to the -dump option. Valid options are format=b and252// file=<file>. Returns <file> if provided. Returns null if <file> not253// provided, or invalid option.254private static String parseDumpOptions(String arg) {255assert arg.startsWith(DUMP_OPTION_PREFIX);256257String filename = null;258259// options are separated by comma (,)260String options[] = arg.substring(DUMP_OPTION_PREFIX.length()).split(",");261262for (int i=0; i<options.length; i++) {263String option = options[i];264265if (option.equals("format=b")) {266// ignore format (not needed at this time)267} else if (option.equals("live")) {268// a valid suboption269} else {270271// file=<file> - check that <file> is specified272if (option.startsWith("file=")) {273filename = option.substring(5);274if (filename.length() == 0) {275return null;276}277} else {278return null; // option not recognized279}280}281}282return filename;283}284285private static boolean isDumpLiveObjects(String arg) {286// options are separated by comma (,)287String options[] = arg.substring(DUMP_OPTION_PREFIX.length()).split(",");288for (String suboption : options) {289if (suboption.equals("live")) {290return true;291}292}293return false;294}295296// Attach to <pid>, existing if we fail to attach297private static VirtualMachine attach(String pid) {298try {299return VirtualMachine.attach(pid);300} catch (Exception x) {301String msg = x.getMessage();302if (msg != null) {303System.err.println(pid + ": " + msg);304} else {305x.printStackTrace();306}307if ((x instanceof AttachNotSupportedException) && haveSA()) {308System.err.println("The -F option can be used when the " +309"target process is not responding");310}311System.exit(1);312return null; // keep compiler happy313}314}315316// Read the stream from the target VM until EOF, then detach317private static void drain(VirtualMachine vm, InputStream in) throws IOException {318// read to EOF and just print output319byte b[] = new byte[256];320int n;321do {322n = in.read(b);323if (n > 0) {324String s = new String(b, 0, n, "UTF-8");325System.out.print(s);326}327} while (n > 0);328in.close();329vm.detach();330}331332// return a new string array with arg as the first element333private static String[] prepend(String arg, String args[]) {334String[] newargs = new String[args.length+1];335newargs[0] = arg;336System.arraycopy(args, 0, newargs, 1, args.length);337return newargs;338}339340// returns true if SA is available341private static boolean haveSA() {342Class<?> c = loadClass("sun.jvm.hotspot.tools.HeapSummary");343return (c != null);344}345346// print usage message347private static void usage(int exit) {348System.err.println("Usage:");349if (haveSA()) {350System.err.println(" jmap [option] <pid>");351System.err.println(" (to connect to running process)");352System.err.println(" jmap [option] <executable <core>");353System.err.println(" (to connect to a core file)");354System.err.println(" jmap [option] [server_id@]<remote server IP or hostname>");355System.err.println(" (to connect to remote debug server)");356System.err.println("");357System.err.println("where <option> is one of:");358System.err.println(" <none> to print same info as Solaris pmap");359System.err.println(" -heap to print java heap summary");360System.err.println(" -histo[:live] to print histogram of java object heap; if the \"live\"");361System.err.println(" suboption is specified, only count live objects");362System.err.println(" -clstats to print class loader statistics");363System.err.println(" -finalizerinfo to print information on objects awaiting finalization");364System.err.println(" -dump:<dump-options> to dump java heap in hprof binary format");365System.err.println(" dump-options:");366System.err.println(" live dump only live objects; if not specified,");367System.err.println(" all objects in the heap are dumped.");368System.err.println(" format=b binary format");369System.err.println(" file=<file> dump heap to <file>");370System.err.println(" Example: jmap -dump:live,format=b,file=heap.bin <pid>");371System.err.println(" -F force. Use with -dump:<dump-options> <pid> or -histo");372System.err.println(" to force a heap dump or histogram when <pid> does not");373System.err.println(" respond. The \"live\" suboption is not supported");374System.err.println(" in this mode.");375System.err.println(" -h | -help to print this help message");376System.err.println(" -J<flag> to pass <flag> directly to the runtime system");377} else {378System.err.println(" jmap -histo <pid>");379System.err.println(" (to connect to running process and print histogram of java object heap");380System.err.println(" jmap -dump:<dump-options> <pid>");381System.err.println(" (to connect to running process and dump java heap)");382System.err.println("");383System.err.println(" dump-options:");384System.err.println(" format=b binary default");385System.err.println(" file=<file> dump heap to <file>");386System.err.println("");387System.err.println(" Example: jmap -dump:format=b,file=heap.bin <pid>");388}389390System.exit(exit);391}392}393394395