1 /*
   2  * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.tools.jstack;
  27 
  28 import java.lang.reflect.Method;
  29 import java.lang.reflect.Constructor;
  30 import java.io.IOException;
  31 import java.io.InputStream;
  32 
  33 import com.sun.tools.attach.VirtualMachine;
  34 import com.sun.tools.attach.AttachNotSupportedException;
  35 import sun.tools.attach.HotSpotVirtualMachine;
  36 
  37 /*
  38  * This class is the main class for the JStack utility. It parses its arguments
  39  * and decides if the command should be executed by the SA JStack tool or by
  40  * obtained the thread dump from a target process using the VM attach mechanism
  41  */
  42 public class JStack {
  43     public static void main(String[] args) throws Exception {
  44         if (args.length == 0) {
  45             usage(); // no arguments
  46         }
  47 
  48         boolean useSA = false;
  49         boolean mixed = false;
  50         boolean locks = false;
  51 
  52         // Parse the options (arguments starting with "-" )
  53         int optionCount = 0;
  54         while (optionCount < args.length) {
  55             String arg = args[optionCount];
  56             if (!arg.startsWith("-")) {
  57                 break;
  58             }
  59             if (arg.equals("-F")) {
  60                 useSA = true;
  61             } else {
  62                 if (arg.equals("-m")) {
  63                     mixed = true;
  64                 } else {
  65                     if (arg.equals("-l")) {
  66                        locks = true;
  67                     } else {
  68                         usage();
  69                     }
  70                 }
  71             }
  72             optionCount++;
  73         }
  74 
  75         // mixed stack implies SA tool
  76         if (mixed) {
  77             useSA = true;
  78         }
  79 
  80         // Next we check the parameter count. If there are two parameters
  81         // we assume core file and executable so we use SA.
  82         int paramCount = args.length - optionCount;
  83         if (paramCount == 0 || paramCount > 2) {
  84             usage();
  85         }
  86         if (paramCount == 2) {
  87             useSA = true;
  88         } else {
  89             // If we can't parse it as a pid then it must be debug server
  90             if (!args[optionCount].matches("[0-9]+")) {
  91                 useSA = true;
  92             }
  93         }
  94 
  95         // now execute using the SA JStack tool or the built-in thread dumper
  96         if (useSA) {
  97             // parameters (<pid> or <exe> <core>
  98             String params[] = new String[paramCount];
  99             for (int i=optionCount; i<args.length; i++ ){
 100                 params[i-optionCount] = args[i];
 101             }
 102             runJStackTool(mixed, locks, params);
 103         } else {
 104             // pass -l to thread dump operation to get extra lock info
 105             String pid = args[optionCount];
 106             String params[];
 107             if (locks) {
 108                 params = new String[] { "-l" };
 109             } else {
 110                 params = new String[0];
 111             }
 112             runThreadDump(pid, params);
 113         }
 114     }
 115 
 116 
 117     // SA JStack tool
 118     private static void runJStackTool(boolean mixed, boolean locks, String args[]) throws Exception {
 119         Class<?> cl = loadSAClass();
 120         if (cl == null) {
 121             usage();            // SA not available
 122         }
 123 
 124         // JStack tool also takes -m and -l arguments
 125         if (mixed) {
 126             args = prepend("-m", args);
 127         }
 128         if (locks) {
 129             args = prepend("-l", args);
 130         }
 131 
 132         Class[] argTypes = { String[].class };
 133         Method m = cl.getDeclaredMethod("main", argTypes);
 134 
 135         Object[] invokeArgs = { args };
 136         m.invoke(null, invokeArgs);
 137     }
 138 
 139     // Returns sun.jvm.hotspot.tools.JStack if available, otherwise null.
 140     private static Class<?> loadSAClass() {
 141         //
 142         // Attempt to load JStack class - we specify the system class
 143         // loader so as to cater for development environments where
 144         // this class is on the boot class path but sa-jdi.jar is on
 145         // the system class path. Once the JDK is deployed then both
 146         // tools.jar and sa-jdi.jar are on the system class path.
 147         //
 148         try {
 149             return Class.forName("sun.jvm.hotspot.tools.JStack", true,
 150                                  ClassLoader.getSystemClassLoader());
 151         } catch (Exception x)  { }
 152         return null;
 153     }
 154 
 155     // Attach to pid and perform a thread dump
 156     private static void runThreadDump(String pid, String args[]) throws Exception {
 157         VirtualMachine vm = null;
 158         try {
 159             vm = VirtualMachine.attach(pid);
 160         } catch (Exception x) {
 161             String msg = x.getMessage();
 162             if (msg != null) {
 163                 System.err.println(pid + ": " + msg);
 164             } else {
 165                 x.printStackTrace();
 166             }
 167             if ((x instanceof AttachNotSupportedException) &&
 168                 (loadSAClass() != null)) {
 169                 System.err.println("The -F option can be used when the target " +
 170                     "process is not responding");
 171             }
 172             System.exit(1);
 173         }
 174 
 175         // Cast to HotSpotVirtualMachine as this is implementation specific
 176         // method.
 177         InputStream in = ((HotSpotVirtualMachine)vm).remoteDataDump((Object[])args);
 178 
 179         // read to EOF and just print output
 180         byte b[] = new byte[256];
 181         int n;
 182         do {
 183             n = in.read(b);
 184             if (n > 0) {
 185                 String s = new String(b, 0, n, "UTF-8");
 186                 System.out.print(s);
 187             }
 188         } while (n > 0);
 189         in.close();
 190         vm.detach();
 191     }
 192 
 193     // return a new string array with arg as the first element
 194     private static String[] prepend(String arg, String args[]) {
 195         String[] newargs = new String[args.length+1];
 196         newargs[0] = arg;
 197         System.arraycopy(args, 0, newargs, 1, args.length);
 198         return newargs;
 199     }
 200 
 201     // print usage message
 202     private static void usage() {
 203         System.out.println("Usage:");
 204         System.out.println("    jstack [-l] <pid>");
 205         System.out.println("        (to connect to running process)");
 206 
 207         if (loadSAClass() != null) {
 208             System.out.println("    jstack -F [-m] [-l] <pid>");
 209             System.out.println("        (to connect to a hung process)");
 210             System.out.println("    jstack [-m] [-l] <executable> <core>");
 211             System.out.println("        (to connect to a core file)");
 212             System.out.println("    jstack [-m] [-l] [server_id@]<remote server IP or hostname>");
 213             System.out.println("        (to connect to a remote debug server)");
 214         }
 215 
 216         System.out.println("");
 217         System.out.println("Options:");
 218 
 219         if (loadSAClass() != null) {
 220             System.out.println("    -F  to force a thread dump. Use when jstack <pid> does not respond" +
 221                 " (process is hung)");
 222             System.out.println("    -m  to print both java and native frames (mixed mode)");
 223         }
 224 
 225         System.out.println("    -l  long listing. Prints additional information about locks");
 226         System.out.println("    -h or -help to print this help message");
 227         System.exit(1);
 228     }
 229 }