1 /*
   2  * Copyright (c) 2011, 2014, 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.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #ifndef SHARE_VM_SERVICES_DIAGNOSTICFRAMEWORK_HPP
  26 #define SHARE_VM_SERVICES_DIAGNOSTICFRAMEWORK_HPP
  27 
  28 #include "classfile/vmSymbols.hpp"
  29 #include "memory/allocation.hpp"
  30 #include "runtime/arguments.hpp"
  31 #include "runtime/os.hpp"
  32 #include "runtime/vmThread.hpp"
  33 #include "utilities/ostream.hpp"
  34 
  35 
  36 enum DCmdSource {
  37   DCmd_Source_Internal  = 0x01U,  // invocation from the JVM
  38   DCmd_Source_AttachAPI = 0x02U,  // invocation via the attachAPI
  39   DCmd_Source_MBean     = 0x04U   // invocation via a MBean
  40 };
  41 
  42 // Warning: strings referenced by the JavaPermission struct are passed to
  43 // the native part of the JDK. Avoid use of dynamically allocated strings
  44 // that could be de-allocated before the JDK native code had time to
  45 // convert them into Java Strings.
  46 struct JavaPermission {
  47   const char* _class;
  48   const char* _name;
  49   const char* _action;
  50 };
  51 
  52 // CmdLine is the class used to handle a command line containing a single
  53 // diagnostic command and its arguments. It provides methods to access the
  54 // command name and the beginning of the arguments. The class is also
  55 // able to identify commented command lines and the "stop" keyword
  56 class CmdLine : public StackObj {
  57 private:
  58   const char* _cmd;
  59   size_t      _cmd_len;
  60   const char* _args;
  61   size_t      _args_len;
  62 public:
  63   CmdLine(const char* line, size_t len, bool no_command_name);
  64   const char* args_addr() const { return _args; }
  65   size_t args_len() const { return _args_len; }
  66   const char* cmd_addr() const { return _cmd; }
  67   size_t cmd_len() const { return _cmd_len; }
  68   bool is_empty() { return _cmd_len == 0; }
  69   bool is_executable() { return is_empty() || _cmd[0] != '#'; }
  70   bool is_stop() { return !is_empty() && strncmp("stop", _cmd, _cmd_len) == 0; }
  71 };
  72 
  73 // Iterator class taking a character string in input and returning a CmdLine
  74 // instance for each command line. The argument delimiter has to be specified.
  75 class DCmdIter : public StackObj {
  76   friend class DCmd;
  77 private:
  78   const char* _str;
  79   char        _delim;
  80   size_t      _len;
  81   size_t      _cursor;
  82 public:
  83 
  84   DCmdIter(const char* str, char delim) {
  85     _str = str;
  86     _delim = delim;
  87     _len = strlen(str);
  88     _cursor = 0;
  89   }
  90   bool has_next() { return _cursor < _len; }
  91   CmdLine next() {
  92     assert(_cursor <= _len, "Cannot iterate more");
  93     size_t n = _cursor;
  94     while (n < _len && _str[n] != _delim) n++;
  95     CmdLine line(&(_str[_cursor]), n - _cursor, false);
  96     _cursor = n + 1;
  97     // The default copy constructor of CmdLine is used to return a CmdLine
  98     // instance to the caller.
  99     return line;
 100   }
 101 };
 102 
 103 // Iterator class to iterate over diagnostic command arguments
 104 class DCmdArgIter : public ResourceObj {
 105   const char* _buffer;
 106   size_t      _len;
 107   size_t      _cursor;
 108   const char* _key_addr;
 109   size_t      _key_len;
 110   const char* _value_addr;
 111   size_t      _value_len;
 112   char        _delim;
 113 public:
 114   DCmdArgIter(const char* buf, size_t len, char delim) {
 115     _buffer = buf;
 116     _len = len;
 117     _delim = delim;
 118     _cursor = 0;
 119   }
 120   bool next(TRAPS);
 121   const char* key_addr() { return _key_addr; }
 122   size_t key_length() { return _key_len; }
 123   const char* value_addr() { return _value_addr; }
 124   size_t value_length() { return _value_len; }
 125 };
 126 
 127 // A DCmdInfo instance provides a description of a diagnostic command. It is
 128 // used to export the description to the JMX interface of the framework.
 129 class DCmdInfo : public ResourceObj {
 130 protected:
 131   const char* _name;           /* Name of the diagnostic command */
 132   const char* _description;    /* Short description */
 133   const char* _impact;         /* Impact on the JVM */
 134   JavaPermission _permission;  /* Java Permission required to execute this command if any */
 135   int         _num_arguments;  /* Number of supported options or arguments */
 136   bool        _is_enabled;     /* True if the diagnostic command can be invoked, false otherwise */
 137 public:
 138   DCmdInfo(const char* name,
 139           const char* description,
 140           const char* impact,
 141           JavaPermission permission,
 142           int num_arguments,
 143           bool enabled) {
 144     this->_name = name;
 145     this->_description = description;
 146     this->_impact = impact;
 147     this->_permission = permission;
 148     this->_num_arguments = num_arguments;
 149     this->_is_enabled = enabled;
 150   }
 151   const char* name() const { return _name; }
 152   const char* description() const { return _description; }
 153   const char* impact() const { return _impact; }
 154   JavaPermission permission() const { return _permission; }
 155   int num_arguments() const { return _num_arguments; }
 156   bool is_enabled() const { return _is_enabled; }
 157 
 158   static bool by_name(void* name, DCmdInfo* info);
 159 };
 160 
 161 // A DCmdArgumentInfo instance provides a description of a diagnostic command
 162 // argument. It is used to export the description to the JMX interface of the
 163 // framework.
 164 class DCmdArgumentInfo : public ResourceObj {
 165 protected:
 166   const char* _name;            /* Option/Argument name*/
 167   const char* _description;     /* Short description */
 168   const char* _type;            /* Type: STRING, BOOLEAN, etc. */
 169   const char* _default_string;  /* Default value in a parsable string */
 170   bool        _mandatory;       /* True if the option/argument is mandatory */
 171   bool        _option;          /* True if it is an option, false if it is an argument */
 172                                 /* (see diagnosticFramework.hpp for option/argument definitions) */
 173   bool        _multiple;        /* True is the option can be specified several time */
 174   int         _position;        /* Expected position for this argument (this field is */
 175                                 /* meaningless for options) */
 176 public:
 177   DCmdArgumentInfo(const char* name, const char* description, const char* type,
 178                    const char* default_string, bool mandatory, bool option,
 179                    bool multiple) {
 180     this->_name = name;
 181     this->_description = description;
 182     this->_type = type;
 183     this->_default_string = default_string;
 184     this->_option = option;
 185     this->_mandatory = mandatory;
 186     this->_option = option;
 187     this->_multiple = multiple;
 188     this->_position = -1;
 189   }
 190   DCmdArgumentInfo(const char* name, const char* description, const char* type,
 191                    const char* default_string, bool mandatory, bool option,
 192                    bool multiple, int position) {
 193     this->_name = name;
 194     this->_description = description;
 195     this->_type = type;
 196     this->_default_string = default_string;
 197     this->_option = option;
 198     this->_mandatory = mandatory;
 199     this->_option = option;
 200     this->_multiple = multiple;
 201     this->_position = position;
 202   }
 203   const char* name() const { return _name; }
 204   const char* description() const { return _description; }
 205   const char* type() const { return _type; }
 206   const char* default_string() const { return _default_string; }
 207   bool is_mandatory() const { return _mandatory; }
 208   bool is_option() const { return _option; }
 209   bool is_multiple() const { return _multiple; }
 210   int position() const { return _position; }
 211 };
 212 
 213 // The DCmdParser class can be used to create an argument parser for a
 214 // diagnostic command. It is not mandatory to use it to parse arguments.
 215 // The DCmdParser parses a CmdLine instance according to the parameters that
 216 // have been declared by its associated diagnostic command. A parameter can
 217 // either be an option or an argument. Options are identified by the option name
 218 // while arguments are identified by their position in the command line. The
 219 // position of an argument is defined relative to all arguments passed on the
 220 // command line, options are not considered when defining an argument position.
 221 // The generic syntax of a diagnostic command is:
 222 //
 223 //    <command name> [<option>=<value>] [<argument_value>]
 224 //
 225 // Example:
 226 //
 227 //    command_name option1=value1 option2=value argumentA argumentB argumentC
 228 //
 229 // In this command line, the diagnostic command receives five parameters, two
 230 // options named option1 and option2, and three arguments. argumentA's position
 231 // is 0, argumentB's position is 1 and argumentC's position is 2.
 232 class DCmdParser {
 233 private:
 234   GenDCmdArgument* _options;
 235   GenDCmdArgument* _arguments_list;
 236   char             _delim;
 237 public:
 238   DCmdParser() {
 239     _options = NULL;
 240     _arguments_list = NULL;
 241     _delim = ' ';
 242   }
 243   void add_dcmd_option(GenDCmdArgument* arg);
 244   void add_dcmd_argument(GenDCmdArgument* arg);
 245   GenDCmdArgument* lookup_dcmd_option(const char* name, size_t len);
 246   GenDCmdArgument* arguments_list() { return _arguments_list; };
 247   void check(TRAPS);
 248   void parse(CmdLine* line, char delim, TRAPS);
 249   void print_help(outputStream* out, const char* cmd_name);
 250   void reset(TRAPS);
 251   void cleanup();
 252   int num_arguments();
 253   GrowableArray<const char*>* argument_name_array();
 254   GrowableArray<DCmdArgumentInfo*>* argument_info_array();
 255 };
 256 
 257 // The DCmd class is the parent class of all diagnostic commands
 258 // Diagnostic command instances should not be instantiated directly but
 259 // created using the associated factory. The factory can be retrieved with
 260 // the DCmdFactory::getFactory() method.
 261 // A diagnostic command instance can either be allocated in the resource Area
 262 // or in the C-heap. Allocation in the resource area is recommended when the
 263 // current thread is the only one which will access the diagnostic command
 264 // instance. Allocation in the C-heap is required when the diagnostic command
 265 // is accessed by several threads (for instance to perform asynchronous
 266 // execution).
 267 // To ensure a proper cleanup, it's highly recommended to use a DCmdMark for
 268 // each diagnostic command instance. In case of a C-heap allocated diagnostic
 269 // command instance, the DCmdMark must be created in the context of the last
 270 // thread that will access the instance.
 271 class DCmd : public ResourceObj {
 272 protected:
 273   outputStream* _output;
 274   bool          _is_heap_allocated;
 275 public:
 276   DCmd(outputStream* output, bool heap_allocated) {
 277     _output = output;
 278     _is_heap_allocated = heap_allocated;
 279   }
 280 
 281   static const char* name() { return "No Name";}
 282   static const char* description() { return "No Help";}
 283   static const char* disabled_message() { return "Diagnostic command currently disabled"; }
 284   // The impact() method returns a description of the intrusiveness of the diagnostic
 285   // command on the Java Virtual Machine behavior. The rational for this method is that some
 286   // diagnostic commands can seriously disrupt the behavior of the Java Virtual Machine
 287   // (for instance a Thread Dump for an application with several tens of thousands of threads,
 288   // or a Head Dump with a 40GB+ heap size) and other diagnostic commands have no serious
 289   // impact on the JVM (for instance, getting the command line arguments or the JVM version).
 290   // The recommended format for the description is <impact level>: [longer description],
 291   // where the impact level is selected among this list: {Low, Medium, High}. The optional
 292   // longer description can provide more specific details like the fact that Thread Dump
 293   // impact depends on the heap size.
 294   static const char* impact() { return "Low: No impact"; }
 295   // The permission() method returns the description of Java Permission. This
 296   // permission is required when the diagnostic command is invoked via the
 297   // DiagnosticCommandMBean. The rationale for this permission check is that
 298   // the DiagnosticCommandMBean can be used to perform remote invocations of
 299   // diagnostic commands through the PlatformMBeanServer. The (optional) Java
 300   // Permission associated with each diagnostic command should ease the work
 301   // of system administrators to write policy files granting permissions to
 302   // execute diagnostic commands to remote users. Any diagnostic command with
 303   // a potential impact on security should overwrite this method.
 304   static const JavaPermission permission() {
 305     JavaPermission p = {NULL, NULL, NULL};
 306     return p;
 307   }
 308   static int num_arguments() { return 0; }
 309   outputStream* output() { return _output; }
 310   bool is_heap_allocated()  { return _is_heap_allocated; }
 311   virtual void print_help(const char* name) {
 312     output()->print_cr("Syntax: %s", name);
 313   }
 314   virtual void parse(CmdLine* line, char delim, TRAPS) {
 315     DCmdArgIter iter(line->args_addr(), line->args_len(), delim);
 316     bool has_arg = iter.next(CHECK);
 317     if (has_arg) {
 318       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 319                 "The argument list of this diagnostic command should be empty.");
 320     }
 321   }
 322   virtual void execute(DCmdSource source, TRAPS) { }
 323   virtual void reset(TRAPS) { }
 324   virtual void cleanup() { }
 325 
 326   // support for the JMX interface
 327   virtual GrowableArray<const char*>* argument_name_array() {
 328     GrowableArray<const char*>* array = new GrowableArray<const char*>(0);
 329     return array;
 330   }
 331   virtual GrowableArray<DCmdArgumentInfo*>* argument_info_array() {
 332     GrowableArray<DCmdArgumentInfo*>* array = new GrowableArray<DCmdArgumentInfo*>(0);
 333     return array;
 334   }
 335 
 336   // main method to invoke the framework
 337   static void parse_and_execute(DCmdSource source, outputStream* out, const char* cmdline,
 338                                 char delim, TRAPS);
 339 };
 340 
 341 class DCmdWithParser : public DCmd {
 342 protected:
 343   DCmdParser _dcmdparser;
 344 public:
 345   DCmdWithParser (outputStream *output, bool heap=false) : DCmd(output, heap) { }
 346   static const char* name() { return "No Name";}
 347   static const char* description() { return "No Help";}
 348   static const char* disabled_message() { return "Diagnostic command currently disabled"; }
 349   static const char* impact() { return "Low: No impact"; }
 350   static const JavaPermission permission() {JavaPermission p = {NULL, NULL, NULL}; return p; }
 351   static int num_arguments() { return 0; }
 352   virtual void parse(CmdLine *line, char delim, TRAPS);
 353   virtual void execute(DCmdSource source, TRAPS) { }
 354   virtual void reset(TRAPS);
 355   virtual void cleanup();
 356   virtual void print_help(const char* name);
 357   virtual GrowableArray<const char*>* argument_name_array();
 358   virtual GrowableArray<DCmdArgumentInfo*>* argument_info_array();
 359 };
 360 
 361 class DCmdMark : public StackObj {
 362   DCmd* _ref;
 363 public:
 364   DCmdMark(DCmd* cmd) { _ref = cmd; }
 365   ~DCmdMark() {
 366     if (_ref != NULL) {
 367       _ref->cleanup();
 368       if (_ref->is_heap_allocated()) {
 369         delete _ref;
 370       }
 371     }
 372   }
 373 };
 374 
 375 // Diagnostic commands are not directly instantiated but created with a factory.
 376 // Each diagnostic command class has its own factory. The DCmdFactory class also
 377 // manages the status of the diagnostic command (hidden, enabled). A DCmdFactory
 378 // has to be registered to make the diagnostic command available (see
 379 // management.cpp)
 380 class DCmdFactory: public CHeapObj<mtInternal> {
 381 private:
 382   static Mutex*       _dcmdFactory_lock;
 383   static bool         _send_jmx_notification;
 384   static bool         _has_pending_jmx_notification;
 385   // Pointer to the next factory in the singly-linked list of registered
 386   // diagnostic commands
 387   DCmdFactory*        _next;
 388   // When disabled, a diagnostic command cannot be executed. Any attempt to
 389   // execute it will result in the printing of the disabled message without
 390   // instantiating the command.
 391   bool                _enabled;
 392   // When hidden, a diagnostic command doesn't appear in the list of commands
 393   // provided by the 'help' command.
 394   bool                _hidden;
 395   uint32_t            _export_flags;
 396   int                 _num_arguments;
 397   static DCmdFactory* _DCmdFactoryList;
 398 public:
 399   DCmdFactory(int num_arguments, uint32_t flags, bool enabled, bool hidden) {
 400     _next = NULL;
 401     _enabled = enabled;
 402     _hidden = hidden;
 403     _export_flags = flags;
 404     _num_arguments = num_arguments;
 405   }
 406   bool is_enabled() const { return _enabled; }
 407   void set_enabled(bool b) { _enabled = b; }
 408   bool is_hidden() const { return _hidden; }
 409   void set_hidden(bool b) { _hidden = b; }
 410   uint32_t export_flags() { return _export_flags; }
 411   void set_export_flags(uint32_t f) { _export_flags = f; }
 412   int num_arguments() { return _num_arguments; }
 413   DCmdFactory* next() { return _next; }
 414   virtual DCmd* create_Cheap_instance(outputStream* output) = 0;
 415   virtual DCmd* create_resource_instance(outputStream* output) = 0;
 416   virtual const char* name() const = 0;
 417   virtual const char* description() const = 0;
 418   virtual const char* impact() const = 0;
 419   virtual const JavaPermission permission() const = 0;
 420   virtual const char* disabled_message() const = 0;
 421   // Register a DCmdFactory to make a diagnostic command available.
 422   // Once registered, a diagnostic command must not be unregistered.
 423   // To prevent a diagnostic command from being executed, just set the
 424   // enabled flag to false.
 425   static int register_DCmdFactory(DCmdFactory* factory);
 426   static DCmdFactory* factory(DCmdSource source, const char* cmd, size_t len);
 427   // Returns a C-heap allocated diagnostic command for the given command line
 428   static DCmd* create_global_DCmd(DCmdSource source, CmdLine &line, outputStream* out, TRAPS);
 429   // Returns a resourceArea allocated diagnostic command for the given command line
 430   static DCmd* create_local_DCmd(DCmdSource source, CmdLine &line, outputStream* out, TRAPS);
 431   static GrowableArray<const char*>* DCmd_list(DCmdSource source);
 432   static GrowableArray<DCmdInfo*>* DCmdInfo_list(DCmdSource source);
 433 
 434   static void set_jmx_notification_enabled(bool enabled) {
 435     _send_jmx_notification = enabled;
 436   }
 437   static void push_jmx_notification_request();
 438   static bool has_pending_jmx_notification() { return _has_pending_jmx_notification; }
 439   static void send_notification(TRAPS);
 440 private:
 441   static void send_notification_internal(TRAPS);
 442 
 443   friend class HelpDCmd;
 444 };
 445 
 446 // Template to easily create DCmdFactory instances. See management.cpp
 447 // where this template is used to create and register factories.
 448 template <class DCmdClass> class DCmdFactoryImpl : public DCmdFactory {
 449 public:
 450   DCmdFactoryImpl(uint32_t flags, bool enabled, bool hidden) :
 451     DCmdFactory(DCmdClass::num_arguments(), flags, enabled, hidden) { }
 452   // Returns a C-heap allocated instance
 453   virtual DCmd* create_Cheap_instance(outputStream* output) {
 454     return new (ResourceObj::C_HEAP, mtInternal) DCmdClass(output, true);
 455   }
 456   // Returns a resourceArea allocated instance
 457   virtual DCmd* create_resource_instance(outputStream* output) {
 458     return new DCmdClass(output, false);
 459   }
 460   virtual const char* name() const {
 461     return DCmdClass::name();
 462   }
 463   virtual const char* description() const {
 464     return DCmdClass::description();
 465   }
 466   virtual const char* impact() const {
 467     return DCmdClass::impact();
 468   }
 469   virtual const JavaPermission permission() const {
 470     return DCmdClass::permission();
 471   }
 472   virtual const char* disabled_message() const {
 473      return DCmdClass::disabled_message();
 474   }
 475 };
 476 
 477 // This class provides a convenient way to register Dcmds, without a need to change
 478 // management.cpp every time. Body of these two methods resides in
 479 // diagnosticCommand.cpp
 480 
 481 class DCmdRegistrant : public AllStatic {
 482 
 483 private:
 484     static void register_dcmds();
 485     static void register_dcmds_ext();
 486 
 487     friend class Management;
 488 };
 489 
 490 #endif // SHARE_VM_SERVICES_DIAGNOSTICFRAMEWORK_HPP