1 /*
   2  * Copyright (c) 2005, 2017, 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.io.InputStream;
  29 import java.util.Collection;
  30 
  31 import com.sun.tools.attach.VirtualMachine;
  32 import com.sun.tools.attach.VirtualMachineDescriptor;
  33 import sun.tools.attach.HotSpotVirtualMachine;
  34 import sun.tools.common.ProcessArgumentMatcher;
  35 
  36 /*
  37  * This class is the main class for the JStack utility. It parses its arguments
  38  * and decides if the command should be executed by the SA JStack tool or by
  39  * obtained the thread dump from a target process using the VM attach mechanism
  40  */
  41 public class JStack {
  42 
  43     public static void main(String[] args) throws Exception {
  44         if (args.length == 0) {
  45             usage(1); // no arguments
  46         }
  47 
  48         checkForUnsupportedOptions(args);
  49 
  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("-?")     ||
  60                 arg.equals("-h")     ||
  61                 arg.equals("--help") ||
  62                 // -help: legacy.
  63                 arg.equals("-help")) {
  64                 usage(0);
  65             }
  66             else {
  67                 if (arg.equals("-l")) {
  68                     locks = true;
  69                 } else {
  70                     usage(1);
  71                 }
  72             }
  73             optionCount++;
  74         }
  75 
  76         // Next we check the parameter count.
  77         int paramCount = args.length - optionCount;
  78         if (paramCount != 1) {
  79             usage(1);
  80         }
  81 
  82         // pass -l to thread dump operation to get extra lock info
  83         String pidArg = args[optionCount];
  84         String params[];
  85         if (locks) {
  86             params = new String[] { "-l" };
  87         } else {
  88             params = new String[0];
  89         }
  90         ProcessArgumentMatcher ap = new ProcessArgumentMatcher(pidArg);
  91         Collection<String> pids = ap.getVirtualMachinePids(JStack.class);
  92 
  93         if (pids.isEmpty()) {
  94             System.err.println("Could not find any processes matching : '" + pidArg + "'");
  95             System.exit(1);
  96         }
  97 
  98         for (String pid : pids) {
  99             if (pids.size() > 1) {
 100                 System.out.println("Pid:" + pid);
 101             }
 102             runThreadDump(pid, params);
 103         }
 104     }
 105 
 106     // Attach to pid and perform a thread dump
 107     private static void runThreadDump(String pid, String args[]) throws Exception {
 108         VirtualMachine vm = null;
 109         try {
 110             vm = VirtualMachine.attach(pid);
 111         } catch (Exception x) {
 112             String msg = x.getMessage();
 113             if (msg != null) {
 114                 System.err.println(pid + ": " + msg);
 115             } else {
 116                 x.printStackTrace();
 117             }
 118             System.exit(1);
 119         }
 120 
 121         // Cast to HotSpotVirtualMachine as this is implementation specific
 122         // method.
 123         InputStream in = ((HotSpotVirtualMachine)vm).remoteDataDump((Object[])args);
 124 
 125         // read to EOF and just print output
 126         byte b[] = new byte[256];
 127         int n;
 128         do {
 129             n = in.read(b);
 130             if (n > 0) {
 131                 String s = new String(b, 0, n, "UTF-8");
 132                 System.out.print(s);
 133             }
 134         } while (n > 0);
 135         in.close();
 136         vm.detach();
 137     }
 138 
 139     private static void checkForUnsupportedOptions(String[] args) {
 140         // Check arguments for -F, -m, and non-numeric value
 141         // and warn the user that SA is not supported anymore
 142 
 143         int paramCount = 0;
 144 
 145         for (String s : args) {
 146             if (s.equals("-F")) {
 147                 SAOptionError("-F option used");
 148             }
 149 
 150             if (s.equals("-m")) {
 151                 SAOptionError("-m option used");
 152             }
 153 
 154             if (! s.startsWith("-")) {
 155                 paramCount += 1;
 156             }
 157         }
 158 
 159         if (paramCount > 1) {
 160             SAOptionError("More than one non-option argument");
 161         }
 162     }
 163 
 164     private static void SAOptionError(String msg) {
 165         System.err.println("Error: " + msg);
 166         System.err.println("Cannot connect to core dump or remote debug server. Use jhsdb jstack instead");
 167         System.exit(1);
 168     }
 169 
 170     // print usage message
 171     private static void usage(int exit) {
 172         System.err.println("Usage:");
 173         System.err.println("    jstack [-l] <pid>");
 174         System.err.println("        (to connect to running process)");
 175         System.err.println("");
 176         System.err.println("Options:");
 177         System.err.println("    -l  long listing. Prints additional information about locks");
 178         System.err.println("    -? -h --help -help to print this help message");
 179         System.exit(exit);
 180     }
 181 }