1 /*
   2  * Copyright (c) 2011, 2018, 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 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "memory/oopFactory.hpp"
  28 #include "memory/resourceArea.hpp"
  29 #include "oops/oop.inline.hpp"
  30 #include "runtime/handles.inline.hpp"
  31 #include "runtime/javaCalls.hpp"
  32 #include "runtime/mutexLocker.hpp"
  33 #include "services/diagnosticArgument.hpp"
  34 #include "services/diagnosticFramework.hpp"
  35 #include "services/management.hpp"
  36 
  37 CmdLine::CmdLine(const char* line, size_t len, bool no_command_name) {
  38   assert(line != NULL, "Command line string should not be NULL");
  39   const char* line_end;
  40   const char* cmd_end;
  41 
  42   _cmd = line;
  43   line_end = &line[len];
  44 
  45   // Skip whitespace in the beginning of the line.
  46   while (_cmd < line_end && isspace((int) _cmd[0])) {
  47     _cmd++;
  48   }
  49   cmd_end = _cmd;
  50 
  51   if (no_command_name) {
  52     _cmd = NULL;
  53     _cmd_len = 0;
  54   } else {
  55     // Look for end of the command name
  56     while (cmd_end < line_end && !isspace((int) cmd_end[0])) {
  57       cmd_end++;
  58     }
  59     _cmd_len = cmd_end - _cmd;
  60   }
  61   _args = cmd_end;
  62   _args_len = line_end - _args;
  63 }
  64 
  65 bool DCmdArgIter::next(TRAPS) {
  66   if (_len == 0) return false;
  67   // skipping delimiters
  68   while (_cursor < _len - 1 && _buffer[_cursor] == _delim) {
  69     _cursor++;
  70   }
  71   // handling end of command line
  72   if (_cursor == _len - 1 && _buffer[_cursor] == _delim) {
  73     _key_addr = &_buffer[_cursor];
  74     _key_len = 0;
  75     _value_addr = &_buffer[_cursor];
  76     _value_len = 0;
  77     return false;
  78   }
  79   // extracting first item, argument or option name
  80   _key_addr = &_buffer[_cursor];
  81   bool arg_had_quotes = false;
  82   while (_cursor <= _len - 1 && _buffer[_cursor] != '=' && _buffer[_cursor] != _delim) {
  83     // argument can be surrounded by single or double quotes
  84     if (_buffer[_cursor] == '\"' || _buffer[_cursor] == '\'') {
  85       _key_addr++;
  86       char quote = _buffer[_cursor];
  87       arg_had_quotes = true;
  88       while (_cursor < _len - 1) {
  89         _cursor++;
  90         if (_buffer[_cursor] == quote && _buffer[_cursor - 1] != '\\') {
  91           break;
  92         }
  93       }
  94       if (_buffer[_cursor] != quote) {
  95         THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
  96                 "Format error in diagnostic command arguments", false);
  97       }
  98       break;
  99     }
 100     _cursor++;
 101   }
 102   _key_len = &_buffer[_cursor] - _key_addr;
 103   if (arg_had_quotes) {
 104     // if the argument was quoted, we need to step past the last quote here
 105     _cursor++;
 106   }
 107   // check if the argument has the <key>=<value> format
 108   if (_cursor <= _len -1 && _buffer[_cursor] == '=') {
 109     _cursor++;
 110     _value_addr = &_buffer[_cursor];
 111     bool value_had_quotes = false;
 112     // extract the value
 113     while (_cursor <= _len - 1 && _buffer[_cursor] != _delim) {
 114       // value can be surrounded by simple or double quotes
 115       if (_buffer[_cursor] == '\"' || _buffer[_cursor] == '\'') {
 116         _value_addr++;
 117         char quote = _buffer[_cursor];
 118         value_had_quotes = true;
 119         while (_cursor < _len - 1) {
 120           _cursor++;
 121           if (_buffer[_cursor] == quote && _buffer[_cursor - 1] != '\\') {
 122             break;
 123           }
 124         }
 125         if (_buffer[_cursor] != quote) {
 126           THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
 127                   "Format error in diagnostic command arguments", false);
 128         }
 129         break;
 130       }
 131       _cursor++;
 132     }
 133     _value_len = &_buffer[_cursor] - _value_addr;
 134     if (value_had_quotes) {
 135       // if the value was quoted, we need to step past the last quote here
 136       _cursor++;
 137     }
 138   } else {
 139     _value_addr = NULL;
 140     _value_len = 0;
 141   }
 142   return _key_len != 0;
 143 }
 144 
 145 bool DCmdInfo::by_name(void* cmd_name, DCmdInfo* info) {
 146   if (info == NULL) return false;
 147   return strcmp((const char*)cmd_name, info->name()) == 0;
 148 }
 149 
 150 void DCmdParser::add_dcmd_option(GenDCmdArgument* arg) {
 151   assert(arg != NULL, "Sanity");
 152   if (_options == NULL) {
 153     _options = arg;
 154   } else {
 155     GenDCmdArgument* o = _options;
 156     while (o->next() != NULL) {
 157       o = o->next();
 158     }
 159     o->set_next(arg);
 160   }
 161   arg->set_next(NULL);
 162   Thread* THREAD = Thread::current();
 163   arg->init_value(THREAD);
 164   if (HAS_PENDING_EXCEPTION) {
 165     fatal("Initialization must be successful");
 166   }
 167 }
 168 
 169 void DCmdParser::add_dcmd_argument(GenDCmdArgument* arg) {
 170   assert(arg != NULL, "Sanity");
 171   if (_arguments_list == NULL) {
 172     _arguments_list = arg;
 173   } else {
 174     GenDCmdArgument* a = _arguments_list;
 175     while (a->next() != NULL) {
 176       a = a->next();
 177     }
 178     a->set_next(arg);
 179   }
 180   arg->set_next(NULL);
 181   Thread* THREAD = Thread::current();
 182   arg->init_value(THREAD);
 183   if (HAS_PENDING_EXCEPTION) {
 184     fatal("Initialization must be successful");
 185   }
 186 }
 187 
 188 void DCmdParser::parse(CmdLine* line, char delim, TRAPS) {
 189   GenDCmdArgument* next_argument = _arguments_list;
 190   DCmdArgIter iter(line->args_addr(), line->args_len(), delim);
 191   bool cont = iter.next(CHECK);
 192   while (cont) {
 193     GenDCmdArgument* arg = lookup_dcmd_option(iter.key_addr(),
 194             iter.key_length());
 195     if (arg != NULL) {
 196       arg->read_value(iter.value_addr(), iter.value_length(), CHECK);
 197     } else {
 198       if (next_argument != NULL) {
 199         arg = next_argument;
 200         arg->read_value(iter.key_addr(), iter.key_length(), CHECK);
 201         next_argument = next_argument->next();
 202       } else {
 203         const size_t buflen    = 120;
 204         const size_t argbuflen = 30;
 205         char buf[buflen];
 206         char argbuf[argbuflen];
 207         size_t len = MIN2<size_t>(iter.key_length(), argbuflen - 1);
 208 
 209         strncpy(argbuf, iter.key_addr(), len);
 210         argbuf[len] = '\0';
 211         jio_snprintf(buf, buflen - 1, "Unknown argument '%s' in diagnostic command.", argbuf);
 212 
 213         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), buf);
 214       }
 215     }
 216     cont = iter.next(CHECK);
 217   }
 218   check(CHECK);
 219 }
 220 
 221 GenDCmdArgument* DCmdParser::lookup_dcmd_option(const char* name, size_t len) {
 222   GenDCmdArgument* arg = _options;
 223   while (arg != NULL) {
 224     if (strlen(arg->name()) == len &&
 225       strncmp(name, arg->name(), len) == 0) {
 226       return arg;
 227     }
 228     arg = arg->next();
 229   }
 230   return NULL;
 231 }
 232 
 233 void DCmdParser::check(TRAPS) {
 234   const size_t buflen = 256;
 235   char buf[buflen];
 236   GenDCmdArgument* arg = _arguments_list;
 237   while (arg != NULL) {
 238     if (arg->is_mandatory() && !arg->has_value()) {
 239       jio_snprintf(buf, buflen - 1, "The argument '%s' is mandatory.", arg->name());
 240       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), buf);
 241     }
 242     arg = arg->next();
 243   }
 244   arg = _options;
 245   while (arg != NULL) {
 246     if (arg->is_mandatory() && !arg->has_value()) {
 247       jio_snprintf(buf, buflen - 1, "The option '%s' is mandatory.", arg->name());
 248       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), buf);
 249     }
 250     arg = arg->next();
 251   }
 252 }
 253 
 254 void DCmdParser::print_help(outputStream* out, const char* cmd_name) const {
 255   out->print("Syntax : %s %s", cmd_name, _options == NULL ? "" : "[options]");
 256   GenDCmdArgument* arg = _arguments_list;
 257   while (arg != NULL) {
 258     if (arg->is_mandatory()) {
 259       out->print(" <%s>", arg->name());
 260     } else {
 261       out->print(" [<%s>]", arg->name());
 262     }
 263     arg = arg->next();
 264   }
 265   out->cr();
 266   if (_arguments_list != NULL) {
 267     out->print_cr("\nArguments:");
 268     arg = _arguments_list;
 269     while (arg != NULL) {
 270       out->print("\t%s : %s %s (%s, ", arg->name(),
 271                  arg->is_mandatory() ? "" : "[optional]",
 272                  arg->description(), arg->type());
 273       if (arg->has_default()) {
 274         out->print("%s", arg->default_string());
 275       } else {
 276         out->print("no default value");
 277       }
 278       out->print_cr(")");
 279       arg = arg->next();
 280     }
 281   }
 282   if (_options != NULL) {
 283     out->print_cr("\nOptions: (options must be specified using the <key> or <key>=<value> syntax)");
 284     arg = _options;
 285     while (arg != NULL) {
 286       out->print("\t%s : %s %s (%s, ", arg->name(),
 287                  arg->is_mandatory() ? "" : "[optional]",
 288                  arg->description(), arg->type());
 289       if (arg->has_default()) {
 290         out->print("%s", arg->default_string());
 291       } else {
 292         out->print("no default value");
 293       }
 294       out->print_cr(")");
 295       arg = arg->next();
 296     }
 297   }
 298 }
 299 
 300 void DCmdParser::reset(TRAPS) {
 301   GenDCmdArgument* arg = _arguments_list;
 302   while (arg != NULL) {
 303     arg->reset(CHECK);
 304     arg = arg->next();
 305   }
 306   arg = _options;
 307   while (arg != NULL) {
 308     arg->reset(CHECK);
 309     arg = arg->next();
 310   }
 311 }
 312 
 313 void DCmdParser::cleanup() {
 314   GenDCmdArgument* arg = _arguments_list;
 315   while (arg != NULL) {
 316     arg->cleanup();
 317     arg = arg->next();
 318   }
 319   arg = _options;
 320   while (arg != NULL) {
 321     arg->cleanup();
 322     arg = arg->next();
 323   }
 324 }
 325 
 326 int DCmdParser::num_arguments() const {
 327   GenDCmdArgument* arg = _arguments_list;
 328   int count = 0;
 329   while (arg != NULL) {
 330     count++;
 331     arg = arg->next();
 332   }
 333   arg = _options;
 334   while (arg != NULL) {
 335     count++;
 336     arg = arg->next();
 337   }
 338   return count;
 339 }
 340 
 341 GrowableArray<const char *>* DCmdParser::argument_name_array() const {
 342   int count = num_arguments();
 343   GrowableArray<const char *>* array = new GrowableArray<const char *>(count);
 344   GenDCmdArgument* arg = _arguments_list;
 345   while (arg != NULL) {
 346     array->append(arg->name());
 347     arg = arg->next();
 348   }
 349   arg = _options;
 350   while (arg != NULL) {
 351     array->append(arg->name());
 352     arg = arg->next();
 353   }
 354   return array;
 355 }
 356 
 357 GrowableArray<DCmdArgumentInfo*>* DCmdParser::argument_info_array() const {
 358   int count = num_arguments();
 359   GrowableArray<DCmdArgumentInfo*>* array = new GrowableArray<DCmdArgumentInfo *>(count);
 360   int idx = 0;
 361   GenDCmdArgument* arg = _arguments_list;
 362   while (arg != NULL) {
 363     array->append(new DCmdArgumentInfo(arg->name(), arg->description(),
 364                   arg->type(), arg->default_string(), arg->is_mandatory(),
 365                   false, arg->allow_multiple(), idx));
 366     idx++;
 367     arg = arg->next();
 368   }
 369   arg = _options;
 370   while (arg != NULL) {
 371     array->append(new DCmdArgumentInfo(arg->name(), arg->description(),
 372                   arg->type(), arg->default_string(), arg->is_mandatory(),
 373                   true, arg->allow_multiple()));
 374     arg = arg->next();
 375   }
 376   return array;
 377 }
 378 
 379 DCmdFactory* DCmdFactory::_DCmdFactoryList = NULL;
 380 bool DCmdFactory::_has_pending_jmx_notification = false;
 381 
 382 void DCmd::parse_and_execute(DCmdSource source, outputStream* out,
 383                              const char* cmdline, char delim, TRAPS) {
 384 
 385   if (cmdline == NULL) return; // Nothing to do!
 386   DCmdIter iter(cmdline, '\n');
 387 
 388   int count = 0;
 389   while (iter.has_next()) {
 390     if(source == DCmd_Source_MBean && count > 0) {
 391       // When diagnostic commands are invoked via JMX, each command line
 392       // must contains one and only one command because of the Permission
 393       // checks performed by the DiagnosticCommandMBean
 394       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 395               "Invalid syntax");
 396     }
 397     CmdLine line = iter.next();
 398     if (line.is_stop()) {
 399       break;
 400     }
 401     if (line.is_executable()) {
 402       ResourceMark rm;
 403       DCmd* command = DCmdFactory::create_local_DCmd(source, line, out, CHECK);
 404       assert(command != NULL, "command error must be handled before this line");
 405       DCmdMark mark(command);
 406       command->parse(&line, delim, CHECK);
 407       command->execute(source, CHECK);
 408     }
 409     count++;
 410   }
 411 }
 412 
 413 void DCmdWithParser::parse(CmdLine* line, char delim, TRAPS) {
 414   _dcmdparser.parse(line, delim, CHECK);
 415 }
 416 
 417 void DCmdWithParser::print_help(const char* name) const {
 418   _dcmdparser.print_help(output(), name);
 419 }
 420 
 421 void DCmdWithParser::reset(TRAPS) {
 422   _dcmdparser.reset(CHECK);
 423 }
 424 
 425 void DCmdWithParser::cleanup() {
 426   _dcmdparser.cleanup();
 427 }
 428 
 429 GrowableArray<const char*>* DCmdWithParser::argument_name_array() const {
 430   return _dcmdparser.argument_name_array();
 431 }
 432 
 433 GrowableArray<DCmdArgumentInfo*>* DCmdWithParser::argument_info_array() const {
 434   return _dcmdparser.argument_info_array();
 435 }
 436 
 437 void DCmdFactory::push_jmx_notification_request() {
 438   MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
 439   _has_pending_jmx_notification = true;
 440   Service_lock->notify_all();
 441 }
 442 
 443 void DCmdFactory::send_notification(TRAPS) {
 444   DCmdFactory::send_notification_internal(THREAD);
 445   // Clearing pending exception to avoid premature termination of
 446   // the service thread
 447   if (HAS_PENDING_EXCEPTION) {
 448     CLEAR_PENDING_EXCEPTION;
 449   }
 450 }
 451 void DCmdFactory::send_notification_internal(TRAPS) {
 452   ResourceMark rm(THREAD);
 453   HandleMark hm(THREAD);
 454   bool notif = false;
 455   {
 456     MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
 457     notif = _has_pending_jmx_notification;
 458     _has_pending_jmx_notification = false;
 459   }
 460   if (notif) {
 461 
 462     Klass* k = Management::com_sun_management_internal_DiagnosticCommandImpl_klass(CHECK);
 463     InstanceKlass* dcmd_mbean_klass = InstanceKlass::cast(k);
 464 
 465     JavaValue result(T_OBJECT);
 466     JavaCalls::call_static(&result,
 467             dcmd_mbean_klass,
 468             vmSymbols::getDiagnosticCommandMBean_name(),
 469             vmSymbols::getDiagnosticCommandMBean_signature(),
 470             CHECK);
 471 
 472     instanceOop m = (instanceOop) result.get_jobject();
 473     instanceHandle dcmd_mbean_h(THREAD, m);
 474 
 475     if (!dcmd_mbean_h->is_a(k)) {
 476       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 477               "DiagnosticCommandImpl.getDiagnosticCommandMBean didn't return a DiagnosticCommandMBean instance");
 478     }
 479 
 480     JavaValue result2(T_VOID);
 481     JavaCallArguments args2(dcmd_mbean_h);
 482 
 483     JavaCalls::call_virtual(&result2,
 484             dcmd_mbean_klass,
 485             vmSymbols::createDiagnosticFrameworkNotification_name(),
 486             vmSymbols::void_method_signature(),
 487             &args2,
 488             CHECK);
 489   }
 490 }
 491 
 492 Mutex* DCmdFactory::_dcmdFactory_lock = new Mutex(Mutex::leaf, "DCmdFactory", true, Monitor::_safepoint_check_never);
 493 bool DCmdFactory::_send_jmx_notification = false;
 494 
 495 DCmdFactory* DCmdFactory::factory(DCmdSource source, const char* name, size_t len) {
 496   MutexLockerEx ml(_dcmdFactory_lock, Mutex::_no_safepoint_check_flag);
 497   DCmdFactory* factory = _DCmdFactoryList;
 498   while (factory != NULL) {
 499     if (strlen(factory->name()) == len &&
 500         strncmp(name, factory->name(), len) == 0) {
 501       if(factory->export_flags() & source) {
 502         return factory;
 503       } else {
 504         return NULL;
 505       }
 506     }
 507     factory = factory->_next;
 508   }
 509   return NULL;
 510 }
 511 
 512 int DCmdFactory::register_DCmdFactory(DCmdFactory* factory) {
 513   MutexLockerEx ml(_dcmdFactory_lock, Mutex::_no_safepoint_check_flag);
 514   factory->_next = _DCmdFactoryList;
 515   _DCmdFactoryList = factory;
 516   if (_send_jmx_notification && !factory->_hidden
 517       && (factory->_export_flags & DCmd_Source_MBean)) {
 518     DCmdFactory::push_jmx_notification_request();
 519   }
 520   return 0; // Actually, there's no checks for duplicates
 521 }
 522 
 523 DCmd* DCmdFactory::create_local_DCmd(DCmdSource source, CmdLine &line,
 524                                      outputStream* out, TRAPS) {
 525   DCmdFactory* f = factory(source, line.cmd_addr(), line.cmd_len());
 526   if (f != NULL) {
 527     if (!f->is_enabled()) {
 528       THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
 529                      f->disabled_message());
 530     }
 531     return f->create_resource_instance(out);
 532   }
 533   THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
 534              "Unknown diagnostic command");
 535 }
 536 
 537 GrowableArray<const char*>* DCmdFactory::DCmd_list(DCmdSource source) {
 538   MutexLockerEx ml(_dcmdFactory_lock, Mutex::_no_safepoint_check_flag);
 539   GrowableArray<const char*>* array = new GrowableArray<const char*>();
 540   DCmdFactory* factory = _DCmdFactoryList;
 541   while (factory != NULL) {
 542     if (!factory->is_hidden() && (factory->export_flags() & source)) {
 543       array->append(factory->name());
 544     }
 545     factory = factory->next();
 546   }
 547   return array;
 548 }
 549 
 550 GrowableArray<DCmdInfo*>* DCmdFactory::DCmdInfo_list(DCmdSource source ) {
 551   MutexLockerEx ml(_dcmdFactory_lock, Mutex::_no_safepoint_check_flag);
 552   GrowableArray<DCmdInfo*>* array = new GrowableArray<DCmdInfo*>();
 553   DCmdFactory* factory = _DCmdFactoryList;
 554   while (factory != NULL) {
 555     if (!factory->is_hidden() && (factory->export_flags() & source)) {
 556       array->append(new DCmdInfo(factory->name(),
 557                     factory->description(), factory->impact(),
 558                     factory->permission(), factory->num_arguments(),
 559                     factory->is_enabled()));
 560     }
 561     factory = factory->next();
 562   }
 563   return array;
 564 }