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(1); // 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("-help") || arg.equals("-h")) {
  60                 usage(0);
  61             }
  62             else if (arg.equals("-F")) {
  63                 useSA = true;
  64             }
  65             else {
  66                 if (arg.equals("-m")) {
  67                     mixed = true;
  68                 } else {
  69                     if (arg.equals("-l")) {
  70                        locks = true;
  71                     } else {
  72                         usage(1);
  73                     }
  74                 }
  75             }
  76             optionCount++;
  77         }
  78 
  79         // mixed stack implies SA tool
  80         if (mixed) {
  81             useSA = true;
  82         }
  83 
  84         // Next we check the parameter count. If there are two parameters
  85         // we assume core file and executable so we use SA.
  86         int paramCount = args.length - optionCount;
  87         if (paramCount == 0 || paramCount > 2) {
  88             usage(1);
  89         }
  90         if (paramCount == 2) {
  91             useSA = true;
  92         } else {
  93             // If we can't parse it as a pid then it must be debug server
  94             if (!args[optionCount].matches("[0-9]+")) {
  95                 useSA = true;
  96             }
  97         }
  98 
  99         // now execute using the SA JStack tool or the built-in thread dumper
 100         if (useSA) {
 101             // parameters (<pid> or <exe> <core>
 102             String params[] = new String[paramCount];
 103             for (int i=optionCount; i<args.length; i++ ){
 104                 params[i-optionCount] = args[i];
 105             }
 106             runJStackTool(mixed, locks, params);
 107         } else {
 108             // pass -l to thread dump operation to get extra lock info
 109             String pid = args[optionCount];
 110             String params[];
 111             if (locks) {
 112                 params = new String[] { "-l" };
 113             } else {
 114                 params = new String[0];
 115             }
 116             runThreadDump(pid, params);
 117         }
 118     }
 119 
 120 
 121     // SA JStack tool
 122     private static void runJStackTool(boolean mixed, boolean locks, String args[]) throws Exception {
 123         Class<?> cl = loadSAClass();
 124         if (cl == null) {
 125             usage(1);            // SA not available
 126         }
 127 
 128         // JStack tool also takes -m and -l arguments
 129         if (mixed) {
 130             args = prepend("-m", args);
 131         }
 132         if (locks) {
 133             args = prepend("-l", args);
 134         }
 135 
 136         Class[] argTypes = { String[].class };
 137         Method m = cl.getDeclaredMethod("main", argTypes);
 138 
 139         Object[] invokeArgs = { args };
 140         m.invoke(null, invokeArgs);
 141     }
 142 
 143     // Returns sun.jvm.hotspot.tools.JStack if available, otherwise null.
 144     private static Class<?> loadSAClass() {
 145         //
 146         // Attempt to load JStack class - we specify the system class
 147         // loader so as to cater for development environments where
 148         // this class is on the boot class path but sa-jdi.jar is on
 149         // the system class path. Once the JDK is deployed then both
 150         // tools.jar and sa-jdi.jar are on the system class path.
 151         //
 152         try {
 153             return Class.forName("sun.jvm.hotspot.tools.JStack", true,
 154                                  ClassLoader.getSystemClassLoader());
 155         } catch (Exception x)  { }
 156         return null;
 157     }
 158 
 159     // Attach to pid and perform a thread dump
 160     private static void runThreadDump(String pid, String args[]) throws Exception {
 161         VirtualMachine vm = null;
 162         try {
 163             vm = VirtualMachine.attach(pid);
 164         } catch (Exception x) {
 165             String msg = x.getMessage();
 166             if (msg != null) {
 167                 System.err.println(pid + ": " + msg);
 168             } else {
 169                 x.printStackTrace();
 170             }
 171             if ((x instanceof AttachNotSupportedException) &&
 172                 (loadSAClass() != null)) {
 173                 System.err.println("The -F option can be used when the target " +
 174                     "process is not responding");
 175             }
 176             System.exit(1);
 177         }
 178 
 179         // Cast to HotSpotVirtualMachine as this is implementation specific
 180         // method.
 181         InputStream in = ((HotSpotVirtualMachine)vm).remoteDataDump((Object[])args);
 182 
 183         // read to EOF and just print output
 184         byte b[] = new byte[256];
 185         int n;
 186         do {
 187             n = in.read(b);
 188             if (n > 0) {
 189                 String s = new String(b, 0, n, "UTF-8");
 190                 System.out.print(s);
 191             }
 192         } while (n > 0);
 193         in.close();
 194         vm.detach();
 195     }
 196 
 197     // return a new string array with arg as the first element
 198     private static String[] prepend(String arg, String args[]) {
 199         String[] newargs = new String[args.length+1];
 200         newargs[0] = arg;
 201         System.arraycopy(args, 0, newargs, 1, args.length);
 202         return newargs;
 203     }
 204 
 205     // print usage message
 206     private static void usage(int exit) {
 207         System.err.println("Usage:");
 208         System.err.println("    jstack [-l] <pid>");
 209         System.err.println("        (to connect to running process)");
 210 
 211         if (loadSAClass() != null) {
 212             System.err.println("    jstack -F [-m] [-l] <pid>");
 213             System.err.println("        (to connect to a hung process)");
 214             System.err.println("    jstack [-m] [-l] <executable> <core>");
 215             System.err.println("        (to connect to a core file)");
 216             System.err.println("    jstack [-m] [-l] [server_id@]<remote server IP or hostname>");
 217             System.err.println("        (to connect to a remote debug server)");
 218         }
 219 
 220         System.err.println("");
 221         System.err.println("Options:");
 222 
 223         if (loadSAClass() != null) {
 224             System.err.println("    -F  to force a thread dump. Use when jstack <pid> does not respond" +
 225                 " (process is hung)");
 226             System.err.println("    -m  to print both java and native frames (mixed mode)");
 227         }
 228 
 229         System.err.println("    -l  long listing. Prints additional information about locks");
 230         System.err.println("    -h or -help to print this help message");
 231         System.exit(exit);
 232     }
 233 }