1 /*
   2  * Copyright (c) 1997, 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 "classfile/classLoader.hpp"
  28 #include "classfile/javaAssertions.hpp"
  29 #include "classfile/moduleEntry.hpp"
  30 #include "classfile/stringTable.hpp"
  31 #include "classfile/symbolTable.hpp"
  32 #include "gc/shared/collectorPolicy.hpp"
  33 #include "gc/shared/gcArguments.hpp"
  34 #include "gc/shared/gcConfig.hpp"
  35 #include "logging/log.hpp"
  36 #include "logging/logConfiguration.hpp"
  37 #include "logging/logStream.hpp"
  38 #include "logging/logTag.hpp"
  39 #include "memory/allocation.inline.hpp"
  40 #include "memory/universe.hpp"
  41 #include "oops/oop.inline.hpp"
  42 #include "prims/jvmtiExport.hpp"
  43 #include "runtime/arguments.hpp"
  44 #include "runtime/arguments_ext.hpp"
  45 #include "runtime/commandLineFlagConstraintList.hpp"
  46 #include "runtime/commandLineFlagWriteableList.hpp"
  47 #include "runtime/commandLineFlagRangeList.hpp"
  48 #include "runtime/globals.hpp"
  49 #include "runtime/globals_extension.hpp"
  50 #include "runtime/java.hpp"
  51 #include "runtime/os.inline.hpp"
  52 #include "runtime/safepoint.hpp"
  53 #include "runtime/safepointMechanism.hpp"
  54 #include "runtime/vm_version.hpp"
  55 #include "services/management.hpp"
  56 #include "services/memTracker.hpp"
  57 #include "utilities/align.hpp"
  58 #include "utilities/defaultStream.hpp"
  59 #include "utilities/macros.hpp"
  60 #include "utilities/stringUtils.hpp"
  61 #if INCLUDE_JVMCI
  62 #include "jvmci/jvmciRuntime.hpp"
  63 #endif
  64 
  65 // Note: This is a special bug reporting site for the JVM
  66 #ifdef VENDOR_URL_VM_BUG
  67 # define DEFAULT_VENDOR_URL_BUG VENDOR_URL_VM_BUG
  68 #else
  69 # define DEFAULT_VENDOR_URL_BUG "http://bugreport.java.com/bugreport/crash.jsp"
  70 #endif
  71 #define DEFAULT_JAVA_LAUNCHER  "generic"
  72 
  73 char*  Arguments::_jvm_flags_file               = NULL;
  74 char** Arguments::_jvm_flags_array              = NULL;
  75 int    Arguments::_num_jvm_flags                = 0;
  76 char** Arguments::_jvm_args_array               = NULL;
  77 int    Arguments::_num_jvm_args                 = 0;
  78 char*  Arguments::_java_command                 = NULL;
  79 SystemProperty* Arguments::_system_properties   = NULL;
  80 const char*  Arguments::_gc_log_filename        = NULL;
  81 size_t Arguments::_conservative_max_heap_alignment = 0;
  82 size_t Arguments::_min_heap_size                = 0;
  83 Arguments::Mode Arguments::_mode                = _mixed;
  84 bool   Arguments::_java_compiler                = false;
  85 bool   Arguments::_xdebug_mode                  = false;
  86 const char*  Arguments::_java_vendor_url_bug    = DEFAULT_VENDOR_URL_BUG;
  87 const char*  Arguments::_sun_java_launcher      = DEFAULT_JAVA_LAUNCHER;
  88 int    Arguments::_sun_java_launcher_pid        = -1;
  89 bool   Arguments::_sun_java_launcher_is_altjvm  = false;
  90 
  91 // These parameters are reset in method parse_vm_init_args()
  92 bool   Arguments::_AlwaysCompileLoopMethods     = AlwaysCompileLoopMethods;
  93 bool   Arguments::_UseOnStackReplacement        = UseOnStackReplacement;
  94 bool   Arguments::_BackgroundCompilation        = BackgroundCompilation;
  95 bool   Arguments::_ClipInlining                 = ClipInlining;
  96 intx   Arguments::_Tier3InvokeNotifyFreqLog     = Tier3InvokeNotifyFreqLog;
  97 intx   Arguments::_Tier4InvocationThreshold     = Tier4InvocationThreshold;
  98 
  99 char*  Arguments::SharedArchivePath             = NULL;
 100 
 101 AgentLibraryList Arguments::_libraryList;
 102 AgentLibraryList Arguments::_agentList;
 103 
 104 abort_hook_t     Arguments::_abort_hook         = NULL;
 105 exit_hook_t      Arguments::_exit_hook          = NULL;
 106 vfprintf_hook_t  Arguments::_vfprintf_hook      = NULL;
 107 
 108 
 109 SystemProperty *Arguments::_sun_boot_library_path = NULL;
 110 SystemProperty *Arguments::_java_library_path = NULL;
 111 SystemProperty *Arguments::_java_home = NULL;
 112 SystemProperty *Arguments::_java_class_path = NULL;
 113 SystemProperty *Arguments::_jdk_boot_class_path_append = NULL;
 114 
 115 GrowableArray<ModulePatchPath*> *Arguments::_patch_mod_prefix = NULL;
 116 PathString *Arguments::_system_boot_class_path = NULL;
 117 bool Arguments::_has_jimage = false;
 118 
 119 char* Arguments::_ext_dirs = NULL;
 120 
 121 bool PathString::set_value(const char *value) {
 122   if (_value != NULL) {
 123     FreeHeap(_value);
 124   }
 125   _value = AllocateHeap(strlen(value)+1, mtArguments);
 126   assert(_value != NULL, "Unable to allocate space for new path value");
 127   if (_value != NULL) {
 128     strcpy(_value, value);
 129   } else {
 130     // not able to allocate
 131     return false;
 132   }
 133   return true;
 134 }
 135 
 136 void PathString::append_value(const char *value) {
 137   char *sp;
 138   size_t len = 0;
 139   if (value != NULL) {
 140     len = strlen(value);
 141     if (_value != NULL) {
 142       len += strlen(_value);
 143     }
 144     sp = AllocateHeap(len+2, mtArguments);
 145     assert(sp != NULL, "Unable to allocate space for new append path value");
 146     if (sp != NULL) {
 147       if (_value != NULL) {
 148         strcpy(sp, _value);
 149         strcat(sp, os::path_separator());
 150         strcat(sp, value);
 151         FreeHeap(_value);
 152       } else {
 153         strcpy(sp, value);
 154       }
 155       _value = sp;
 156     }
 157   }
 158 }
 159 
 160 PathString::PathString(const char* value) {
 161   if (value == NULL) {
 162     _value = NULL;
 163   } else {
 164     _value = AllocateHeap(strlen(value)+1, mtArguments);
 165     strcpy(_value, value);
 166   }
 167 }
 168 
 169 PathString::~PathString() {
 170   if (_value != NULL) {
 171     FreeHeap(_value);
 172     _value = NULL;
 173   }
 174 }
 175 
 176 ModulePatchPath::ModulePatchPath(const char* module_name, const char* path) {
 177   assert(module_name != NULL && path != NULL, "Invalid module name or path value");
 178   size_t len = strlen(module_name) + 1;
 179   _module_name = AllocateHeap(len, mtInternal);
 180   strncpy(_module_name, module_name, len); // copy the trailing null
 181   _path =  new PathString(path);
 182 }
 183 
 184 ModulePatchPath::~ModulePatchPath() {
 185   if (_module_name != NULL) {
 186     FreeHeap(_module_name);
 187     _module_name = NULL;
 188   }
 189   if (_path != NULL) {
 190     delete _path;
 191     _path = NULL;
 192   }
 193 }
 194 
 195 SystemProperty::SystemProperty(const char* key, const char* value, bool writeable, bool internal) : PathString(value) {
 196   if (key == NULL) {
 197     _key = NULL;
 198   } else {
 199     _key = AllocateHeap(strlen(key)+1, mtArguments);
 200     strcpy(_key, key);
 201   }
 202   _next = NULL;
 203   _internal = internal;
 204   _writeable = writeable;
 205 }
 206 
 207 AgentLibrary::AgentLibrary(const char* name, const char* options,
 208                bool is_absolute_path, void* os_lib,
 209                bool instrument_lib) {
 210   _name = AllocateHeap(strlen(name)+1, mtArguments);
 211   strcpy(_name, name);
 212   if (options == NULL) {
 213     _options = NULL;
 214   } else {
 215     _options = AllocateHeap(strlen(options)+1, mtArguments);
 216     strcpy(_options, options);
 217   }
 218   _is_absolute_path = is_absolute_path;
 219   _os_lib = os_lib;
 220   _next = NULL;
 221   _state = agent_invalid;
 222   _is_static_lib = false;
 223   _is_instrument_lib = instrument_lib;
 224 }
 225 
 226 // Check if head of 'option' matches 'name', and sets 'tail' to the remaining
 227 // part of the option string.
 228 static bool match_option(const JavaVMOption *option, const char* name,
 229                          const char** tail) {
 230   size_t len = strlen(name);
 231   if (strncmp(option->optionString, name, len) == 0) {
 232     *tail = option->optionString + len;
 233     return true;
 234   } else {
 235     return false;
 236   }
 237 }
 238 
 239 // Check if 'option' matches 'name'. No "tail" is allowed.
 240 static bool match_option(const JavaVMOption *option, const char* name) {
 241   const char* tail = NULL;
 242   bool result = match_option(option, name, &tail);
 243   if (tail != NULL && *tail == '\0') {
 244     return result;
 245   } else {
 246     return false;
 247   }
 248 }
 249 
 250 // Return true if any of the strings in null-terminated array 'names' matches.
 251 // If tail_allowed is true, then the tail must begin with a colon; otherwise,
 252 // the option must match exactly.
 253 static bool match_option(const JavaVMOption* option, const char** names, const char** tail,
 254   bool tail_allowed) {
 255   for (/* empty */; *names != NULL; ++names) {
 256   if (match_option(option, *names, tail)) {
 257       if (**tail == '\0' || (tail_allowed && **tail == ':')) {
 258         return true;
 259       }
 260     }
 261   }
 262   return false;
 263 }
 264 
 265 static void logOption(const char* opt) {
 266   if (PrintVMOptions) {
 267     jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);
 268   }
 269 }
 270 
 271 bool needs_module_property_warning = false;
 272 
 273 #define MODULE_PROPERTY_PREFIX "jdk.module."
 274 #define MODULE_PROPERTY_PREFIX_LEN 11
 275 #define ADDEXPORTS "addexports"
 276 #define ADDEXPORTS_LEN 10
 277 #define ADDREADS "addreads"
 278 #define ADDREADS_LEN 8
 279 #define ADDOPENS "addopens"
 280 #define ADDOPENS_LEN 8
 281 #define PATCH "patch"
 282 #define PATCH_LEN 5
 283 #define ADDMODS "addmods"
 284 #define ADDMODS_LEN 7
 285 #define LIMITMODS "limitmods"
 286 #define LIMITMODS_LEN 9
 287 #define PATH "path"
 288 #define PATH_LEN 4
 289 #define UPGRADE_PATH "upgrade.path"
 290 #define UPGRADE_PATH_LEN 12
 291 
 292 void Arguments::add_init_library(const char* name, char* options) {
 293   _libraryList.add(new AgentLibrary(name, options, false, NULL));
 294 }
 295 
 296 void Arguments::add_init_agent(const char* name, char* options, bool absolute_path) {
 297   _agentList.add(new AgentLibrary(name, options, absolute_path, NULL));
 298 }
 299 
 300 void Arguments::add_instrument_agent(const char* name, char* options, bool absolute_path) {
 301   _agentList.add(new AgentLibrary(name, options, absolute_path, NULL, true));
 302 }
 303 
 304 // Late-binding agents not started via arguments
 305 void Arguments::add_loaded_agent(AgentLibrary *agentLib) {
 306   _agentList.add(agentLib);
 307 }
 308 
 309 void Arguments::add_loaded_agent(const char* name, char* options, bool absolute_path, void* os_lib) {
 310   _agentList.add(new AgentLibrary(name, options, absolute_path, os_lib));
 311 }
 312 
 313 // Return TRUE if option matches 'property', or 'property=', or 'property.'.
 314 static bool matches_property_suffix(const char* option, const char* property, size_t len) {
 315   return ((strncmp(option, property, len) == 0) &&
 316           (option[len] == '=' || option[len] == '.' || option[len] == '\0'));
 317 }
 318 
 319 // Return true if property starts with "jdk.module." and its ensuing chars match
 320 // any of the reserved module properties.
 321 // property should be passed without the leading "-D".
 322 bool Arguments::is_internal_module_property(const char* property) {
 323   assert((strncmp(property, "-D", 2) != 0), "Unexpected leading -D");
 324   if  (strncmp(property, MODULE_PROPERTY_PREFIX, MODULE_PROPERTY_PREFIX_LEN) == 0) {
 325     const char* property_suffix = property + MODULE_PROPERTY_PREFIX_LEN;
 326     if (matches_property_suffix(property_suffix, ADDEXPORTS, ADDEXPORTS_LEN) ||
 327         matches_property_suffix(property_suffix, ADDREADS, ADDREADS_LEN) ||
 328         matches_property_suffix(property_suffix, ADDOPENS, ADDOPENS_LEN) ||
 329         matches_property_suffix(property_suffix, PATCH, PATCH_LEN) ||
 330         matches_property_suffix(property_suffix, ADDMODS, ADDMODS_LEN) ||
 331         matches_property_suffix(property_suffix, LIMITMODS, LIMITMODS_LEN) ||
 332         matches_property_suffix(property_suffix, PATH, PATH_LEN) ||
 333         matches_property_suffix(property_suffix, UPGRADE_PATH, UPGRADE_PATH_LEN)) {
 334       return true;
 335     }
 336   }
 337   return false;
 338 }
 339 
 340 // Process java launcher properties.
 341 void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
 342   // See if sun.java.launcher, sun.java.launcher.is_altjvm or
 343   // sun.java.launcher.pid is defined.
 344   // Must do this before setting up other system properties,
 345   // as some of them may depend on launcher type.
 346   for (int index = 0; index < args->nOptions; index++) {
 347     const JavaVMOption* option = args->options + index;
 348     const char* tail;
 349 
 350     if (match_option(option, "-Dsun.java.launcher=", &tail)) {
 351       process_java_launcher_argument(tail, option->extraInfo);
 352       continue;
 353     }
 354     if (match_option(option, "-Dsun.java.launcher.is_altjvm=", &tail)) {
 355       if (strcmp(tail, "true") == 0) {
 356         _sun_java_launcher_is_altjvm = true;
 357       }
 358       continue;
 359     }
 360     if (match_option(option, "-Dsun.java.launcher.pid=", &tail)) {
 361       _sun_java_launcher_pid = atoi(tail);
 362       continue;
 363     }
 364   }
 365 }
 366 
 367 // Initialize system properties key and value.
 368 void Arguments::init_system_properties() {
 369 
 370   // Set up _system_boot_class_path which is not a property but
 371   // relies heavily on argument processing and the jdk.boot.class.path.append
 372   // property. It is used to store the underlying system boot class path.
 373   _system_boot_class_path = new PathString(NULL);
 374 
 375   PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
 376                                                            "Java Virtual Machine Specification",  false));
 377   PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(),  false));
 378   PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(),  false));
 379   PropertyList_add(&_system_properties, new SystemProperty("java.vm.info", VM_Version::vm_info_string(),  true));
 380   PropertyList_add(&_system_properties, new SystemProperty("jdk.debug", VM_Version::jdk_debug_level(),  false));
 381 
 382   // Following are JVMTI agent writable properties.
 383   // Properties values are set to NULL and they are
 384   // os specific they are initialized in os::init_system_properties_values().
 385   _sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL,  true);
 386   _java_library_path = new SystemProperty("java.library.path", NULL,  true);
 387   _java_home =  new SystemProperty("java.home", NULL,  true);
 388   _java_class_path = new SystemProperty("java.class.path", "",  true);
 389   // jdk.boot.class.path.append is a non-writeable, internal property.
 390   // It can only be set by either:
 391   //    - -Xbootclasspath/a:
 392   //    - AddToBootstrapClassLoaderSearch during JVMTI OnLoad phase
 393   _jdk_boot_class_path_append = new SystemProperty("jdk.boot.class.path.append", "", false, true);
 394 
 395   // Add to System Property list.
 396   PropertyList_add(&_system_properties, _sun_boot_library_path);
 397   PropertyList_add(&_system_properties, _java_library_path);
 398   PropertyList_add(&_system_properties, _java_home);
 399   PropertyList_add(&_system_properties, _java_class_path);
 400   PropertyList_add(&_system_properties, _jdk_boot_class_path_append);
 401 
 402   // Set OS specific system properties values
 403   os::init_system_properties_values();
 404 }
 405 
 406 // Update/Initialize System properties after JDK version number is known
 407 void Arguments::init_version_specific_system_properties() {
 408   enum { bufsz = 16 };
 409   char buffer[bufsz];
 410   const char* spec_vendor = "Oracle Corporation";
 411   uint32_t spec_version = JDK_Version::current().major_version();
 412 
 413   jio_snprintf(buffer, bufsz, UINT32_FORMAT, spec_version);
 414 
 415   PropertyList_add(&_system_properties,
 416       new SystemProperty("java.vm.specification.vendor",  spec_vendor, false));
 417   PropertyList_add(&_system_properties,
 418       new SystemProperty("java.vm.specification.version", buffer, false));
 419   PropertyList_add(&_system_properties,
 420       new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(),  false));
 421 }
 422 
 423 /*
 424  *  -XX argument processing:
 425  *
 426  *  -XX arguments are defined in several places, such as:
 427  *      globals.hpp, globals_<cpu>.hpp, globals_<os>.hpp, <compiler>_globals.hpp, or <gc>_globals.hpp.
 428  *  -XX arguments are parsed in parse_argument().
 429  *  -XX argument bounds checking is done in check_vm_args_consistency().
 430  *
 431  * Over time -XX arguments may change. There are mechanisms to handle common cases:
 432  *
 433  *      ALIASED: An option that is simply another name for another option. This is often
 434  *               part of the process of deprecating a flag, but not all aliases need
 435  *               to be deprecated.
 436  *
 437  *               Create an alias for an option by adding the old and new option names to the
 438  *               "aliased_jvm_flags" table. Delete the old variable from globals.hpp (etc).
 439  *
 440  *   DEPRECATED: An option that is supported, but a warning is printed to let the user know that
 441  *               support may be removed in the future. Both regular and aliased options may be
 442  *               deprecated.
 443  *
 444  *               Add a deprecation warning for an option (or alias) by adding an entry in the
 445  *               "special_jvm_flags" table and setting the "deprecated_in" field.
 446  *               Often an option "deprecated" in one major release will
 447  *               be made "obsolete" in the next. In this case the entry should also have its
 448  *               "obsolete_in" field set.
 449  *
 450  *     OBSOLETE: An option that has been removed (and deleted from globals.hpp), but is still accepted
 451  *               on the command line. A warning is printed to let the user know that option might not
 452  *               be accepted in the future.
 453  *
 454  *               Add an obsolete warning for an option by adding an entry in the "special_jvm_flags"
 455  *               table and setting the "obsolete_in" field.
 456  *
 457  *      EXPIRED: A deprecated or obsolete option that has an "accept_until" version less than or equal
 458  *               to the current JDK version. The system will flatly refuse to admit the existence of
 459  *               the flag. This allows a flag to die automatically over JDK releases.
 460  *
 461  *               Note that manual cleanup of expired options should be done at major JDK version upgrades:
 462  *                  - Newly expired options should be removed from the special_jvm_flags and aliased_jvm_flags tables.
 463  *                  - Newly obsolete or expired deprecated options should have their global variable
 464  *                    definitions removed (from globals.hpp, etc) and related implementations removed.
 465  *
 466  * Recommended approach for removing options:
 467  *
 468  * To remove options commonly used by customers (e.g. product, commercial -XX options), use
 469  * the 3-step model adding major release numbers to the deprecate, obsolete and expire columns.
 470  *
 471  * To remove internal options (e.g. diagnostic, experimental, develop options), use
 472  * a 2-step model adding major release numbers to the obsolete and expire columns.
 473  *
 474  * To change the name of an option, use the alias table as well as a 2-step
 475  * model adding major release numbers to the deprecate and expire columns.
 476  * Think twice about aliasing commonly used customer options.
 477  *
 478  * There are times when it is appropriate to leave a future release number as undefined.
 479  *
 480  * Tests:  Aliases should be tested in VMAliasOptions.java.
 481  *         Deprecated options should be tested in VMDeprecatedOptions.java.
 482  */
 483 
 484 // The special_jvm_flags table declares options that are being deprecated and/or obsoleted. The
 485 // "deprecated_in" or "obsolete_in" fields may be set to "undefined", but not both.
 486 // When the JDK version reaches 'deprecated_in' limit, the JVM will process this flag on
 487 // the command-line as usual, but will issue a warning.
 488 // When the JDK version reaches 'obsolete_in' limit, the JVM will continue accepting this flag on
 489 // the command-line, while issuing a warning and ignoring the flag value.
 490 // Once the JDK version reaches 'expired_in' limit, the JVM will flatly refuse to admit the
 491 // existence of the flag.
 492 //
 493 // MANUAL CLEANUP ON JDK VERSION UPDATES:
 494 // This table ensures that the handling of options will update automatically when the JDK
 495 // version is incremented, but the source code needs to be cleanup up manually:
 496 // - As "deprecated" options age into "obsolete" or "expired" options, the associated "globals"
 497 //   variable should be removed, as well as users of the variable.
 498 // - As "deprecated" options age into "obsolete" options, move the entry into the
 499 //   "Obsolete Flags" section of the table.
 500 // - All expired options should be removed from the table.
 501 static SpecialFlag const special_jvm_flags[] = {
 502   // -------------- Deprecated Flags --------------
 503   // --- Non-alias flags - sorted by obsolete_in then expired_in:
 504   { "MaxGCMinorPauseMillis",        JDK_Version::jdk(8), JDK_Version::undefined(), JDK_Version::undefined() },
 505   { "UseConcMarkSweepGC",           JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 506   { "AssumeMP",                     JDK_Version::jdk(10),JDK_Version::undefined(), JDK_Version::undefined() },
 507   { "MonitorInUseLists",            JDK_Version::jdk(10),JDK_Version::undefined(), JDK_Version::undefined() },
 508   { "MaxRAMFraction",               JDK_Version::jdk(10),  JDK_Version::undefined(), JDK_Version::undefined() },
 509   { "MinRAMFraction",               JDK_Version::jdk(10),  JDK_Version::undefined(), JDK_Version::undefined() },
 510   { "InitialRAMFraction",           JDK_Version::jdk(10),  JDK_Version::undefined(), JDK_Version::undefined() },
 511   { "UseMembar",                    JDK_Version::jdk(10), JDK_Version::undefined(), JDK_Version::undefined() },
 512   { "IgnoreUnverifiableClassesDuringDump", JDK_Version::jdk(10),  JDK_Version::undefined(), JDK_Version::undefined() },
 513   { "CompilerThreadHintNoPreempt",  JDK_Version::jdk(11), JDK_Version::jdk(12), JDK_Version::jdk(13) },
 514   { "VMThreadHintNoPreempt",        JDK_Version::jdk(11), JDK_Version::jdk(12), JDK_Version::jdk(13) },
 515   { "PrintSafepointStatistics",     JDK_Version::jdk(11), JDK_Version::jdk(12), JDK_Version::jdk(13) },
 516   { "PrintSafepointStatisticsTimeout", JDK_Version::jdk(11), JDK_Version::jdk(12), JDK_Version::jdk(13) },
 517   { "PrintSafepointStatisticsCount",JDK_Version::jdk(11), JDK_Version::jdk(12), JDK_Version::jdk(13) },
 518   { "AggressiveOpts",               JDK_Version::jdk(11), JDK_Version::jdk(12), JDK_Version::jdk(13) },
 519 
 520   // --- Deprecated alias flags (see also aliased_jvm_flags) - sorted by obsolete_in then expired_in:
 521   { "DefaultMaxRAMFraction",        JDK_Version::jdk(8),  JDK_Version::undefined(), JDK_Version::undefined() },
 522   { "CreateMinidumpOnCrash",        JDK_Version::jdk(9),  JDK_Version::undefined(), JDK_Version::undefined() },
 523   { "MustCallLoadClassInternal",    JDK_Version::jdk(10), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 524   { "UnsyncloadClass",              JDK_Version::jdk(10), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 525 
 526   // -------------- Obsolete Flags - sorted by expired_in --------------
 527   { "ConvertSleepToYield",           JDK_Version::jdk(9),      JDK_Version::jdk(10), JDK_Version::jdk(11) },
 528   { "ConvertYieldToSleep",           JDK_Version::jdk(9),      JDK_Version::jdk(10), JDK_Version::jdk(11) },
 529   { "MinSleepInterval",              JDK_Version::jdk(9),      JDK_Version::jdk(10), JDK_Version::jdk(11) },
 530   { "CheckAssertionStatusDirectives",JDK_Version::undefined(), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 531   { "PrintMallocFree",               JDK_Version::undefined(), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 532   { "PrintMalloc",                   JDK_Version::undefined(), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 533   { "ShowSafepointMsgs",             JDK_Version::undefined(), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 534   { "FastTLABRefill",                JDK_Version::jdk(10),     JDK_Version::jdk(11), JDK_Version::jdk(12) },
 535   { "SafepointSpinBeforeYield",      JDK_Version::jdk(10),     JDK_Version::jdk(11), JDK_Version::jdk(12) },
 536   { "CheckEndorsedAndExtDirs",       JDK_Version::jdk(10),     JDK_Version::jdk(11), JDK_Version::jdk(12) },
 537   { "DeferThrSuspendLoopCount",      JDK_Version::jdk(10),     JDK_Version::jdk(11), JDK_Version::jdk(12) },
 538   { "DeferPollingPageLoopCount",     JDK_Version::jdk(10),     JDK_Version::jdk(11), JDK_Version::jdk(12) },
 539   { "PermSize",                      JDK_Version::undefined(), JDK_Version::jdk(8),  JDK_Version::undefined() },
 540   { "MaxPermSize",                   JDK_Version::undefined(), JDK_Version::jdk(8),  JDK_Version::undefined() },
 541   { "SharedReadWriteSize",           JDK_Version::undefined(), JDK_Version::jdk(10), JDK_Version::undefined() },
 542   { "SharedReadOnlySize",            JDK_Version::undefined(), JDK_Version::jdk(10), JDK_Version::undefined() },
 543   { "SharedMiscDataSize",            JDK_Version::undefined(), JDK_Version::jdk(10), JDK_Version::undefined() },
 544   { "SharedMiscCodeSize",            JDK_Version::undefined(), JDK_Version::jdk(10), JDK_Version::undefined() },
 545   { "UseUTCFileTimestamp",           JDK_Version::undefined(), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 546 
 547 #ifdef TEST_VERIFY_SPECIAL_JVM_FLAGS
 548   { "dep > obs",                    JDK_Version::jdk(9), JDK_Version::jdk(8), JDK_Version::undefined() },
 549   { "dep > exp ",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(8) },
 550   { "obs > exp ",                   JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(8) },
 551   { "not deprecated or obsolete",   JDK_Version::undefined(), JDK_Version::undefined(), JDK_Version::jdk(9) },
 552   { "dup option",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 553   { "dup option",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 554   { "BytecodeVerificationRemote",   JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::undefined() },
 555 #endif
 556 
 557   { NULL, JDK_Version(0), JDK_Version(0) }
 558 };
 559 
 560 // Flags that are aliases for other flags.
 561 typedef struct {
 562   const char* alias_name;
 563   const char* real_name;
 564 } AliasedFlag;
 565 
 566 static AliasedFlag const aliased_jvm_flags[] = {
 567   { "DefaultMaxRAMFraction",    "MaxRAMFraction"    },
 568   { "CreateMinidumpOnCrash",    "CreateCoredumpOnCrash" },
 569   { NULL, NULL}
 570 };
 571 
 572 // NOTE: A compatibility request will be necessary for each alias to be removed.
 573 static AliasedLoggingFlag const aliased_logging_flags[] = {
 574   { "PrintCompressedOopsMode",   LogLevel::Info,  true,  LOG_TAGS(gc, heap, coops) },
 575   { "PrintSharedSpaces",         LogLevel::Info,  true,  LOG_TAGS(cds) },
 576   { "TraceBiasedLocking",        LogLevel::Info,  true,  LOG_TAGS(biasedlocking) },
 577   { "TraceClassLoading",         LogLevel::Info,  true,  LOG_TAGS(class, load) },
 578   { "TraceClassLoadingPreorder", LogLevel::Debug, true,  LOG_TAGS(class, preorder) },
 579   { "TraceClassPaths",           LogLevel::Info,  true,  LOG_TAGS(class, path) },
 580   { "TraceClassResolution",      LogLevel::Debug, true,  LOG_TAGS(class, resolve) },
 581   { "TraceClassUnloading",       LogLevel::Info,  true,  LOG_TAGS(class, unload) },
 582   { "TraceExceptions",           LogLevel::Info,  true,  LOG_TAGS(exceptions) },
 583   { "TraceLoaderConstraints",    LogLevel::Info,  true,  LOG_TAGS(class, loader, constraints) },
 584   { "TraceMonitorInflation",     LogLevel::Debug, true,  LOG_TAGS(monitorinflation) },
 585   { "TraceSafepointCleanupTime", LogLevel::Info,  true,  LOG_TAGS(safepoint, cleanup) },
 586   { "TraceJVMTIObjectTagging",   LogLevel::Debug, true,  LOG_TAGS(jvmti, objecttagging) },
 587   { "TraceRedefineClasses",      LogLevel::Info,  false, LOG_TAGS(redefine, class) },
 588   { NULL,                        LogLevel::Off,   false, LOG_TAGS(_NO_TAG) }
 589 };
 590 
 591 #ifndef PRODUCT
 592 // These options are removed in jdk9. Remove this code for jdk10.
 593 static AliasedFlag const removed_develop_logging_flags[] = {
 594   { "TraceClassInitialization",   "-Xlog:class+init" },
 595   { "TraceClassLoaderData",       "-Xlog:class+loader+data" },
 596   { "TraceDefaultMethods",        "-Xlog:defaultmethods=debug" },
 597   { "TraceItables",               "-Xlog:itables=debug" },
 598   { "TraceMonitorMismatch",       "-Xlog:monitormismatch=info" },
 599   { "TraceSafepoint",             "-Xlog:safepoint=debug" },
 600   { "TraceStartupTime",           "-Xlog:startuptime" },
 601   { "TraceVMOperation",           "-Xlog:vmoperation=debug" },
 602   { "PrintVtables",               "-Xlog:vtables=debug" },
 603   { "VerboseVerification",        "-Xlog:verification" },
 604   { NULL, NULL }
 605 };
 606 #endif //PRODUCT
 607 
 608 // Return true if "v" is less than "other", where "other" may be "undefined".
 609 static bool version_less_than(JDK_Version v, JDK_Version other) {
 610   assert(!v.is_undefined(), "must be defined");
 611   if (!other.is_undefined() && v.compare(other) >= 0) {
 612     return false;
 613   } else {
 614     return true;
 615   }
 616 }
 617 
 618 extern bool lookup_special_flag_ext(const char *flag_name, SpecialFlag& flag);
 619 
 620 static bool lookup_special_flag(const char *flag_name, SpecialFlag& flag) {
 621   // Allow extensions to have priority
 622   if (lookup_special_flag_ext(flag_name, flag)) {
 623     return true;
 624   }
 625 
 626   for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {
 627     if ((strcmp(special_jvm_flags[i].name, flag_name) == 0)) {
 628       flag = special_jvm_flags[i];
 629       return true;
 630     }
 631   }
 632   return false;
 633 }
 634 
 635 bool Arguments::is_obsolete_flag(const char *flag_name, JDK_Version* version) {
 636   assert(version != NULL, "Must provide a version buffer");
 637   SpecialFlag flag;
 638   if (lookup_special_flag(flag_name, flag)) {
 639     if (!flag.obsolete_in.is_undefined()) {
 640       if (!version_less_than(JDK_Version::current(), flag.obsolete_in)) {
 641         *version = flag.obsolete_in;
 642         return true;
 643       }
 644     }
 645   }
 646   return false;
 647 }
 648 
 649 int Arguments::is_deprecated_flag(const char *flag_name, JDK_Version* version) {
 650   assert(version != NULL, "Must provide a version buffer");
 651   SpecialFlag flag;
 652   if (lookup_special_flag(flag_name, flag)) {
 653     if (!flag.deprecated_in.is_undefined()) {
 654       if (version_less_than(JDK_Version::current(), flag.obsolete_in) &&
 655           version_less_than(JDK_Version::current(), flag.expired_in)) {
 656         *version = flag.deprecated_in;
 657         return 1;
 658       } else {
 659         return -1;
 660       }
 661     }
 662   }
 663   return 0;
 664 }
 665 
 666 #ifndef PRODUCT
 667 const char* Arguments::removed_develop_logging_flag_name(const char* name){
 668   for (size_t i = 0; removed_develop_logging_flags[i].alias_name != NULL; i++) {
 669     const AliasedFlag& flag = removed_develop_logging_flags[i];
 670     if (strcmp(flag.alias_name, name) == 0) {
 671       return flag.real_name;
 672     }
 673   }
 674   return NULL;
 675 }
 676 #endif // PRODUCT
 677 
 678 const char* Arguments::real_flag_name(const char *flag_name) {
 679   for (size_t i = 0; aliased_jvm_flags[i].alias_name != NULL; i++) {
 680     const AliasedFlag& flag_status = aliased_jvm_flags[i];
 681     if (strcmp(flag_status.alias_name, flag_name) == 0) {
 682         return flag_status.real_name;
 683     }
 684   }
 685   return flag_name;
 686 }
 687 
 688 #ifdef ASSERT
 689 static bool lookup_special_flag(const char *flag_name, size_t skip_index) {
 690   for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {
 691     if ((i != skip_index) && (strcmp(special_jvm_flags[i].name, flag_name) == 0)) {
 692       return true;
 693     }
 694   }
 695   return false;
 696 }
 697 
 698 // Verifies the correctness of the entries in the special_jvm_flags table.
 699 // If there is a semantic error (i.e. a bug in the table) such as the obsoletion
 700 // version being earlier than the deprecation version, then a warning is issued
 701 // and verification fails - by returning false. If it is detected that the table
 702 // is out of date, with respect to the current version, then a warning is issued
 703 // but verification does not fail. This allows the VM to operate when the version
 704 // is first updated, without needing to update all the impacted flags at the
 705 // same time.
 706 static bool verify_special_jvm_flags() {
 707   bool success = true;
 708   for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {
 709     const SpecialFlag& flag = special_jvm_flags[i];
 710     if (lookup_special_flag(flag.name, i)) {
 711       warning("Duplicate special flag declaration \"%s\"", flag.name);
 712       success = false;
 713     }
 714     if (flag.deprecated_in.is_undefined() &&
 715         flag.obsolete_in.is_undefined()) {
 716       warning("Special flag entry \"%s\" must declare version deprecated and/or obsoleted in.", flag.name);
 717       success = false;
 718     }
 719 
 720     if (!flag.deprecated_in.is_undefined()) {
 721       if (!version_less_than(flag.deprecated_in, flag.obsolete_in)) {
 722         warning("Special flag entry \"%s\" must be deprecated before obsoleted.", flag.name);
 723         success = false;
 724       }
 725 
 726       if (!version_less_than(flag.deprecated_in, flag.expired_in)) {
 727         warning("Special flag entry \"%s\" must be deprecated before expired.", flag.name);
 728         success = false;
 729       }
 730     }
 731 
 732     if (!flag.obsolete_in.is_undefined()) {
 733       if (!version_less_than(flag.obsolete_in, flag.expired_in)) {
 734         warning("Special flag entry \"%s\" must be obsoleted before expired.", flag.name);
 735         success = false;
 736       }
 737 
 738       // if flag has become obsolete it should not have a "globals" flag defined anymore.
 739       if (!version_less_than(JDK_Version::current(), flag.obsolete_in)) {
 740         if (Flag::find_flag(flag.name) != NULL) {
 741           // Temporarily disable the warning: 8196739
 742           // warning("Global variable for obsolete special flag entry \"%s\" should be removed", flag.name);
 743         }
 744       }
 745     }
 746 
 747     if (!flag.expired_in.is_undefined()) {
 748       // if flag has become expired it should not have a "globals" flag defined anymore.
 749       if (!version_less_than(JDK_Version::current(), flag.expired_in)) {
 750         if (Flag::find_flag(flag.name) != NULL) {
 751           // Temporarily disable the warning: 8196739
 752           // warning("Global variable for expired flag entry \"%s\" should be removed", flag.name);
 753         }
 754       }
 755     }
 756 
 757   }
 758   return success;
 759 }
 760 #endif
 761 
 762 // Parses a size specification string.
 763 bool Arguments::atojulong(const char *s, julong* result) {
 764   julong n = 0;
 765 
 766   // First char must be a digit. Don't allow negative numbers or leading spaces.
 767   if (!isdigit(*s)) {
 768     return false;
 769   }
 770 
 771   bool is_hex = (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'));
 772   char* remainder;
 773   errno = 0;
 774   n = strtoull(s, &remainder, (is_hex ? 16 : 10));
 775   if (errno != 0) {
 776     return false;
 777   }
 778 
 779   // Fail if no number was read at all or if the remainder contains more than a single non-digit character.
 780   if (remainder == s || strlen(remainder) > 1) {
 781     return false;
 782   }
 783 
 784   switch (*remainder) {
 785     case 'T': case 't':
 786       *result = n * G * K;
 787       // Check for overflow.
 788       if (*result/((julong)G * K) != n) return false;
 789       return true;
 790     case 'G': case 'g':
 791       *result = n * G;
 792       if (*result/G != n) return false;
 793       return true;
 794     case 'M': case 'm':
 795       *result = n * M;
 796       if (*result/M != n) return false;
 797       return true;
 798     case 'K': case 'k':
 799       *result = n * K;
 800       if (*result/K != n) return false;
 801       return true;
 802     case '\0':
 803       *result = n;
 804       return true;
 805     default:
 806       return false;
 807   }
 808 }
 809 
 810 Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size, julong max_size) {
 811   if (size < min_size) return arg_too_small;
 812   if (size > max_size) return arg_too_big;
 813   return arg_in_range;
 814 }
 815 
 816 // Describe an argument out of range error
 817 void Arguments::describe_range_error(ArgsRange errcode) {
 818   switch(errcode) {
 819   case arg_too_big:
 820     jio_fprintf(defaultStream::error_stream(),
 821                 "The specified size exceeds the maximum "
 822                 "representable size.\n");
 823     break;
 824   case arg_too_small:
 825   case arg_unreadable:
 826   case arg_in_range:
 827     // do nothing for now
 828     break;
 829   default:
 830     ShouldNotReachHere();
 831   }
 832 }
 833 
 834 static bool set_bool_flag(const char* name, bool value, Flag::Flags origin) {
 835   if (CommandLineFlags::boolAtPut(name, &value, origin) == Flag::SUCCESS) {
 836     return true;
 837   } else {
 838     return false;
 839   }
 840 }
 841 
 842 static bool set_fp_numeric_flag(const char* name, char* value, Flag::Flags origin) {
 843   char* end;
 844   errno = 0;
 845   double v = strtod(value, &end);
 846   if ((errno != 0) || (*end != 0)) {
 847     return false;
 848   }
 849 
 850   if (CommandLineFlags::doubleAtPut(name, &v, origin) == Flag::SUCCESS) {
 851     return true;
 852   }
 853   return false;
 854 }
 855 
 856 static bool set_numeric_flag(const char* name, char* value, Flag::Flags origin) {
 857   julong v;
 858   int int_v;
 859   intx intx_v;
 860   bool is_neg = false;
 861   Flag* result = Flag::find_flag(name, strlen(name));
 862 
 863   if (result == NULL) {
 864     return false;
 865   }
 866 
 867   // Check the sign first since atojulong() parses only unsigned values.
 868   if (*value == '-') {
 869     if (!result->is_intx() && !result->is_int()) {
 870       return false;
 871     }
 872     value++;
 873     is_neg = true;
 874   }
 875   if (!Arguments::atojulong(value, &v)) {
 876     return false;
 877   }
 878   if (result->is_int()) {
 879     int_v = (int) v;
 880     if (is_neg) {
 881       int_v = -int_v;
 882     }
 883     return CommandLineFlags::intAtPut(result, &int_v, origin) == Flag::SUCCESS;
 884   } else if (result->is_uint()) {
 885     uint uint_v = (uint) v;
 886     return CommandLineFlags::uintAtPut(result, &uint_v, origin) == Flag::SUCCESS;
 887   } else if (result->is_intx()) {
 888     intx_v = (intx) v;
 889     if (is_neg) {
 890       intx_v = -intx_v;
 891     }
 892     return CommandLineFlags::intxAtPut(result, &intx_v, origin) == Flag::SUCCESS;
 893   } else if (result->is_uintx()) {
 894     uintx uintx_v = (uintx) v;
 895     return CommandLineFlags::uintxAtPut(result, &uintx_v, origin) == Flag::SUCCESS;
 896   } else if (result->is_uint64_t()) {
 897     uint64_t uint64_t_v = (uint64_t) v;
 898     return CommandLineFlags::uint64_tAtPut(result, &uint64_t_v, origin) == Flag::SUCCESS;
 899   } else if (result->is_size_t()) {
 900     size_t size_t_v = (size_t) v;
 901     return CommandLineFlags::size_tAtPut(result, &size_t_v, origin) == Flag::SUCCESS;
 902   } else if (result->is_double()) {
 903     double double_v = (double) v;
 904     return CommandLineFlags::doubleAtPut(result, &double_v, origin) == Flag::SUCCESS;
 905   } else {
 906     return false;
 907   }
 908 }
 909 
 910 static bool set_string_flag(const char* name, const char* value, Flag::Flags origin) {
 911   if (CommandLineFlags::ccstrAtPut(name, &value, origin) != Flag::SUCCESS) return false;
 912   // Contract:  CommandLineFlags always returns a pointer that needs freeing.
 913   FREE_C_HEAP_ARRAY(char, value);
 914   return true;
 915 }
 916 
 917 static bool append_to_string_flag(const char* name, const char* new_value, Flag::Flags origin) {
 918   const char* old_value = "";
 919   if (CommandLineFlags::ccstrAt(name, &old_value) != Flag::SUCCESS) return false;
 920   size_t old_len = old_value != NULL ? strlen(old_value) : 0;
 921   size_t new_len = strlen(new_value);
 922   const char* value;
 923   char* free_this_too = NULL;
 924   if (old_len == 0) {
 925     value = new_value;
 926   } else if (new_len == 0) {
 927     value = old_value;
 928   } else {
 929      size_t length = old_len + 1 + new_len + 1;
 930      char* buf = NEW_C_HEAP_ARRAY(char, length, mtArguments);
 931     // each new setting adds another LINE to the switch:
 932     jio_snprintf(buf, length, "%s\n%s", old_value, new_value);
 933     value = buf;
 934     free_this_too = buf;
 935   }
 936   (void) CommandLineFlags::ccstrAtPut(name, &value, origin);
 937   // CommandLineFlags always returns a pointer that needs freeing.
 938   FREE_C_HEAP_ARRAY(char, value);
 939   if (free_this_too != NULL) {
 940     // CommandLineFlags made its own copy, so I must delete my own temp. buffer.
 941     FREE_C_HEAP_ARRAY(char, free_this_too);
 942   }
 943   return true;
 944 }
 945 
 946 const char* Arguments::handle_aliases_and_deprecation(const char* arg, bool warn) {
 947   const char* real_name = real_flag_name(arg);
 948   JDK_Version since = JDK_Version();
 949   switch (is_deprecated_flag(arg, &since)) {
 950     case -1:
 951       return NULL; // obsolete or expired, don't process normally
 952     case 0:
 953       return real_name;
 954     case 1: {
 955       if (warn) {
 956         char version[256];
 957         since.to_string(version, sizeof(version));
 958         if (real_name != arg) {
 959           warning("Option %s was deprecated in version %s and will likely be removed in a future release. Use option %s instead.",
 960                   arg, version, real_name);
 961         } else {
 962           warning("Option %s was deprecated in version %s and will likely be removed in a future release.",
 963                   arg, version);
 964         }
 965       }
 966       return real_name;
 967     }
 968   }
 969   ShouldNotReachHere();
 970   return NULL;
 971 }
 972 
 973 void log_deprecated_flag(const char* name, bool on, AliasedLoggingFlag alf) {
 974   LogTagType tagSet[] = {alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5};
 975   // Set tagset string buffer at max size of 256, large enough for any alias tagset
 976   const int max_tagset_size = 256;
 977   int max_tagset_len = max_tagset_size - 1;
 978   char tagset_buffer[max_tagset_size];
 979   tagset_buffer[0] = '\0';
 980 
 981   // Write tag-set for aliased logging option, in string list form
 982   int max_tags = sizeof(tagSet)/sizeof(tagSet[0]);
 983   for (int i = 0; i < max_tags && tagSet[i] != LogTag::__NO_TAG; i++) {
 984     if (i > 0) {
 985       strncat(tagset_buffer, "+", max_tagset_len - strlen(tagset_buffer));
 986     }
 987     strncat(tagset_buffer, LogTag::name(tagSet[i]), max_tagset_len - strlen(tagset_buffer));
 988   }
 989   if (!alf.exactMatch) {
 990       strncat(tagset_buffer, "*", max_tagset_len - strlen(tagset_buffer));
 991   }
 992   log_warning(arguments)("-XX:%s%s is deprecated. Will use -Xlog:%s=%s instead.",
 993                          (on) ? "+" : "-",
 994                          name,
 995                          tagset_buffer,
 996                          (on) ? LogLevel::name(alf.level) : "off");
 997 }
 998 
 999 AliasedLoggingFlag Arguments::catch_logging_aliases(const char* name, bool on){
1000   for (size_t i = 0; aliased_logging_flags[i].alias_name != NULL; i++) {
1001     const AliasedLoggingFlag& alf = aliased_logging_flags[i];
1002     if (strcmp(alf.alias_name, name) == 0) {
1003       log_deprecated_flag(name, on, alf);
1004       return alf;
1005     }
1006   }
1007   AliasedLoggingFlag a = {NULL, LogLevel::Off, false, LOG_TAGS(_NO_TAG)};
1008   return a;
1009 }
1010 
1011 bool Arguments::parse_argument(const char* arg, Flag::Flags origin) {
1012 
1013   // range of acceptable characters spelled out for portability reasons
1014 #define NAME_RANGE  "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"
1015 #define BUFLEN 255
1016   char name[BUFLEN+1];
1017   char dummy;
1018   const char* real_name;
1019   bool warn_if_deprecated = true;
1020 
1021   if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
1022     AliasedLoggingFlag alf = catch_logging_aliases(name, false);
1023     if (alf.alias_name != NULL){
1024       LogConfiguration::configure_stdout(LogLevel::Off, alf.exactMatch, alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5);
1025       return true;
1026     }
1027     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1028     if (real_name == NULL) {
1029       return false;
1030     }
1031     return set_bool_flag(real_name, false, origin);
1032   }
1033   if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
1034     AliasedLoggingFlag alf = catch_logging_aliases(name, true);
1035     if (alf.alias_name != NULL){
1036       LogConfiguration::configure_stdout(alf.level, alf.exactMatch, alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5);
1037       return true;
1038     }
1039     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1040     if (real_name == NULL) {
1041       return false;
1042     }
1043     return set_bool_flag(real_name, true, origin);
1044   }
1045 
1046   char punct;
1047   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {
1048     const char* value = strchr(arg, '=') + 1;
1049     Flag* flag;
1050 
1051     // this scanf pattern matches both strings (handled here) and numbers (handled later))
1052     AliasedLoggingFlag alf = catch_logging_aliases(name, true);
1053     if (alf.alias_name != NULL) {
1054       LogConfiguration::configure_stdout(alf.level, alf.exactMatch, alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5);
1055       return true;
1056     }
1057     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1058     if (real_name == NULL) {
1059       return false;
1060     }
1061     flag = Flag::find_flag(real_name);
1062     if (flag != NULL && flag->is_ccstr()) {
1063       if (flag->ccstr_accumulates()) {
1064         return append_to_string_flag(real_name, value, origin);
1065       } else {
1066         if (value[0] == '\0') {
1067           value = NULL;
1068         }
1069         return set_string_flag(real_name, value, origin);
1070       }
1071     } else {
1072       warn_if_deprecated = false; // if arg is deprecated, we've already done warning...
1073     }
1074   }
1075 
1076   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {
1077     const char* value = strchr(arg, '=') + 1;
1078     // -XX:Foo:=xxx will reset the string flag to the given value.
1079     if (value[0] == '\0') {
1080       value = NULL;
1081     }
1082     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1083     if (real_name == NULL) {
1084       return false;
1085     }
1086     return set_string_flag(real_name, value, origin);
1087   }
1088 
1089 #define SIGNED_FP_NUMBER_RANGE "[-0123456789.eE+]"
1090 #define SIGNED_NUMBER_RANGE    "[-0123456789]"
1091 #define        NUMBER_RANGE    "[0123456789eE+-]"
1092   char value[BUFLEN + 1];
1093   char value2[BUFLEN + 1];
1094   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {
1095     // Looks like a floating-point number -- try again with more lenient format string
1096     if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {
1097       real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1098       if (real_name == NULL) {
1099         return false;
1100       }
1101       return set_fp_numeric_flag(real_name, value, origin);
1102     }
1103   }
1104 
1105 #define VALUE_RANGE "[-kmgtxKMGTX0123456789abcdefABCDEF]"
1106   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_RANGE "%c", name, value, &dummy) == 2) {
1107     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1108     if (real_name == NULL) {
1109       return false;
1110     }
1111     return set_numeric_flag(real_name, value, origin);
1112   }
1113 
1114   return false;
1115 }
1116 
1117 void Arguments::add_string(char*** bldarray, int* count, const char* arg) {
1118   assert(bldarray != NULL, "illegal argument");
1119 
1120   if (arg == NULL) {
1121     return;
1122   }
1123 
1124   int new_count = *count + 1;
1125 
1126   // expand the array and add arg to the last element
1127   if (*bldarray == NULL) {
1128     *bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtArguments);
1129   } else {
1130     *bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtArguments);
1131   }
1132   (*bldarray)[*count] = os::strdup_check_oom(arg);
1133   *count = new_count;
1134 }
1135 
1136 void Arguments::build_jvm_args(const char* arg) {
1137   add_string(&_jvm_args_array, &_num_jvm_args, arg);
1138 }
1139 
1140 void Arguments::build_jvm_flags(const char* arg) {
1141   add_string(&_jvm_flags_array, &_num_jvm_flags, arg);
1142 }
1143 
1144 // utility function to return a string that concatenates all
1145 // strings in a given char** array
1146 const char* Arguments::build_resource_string(char** args, int count) {
1147   if (args == NULL || count == 0) {
1148     return NULL;
1149   }
1150   size_t length = 0;
1151   for (int i = 0; i < count; i++) {
1152     length += strlen(args[i]) + 1; // add 1 for a space or NULL terminating character
1153   }
1154   char* s = NEW_RESOURCE_ARRAY(char, length);
1155   char* dst = s;
1156   for (int j = 0; j < count; j++) {
1157     size_t offset = strlen(args[j]) + 1; // add 1 for a space or NULL terminating character
1158     jio_snprintf(dst, length, "%s ", args[j]); // jio_snprintf will replace the last space character with NULL character
1159     dst += offset;
1160     length -= offset;
1161   }
1162   return (const char*) s;
1163 }
1164 
1165 void Arguments::print_on(outputStream* st) {
1166   st->print_cr("VM Arguments:");
1167   if (num_jvm_flags() > 0) {
1168     st->print("jvm_flags: "); print_jvm_flags_on(st);
1169     st->cr();
1170   }
1171   if (num_jvm_args() > 0) {
1172     st->print("jvm_args: "); print_jvm_args_on(st);
1173     st->cr();
1174   }
1175   st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");
1176   if (_java_class_path != NULL) {
1177     char* path = _java_class_path->value();
1178     st->print_cr("java_class_path (initial): %s", strlen(path) == 0 ? "<not set>" : path );
1179   }
1180   st->print_cr("Launcher Type: %s", _sun_java_launcher);
1181 }
1182 
1183 void Arguments::print_summary_on(outputStream* st) {
1184   // Print the command line.  Environment variables that are helpful for
1185   // reproducing the problem are written later in the hs_err file.
1186   // flags are from setting file
1187   if (num_jvm_flags() > 0) {
1188     st->print_raw("Settings File: ");
1189     print_jvm_flags_on(st);
1190     st->cr();
1191   }
1192   // args are the command line and environment variable arguments.
1193   st->print_raw("Command Line: ");
1194   if (num_jvm_args() > 0) {
1195     print_jvm_args_on(st);
1196   }
1197   // this is the classfile and any arguments to the java program
1198   if (java_command() != NULL) {
1199     st->print("%s", java_command());
1200   }
1201   st->cr();
1202 }
1203 
1204 void Arguments::print_jvm_flags_on(outputStream* st) {
1205   if (_num_jvm_flags > 0) {
1206     for (int i=0; i < _num_jvm_flags; i++) {
1207       st->print("%s ", _jvm_flags_array[i]);
1208     }
1209   }
1210 }
1211 
1212 void Arguments::print_jvm_args_on(outputStream* st) {
1213   if (_num_jvm_args > 0) {
1214     for (int i=0; i < _num_jvm_args; i++) {
1215       st->print("%s ", _jvm_args_array[i]);
1216     }
1217   }
1218 }
1219 
1220 bool Arguments::process_argument(const char* arg,
1221                                  jboolean ignore_unrecognized,
1222                                  Flag::Flags origin) {
1223   JDK_Version since = JDK_Version();
1224 
1225   if (parse_argument(arg, origin)) {
1226     return true;
1227   }
1228 
1229   // Determine if the flag has '+', '-', or '=' characters.
1230   bool has_plus_minus = (*arg == '+' || *arg == '-');
1231   const char* const argname = has_plus_minus ? arg + 1 : arg;
1232 
1233   size_t arg_len;
1234   const char* equal_sign = strchr(argname, '=');
1235   if (equal_sign == NULL) {
1236     arg_len = strlen(argname);
1237   } else {
1238     arg_len = equal_sign - argname;
1239   }
1240 
1241   // Only make the obsolete check for valid arguments.
1242   if (arg_len <= BUFLEN) {
1243     // Construct a string which consists only of the argument name without '+', '-', or '='.
1244     char stripped_argname[BUFLEN+1]; // +1 for '\0'
1245     jio_snprintf(stripped_argname, arg_len+1, "%s", argname); // +1 for '\0'
1246     if (is_obsolete_flag(stripped_argname, &since)) {
1247       char version[256];
1248       since.to_string(version, sizeof(version));
1249       warning("Ignoring option %s; support was removed in %s", stripped_argname, version);
1250       return true;
1251     }
1252 #ifndef PRODUCT
1253     else {
1254       const char* replacement;
1255       if ((replacement = removed_develop_logging_flag_name(stripped_argname)) != NULL){
1256         log_warning(arguments)("%s has been removed. Please use %s instead.",
1257                                stripped_argname,
1258                                replacement);
1259         return false;
1260       }
1261     }
1262 #endif //PRODUCT
1263   }
1264 
1265   // For locked flags, report a custom error message if available.
1266   // Otherwise, report the standard unrecognized VM option.
1267   Flag* found_flag = Flag::find_flag((const char*)argname, arg_len, true, true);
1268   if (found_flag != NULL) {
1269     char locked_message_buf[BUFLEN];
1270     Flag::MsgType msg_type = found_flag->get_locked_message(locked_message_buf, BUFLEN);
1271     if (strlen(locked_message_buf) == 0) {
1272       if (found_flag->is_bool() && !has_plus_minus) {
1273         jio_fprintf(defaultStream::error_stream(),
1274           "Missing +/- setting for VM option '%s'\n", argname);
1275       } else if (!found_flag->is_bool() && has_plus_minus) {
1276         jio_fprintf(defaultStream::error_stream(),
1277           "Unexpected +/- setting in VM option '%s'\n", argname);
1278       } else {
1279         jio_fprintf(defaultStream::error_stream(),
1280           "Improperly specified VM option '%s'\n", argname);
1281       }
1282     } else {
1283 #ifdef PRODUCT
1284       bool mismatched = ((msg_type == Flag::NOTPRODUCT_FLAG_BUT_PRODUCT_BUILD) ||
1285                          (msg_type == Flag::DEVELOPER_FLAG_BUT_PRODUCT_BUILD));
1286       if (ignore_unrecognized && mismatched) {
1287         return true;
1288       }
1289 #endif
1290       jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);
1291     }
1292   } else {
1293     if (ignore_unrecognized) {
1294       return true;
1295     }
1296     jio_fprintf(defaultStream::error_stream(),
1297                 "Unrecognized VM option '%s'\n", argname);
1298     Flag* fuzzy_matched = Flag::fuzzy_match((const char*)argname, arg_len, true);
1299     if (fuzzy_matched != NULL) {
1300       jio_fprintf(defaultStream::error_stream(),
1301                   "Did you mean '%s%s%s'? ",
1302                   (fuzzy_matched->is_bool()) ? "(+/-)" : "",
1303                   fuzzy_matched->_name,
1304                   (fuzzy_matched->is_bool()) ? "" : "=<value>");
1305     }
1306   }
1307 
1308   // allow for commandline "commenting out" options like -XX:#+Verbose
1309   return arg[0] == '#';
1310 }
1311 
1312 bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
1313   FILE* stream = fopen(file_name, "rb");
1314   if (stream == NULL) {
1315     if (should_exist) {
1316       jio_fprintf(defaultStream::error_stream(),
1317                   "Could not open settings file %s\n", file_name);
1318       return false;
1319     } else {
1320       return true;
1321     }
1322   }
1323 
1324   char token[1024];
1325   int  pos = 0;
1326 
1327   bool in_white_space = true;
1328   bool in_comment     = false;
1329   bool in_quote       = false;
1330   char quote_c        = 0;
1331   bool result         = true;
1332 
1333   int c = getc(stream);
1334   while(c != EOF && pos < (int)(sizeof(token)-1)) {
1335     if (in_white_space) {
1336       if (in_comment) {
1337         if (c == '\n') in_comment = false;
1338       } else {
1339         if (c == '#') in_comment = true;
1340         else if (!isspace(c)) {
1341           in_white_space = false;
1342           token[pos++] = c;
1343         }
1344       }
1345     } else {
1346       if (c == '\n' || (!in_quote && isspace(c))) {
1347         // token ends at newline, or at unquoted whitespace
1348         // this allows a way to include spaces in string-valued options
1349         token[pos] = '\0';
1350         logOption(token);
1351         result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
1352         build_jvm_flags(token);
1353         pos = 0;
1354         in_white_space = true;
1355         in_quote = false;
1356       } else if (!in_quote && (c == '\'' || c == '"')) {
1357         in_quote = true;
1358         quote_c = c;
1359       } else if (in_quote && (c == quote_c)) {
1360         in_quote = false;
1361       } else {
1362         token[pos++] = c;
1363       }
1364     }
1365     c = getc(stream);
1366   }
1367   if (pos > 0) {
1368     token[pos] = '\0';
1369     result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
1370     build_jvm_flags(token);
1371   }
1372   fclose(stream);
1373   return result;
1374 }
1375 
1376 //=============================================================================================================
1377 // Parsing of properties (-D)
1378 
1379 const char* Arguments::get_property(const char* key) {
1380   return PropertyList_get_value(system_properties(), key);
1381 }
1382 
1383 bool Arguments::add_property(const char* prop, PropertyWriteable writeable, PropertyInternal internal) {
1384   const char* eq = strchr(prop, '=');
1385   const char* key;
1386   const char* value = "";
1387 
1388   if (eq == NULL) {
1389     // property doesn't have a value, thus use passed string
1390     key = prop;
1391   } else {
1392     // property have a value, thus extract it and save to the
1393     // allocated string
1394     size_t key_len = eq - prop;
1395     char* tmp_key = AllocateHeap(key_len + 1, mtArguments);
1396 
1397     jio_snprintf(tmp_key, key_len + 1, "%s", prop);
1398     key = tmp_key;
1399 
1400     value = &prop[key_len + 1];
1401   }
1402 
1403   if (strcmp(key, "java.compiler") == 0) {
1404     process_java_compiler_argument(value);
1405     // Record value in Arguments, but let it get passed to Java.
1406   } else if (strcmp(key, "sun.java.launcher.is_altjvm") == 0 ||
1407              strcmp(key, "sun.java.launcher.pid") == 0) {
1408     // sun.java.launcher.is_altjvm and sun.java.launcher.pid property are
1409     // private and are processed in process_sun_java_launcher_properties();
1410     // the sun.java.launcher property is passed on to the java application
1411   } else if (strcmp(key, "sun.boot.library.path") == 0) {
1412     // append is true, writable is true, internal is false
1413     PropertyList_unique_add(&_system_properties, key, value, AppendProperty,
1414                             WriteableProperty, ExternalProperty);
1415   } else {
1416     if (strcmp(key, "sun.java.command") == 0) {
1417       char *old_java_command = _java_command;
1418       _java_command = os::strdup_check_oom(value, mtArguments);
1419       if (old_java_command != NULL) {
1420         os::free(old_java_command);
1421       }
1422     } else if (strcmp(key, "java.vendor.url.bug") == 0) {
1423       const char* old_java_vendor_url_bug = _java_vendor_url_bug;
1424       // save it in _java_vendor_url_bug, so JVM fatal error handler can access
1425       // its value without going through the property list or making a Java call.
1426       _java_vendor_url_bug = os::strdup_check_oom(value, mtArguments);
1427       if (old_java_vendor_url_bug != DEFAULT_VENDOR_URL_BUG) {
1428         assert(old_java_vendor_url_bug != NULL, "_java_vendor_url_bug is NULL");
1429         os::free((void *)old_java_vendor_url_bug);
1430       }
1431     }
1432 
1433     // Create new property and add at the end of the list
1434     PropertyList_unique_add(&_system_properties, key, value, AddProperty, writeable, internal);
1435   }
1436 
1437   if (key != prop) {
1438     // SystemProperty copy passed value, thus free previously allocated
1439     // memory
1440     FreeHeap((void *)key);
1441   }
1442 
1443   return true;
1444 }
1445 
1446 #if INCLUDE_CDS
1447 void Arguments::check_unsupported_dumping_properties() {
1448   assert(DumpSharedSpaces, "this function is only used with -Xshare:dump");
1449   const char* unsupported_properties[] = { "jdk.module.main",
1450                                            "jdk.module.limitmods",
1451                                            "jdk.module.path",
1452                                            "jdk.module.upgrade.path",
1453                                            "jdk.module.patch.0" };
1454   const char* unsupported_options[] = { "-m", // cannot use at dump time
1455                                         "--limit-modules", // ignored at dump time
1456                                         "--module-path", // ignored at dump time
1457                                         "--upgrade-module-path", // ignored at dump time
1458                                         "--patch-module" // ignored at dump time
1459                                       };
1460   assert(ARRAY_SIZE(unsupported_properties) == ARRAY_SIZE(unsupported_options), "must be");
1461   // If a vm option is found in the unsupported_options array with index less than the info_idx,
1462   // vm will exit with an error message. Otherwise, it will print an informational message if
1463   // -Xlog:cds is enabled.
1464   uint info_idx = 1;
1465   SystemProperty* sp = system_properties();
1466   while (sp != NULL) {
1467     for (uint i = 0; i < ARRAY_SIZE(unsupported_properties); i++) {
1468       if (strcmp(sp->key(), unsupported_properties[i]) == 0) {
1469         if (i < info_idx) {
1470           vm_exit_during_initialization(
1471             "Cannot use the following option when dumping the shared archive", unsupported_options[i]);
1472         } else {
1473           log_info(cds)("Info: the %s option is ignored when dumping the shared archive",
1474                         unsupported_options[i]);
1475         }
1476       }
1477     }
1478     sp = sp->next();
1479   }
1480 
1481   // Check for an exploded module build in use with -Xshare:dump.
1482   if (!has_jimage()) {
1483     vm_exit_during_initialization("Dumping the shared archive is not supported with an exploded module build");
1484   }
1485 }
1486 #endif
1487 
1488 //===========================================================================================================
1489 // Setting int/mixed/comp mode flags
1490 
1491 void Arguments::set_mode_flags(Mode mode) {
1492   // Set up default values for all flags.
1493   // If you add a flag to any of the branches below,
1494   // add a default value for it here.
1495   set_java_compiler(false);
1496   _mode                      = mode;
1497 
1498   // Ensure Agent_OnLoad has the correct initial values.
1499   // This may not be the final mode; mode may change later in onload phase.
1500   PropertyList_unique_add(&_system_properties, "java.vm.info",
1501                           VM_Version::vm_info_string(), AddProperty, UnwriteableProperty, ExternalProperty);
1502 
1503   UseInterpreter             = true;
1504   UseCompiler                = true;
1505   UseLoopCounter             = true;
1506 
1507   // Default values may be platform/compiler dependent -
1508   // use the saved values
1509   ClipInlining               = Arguments::_ClipInlining;
1510   AlwaysCompileLoopMethods   = Arguments::_AlwaysCompileLoopMethods;
1511   UseOnStackReplacement      = Arguments::_UseOnStackReplacement;
1512   BackgroundCompilation      = Arguments::_BackgroundCompilation;
1513   if (TieredCompilation) {
1514     if (FLAG_IS_DEFAULT(Tier3InvokeNotifyFreqLog)) {
1515       Tier3InvokeNotifyFreqLog = Arguments::_Tier3InvokeNotifyFreqLog;
1516     }
1517     if (FLAG_IS_DEFAULT(Tier4InvocationThreshold)) {
1518       Tier4InvocationThreshold = Arguments::_Tier4InvocationThreshold;
1519     }
1520   }
1521 
1522   // Change from defaults based on mode
1523   switch (mode) {
1524   default:
1525     ShouldNotReachHere();
1526     break;
1527   case _int:
1528     UseCompiler              = false;
1529     UseLoopCounter           = false;
1530     AlwaysCompileLoopMethods = false;
1531     UseOnStackReplacement    = false;
1532     break;
1533   case _mixed:
1534     // same as default
1535     break;
1536   case _comp:
1537     UseInterpreter           = false;
1538     BackgroundCompilation    = false;
1539     ClipInlining             = false;
1540     // Be much more aggressive in tiered mode with -Xcomp and exercise C2 more.
1541     // We will first compile a level 3 version (C1 with full profiling), then do one invocation of it and
1542     // compile a level 4 (C2) and then continue executing it.
1543     if (TieredCompilation) {
1544       Tier3InvokeNotifyFreqLog = 0;
1545       Tier4InvocationThreshold = 0;
1546     }
1547     break;
1548   }
1549 }
1550 
1551 // Conflict: required to use shared spaces (-Xshare:on), but
1552 // incompatible command line options were chosen.
1553 static void no_shared_spaces(const char* message) {
1554   if (RequireSharedSpaces) {
1555     jio_fprintf(defaultStream::error_stream(),
1556       "Class data sharing is inconsistent with other specified options.\n");
1557     vm_exit_during_initialization("Unable to use shared archive.", message);
1558   } else {
1559     FLAG_SET_DEFAULT(UseSharedSpaces, false);
1560   }
1561 }
1562 
1563 // Returns threshold scaled with the value of scale.
1564 // If scale < 0.0, threshold is returned without scaling.
1565 intx Arguments::scaled_compile_threshold(intx threshold, double scale) {
1566   if (scale == 1.0 || scale < 0.0) {
1567     return threshold;
1568   } else {
1569     return (intx)(threshold * scale);
1570   }
1571 }
1572 
1573 // Returns freq_log scaled with the value of scale.
1574 // Returned values are in the range of [0, InvocationCounter::number_of_count_bits + 1].
1575 // If scale < 0.0, freq_log is returned without scaling.
1576 intx Arguments::scaled_freq_log(intx freq_log, double scale) {
1577   // Check if scaling is necessary or if negative value was specified.
1578   if (scale == 1.0 || scale < 0.0) {
1579     return freq_log;
1580   }
1581   // Check values to avoid calculating log2 of 0.
1582   if (scale == 0.0 || freq_log == 0) {
1583     return 0;
1584   }
1585   // Determine the maximum notification frequency value currently supported.
1586   // The largest mask value that the interpreter/C1 can handle is
1587   // of length InvocationCounter::number_of_count_bits. Mask values are always
1588   // one bit shorter then the value of the notification frequency. Set
1589   // max_freq_bits accordingly.
1590   intx max_freq_bits = InvocationCounter::number_of_count_bits + 1;
1591   intx scaled_freq = scaled_compile_threshold((intx)1 << freq_log, scale);
1592   if (scaled_freq == 0) {
1593     // Return 0 right away to avoid calculating log2 of 0.
1594     return 0;
1595   } else if (scaled_freq > nth_bit(max_freq_bits)) {
1596     return max_freq_bits;
1597   } else {
1598     return log2_intptr(scaled_freq);
1599   }
1600 }
1601 
1602 void Arguments::set_tiered_flags() {
1603   // With tiered, set default policy to AdvancedThresholdPolicy, which is 3.
1604   if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {
1605     FLAG_SET_DEFAULT(CompilationPolicyChoice, 3);
1606   }
1607   if (CompilationPolicyChoice < 2) {
1608     vm_exit_during_initialization(
1609       "Incompatible compilation policy selected", NULL);
1610   }
1611   // Increase the code cache size - tiered compiles a lot more.
1612   if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1613     FLAG_SET_ERGO(uintx, ReservedCodeCacheSize,
1614                   MIN2(CODE_CACHE_DEFAULT_LIMIT, ReservedCodeCacheSize * 5));
1615   }
1616   // Enable SegmentedCodeCache if TieredCompilation is enabled and ReservedCodeCacheSize >= 240M
1617   if (FLAG_IS_DEFAULT(SegmentedCodeCache) && ReservedCodeCacheSize >= 240*M) {
1618     FLAG_SET_ERGO(bool, SegmentedCodeCache, true);
1619   }
1620   if (!UseInterpreter) { // -Xcomp
1621     Tier3InvokeNotifyFreqLog = 0;
1622     Tier4InvocationThreshold = 0;
1623   }
1624 
1625   if (CompileThresholdScaling < 0) {
1626     vm_exit_during_initialization("Negative value specified for CompileThresholdScaling", NULL);
1627   }
1628 
1629   // Scale tiered compilation thresholds.
1630   // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves compilation thresholds unchanged.
1631   if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
1632     FLAG_SET_ERGO(intx, Tier0InvokeNotifyFreqLog, scaled_freq_log(Tier0InvokeNotifyFreqLog));
1633     FLAG_SET_ERGO(intx, Tier0BackedgeNotifyFreqLog, scaled_freq_log(Tier0BackedgeNotifyFreqLog));
1634 
1635     FLAG_SET_ERGO(intx, Tier3InvocationThreshold, scaled_compile_threshold(Tier3InvocationThreshold));
1636     FLAG_SET_ERGO(intx, Tier3MinInvocationThreshold, scaled_compile_threshold(Tier3MinInvocationThreshold));
1637     FLAG_SET_ERGO(intx, Tier3CompileThreshold, scaled_compile_threshold(Tier3CompileThreshold));
1638     FLAG_SET_ERGO(intx, Tier3BackEdgeThreshold, scaled_compile_threshold(Tier3BackEdgeThreshold));
1639 
1640     // Tier2{Invocation,MinInvocation,Compile,Backedge}Threshold should be scaled here
1641     // once these thresholds become supported.
1642 
1643     FLAG_SET_ERGO(intx, Tier2InvokeNotifyFreqLog, scaled_freq_log(Tier2InvokeNotifyFreqLog));
1644     FLAG_SET_ERGO(intx, Tier2BackedgeNotifyFreqLog, scaled_freq_log(Tier2BackedgeNotifyFreqLog));
1645 
1646     FLAG_SET_ERGO(intx, Tier3InvokeNotifyFreqLog, scaled_freq_log(Tier3InvokeNotifyFreqLog));
1647     FLAG_SET_ERGO(intx, Tier3BackedgeNotifyFreqLog, scaled_freq_log(Tier3BackedgeNotifyFreqLog));
1648 
1649     FLAG_SET_ERGO(intx, Tier23InlineeNotifyFreqLog, scaled_freq_log(Tier23InlineeNotifyFreqLog));
1650 
1651     FLAG_SET_ERGO(intx, Tier4InvocationThreshold, scaled_compile_threshold(Tier4InvocationThreshold));
1652     FLAG_SET_ERGO(intx, Tier4MinInvocationThreshold, scaled_compile_threshold(Tier4MinInvocationThreshold));
1653     FLAG_SET_ERGO(intx, Tier4CompileThreshold, scaled_compile_threshold(Tier4CompileThreshold));
1654     FLAG_SET_ERGO(intx, Tier4BackEdgeThreshold, scaled_compile_threshold(Tier4BackEdgeThreshold));
1655   }
1656 }
1657 
1658 void set_object_alignment() {
1659   // Object alignment.
1660   assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
1661   MinObjAlignmentInBytes     = ObjectAlignmentInBytes;
1662   assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
1663   MinObjAlignment            = MinObjAlignmentInBytes / HeapWordSize;
1664   assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
1665   MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
1666 
1667   LogMinObjAlignmentInBytes  = exact_log2(ObjectAlignmentInBytes);
1668   LogMinObjAlignment         = LogMinObjAlignmentInBytes - LogHeapWordSize;
1669 
1670   // Oop encoding heap max
1671   OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
1672 
1673   if (SurvivorAlignmentInBytes == 0) {
1674     SurvivorAlignmentInBytes = ObjectAlignmentInBytes;
1675   }
1676 }
1677 
1678 size_t Arguments::max_heap_for_compressed_oops() {
1679   // Avoid sign flip.
1680   assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
1681   // We need to fit both the NULL page and the heap into the memory budget, while
1682   // keeping alignment constraints of the heap. To guarantee the latter, as the
1683   // NULL page is located before the heap, we pad the NULL page to the conservative
1684   // maximum alignment that the GC may ever impose upon the heap.
1685   size_t displacement_due_to_null_page = align_up((size_t)os::vm_page_size(),
1686                                                   _conservative_max_heap_alignment);
1687 
1688   LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
1689   NOT_LP64(ShouldNotReachHere(); return 0);
1690 }
1691 
1692 void Arguments::set_use_compressed_oops() {
1693 #ifndef ZERO
1694 #ifdef _LP64
1695   // MaxHeapSize is not set up properly at this point, but
1696   // the only value that can override MaxHeapSize if we are
1697   // to use UseCompressedOops is InitialHeapSize.
1698   size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);
1699 
1700   if (max_heap_size <= max_heap_for_compressed_oops()) {
1701 #if !defined(COMPILER1) || defined(TIERED)
1702     if (FLAG_IS_DEFAULT(UseCompressedOops)) {
1703       FLAG_SET_ERGO(bool, UseCompressedOops, true);
1704     }
1705 #endif
1706   } else {
1707     if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
1708       warning("Max heap size too large for Compressed Oops");
1709       FLAG_SET_DEFAULT(UseCompressedOops, false);
1710       FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1711     }
1712   }
1713 #endif // _LP64
1714 #endif // ZERO
1715 }
1716 
1717 
1718 // NOTE: set_use_compressed_klass_ptrs() must be called after calling
1719 // set_use_compressed_oops().
1720 void Arguments::set_use_compressed_klass_ptrs() {
1721 #ifndef ZERO
1722 #ifdef _LP64
1723   // UseCompressedOops must be on for UseCompressedClassPointers to be on.
1724   if (!UseCompressedOops) {
1725     if (UseCompressedClassPointers) {
1726       warning("UseCompressedClassPointers requires UseCompressedOops");
1727     }
1728     FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1729   } else {
1730     // Turn on UseCompressedClassPointers too
1731     if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
1732       FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);
1733     }
1734     // Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
1735     if (UseCompressedClassPointers) {
1736       if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
1737         warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
1738         FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1739       }
1740     }
1741   }
1742 #endif // _LP64
1743 #endif // !ZERO
1744 }
1745 
1746 void Arguments::set_conservative_max_heap_alignment() {
1747   // The conservative maximum required alignment for the heap is the maximum of
1748   // the alignments imposed by several sources: any requirements from the heap
1749   // itself, the collector policy and the maximum page size we may run the VM
1750   // with.
1751   size_t heap_alignment = GCConfig::arguments()->conservative_max_heap_alignment();
1752   _conservative_max_heap_alignment = MAX4(heap_alignment,
1753                                           (size_t)os::vm_allocation_granularity(),
1754                                           os::max_page_size(),
1755                                           CollectorPolicy::compute_heap_alignment());
1756 }
1757 
1758 #ifdef TIERED
1759 bool Arguments::compilation_mode_selected() {
1760  return !FLAG_IS_DEFAULT(TieredCompilation) || !FLAG_IS_DEFAULT(TieredStopAtLevel) ||
1761         !FLAG_IS_DEFAULT(UseAOT) JVMCI_ONLY(|| !FLAG_IS_DEFAULT(EnableJVMCI) || !FLAG_IS_DEFAULT(UseJVMCICompiler));
1762 
1763 }
1764 
1765 void Arguments::select_compilation_mode_ergonomically() {
1766 #if defined(_WINDOWS) && !defined(_LP64)
1767   if (FLAG_IS_DEFAULT(NeverActAsServerClassMachine)) {
1768     FLAG_SET_ERGO(bool, NeverActAsServerClassMachine, true);
1769   }
1770 #endif
1771   if (NeverActAsServerClassMachine) {
1772     set_client_compilation_mode();
1773   }
1774 }
1775 #endif //TIERED
1776 
1777 #if INCLUDE_JVMCI
1778 void Arguments::set_jvmci_specific_flags() {
1779   if (UseJVMCICompiler) {
1780     if (FLAG_IS_DEFAULT(TypeProfileWidth)) {
1781       FLAG_SET_DEFAULT(TypeProfileWidth, 8);
1782     }
1783     if (FLAG_IS_DEFAULT(OnStackReplacePercentage)) {
1784       FLAG_SET_DEFAULT(OnStackReplacePercentage, 933);
1785     }
1786     if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1787       FLAG_SET_DEFAULT(ReservedCodeCacheSize, 64*M);
1788     }
1789     if (FLAG_IS_DEFAULT(InitialCodeCacheSize)) {
1790       FLAG_SET_DEFAULT(InitialCodeCacheSize, 16*M);
1791     }
1792     if (FLAG_IS_DEFAULT(MetaspaceSize)) {
1793       FLAG_SET_DEFAULT(MetaspaceSize, 12*M);
1794     }
1795     if (FLAG_IS_DEFAULT(NewSizeThreadIncrease)) {
1796       FLAG_SET_DEFAULT(NewSizeThreadIncrease, 4*K);
1797     }
1798     if (TieredStopAtLevel != CompLevel_full_optimization) {
1799       // Currently JVMCI compiler can only work at the full optimization level
1800       warning("forcing TieredStopAtLevel to full optimization because JVMCI is enabled");
1801       TieredStopAtLevel = CompLevel_full_optimization;
1802     }
1803     if (FLAG_IS_DEFAULT(TypeProfileLevel)) {
1804       FLAG_SET_DEFAULT(TypeProfileLevel, 0);
1805     }
1806   }
1807 }
1808 #endif
1809 
1810 jint Arguments::set_ergonomics_flags() {
1811 #ifdef TIERED
1812   if (!compilation_mode_selected()) {
1813     select_compilation_mode_ergonomically();
1814   }
1815 #endif
1816 
1817   GCConfig::initialize();
1818 
1819 #if COMPILER2_OR_JVMCI
1820   // Shared spaces work fine with other GCs but causes bytecode rewriting
1821   // to be disabled, which hurts interpreter performance and decreases
1822   // server performance.  When -server is specified, keep the default off
1823   // unless it is asked for.  Future work: either add bytecode rewriting
1824   // at link time, or rewrite bytecodes in non-shared methods.
1825   if (is_server_compilation_mode_vm() && !DumpSharedSpaces && !RequireSharedSpaces &&
1826       (FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {
1827     no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");
1828   }
1829 #endif
1830 
1831 #if defined(IA32)
1832   // Only server compiler can optimize safepoints well enough.
1833   if (!is_server_compilation_mode_vm()) {
1834     FLAG_SET_ERGO_IF_DEFAULT(bool, ThreadLocalHandshakes, false);
1835   }
1836 #endif
1837 
1838   set_conservative_max_heap_alignment();
1839 
1840 #ifndef ZERO
1841 #ifdef _LP64
1842   set_use_compressed_oops();
1843 
1844   // set_use_compressed_klass_ptrs() must be called after calling
1845   // set_use_compressed_oops().
1846   set_use_compressed_klass_ptrs();
1847 
1848   // Also checks that certain machines are slower with compressed oops
1849   // in vm_version initialization code.
1850 #endif // _LP64
1851 #endif // !ZERO
1852 
1853   return JNI_OK;
1854 }
1855 
1856 julong Arguments::limit_by_allocatable_memory(julong limit) {
1857   julong max_allocatable;
1858   julong result = limit;
1859   if (os::has_allocatable_memory_limit(&max_allocatable)) {
1860     result = MIN2(result, max_allocatable / MaxVirtMemFraction);
1861   }
1862   return result;
1863 }
1864 
1865 // Use static initialization to get the default before parsing
1866 static const size_t DefaultHeapBaseMinAddress = HeapBaseMinAddress;
1867 
1868 void Arguments::set_heap_size() {
1869   julong phys_mem =
1870     FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
1871                             : (julong)MaxRAM;
1872 
1873   // Convert deprecated flags
1874   if (FLAG_IS_DEFAULT(MaxRAMPercentage) &&
1875       !FLAG_IS_DEFAULT(MaxRAMFraction))
1876     MaxRAMPercentage = 100.0 / MaxRAMFraction;
1877 
1878   if (FLAG_IS_DEFAULT(MinRAMPercentage) &&
1879       !FLAG_IS_DEFAULT(MinRAMFraction))
1880     MinRAMPercentage = 100.0 / MinRAMFraction;
1881 
1882   if (FLAG_IS_DEFAULT(InitialRAMPercentage) &&
1883       !FLAG_IS_DEFAULT(InitialRAMFraction))
1884     InitialRAMPercentage = 100.0 / InitialRAMFraction;
1885 
1886   // If the maximum heap size has not been set with -Xmx,
1887   // then set it as fraction of the size of physical memory,
1888   // respecting the maximum and minimum sizes of the heap.
1889   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1890     julong reasonable_max = (julong)((phys_mem * MaxRAMPercentage) / 100);
1891     const julong reasonable_min = (julong)((phys_mem * MinRAMPercentage) / 100);
1892     if (reasonable_min < MaxHeapSize) {
1893       // Small physical memory, so use a minimum fraction of it for the heap
1894       reasonable_max = reasonable_min;
1895     } else {
1896       // Not-small physical memory, so require a heap at least
1897       // as large as MaxHeapSize
1898       reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
1899     }
1900 
1901     if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
1902       // Limit the heap size to ErgoHeapSizeLimit
1903       reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
1904     }
1905     if (UseCompressedOops) {
1906       // Limit the heap size to the maximum possible when using compressed oops
1907       julong max_coop_heap = (julong)max_heap_for_compressed_oops();
1908 
1909       // HeapBaseMinAddress can be greater than default but not less than.
1910       if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
1911         if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
1912           // matches compressed oops printing flags
1913           log_debug(gc, heap, coops)("HeapBaseMinAddress must be at least " SIZE_FORMAT
1914                                      " (" SIZE_FORMAT "G) which is greater than value given " SIZE_FORMAT,
1915                                      DefaultHeapBaseMinAddress,
1916                                      DefaultHeapBaseMinAddress/G,
1917                                      HeapBaseMinAddress);
1918           FLAG_SET_ERGO(size_t, HeapBaseMinAddress, DefaultHeapBaseMinAddress);
1919         }
1920       }
1921 
1922       if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
1923         // Heap should be above HeapBaseMinAddress to get zero based compressed oops
1924         // but it should be not less than default MaxHeapSize.
1925         max_coop_heap -= HeapBaseMinAddress;
1926       }
1927       reasonable_max = MIN2(reasonable_max, max_coop_heap);
1928     }
1929     reasonable_max = limit_by_allocatable_memory(reasonable_max);
1930 
1931     if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
1932       // An initial heap size was specified on the command line,
1933       // so be sure that the maximum size is consistent.  Done
1934       // after call to limit_by_allocatable_memory because that
1935       // method might reduce the allocation size.
1936       reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
1937     }
1938 
1939     log_trace(gc, heap)("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
1940     FLAG_SET_ERGO(size_t, MaxHeapSize, (size_t)reasonable_max);
1941   }
1942 
1943   // If the minimum or initial heap_size have not been set or requested to be set
1944   // ergonomically, set them accordingly.
1945   if (InitialHeapSize == 0 || min_heap_size() == 0) {
1946     julong reasonable_minimum = (julong)(OldSize + NewSize);
1947 
1948     reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
1949 
1950     reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
1951 
1952     if (InitialHeapSize == 0) {
1953       julong reasonable_initial = (julong)((phys_mem * InitialRAMPercentage) / 100);
1954 
1955       reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());
1956       reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
1957 
1958       reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
1959 
1960       log_trace(gc, heap)("  Initial heap size " SIZE_FORMAT, (size_t)reasonable_initial);
1961       FLAG_SET_ERGO(size_t, InitialHeapSize, (size_t)reasonable_initial);
1962     }
1963     // If the minimum heap size has not been set (via -Xms),
1964     // synchronize with InitialHeapSize to avoid errors with the default value.
1965     if (min_heap_size() == 0) {
1966       set_min_heap_size(MIN2((size_t)reasonable_minimum, InitialHeapSize));
1967       log_trace(gc, heap)("  Minimum heap size " SIZE_FORMAT, min_heap_size());
1968     }
1969   }
1970 }
1971 
1972 // This option inspects the machine and attempts to set various
1973 // parameters to be optimal for long-running, memory allocation
1974 // intensive jobs.  It is intended for machines with large
1975 // amounts of cpu and memory.
1976 jint Arguments::set_aggressive_heap_flags() {
1977   // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
1978   // VM, but we may not be able to represent the total physical memory
1979   // available (like having 8gb of memory on a box but using a 32bit VM).
1980   // Thus, we need to make sure we're using a julong for intermediate
1981   // calculations.
1982   julong initHeapSize;
1983   julong total_memory = os::physical_memory();
1984 
1985   if (total_memory < (julong) 256 * M) {
1986     jio_fprintf(defaultStream::error_stream(),
1987             "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
1988     vm_exit(1);
1989   }
1990 
1991   // The heap size is half of available memory, or (at most)
1992   // all of possible memory less 160mb (leaving room for the OS
1993   // when using ISM).  This is the maximum; because adaptive sizing
1994   // is turned on below, the actual space used may be smaller.
1995 
1996   initHeapSize = MIN2(total_memory / (julong) 2,
1997           total_memory - (julong) 160 * M);
1998 
1999   initHeapSize = limit_by_allocatable_memory(initHeapSize);
2000 
2001   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
2002     if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, initHeapSize) != Flag::SUCCESS) {
2003       return JNI_EINVAL;
2004     }
2005     if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, initHeapSize) != Flag::SUCCESS) {
2006       return JNI_EINVAL;
2007     }
2008     // Currently the minimum size and the initial heap sizes are the same.
2009     set_min_heap_size(initHeapSize);
2010   }
2011   if (FLAG_IS_DEFAULT(NewSize)) {
2012     // Make the young generation 3/8ths of the total heap.
2013     if (FLAG_SET_CMDLINE(size_t, NewSize,
2014             ((julong) MaxHeapSize / (julong) 8) * (julong) 3) != Flag::SUCCESS) {
2015       return JNI_EINVAL;
2016     }
2017     if (FLAG_SET_CMDLINE(size_t, MaxNewSize, NewSize) != Flag::SUCCESS) {
2018       return JNI_EINVAL;
2019     }
2020   }
2021 
2022 #if !defined(_ALLBSD_SOURCE) && !defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
2023   FLAG_SET_DEFAULT(UseLargePages, true);
2024 #endif
2025 
2026   // Increase some data structure sizes for efficiency
2027   if (FLAG_SET_CMDLINE(size_t, BaseFootPrintEstimate, MaxHeapSize) != Flag::SUCCESS) {
2028     return JNI_EINVAL;
2029   }
2030   if (FLAG_SET_CMDLINE(bool, ResizeTLAB, false) != Flag::SUCCESS) {
2031     return JNI_EINVAL;
2032   }
2033   if (FLAG_SET_CMDLINE(size_t, TLABSize, 256 * K) != Flag::SUCCESS) {
2034     return JNI_EINVAL;
2035   }
2036 
2037   // See the OldPLABSize comment below, but replace 'after promotion'
2038   // with 'after copying'.  YoungPLABSize is the size of the survivor
2039   // space per-gc-thread buffers.  The default is 4kw.
2040   if (FLAG_SET_CMDLINE(size_t, YoungPLABSize, 256 * K) != Flag::SUCCESS) { // Note: this is in words
2041     return JNI_EINVAL;
2042   }
2043 
2044   // OldPLABSize is the size of the buffers in the old gen that
2045   // UseParallelGC uses to promote live data that doesn't fit in the
2046   // survivor spaces.  At any given time, there's one for each gc thread.
2047   // The default size is 1kw. These buffers are rarely used, since the
2048   // survivor spaces are usually big enough.  For specjbb, however, there
2049   // are occasions when there's lots of live data in the young gen
2050   // and we end up promoting some of it.  We don't have a definite
2051   // explanation for why bumping OldPLABSize helps, but the theory
2052   // is that a bigger PLAB results in retaining something like the
2053   // original allocation order after promotion, which improves mutator
2054   // locality.  A minor effect may be that larger PLABs reduce the
2055   // number of PLAB allocation events during gc.  The value of 8kw
2056   // was arrived at by experimenting with specjbb.
2057   if (FLAG_SET_CMDLINE(size_t, OldPLABSize, 8 * K) != Flag::SUCCESS) { // Note: this is in words
2058     return JNI_EINVAL;
2059   }
2060 
2061   // Enable parallel GC and adaptive generation sizing
2062   if (FLAG_SET_CMDLINE(bool, UseParallelGC, true) != Flag::SUCCESS) {
2063     return JNI_EINVAL;
2064   }
2065 
2066   // Encourage steady state memory management
2067   if (FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100) != Flag::SUCCESS) {
2068     return JNI_EINVAL;
2069   }
2070 
2071   // This appears to improve mutator locality
2072   if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
2073     return JNI_EINVAL;
2074   }
2075 
2076   // Get around early Solaris scheduling bug
2077   // (affinity vs other jobs on system)
2078   // but disallow DR and offlining (5008695).
2079   if (FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true) != Flag::SUCCESS) {
2080     return JNI_EINVAL;
2081   }
2082 
2083   return JNI_OK;
2084 }
2085 
2086 // This must be called after ergonomics.
2087 void Arguments::set_bytecode_flags() {
2088   if (!RewriteBytecodes) {
2089     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
2090   }
2091 }
2092 
2093 // Aggressive optimization flags  -XX:+AggressiveOpts
2094 jint Arguments::set_aggressive_opts_flags() {
2095 #ifdef COMPILER2
2096   if (AggressiveUnboxing) {
2097     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
2098       FLAG_SET_DEFAULT(EliminateAutoBox, true);
2099     } else if (!EliminateAutoBox) {
2100       // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
2101       AggressiveUnboxing = false;
2102     }
2103     if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
2104       FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
2105     } else if (!DoEscapeAnalysis) {
2106       // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
2107       AggressiveUnboxing = false;
2108     }
2109   }
2110   if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
2111     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
2112       FLAG_SET_DEFAULT(EliminateAutoBox, true);
2113     }
2114     if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
2115       FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
2116     }
2117 
2118     // Feed the cache size setting into the JDK
2119     char buffer[1024];
2120     jio_snprintf(buffer, 1024, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
2121     if (!add_property(buffer)) {
2122       return JNI_ENOMEM;
2123     }
2124   }
2125   if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
2126     FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
2127   }
2128 #endif
2129 
2130   if (AggressiveOpts) {
2131 // Sample flag setting code
2132 //    if (FLAG_IS_DEFAULT(EliminateZeroing)) {
2133 //      FLAG_SET_DEFAULT(EliminateZeroing, true);
2134 //    }
2135   }
2136 
2137   return JNI_OK;
2138 }
2139 
2140 //===========================================================================================================
2141 // Parsing of java.compiler property
2142 
2143 void Arguments::process_java_compiler_argument(const char* arg) {
2144   // For backwards compatibility, Djava.compiler=NONE or ""
2145   // causes us to switch to -Xint mode UNLESS -Xdebug
2146   // is also specified.
2147   if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
2148     set_java_compiler(true);    // "-Djava.compiler[=...]" most recently seen.
2149   }
2150 }
2151 
2152 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
2153   _sun_java_launcher = os::strdup_check_oom(launcher);
2154 }
2155 
2156 bool Arguments::created_by_java_launcher() {
2157   assert(_sun_java_launcher != NULL, "property must have value");
2158   return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
2159 }
2160 
2161 bool Arguments::sun_java_launcher_is_altjvm() {
2162   return _sun_java_launcher_is_altjvm;
2163 }
2164 
2165 //===========================================================================================================
2166 // Parsing of main arguments
2167 
2168 #if INCLUDE_JVMCI
2169 // Check consistency of jvmci vm argument settings.
2170 bool Arguments::check_jvmci_args_consistency() {
2171    return JVMCIGlobals::check_jvmci_flags_are_consistent();
2172 }
2173 #endif //INCLUDE_JVMCI
2174 
2175 // Check the consistency of vm_init_args
2176 bool Arguments::check_vm_args_consistency() {
2177   // Method for adding checks for flag consistency.
2178   // The intent is to warn the user of all possible conflicts,
2179   // before returning an error.
2180   // Note: Needs platform-dependent factoring.
2181   bool status = true;
2182 
2183   if (TLABRefillWasteFraction == 0) {
2184     jio_fprintf(defaultStream::error_stream(),
2185                 "TLABRefillWasteFraction should be a denominator, "
2186                 "not " SIZE_FORMAT "\n",
2187                 TLABRefillWasteFraction);
2188     status = false;
2189   }
2190 
2191   if (PrintNMTStatistics) {
2192 #if INCLUDE_NMT
2193     if (MemTracker::tracking_level() == NMT_off) {
2194 #endif // INCLUDE_NMT
2195       warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
2196       PrintNMTStatistics = false;
2197 #if INCLUDE_NMT
2198     }
2199 #endif
2200   }
2201 
2202 #if INCLUDE_JVMCI
2203   status = status && check_jvmci_args_consistency();
2204 
2205   if (EnableJVMCI) {
2206     PropertyList_unique_add(&_system_properties, "jdk.internal.vm.ci.enabled", "true",
2207         AddProperty, UnwriteableProperty, InternalProperty);
2208 
2209     if (!ScavengeRootsInCode) {
2210       warning("forcing ScavengeRootsInCode non-zero because JVMCI is enabled");
2211       ScavengeRootsInCode = 1;
2212     }
2213   }
2214 #endif
2215 
2216   // Check lower bounds of the code cache
2217   // Template Interpreter code is approximately 3X larger in debug builds.
2218   uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
2219   if (ReservedCodeCacheSize < InitialCodeCacheSize) {
2220     jio_fprintf(defaultStream::error_stream(),
2221                 "Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",
2222                 ReservedCodeCacheSize/K, InitialCodeCacheSize/K);
2223     status = false;
2224   } else if (ReservedCodeCacheSize < min_code_cache_size) {
2225     jio_fprintf(defaultStream::error_stream(),
2226                 "Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,
2227                 min_code_cache_size/K);
2228     status = false;
2229   } else if (ReservedCodeCacheSize > CODE_CACHE_SIZE_LIMIT) {
2230     // Code cache size larger than CODE_CACHE_SIZE_LIMIT is not supported.
2231     jio_fprintf(defaultStream::error_stream(),
2232                 "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,
2233                 CODE_CACHE_SIZE_LIMIT/M);
2234     status = false;
2235   } else if (NonNMethodCodeHeapSize < min_code_cache_size) {
2236     jio_fprintf(defaultStream::error_stream(),
2237                 "Invalid NonNMethodCodeHeapSize=%dK. Must be at least %uK.\n", NonNMethodCodeHeapSize/K,
2238                 min_code_cache_size/K);
2239     status = false;
2240   }
2241 
2242 #ifdef _LP64
2243   if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {
2244     warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");
2245   }
2246 #endif
2247 
2248 #ifndef SUPPORT_RESERVED_STACK_AREA
2249   if (StackReservedPages != 0) {
2250     FLAG_SET_CMDLINE(intx, StackReservedPages, 0);
2251     warning("Reserved Stack Area not supported on this platform");
2252   }
2253 #endif
2254 
2255   if (BackgroundCompilation && (CompileTheWorld || ReplayCompiles)) {
2256     if (!FLAG_IS_DEFAULT(BackgroundCompilation)) {
2257       warning("BackgroundCompilation disabled due to CompileTheWorld or ReplayCompiles options.");
2258     }
2259     FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
2260   }
2261   if (UseCompiler && is_interpreter_only()) {
2262     if (!FLAG_IS_DEFAULT(UseCompiler)) {
2263       warning("UseCompiler disabled due to -Xint.");
2264     }
2265     FLAG_SET_CMDLINE(bool, UseCompiler, false);
2266   }
2267 #ifdef COMPILER2
2268   if (PostLoopMultiversioning && !RangeCheckElimination) {
2269     if (!FLAG_IS_DEFAULT(PostLoopMultiversioning)) {
2270       warning("PostLoopMultiversioning disabled because RangeCheckElimination is disabled.");
2271     }
2272     FLAG_SET_CMDLINE(bool, PostLoopMultiversioning, false);
2273   }
2274   if (UseCountedLoopSafepoints && LoopStripMiningIter == 0) {
2275     if (!FLAG_IS_DEFAULT(UseCountedLoopSafepoints) || !FLAG_IS_DEFAULT(LoopStripMiningIter)) {
2276       warning("When counted loop safepoints are enabled, LoopStripMiningIter must be at least 1 (a safepoint every 1 iteration): setting it to 1");
2277     }
2278     LoopStripMiningIter = 1;
2279   } else if (!UseCountedLoopSafepoints && LoopStripMiningIter > 0) {
2280     if (!FLAG_IS_DEFAULT(UseCountedLoopSafepoints) || !FLAG_IS_DEFAULT(LoopStripMiningIter)) {
2281       warning("Disabling counted safepoints implies no loop strip mining: setting LoopStripMiningIter to 0");
2282     }
2283     LoopStripMiningIter = 0;
2284   }
2285 #endif
2286   if (!FLAG_IS_DEFAULT(AllocateHeapAt)) {
2287     if ((UseNUMAInterleaving && !FLAG_IS_DEFAULT(UseNUMAInterleaving)) || (UseNUMA && !FLAG_IS_DEFAULT(UseNUMA))) {
2288       log_warning(arguments) ("NUMA support for Heap depends on the file system when AllocateHeapAt option is used.\n");
2289     }
2290   }
2291   return status;
2292 }
2293 
2294 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
2295   const char* option_type) {
2296   if (ignore) return false;
2297 
2298   const char* spacer = " ";
2299   if (option_type == NULL) {
2300     option_type = ++spacer; // Set both to the empty string.
2301   }
2302 
2303   if (os::obsolete_option(option)) {
2304     jio_fprintf(defaultStream::error_stream(),
2305                 "Obsolete %s%soption: %s\n", option_type, spacer,
2306       option->optionString);
2307     return false;
2308   } else {
2309     jio_fprintf(defaultStream::error_stream(),
2310                 "Unrecognized %s%soption: %s\n", option_type, spacer,
2311       option->optionString);
2312     return true;
2313   }
2314 }
2315 
2316 static const char* user_assertion_options[] = {
2317   "-da", "-ea", "-disableassertions", "-enableassertions", 0
2318 };
2319 
2320 static const char* system_assertion_options[] = {
2321   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
2322 };
2323 
2324 bool Arguments::parse_uintx(const char* value,
2325                             uintx* uintx_arg,
2326                             uintx min_size) {
2327 
2328   // Check the sign first since atojulong() parses only unsigned values.
2329   bool value_is_positive = !(*value == '-');
2330 
2331   if (value_is_positive) {
2332     julong n;
2333     bool good_return = atojulong(value, &n);
2334     if (good_return) {
2335       bool above_minimum = n >= min_size;
2336       bool value_is_too_large = n > max_uintx;
2337 
2338       if (above_minimum && !value_is_too_large) {
2339         *uintx_arg = n;
2340         return true;
2341       }
2342     }
2343   }
2344   return false;
2345 }
2346 
2347 unsigned int addreads_count = 0;
2348 unsigned int addexports_count = 0;
2349 unsigned int addopens_count = 0;
2350 unsigned int addmods_count = 0;
2351 unsigned int patch_mod_count = 0;
2352 
2353 bool Arguments::create_property(const char* prop_name, const char* prop_value, PropertyInternal internal) {
2354   size_t prop_len = strlen(prop_name) + strlen(prop_value) + 2;
2355   char* property = AllocateHeap(prop_len, mtArguments);
2356   int ret = jio_snprintf(property, prop_len, "%s=%s", prop_name, prop_value);
2357   if (ret < 0 || ret >= (int)prop_len) {
2358     FreeHeap(property);
2359     return false;
2360   }
2361   bool added = add_property(property, UnwriteableProperty, internal);
2362   FreeHeap(property);
2363   return added;
2364 }
2365 
2366 bool Arguments::create_numbered_property(const char* prop_base_name, const char* prop_value, unsigned int count) {
2367   const unsigned int props_count_limit = 1000;
2368   const int max_digits = 3;
2369   const int extra_symbols_count = 3; // includes '.', '=', '\0'
2370 
2371   // Make sure count is < props_count_limit. Otherwise, memory allocation will be too small.
2372   if (count < props_count_limit) {
2373     size_t prop_len = strlen(prop_base_name) + strlen(prop_value) + max_digits + extra_symbols_count;
2374     char* property = AllocateHeap(prop_len, mtArguments);
2375     int ret = jio_snprintf(property, prop_len, "%s.%d=%s", prop_base_name, count, prop_value);
2376     if (ret < 0 || ret >= (int)prop_len) {
2377       FreeHeap(property);
2378       jio_fprintf(defaultStream::error_stream(), "Failed to create property %s.%d=%s\n", prop_base_name, count, prop_value);
2379       return false;
2380     }
2381     bool added = add_property(property, UnwriteableProperty, InternalProperty);
2382     FreeHeap(property);
2383     return added;
2384   }
2385 
2386   jio_fprintf(defaultStream::error_stream(), "Property count limit exceeded: %s, limit=%d\n", prop_base_name, props_count_limit);
2387   return false;
2388 }
2389 
2390 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2391                                                   julong* long_arg,
2392                                                   julong min_size,
2393                                                   julong max_size) {
2394   if (!atojulong(s, long_arg)) return arg_unreadable;
2395   return check_memory_size(*long_arg, min_size, max_size);
2396 }
2397 
2398 // Parse JavaVMInitArgs structure
2399 
2400 jint Arguments::parse_vm_init_args(const JavaVMInitArgs *java_tool_options_args,
2401                                    const JavaVMInitArgs *java_options_args,
2402                                    const JavaVMInitArgs *cmd_line_args) {
2403   bool patch_mod_javabase = false;
2404 
2405   // Save default settings for some mode flags
2406   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
2407   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
2408   Arguments::_ClipInlining             = ClipInlining;
2409   Arguments::_BackgroundCompilation    = BackgroundCompilation;
2410   if (TieredCompilation) {
2411     Arguments::_Tier3InvokeNotifyFreqLog = Tier3InvokeNotifyFreqLog;
2412     Arguments::_Tier4InvocationThreshold = Tier4InvocationThreshold;
2413   }
2414 
2415   // Setup flags for mixed which is the default
2416   set_mode_flags(_mixed);
2417 
2418   // Parse args structure generated from JAVA_TOOL_OPTIONS environment
2419   // variable (if present).
2420   jint result = parse_each_vm_init_arg(java_tool_options_args, &patch_mod_javabase, Flag::ENVIRON_VAR);
2421   if (result != JNI_OK) {
2422     return result;
2423   }
2424 
2425   // Parse args structure generated from the command line flags.
2426   result = parse_each_vm_init_arg(cmd_line_args, &patch_mod_javabase, Flag::COMMAND_LINE);
2427   if (result != JNI_OK) {
2428     return result;
2429   }
2430 
2431   // Parse args structure generated from the _JAVA_OPTIONS environment
2432   // variable (if present) (mimics classic VM)
2433   result = parse_each_vm_init_arg(java_options_args, &patch_mod_javabase, Flag::ENVIRON_VAR);
2434   if (result != JNI_OK) {
2435     return result;
2436   }
2437 
2438   // We need to ensure processor and memory resources have been properly
2439   // configured - which may rely on arguments we just processed - before
2440   // doing the final argument processing. Any argument processing that
2441   // needs to know about processor and memory resources must occur after
2442   // this point.
2443 
2444   os::init_container_support();
2445 
2446   // Do final processing now that all arguments have been parsed
2447   result = finalize_vm_init_args(patch_mod_javabase);
2448   if (result != JNI_OK) {
2449     return result;
2450   }
2451 
2452   return JNI_OK;
2453 }
2454 
2455 // Checks if name in command-line argument -agent{lib,path}:name[=options]
2456 // represents a valid JDWP agent.  is_path==true denotes that we
2457 // are dealing with -agentpath (case where name is a path), otherwise with
2458 // -agentlib
2459 bool valid_jdwp_agent(char *name, bool is_path) {
2460   char *_name;
2461   const char *_jdwp = "jdwp";
2462   size_t _len_jdwp, _len_prefix;
2463 
2464   if (is_path) {
2465     if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
2466       return false;
2467     }
2468 
2469     _name++;  // skip past last path separator
2470     _len_prefix = strlen(JNI_LIB_PREFIX);
2471 
2472     if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2473       return false;
2474     }
2475 
2476     _name += _len_prefix;
2477     _len_jdwp = strlen(_jdwp);
2478 
2479     if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2480       _name += _len_jdwp;
2481     }
2482     else {
2483       return false;
2484     }
2485 
2486     if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2487       return false;
2488     }
2489 
2490     return true;
2491   }
2492 
2493   if (strcmp(name, _jdwp) == 0) {
2494     return true;
2495   }
2496 
2497   return false;
2498 }
2499 
2500 int Arguments::process_patch_mod_option(const char* patch_mod_tail, bool* patch_mod_javabase) {
2501   // --patch-module=<module>=<file>(<pathsep><file>)*
2502   assert(patch_mod_tail != NULL, "Unexpected NULL patch-module value");
2503   // Find the equal sign between the module name and the path specification
2504   const char* module_equal = strchr(patch_mod_tail, '=');
2505   if (module_equal == NULL) {
2506     jio_fprintf(defaultStream::output_stream(), "Missing '=' in --patch-module specification\n");
2507     return JNI_ERR;
2508   } else {
2509     // Pick out the module name
2510     size_t module_len = module_equal - patch_mod_tail;
2511     char* module_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, module_len+1, mtArguments);
2512     if (module_name != NULL) {
2513       memcpy(module_name, patch_mod_tail, module_len);
2514       *(module_name + module_len) = '\0';
2515       // The path piece begins one past the module_equal sign
2516       add_patch_mod_prefix(module_name, module_equal + 1, patch_mod_javabase);
2517       FREE_C_HEAP_ARRAY(char, module_name);
2518       if (!create_numbered_property("jdk.module.patch", patch_mod_tail, patch_mod_count++)) {
2519         return JNI_ENOMEM;
2520       }
2521     } else {
2522       return JNI_ENOMEM;
2523     }
2524   }
2525   return JNI_OK;
2526 }
2527 
2528 // Parse -Xss memory string parameter and convert to ThreadStackSize in K.
2529 jint Arguments::parse_xss(const JavaVMOption* option, const char* tail, intx* out_ThreadStackSize) {
2530   // The min and max sizes match the values in globals.hpp, but scaled
2531   // with K. The values have been chosen so that alignment with page
2532   // size doesn't change the max value, which makes the conversions
2533   // back and forth between Xss value and ThreadStackSize value easier.
2534   // The values have also been chosen to fit inside a 32-bit signed type.
2535   const julong min_ThreadStackSize = 0;
2536   const julong max_ThreadStackSize = 1 * M;
2537 
2538   const julong min_size = min_ThreadStackSize * K;
2539   const julong max_size = max_ThreadStackSize * K;
2540 
2541   assert(is_aligned(max_size, os::vm_page_size()), "Implementation assumption");
2542 
2543   julong size = 0;
2544   ArgsRange errcode = parse_memory_size(tail, &size, min_size, max_size);
2545   if (errcode != arg_in_range) {
2546     bool silent = (option == NULL); // Allow testing to silence error messages
2547     if (!silent) {
2548       jio_fprintf(defaultStream::error_stream(),
2549                   "Invalid thread stack size: %s\n", option->optionString);
2550       describe_range_error(errcode);
2551     }
2552     return JNI_EINVAL;
2553   }
2554 
2555   // Internally track ThreadStackSize in units of 1024 bytes.
2556   const julong size_aligned = align_up(size, K);
2557   assert(size <= size_aligned,
2558          "Overflow: " JULONG_FORMAT " " JULONG_FORMAT,
2559          size, size_aligned);
2560 
2561   const julong size_in_K = size_aligned / K;
2562   assert(size_in_K < (julong)max_intx,
2563          "size_in_K doesn't fit in the type of ThreadStackSize: " JULONG_FORMAT,
2564          size_in_K);
2565 
2566   // Check that code expanding ThreadStackSize to a page aligned number of bytes won't overflow.
2567   const julong max_expanded = align_up(size_in_K * K, os::vm_page_size());
2568   assert(max_expanded < max_uintx && max_expanded >= size_in_K,
2569          "Expansion overflowed: " JULONG_FORMAT " " JULONG_FORMAT,
2570          max_expanded, size_in_K);
2571 
2572   *out_ThreadStackSize = (intx)size_in_K;
2573 
2574   return JNI_OK;
2575 }
2576 
2577 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_mod_javabase, Flag::Flags origin) {
2578   // For match_option to return remaining or value part of option string
2579   const char* tail;
2580 
2581   // iterate over arguments
2582   for (int index = 0; index < args->nOptions; index++) {
2583     bool is_absolute_path = false;  // for -agentpath vs -agentlib
2584 
2585     const JavaVMOption* option = args->options + index;
2586 
2587     if (!match_option(option, "-Djava.class.path", &tail) &&
2588         !match_option(option, "-Dsun.java.command", &tail) &&
2589         !match_option(option, "-Dsun.java.launcher", &tail)) {
2590 
2591         // add all jvm options to the jvm_args string. This string
2592         // is used later to set the java.vm.args PerfData string constant.
2593         // the -Djava.class.path and the -Dsun.java.command options are
2594         // omitted from jvm_args string as each have their own PerfData
2595         // string constant object.
2596         build_jvm_args(option->optionString);
2597     }
2598 
2599     // -verbose:[class/module/gc/jni]
2600     if (match_option(option, "-verbose", &tail)) {
2601       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2602         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, load));
2603         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, unload));
2604       } else if (!strcmp(tail, ":module")) {
2605         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(module, load));
2606         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(module, unload));
2607       } else if (!strcmp(tail, ":gc")) {
2608         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(gc));
2609       } else if (!strcmp(tail, ":jni")) {
2610         if (FLAG_SET_CMDLINE(bool, PrintJNIResolving, true) != Flag::SUCCESS) {
2611           return JNI_EINVAL;
2612         }
2613       }
2614     // -da / -ea / -disableassertions / -enableassertions
2615     // These accept an optional class/package name separated by a colon, e.g.,
2616     // -da:java.lang.Thread.
2617     } else if (match_option(option, user_assertion_options, &tail, true)) {
2618       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2619       if (*tail == '\0') {
2620         JavaAssertions::setUserClassDefault(enable);
2621       } else {
2622         assert(*tail == ':', "bogus match by match_option()");
2623         JavaAssertions::addOption(tail + 1, enable);
2624       }
2625     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2626     } else if (match_option(option, system_assertion_options, &tail, false)) {
2627       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2628       JavaAssertions::setSystemClassDefault(enable);
2629     // -bootclasspath:
2630     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2631         jio_fprintf(defaultStream::output_stream(),
2632           "-Xbootclasspath is no longer a supported option.\n");
2633         return JNI_EINVAL;
2634     // -bootclasspath/a:
2635     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2636       Arguments::append_sysclasspath(tail);
2637     // -bootclasspath/p:
2638     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2639         jio_fprintf(defaultStream::output_stream(),
2640           "-Xbootclasspath/p is no longer a supported option.\n");
2641         return JNI_EINVAL;
2642     // -Xrun
2643     } else if (match_option(option, "-Xrun", &tail)) {
2644       if (tail != NULL) {
2645         const char* pos = strchr(tail, ':');
2646         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2647         char* name = NEW_C_HEAP_ARRAY(char, len + 1, mtArguments);
2648         jio_snprintf(name, len + 1, "%s", tail);
2649 
2650         char *options = NULL;
2651         if(pos != NULL) {
2652           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2653           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtArguments), pos+1, len2);
2654         }
2655 #if !INCLUDE_JVMTI
2656         if (strcmp(name, "jdwp") == 0) {
2657           jio_fprintf(defaultStream::error_stream(),
2658             "Debugging agents are not supported in this VM\n");
2659           return JNI_ERR;
2660         }
2661 #endif // !INCLUDE_JVMTI
2662         add_init_library(name, options);
2663       }
2664     } else if (match_option(option, "--add-reads=", &tail)) {
2665       if (!create_numbered_property("jdk.module.addreads", tail, addreads_count++)) {
2666         return JNI_ENOMEM;
2667       }
2668     } else if (match_option(option, "--add-exports=", &tail)) {
2669       if (!create_numbered_property("jdk.module.addexports", tail, addexports_count++)) {
2670         return JNI_ENOMEM;
2671       }
2672     } else if (match_option(option, "--add-opens=", &tail)) {
2673       if (!create_numbered_property("jdk.module.addopens", tail, addopens_count++)) {
2674         return JNI_ENOMEM;
2675       }
2676     } else if (match_option(option, "--add-modules=", &tail)) {
2677       if (!create_numbered_property("jdk.module.addmods", tail, addmods_count++)) {
2678         return JNI_ENOMEM;
2679       }
2680     } else if (match_option(option, "--limit-modules=", &tail)) {
2681       if (!create_property("jdk.module.limitmods", tail, InternalProperty)) {
2682         return JNI_ENOMEM;
2683       }
2684     } else if (match_option(option, "--module-path=", &tail)) {
2685       if (!create_property("jdk.module.path", tail, ExternalProperty)) {
2686         return JNI_ENOMEM;
2687       }
2688     } else if (match_option(option, "--upgrade-module-path=", &tail)) {
2689       if (!create_property("jdk.module.upgrade.path", tail, ExternalProperty)) {
2690         return JNI_ENOMEM;
2691       }
2692     } else if (match_option(option, "--patch-module=", &tail)) {
2693       // --patch-module=<module>=<file>(<pathsep><file>)*
2694       int res = process_patch_mod_option(tail, patch_mod_javabase);
2695       if (res != JNI_OK) {
2696         return res;
2697       }
2698     } else if (match_option(option, "--illegal-access=", &tail)) {
2699       if (!create_property("jdk.module.illegalAccess", tail, ExternalProperty)) {
2700         return JNI_ENOMEM;
2701       }
2702     // -agentlib and -agentpath
2703     } else if (match_option(option, "-agentlib:", &tail) ||
2704           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2705       if(tail != NULL) {
2706         const char* pos = strchr(tail, '=');
2707         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2708         char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtArguments), tail, len);
2709         name[len] = '\0';
2710 
2711         char *options = NULL;
2712         if(pos != NULL) {
2713           options = os::strdup_check_oom(pos + 1, mtArguments);
2714         }
2715 #if !INCLUDE_JVMTI
2716         if (valid_jdwp_agent(name, is_absolute_path)) {
2717           jio_fprintf(defaultStream::error_stream(),
2718             "Debugging agents are not supported in this VM\n");
2719           return JNI_ERR;
2720         }
2721 #endif // !INCLUDE_JVMTI
2722         add_init_agent(name, options, is_absolute_path);
2723       }
2724     // -javaagent
2725     } else if (match_option(option, "-javaagent:", &tail)) {
2726 #if !INCLUDE_JVMTI
2727       jio_fprintf(defaultStream::error_stream(),
2728         "Instrumentation agents are not supported in this VM\n");
2729       return JNI_ERR;
2730 #else
2731       if (tail != NULL) {
2732         size_t length = strlen(tail) + 1;
2733         char *options = NEW_C_HEAP_ARRAY(char, length, mtArguments);
2734         jio_snprintf(options, length, "%s", tail);
2735         add_instrument_agent("instrument", options, false);
2736         // java agents need module java.instrument
2737         if (!create_numbered_property("jdk.module.addmods", "java.instrument", addmods_count++)) {
2738           return JNI_ENOMEM;
2739         }
2740       }
2741 #endif // !INCLUDE_JVMTI
2742     // -Xnoclassgc
2743     } else if (match_option(option, "-Xnoclassgc")) {
2744       if (FLAG_SET_CMDLINE(bool, ClassUnloading, false) != Flag::SUCCESS) {
2745         return JNI_EINVAL;
2746       }
2747     // -Xconcgc
2748     } else if (match_option(option, "-Xconcgc")) {
2749       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true) != Flag::SUCCESS) {
2750         return JNI_EINVAL;
2751       }
2752       handle_extra_cms_flags("-Xconcgc uses UseConcMarkSweepGC");
2753     // -Xnoconcgc
2754     } else if (match_option(option, "-Xnoconcgc")) {
2755       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false) != Flag::SUCCESS) {
2756         return JNI_EINVAL;
2757       }
2758       handle_extra_cms_flags("-Xnoconcgc uses UseConcMarkSweepGC");
2759     // -Xbatch
2760     } else if (match_option(option, "-Xbatch")) {
2761       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
2762         return JNI_EINVAL;
2763       }
2764     // -Xmn for compatibility with other JVM vendors
2765     } else if (match_option(option, "-Xmn", &tail)) {
2766       julong long_initial_young_size = 0;
2767       ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2768       if (errcode != arg_in_range) {
2769         jio_fprintf(defaultStream::error_stream(),
2770                     "Invalid initial young generation size: %s\n", option->optionString);
2771         describe_range_error(errcode);
2772         return JNI_EINVAL;
2773       }
2774       if (FLAG_SET_CMDLINE(size_t, MaxNewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2775         return JNI_EINVAL;
2776       }
2777       if (FLAG_SET_CMDLINE(size_t, NewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2778         return JNI_EINVAL;
2779       }
2780     // -Xms
2781     } else if (match_option(option, "-Xms", &tail)) {
2782       julong long_initial_heap_size = 0;
2783       // an initial heap size of 0 means automatically determine
2784       ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);
2785       if (errcode != arg_in_range) {
2786         jio_fprintf(defaultStream::error_stream(),
2787                     "Invalid initial heap size: %s\n", option->optionString);
2788         describe_range_error(errcode);
2789         return JNI_EINVAL;
2790       }
2791       set_min_heap_size((size_t)long_initial_heap_size);
2792       // Currently the minimum size and the initial heap sizes are the same.
2793       // Can be overridden with -XX:InitialHeapSize.
2794       if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, (size_t)long_initial_heap_size) != Flag::SUCCESS) {
2795         return JNI_EINVAL;
2796       }
2797     // -Xmx
2798     } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2799       julong long_max_heap_size = 0;
2800       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2801       if (errcode != arg_in_range) {
2802         jio_fprintf(defaultStream::error_stream(),
2803                     "Invalid maximum heap size: %s\n", option->optionString);
2804         describe_range_error(errcode);
2805         return JNI_EINVAL;
2806       }
2807       if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, (size_t)long_max_heap_size) != Flag::SUCCESS) {
2808         return JNI_EINVAL;
2809       }
2810     // Xmaxf
2811     } else if (match_option(option, "-Xmaxf", &tail)) {
2812       char* err;
2813       int maxf = (int)(strtod(tail, &err) * 100);
2814       if (*err != '\0' || *tail == '\0') {
2815         jio_fprintf(defaultStream::error_stream(),
2816                     "Bad max heap free percentage size: %s\n",
2817                     option->optionString);
2818         return JNI_EINVAL;
2819       } else {
2820         if (FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf) != Flag::SUCCESS) {
2821             return JNI_EINVAL;
2822         }
2823       }
2824     // Xminf
2825     } else if (match_option(option, "-Xminf", &tail)) {
2826       char* err;
2827       int minf = (int)(strtod(tail, &err) * 100);
2828       if (*err != '\0' || *tail == '\0') {
2829         jio_fprintf(defaultStream::error_stream(),
2830                     "Bad min heap free percentage size: %s\n",
2831                     option->optionString);
2832         return JNI_EINVAL;
2833       } else {
2834         if (FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf) != Flag::SUCCESS) {
2835           return JNI_EINVAL;
2836         }
2837       }
2838     // -Xss
2839     } else if (match_option(option, "-Xss", &tail)) {
2840       intx value = 0;
2841       jint err = parse_xss(option, tail, &value);
2842       if (err != JNI_OK) {
2843         return err;
2844       }
2845       if (FLAG_SET_CMDLINE(intx, ThreadStackSize, value) != Flag::SUCCESS) {
2846         return JNI_EINVAL;
2847       }
2848     } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
2849                match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
2850       julong long_ReservedCodeCacheSize = 0;
2851 
2852       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
2853       if (errcode != arg_in_range) {
2854         jio_fprintf(defaultStream::error_stream(),
2855                     "Invalid maximum code cache size: %s.\n", option->optionString);
2856         return JNI_EINVAL;
2857       }
2858       if (FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize) != Flag::SUCCESS) {
2859         return JNI_EINVAL;
2860       }
2861     // -green
2862     } else if (match_option(option, "-green")) {
2863       jio_fprintf(defaultStream::error_stream(),
2864                   "Green threads support not available\n");
2865           return JNI_EINVAL;
2866     // -native
2867     } else if (match_option(option, "-native")) {
2868           // HotSpot always uses native threads, ignore silently for compatibility
2869     // -Xrs
2870     } else if (match_option(option, "-Xrs")) {
2871           // Classic/EVM option, new functionality
2872       if (FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true) != Flag::SUCCESS) {
2873         return JNI_EINVAL;
2874       }
2875       // -Xprof
2876     } else if (match_option(option, "-Xprof")) {
2877       char version[256];
2878       // Obsolete in JDK 10
2879       JDK_Version::jdk(10).to_string(version, sizeof(version));
2880       warning("Ignoring option %s; support was removed in %s", option->optionString, version);
2881     // -Xconcurrentio
2882     } else if (match_option(option, "-Xconcurrentio")) {
2883       if (FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true) != Flag::SUCCESS) {
2884         return JNI_EINVAL;
2885       }
2886       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
2887         return JNI_EINVAL;
2888       }
2889       SafepointSynchronize::set_defer_thr_suspend_loop_count();
2890       if (FLAG_SET_CMDLINE(bool, UseTLAB, false) != Flag::SUCCESS) {
2891         return JNI_EINVAL;
2892       }
2893       if (FLAG_SET_CMDLINE(size_t, NewSizeThreadIncrease, 16 * K) != Flag::SUCCESS) {  // 20Kb per thread added to new generation
2894         return JNI_EINVAL;
2895       }
2896 
2897       // -Xinternalversion
2898     } else if (match_option(option, "-Xinternalversion")) {
2899       jio_fprintf(defaultStream::output_stream(), "%s\n",
2900                   VM_Version::internal_vm_info_string());
2901       vm_exit(0);
2902 #ifndef PRODUCT
2903     // -Xprintflags
2904     } else if (match_option(option, "-Xprintflags")) {
2905       CommandLineFlags::printFlags(tty, false);
2906       vm_exit(0);
2907 #endif
2908     // -D
2909     } else if (match_option(option, "-D", &tail)) {
2910       const char* value;
2911       if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
2912             *value!= '\0' && strcmp(value, "\"\"") != 0) {
2913         // abort if -Djava.endorsed.dirs is set
2914         jio_fprintf(defaultStream::output_stream(),
2915           "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
2916           "in modular form will be supported via the concept of upgradeable modules.\n", value);
2917         return JNI_EINVAL;
2918       }
2919       if (match_option(option, "-Djava.ext.dirs=", &value) &&
2920             *value != '\0' && strcmp(value, "\"\"") != 0) {
2921         // abort if -Djava.ext.dirs is set
2922         jio_fprintf(defaultStream::output_stream(),
2923           "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
2924         return JNI_EINVAL;
2925       }
2926       // Check for module related properties.  They must be set using the modules
2927       // options. For example: use "--add-modules=java.sql", not
2928       // "-Djdk.module.addmods=java.sql"
2929       if (is_internal_module_property(option->optionString + 2)) {
2930         needs_module_property_warning = true;
2931         continue;
2932       }
2933 
2934       if (!add_property(tail)) {
2935         return JNI_ENOMEM;
2936       }
2937       // Out of the box management support
2938       if (match_option(option, "-Dcom.sun.management", &tail)) {
2939 #if INCLUDE_MANAGEMENT
2940         if (FLAG_SET_CMDLINE(bool, ManagementServer, true) != Flag::SUCCESS) {
2941           return JNI_EINVAL;
2942         }
2943         // management agent in module jdk.management.agent
2944         if (!create_numbered_property("jdk.module.addmods", "jdk.management.agent", addmods_count++)) {
2945           return JNI_ENOMEM;
2946         }
2947 #else
2948         jio_fprintf(defaultStream::output_stream(),
2949           "-Dcom.sun.management is not supported in this VM.\n");
2950         return JNI_ERR;
2951 #endif
2952       }
2953     // -Xint
2954     } else if (match_option(option, "-Xint")) {
2955           set_mode_flags(_int);
2956     // -Xmixed
2957     } else if (match_option(option, "-Xmixed")) {
2958           set_mode_flags(_mixed);
2959     // -Xcomp
2960     } else if (match_option(option, "-Xcomp")) {
2961       // for testing the compiler; turn off all flags that inhibit compilation
2962           set_mode_flags(_comp);
2963     // -Xshare:dump
2964     } else if (match_option(option, "-Xshare:dump")) {
2965       if (FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true) != Flag::SUCCESS) {
2966         return JNI_EINVAL;
2967       }
2968       set_mode_flags(_int);     // Prevent compilation, which creates objects
2969     // -Xshare:on
2970     } else if (match_option(option, "-Xshare:on")) {
2971       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
2972         return JNI_EINVAL;
2973       }
2974       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
2975         return JNI_EINVAL;
2976       }
2977     // -Xshare:auto
2978     } else if (match_option(option, "-Xshare:auto")) {
2979       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
2980         return JNI_EINVAL;
2981       }
2982       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
2983         return JNI_EINVAL;
2984       }
2985     // -Xshare:off
2986     } else if (match_option(option, "-Xshare:off")) {
2987       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, false) != Flag::SUCCESS) {
2988         return JNI_EINVAL;
2989       }
2990       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
2991         return JNI_EINVAL;
2992       }
2993     // -Xverify
2994     } else if (match_option(option, "-Xverify", &tail)) {
2995       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
2996         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true) != Flag::SUCCESS) {
2997           return JNI_EINVAL;
2998         }
2999         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
3000           return JNI_EINVAL;
3001         }
3002       } else if (strcmp(tail, ":remote") == 0) {
3003         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
3004           return JNI_EINVAL;
3005         }
3006         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
3007           return JNI_EINVAL;
3008         }
3009       } else if (strcmp(tail, ":none") == 0) {
3010         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
3011           return JNI_EINVAL;
3012         }
3013         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false) != Flag::SUCCESS) {
3014           return JNI_EINVAL;
3015         }
3016       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
3017         return JNI_EINVAL;
3018       }
3019     // -Xdebug
3020     } else if (match_option(option, "-Xdebug")) {
3021       // note this flag has been used, then ignore
3022       set_xdebug_mode(true);
3023     // -Xnoagent
3024     } else if (match_option(option, "-Xnoagent")) {
3025       // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
3026     } else if (match_option(option, "-Xloggc:", &tail)) {
3027       // Deprecated flag to redirect GC output to a file. -Xloggc:<filename>
3028       log_warning(gc)("-Xloggc is deprecated. Will use -Xlog:gc:%s instead.", tail);
3029       _gc_log_filename = os::strdup_check_oom(tail);
3030     } else if (match_option(option, "-Xlog", &tail)) {
3031       bool ret = false;
3032       if (strcmp(tail, ":help") == 0) {
3033         fileStream stream(defaultStream::output_stream());
3034         LogConfiguration::print_command_line_help(&stream);
3035         vm_exit(0);
3036       } else if (strcmp(tail, ":disable") == 0) {
3037         LogConfiguration::disable_logging();
3038         ret = true;
3039       } else if (*tail == '\0') {
3040         ret = LogConfiguration::parse_command_line_arguments();
3041         assert(ret, "-Xlog without arguments should never fail to parse");
3042       } else if (*tail == ':') {
3043         ret = LogConfiguration::parse_command_line_arguments(tail + 1);
3044       }
3045       if (ret == false) {
3046         jio_fprintf(defaultStream::error_stream(),
3047                     "Invalid -Xlog option '-Xlog%s', see error log for details.\n",
3048                     tail);
3049         return JNI_EINVAL;
3050       }
3051     // JNI hooks
3052     } else if (match_option(option, "-Xcheck", &tail)) {
3053       if (!strcmp(tail, ":jni")) {
3054 #if !INCLUDE_JNI_CHECK
3055         warning("JNI CHECKING is not supported in this VM");
3056 #else
3057         CheckJNICalls = true;
3058 #endif // INCLUDE_JNI_CHECK
3059       } else if (is_bad_option(option, args->ignoreUnrecognized,
3060                                      "check")) {
3061         return JNI_EINVAL;
3062       }
3063     } else if (match_option(option, "vfprintf")) {
3064       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
3065     } else if (match_option(option, "exit")) {
3066       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
3067     } else if (match_option(option, "abort")) {
3068       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
3069     // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
3070     // and the last option wins.
3071     } else if (match_option(option, "-XX:+NeverTenure")) {
3072       if (FLAG_SET_CMDLINE(bool, NeverTenure, true) != Flag::SUCCESS) {
3073         return JNI_EINVAL;
3074       }
3075       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
3076         return JNI_EINVAL;
3077       }
3078       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, markOopDesc::max_age + 1) != Flag::SUCCESS) {
3079         return JNI_EINVAL;
3080       }
3081     } else if (match_option(option, "-XX:+AlwaysTenure")) {
3082       if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3083         return JNI_EINVAL;
3084       }
3085       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
3086         return JNI_EINVAL;
3087       }
3088       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0) != Flag::SUCCESS) {
3089         return JNI_EINVAL;
3090       }
3091     } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
3092       uintx max_tenuring_thresh = 0;
3093       if (!parse_uintx(tail, &max_tenuring_thresh, 0)) {
3094         jio_fprintf(defaultStream::error_stream(),
3095                     "Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);
3096         return JNI_EINVAL;
3097       }
3098 
3099       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, max_tenuring_thresh) != Flag::SUCCESS) {
3100         return JNI_EINVAL;
3101       }
3102 
3103       if (MaxTenuringThreshold == 0) {
3104         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3105           return JNI_EINVAL;
3106         }
3107         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
3108           return JNI_EINVAL;
3109         }
3110       } else {
3111         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3112           return JNI_EINVAL;
3113         }
3114         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
3115           return JNI_EINVAL;
3116         }
3117       }
3118     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
3119       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false) != Flag::SUCCESS) {
3120         return JNI_EINVAL;
3121       }
3122       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true) != Flag::SUCCESS) {
3123         return JNI_EINVAL;
3124       }
3125     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
3126       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false) != Flag::SUCCESS) {
3127         return JNI_EINVAL;
3128       }
3129       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true) != Flag::SUCCESS) {
3130         return JNI_EINVAL;
3131       }
3132     } else if (match_option(option, "-XX:+ExtendedDTraceProbes")) {
3133 #if defined(DTRACE_ENABLED)
3134       if (FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true) != Flag::SUCCESS) {
3135         return JNI_EINVAL;
3136       }
3137       if (FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true) != Flag::SUCCESS) {
3138         return JNI_EINVAL;
3139       }
3140       if (FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true) != Flag::SUCCESS) {
3141         return JNI_EINVAL;
3142       }
3143       if (FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true) != Flag::SUCCESS) {
3144         return JNI_EINVAL;
3145       }
3146 #else // defined(DTRACE_ENABLED)
3147       jio_fprintf(defaultStream::error_stream(),
3148                   "ExtendedDTraceProbes flag is not applicable for this configuration\n");
3149       return JNI_EINVAL;
3150 #endif // defined(DTRACE_ENABLED)
3151 #ifdef ASSERT
3152     } else if (match_option(option, "-XX:+FullGCALot")) {
3153       if (FLAG_SET_CMDLINE(bool, FullGCALot, true) != Flag::SUCCESS) {
3154         return JNI_EINVAL;
3155       }
3156       // disable scavenge before parallel mark-compact
3157       if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
3158         return JNI_EINVAL;
3159       }
3160 #endif
3161 #if !INCLUDE_MANAGEMENT
3162     } else if (match_option(option, "-XX:+ManagementServer")) {
3163         jio_fprintf(defaultStream::error_stream(),
3164           "ManagementServer is not supported in this VM.\n");
3165         return JNI_ERR;
3166 #endif // INCLUDE_MANAGEMENT
3167     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
3168       // Skip -XX:Flags= and -XX:VMOptionsFile= since those cases have
3169       // already been handled
3170       if ((strncmp(tail, "Flags=", strlen("Flags=")) != 0) &&
3171           (strncmp(tail, "VMOptionsFile=", strlen("VMOptionsFile=")) != 0)) {
3172         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
3173           return JNI_EINVAL;
3174         }
3175       }
3176     // Unknown option
3177     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
3178       return JNI_ERR;
3179     }
3180   }
3181 
3182   // PrintSharedArchiveAndExit will turn on
3183   //   -Xshare:on
3184   //   -Xlog:class+path=info
3185   if (PrintSharedArchiveAndExit) {
3186     if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3187       return JNI_EINVAL;
3188     }
3189     if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3190       return JNI_EINVAL;
3191     }
3192     LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, path));
3193   }
3194 
3195   // Change the default value for flags  which have different default values
3196   // when working with older JDKs.
3197 #ifdef LINUX
3198  if (JDK_Version::current().compare_major(6) <= 0 &&
3199       FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
3200     FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
3201   }
3202 #endif // LINUX
3203   fix_appclasspath();
3204   return JNI_OK;
3205 }
3206 
3207 void Arguments::add_patch_mod_prefix(const char* module_name, const char* path, bool* patch_mod_javabase) {
3208   // For java.base check for duplicate --patch-module options being specified on the command line.
3209   // This check is only required for java.base, all other duplicate module specifications
3210   // will be checked during module system initialization.  The module system initialization
3211   // will throw an ExceptionInInitializerError if this situation occurs.
3212   if (strcmp(module_name, JAVA_BASE_NAME) == 0) {
3213     if (*patch_mod_javabase) {
3214       vm_exit_during_initialization("Cannot specify " JAVA_BASE_NAME " more than once to --patch-module");
3215     } else {
3216       *patch_mod_javabase = true;
3217     }
3218   }
3219 
3220   // Create GrowableArray lazily, only if --patch-module has been specified
3221   if (_patch_mod_prefix == NULL) {
3222     _patch_mod_prefix = new (ResourceObj::C_HEAP, mtArguments) GrowableArray<ModulePatchPath*>(10, true);
3223   }
3224 
3225   _patch_mod_prefix->push(new ModulePatchPath(module_name, path));
3226 }
3227 
3228 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
3229 //
3230 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
3231 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
3232 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
3233 // path is treated as the current directory.
3234 //
3235 // This causes problems with CDS, which requires that all directories specified in the classpath
3236 // must be empty. In most cases, applications do NOT want to load classes from the current
3237 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
3238 // scripts compatible with CDS.
3239 void Arguments::fix_appclasspath() {
3240   if (IgnoreEmptyClassPaths) {
3241     const char separator = *os::path_separator();
3242     const char* src = _java_class_path->value();
3243 
3244     // skip over all the leading empty paths
3245     while (*src == separator) {
3246       src ++;
3247     }
3248 
3249     char* copy = os::strdup_check_oom(src, mtArguments);
3250 
3251     // trim all trailing empty paths
3252     for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
3253       *tail = '\0';
3254     }
3255 
3256     char from[3] = {separator, separator, '\0'};
3257     char to  [2] = {separator, '\0'};
3258     while (StringUtils::replace_no_expand(copy, from, to) > 0) {
3259       // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
3260       // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
3261     }
3262 
3263     _java_class_path->set_writeable_value(copy);
3264     FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
3265   }
3266 }
3267 
3268 jint Arguments::finalize_vm_init_args(bool patch_mod_javabase) {
3269   // check if the default lib/endorsed directory exists; if so, error
3270   char path[JVM_MAXPATHLEN];
3271   const char* fileSep = os::file_separator();
3272   jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
3273 
3274   DIR* dir = os::opendir(path);
3275   if (dir != NULL) {
3276     jio_fprintf(defaultStream::output_stream(),
3277       "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
3278       "in modular form will be supported via the concept of upgradeable modules.\n");
3279     os::closedir(dir);
3280     return JNI_ERR;
3281   }
3282 
3283   jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
3284   dir = os::opendir(path);
3285   if (dir != NULL) {
3286     jio_fprintf(defaultStream::output_stream(),
3287       "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
3288       "Use -classpath instead.\n.");
3289     os::closedir(dir);
3290     return JNI_ERR;
3291   }
3292 
3293   // This must be done after all arguments have been processed
3294   // and the container support has been initialized since AggressiveHeap
3295   // relies on the amount of total memory available.
3296   if (AggressiveHeap) {
3297     jint result = set_aggressive_heap_flags();
3298     if (result != JNI_OK) {
3299       return result;
3300     }
3301   }
3302 
3303   // This must be done after all arguments have been processed.
3304   // java_compiler() true means set to "NONE" or empty.
3305   if (java_compiler() && !xdebug_mode()) {
3306     // For backwards compatibility, we switch to interpreted mode if
3307     // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
3308     // not specified.
3309     set_mode_flags(_int);
3310   }
3311 
3312   // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
3313   // but like -Xint, leave compilation thresholds unaffected.
3314   // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
3315   if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
3316     set_mode_flags(_int);
3317   }
3318 
3319   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3320   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3321     FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
3322   }
3323 
3324 #if !defined(COMPILER2) && !INCLUDE_JVMCI
3325   // Don't degrade server performance for footprint
3326   if (FLAG_IS_DEFAULT(UseLargePages) &&
3327       MaxHeapSize < LargePageHeapSizeThreshold) {
3328     // No need for large granularity pages w/small heaps.
3329     // Note that large pages are enabled/disabled for both the
3330     // Java heap and the code cache.
3331     FLAG_SET_DEFAULT(UseLargePages, false);
3332   }
3333 
3334 #elif defined(COMPILER2)
3335   if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
3336     FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
3337   }
3338 #endif
3339 
3340 #if !defined(COMPILER2) && !INCLUDE_JVMCI
3341   UNSUPPORTED_OPTION(ProfileInterpreter);
3342   NOT_PRODUCT(UNSUPPORTED_OPTION(TraceProfileInterpreter));
3343 #endif
3344 
3345 #ifndef TIERED
3346   // Tiered compilation is undefined.
3347   UNSUPPORTED_OPTION(TieredCompilation);
3348 #endif
3349 
3350 #if INCLUDE_JVMCI
3351   if (EnableJVMCI &&
3352       !create_numbered_property("jdk.module.addmods", "jdk.internal.vm.ci", addmods_count++)) {
3353     return JNI_ENOMEM;
3354   }
3355 #endif
3356 
3357   if (!check_vm_args_consistency()) {
3358     return JNI_ERR;
3359   }
3360 
3361 #if INCLUDE_JVMCI
3362   if (UseJVMCICompiler) {
3363     Compilation_mode = CompMode_server;
3364   }
3365 #endif
3366 
3367 #if INCLUDE_CDS
3368   if (DumpSharedSpaces) {
3369     // Disable biased locking now as it interferes with the clean up of
3370     // the archived Klasses and Java string objects (at dump time only).
3371     UseBiasedLocking = false;
3372   }
3373   if (UseSharedSpaces && patch_mod_javabase) {
3374     no_shared_spaces("CDS is disabled when " JAVA_BASE_NAME " module is patched.");
3375   }
3376 #endif
3377 
3378 #ifndef CAN_SHOW_REGISTERS_ON_ASSERT
3379   UNSUPPORTED_OPTION(ShowRegistersOnAssert);
3380 #endif // CAN_SHOW_REGISTERS_ON_ASSERT
3381 
3382   return JNI_OK;
3383 }
3384 
3385 // Helper class for controlling the lifetime of JavaVMInitArgs
3386 // objects.  The contents of the JavaVMInitArgs are guaranteed to be
3387 // deleted on the destruction of the ScopedVMInitArgs object.
3388 class ScopedVMInitArgs : public StackObj {
3389  private:
3390   JavaVMInitArgs _args;
3391   char*          _container_name;
3392   bool           _is_set;
3393   char*          _vm_options_file_arg;
3394 
3395  public:
3396   ScopedVMInitArgs(const char *container_name) {
3397     _args.version = JNI_VERSION_1_2;
3398     _args.nOptions = 0;
3399     _args.options = NULL;
3400     _args.ignoreUnrecognized = false;
3401     _container_name = (char *)container_name;
3402     _is_set = false;
3403     _vm_options_file_arg = NULL;
3404   }
3405 
3406   // Populates the JavaVMInitArgs object represented by this
3407   // ScopedVMInitArgs object with the arguments in options.  The
3408   // allocated memory is deleted by the destructor.  If this method
3409   // returns anything other than JNI_OK, then this object is in a
3410   // partially constructed state, and should be abandoned.
3411   jint set_args(GrowableArray<JavaVMOption>* options) {
3412     _is_set = true;
3413     JavaVMOption* options_arr = NEW_C_HEAP_ARRAY_RETURN_NULL(
3414         JavaVMOption, options->length(), mtArguments);
3415     if (options_arr == NULL) {
3416       return JNI_ENOMEM;
3417     }
3418     _args.options = options_arr;
3419 
3420     for (int i = 0; i < options->length(); i++) {
3421       options_arr[i] = options->at(i);
3422       options_arr[i].optionString = os::strdup(options_arr[i].optionString);
3423       if (options_arr[i].optionString == NULL) {
3424         // Rely on the destructor to do cleanup.
3425         _args.nOptions = i;
3426         return JNI_ENOMEM;
3427       }
3428     }
3429 
3430     _args.nOptions = options->length();
3431     _args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3432     return JNI_OK;
3433   }
3434 
3435   JavaVMInitArgs* get()             { return &_args; }
3436   char* container_name()            { return _container_name; }
3437   bool  is_set()                    { return _is_set; }
3438   bool  found_vm_options_file_arg() { return _vm_options_file_arg != NULL; }
3439   char* vm_options_file_arg()       { return _vm_options_file_arg; }
3440 
3441   void set_vm_options_file_arg(const char *vm_options_file_arg) {
3442     if (_vm_options_file_arg != NULL) {
3443       os::free(_vm_options_file_arg);
3444     }
3445     _vm_options_file_arg = os::strdup_check_oom(vm_options_file_arg);
3446   }
3447 
3448   ~ScopedVMInitArgs() {
3449     if (_vm_options_file_arg != NULL) {
3450       os::free(_vm_options_file_arg);
3451     }
3452     if (_args.options == NULL) return;
3453     for (int i = 0; i < _args.nOptions; i++) {
3454       os::free(_args.options[i].optionString);
3455     }
3456     FREE_C_HEAP_ARRAY(JavaVMOption, _args.options);
3457   }
3458 
3459   // Insert options into this option list, to replace option at
3460   // vm_options_file_pos (-XX:VMOptionsFile)
3461   jint insert(const JavaVMInitArgs* args,
3462               const JavaVMInitArgs* args_to_insert,
3463               const int vm_options_file_pos) {
3464     assert(_args.options == NULL, "shouldn't be set yet");
3465     assert(args_to_insert->nOptions != 0, "there should be args to insert");
3466     assert(vm_options_file_pos != -1, "vm_options_file_pos should be set");
3467 
3468     int length = args->nOptions + args_to_insert->nOptions - 1;
3469     GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtArguments)
3470               GrowableArray<JavaVMOption>(length, true);    // Construct new option array
3471     for (int i = 0; i < args->nOptions; i++) {
3472       if (i == vm_options_file_pos) {
3473         // insert the new options starting at the same place as the
3474         // -XX:VMOptionsFile option
3475         for (int j = 0; j < args_to_insert->nOptions; j++) {
3476           options->push(args_to_insert->options[j]);
3477         }
3478       } else {
3479         options->push(args->options[i]);
3480       }
3481     }
3482     // make into options array
3483     jint result = set_args(options);
3484     delete options;
3485     return result;
3486   }
3487 };
3488 
3489 jint Arguments::parse_java_options_environment_variable(ScopedVMInitArgs* args) {
3490   return parse_options_environment_variable("_JAVA_OPTIONS", args);
3491 }
3492 
3493 jint Arguments::parse_java_tool_options_environment_variable(ScopedVMInitArgs* args) {
3494   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", args);
3495 }
3496 
3497 jint Arguments::parse_options_environment_variable(const char* name,
3498                                                    ScopedVMInitArgs* vm_args) {
3499   char *buffer = ::getenv(name);
3500 
3501   // Don't check this environment variable if user has special privileges
3502   // (e.g. unix su command).
3503   if (buffer == NULL || os::have_special_privileges()) {
3504     return JNI_OK;
3505   }
3506 
3507   if ((buffer = os::strdup(buffer)) == NULL) {
3508     return JNI_ENOMEM;
3509   }
3510 
3511   jio_fprintf(defaultStream::error_stream(),
3512               "Picked up %s: %s\n", name, buffer);
3513 
3514   int retcode = parse_options_buffer(name, buffer, strlen(buffer), vm_args);
3515 
3516   os::free(buffer);
3517   return retcode;
3518 }
3519 
3520 jint Arguments::parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args) {
3521   // read file into buffer
3522   int fd = ::open(file_name, O_RDONLY);
3523   if (fd < 0) {
3524     jio_fprintf(defaultStream::error_stream(),
3525                 "Could not open options file '%s'\n",
3526                 file_name);
3527     return JNI_ERR;
3528   }
3529 
3530   struct stat stbuf;
3531   int retcode = os::stat(file_name, &stbuf);
3532   if (retcode != 0) {
3533     jio_fprintf(defaultStream::error_stream(),
3534                 "Could not stat options file '%s'\n",
3535                 file_name);
3536     os::close(fd);
3537     return JNI_ERR;
3538   }
3539 
3540   if (stbuf.st_size == 0) {
3541     // tell caller there is no option data and that is ok
3542     os::close(fd);
3543     return JNI_OK;
3544   }
3545 
3546   // '+ 1' for NULL termination even with max bytes
3547   size_t bytes_alloc = stbuf.st_size + 1;
3548 
3549   char *buf = NEW_C_HEAP_ARRAY_RETURN_NULL(char, bytes_alloc, mtArguments);
3550   if (NULL == buf) {
3551     jio_fprintf(defaultStream::error_stream(),
3552                 "Could not allocate read buffer for options file parse\n");
3553     os::close(fd);
3554     return JNI_ENOMEM;
3555   }
3556 
3557   memset(buf, 0, bytes_alloc);
3558 
3559   // Fill buffer
3560   // Use ::read() instead of os::read because os::read()
3561   // might do a thread state transition
3562   // and it is too early for that here
3563 
3564   ssize_t bytes_read = ::read(fd, (void *)buf, (unsigned)bytes_alloc);
3565   os::close(fd);
3566   if (bytes_read < 0) {
3567     FREE_C_HEAP_ARRAY(char, buf);
3568     jio_fprintf(defaultStream::error_stream(),
3569                 "Could not read options file '%s'\n", file_name);
3570     return JNI_ERR;
3571   }
3572 
3573   if (bytes_read == 0) {
3574     // tell caller there is no option data and that is ok
3575     FREE_C_HEAP_ARRAY(char, buf);
3576     return JNI_OK;
3577   }
3578 
3579   retcode = parse_options_buffer(file_name, buf, bytes_read, vm_args);
3580 
3581   FREE_C_HEAP_ARRAY(char, buf);
3582   return retcode;
3583 }
3584 
3585 jint Arguments::parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args) {
3586   GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtArguments) GrowableArray<JavaVMOption>(2, true);    // Construct option array
3587 
3588   // some pointers to help with parsing
3589   char *buffer_end = buffer + buf_len;
3590   char *opt_hd = buffer;
3591   char *wrt = buffer;
3592   char *rd = buffer;
3593 
3594   // parse all options
3595   while (rd < buffer_end) {
3596     // skip leading white space from the input string
3597     while (rd < buffer_end && isspace(*rd)) {
3598       rd++;
3599     }
3600 
3601     if (rd >= buffer_end) {
3602       break;
3603     }
3604 
3605     // Remember this is where we found the head of the token.
3606     opt_hd = wrt;
3607 
3608     // Tokens are strings of non white space characters separated
3609     // by one or more white spaces.
3610     while (rd < buffer_end && !isspace(*rd)) {
3611       if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3612         int quote = *rd;                    // matching quote to look for
3613         rd++;                               // don't copy open quote
3614         while (rd < buffer_end && *rd != quote) {
3615                                             // include everything (even spaces)
3616                                             // up until the close quote
3617           *wrt++ = *rd++;                   // copy to option string
3618         }
3619 
3620         if (rd < buffer_end) {
3621           rd++;                             // don't copy close quote
3622         } else {
3623                                             // did not see closing quote
3624           jio_fprintf(defaultStream::error_stream(),
3625                       "Unmatched quote in %s\n", name);
3626           delete options;
3627           return JNI_ERR;
3628         }
3629       } else {
3630         *wrt++ = *rd++;                     // copy to option string
3631       }
3632     }
3633 
3634     // steal a white space character and set it to NULL
3635     *wrt++ = '\0';
3636     // We now have a complete token
3637 
3638     JavaVMOption option;
3639     option.optionString = opt_hd;
3640     option.extraInfo = NULL;
3641 
3642     options->append(option);                // Fill in option
3643 
3644     rd++;  // Advance to next character
3645   }
3646 
3647   // Fill out JavaVMInitArgs structure.
3648   jint status = vm_args->set_args(options);
3649 
3650   delete options;
3651   return status;
3652 }
3653 
3654 void Arguments::set_shared_spaces_flags() {
3655   if (DumpSharedSpaces) {
3656     if (FailOverToOldVerifier) {
3657       // Don't fall back to the old verifier on verification failure. If a
3658       // class fails verification with the split verifier, it might fail the
3659       // CDS runtime verifier constraint check. In that case, we don't want
3660       // to share the class. We only archive classes that pass the split verifier.
3661       FLAG_SET_DEFAULT(FailOverToOldVerifier, false);
3662     }
3663 
3664     if (RequireSharedSpaces) {
3665       warning("Cannot dump shared archive while using shared archive");
3666     }
3667     UseSharedSpaces = false;
3668 #ifdef _LP64
3669     if (!UseCompressedOops || !UseCompressedClassPointers) {
3670       vm_exit_during_initialization(
3671         "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
3672     }
3673   } else {
3674     if (!UseCompressedOops || !UseCompressedClassPointers) {
3675       no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
3676     }
3677 #endif
3678   }
3679 }
3680 
3681 // Sharing support
3682 // Construct the path to the archive
3683 static char* get_shared_archive_path() {
3684   char *shared_archive_path;
3685   if (SharedArchiveFile == NULL) {
3686     char jvm_path[JVM_MAXPATHLEN];
3687     os::jvm_path(jvm_path, sizeof(jvm_path));
3688     char *end = strrchr(jvm_path, *os::file_separator());
3689     if (end != NULL) *end = '\0';
3690     size_t jvm_path_len = strlen(jvm_path);
3691     size_t file_sep_len = strlen(os::file_separator());
3692     const size_t len = jvm_path_len + file_sep_len + 20;
3693     shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtArguments);
3694     if (shared_archive_path != NULL) {
3695       jio_snprintf(shared_archive_path, len, "%s%sclasses.jsa",
3696         jvm_path, os::file_separator());
3697     }
3698   } else {
3699     shared_archive_path = os::strdup_check_oom(SharedArchiveFile, mtArguments);
3700   }
3701   return shared_archive_path;
3702 }
3703 
3704 #ifndef PRODUCT
3705 // Determine whether LogVMOutput should be implicitly turned on.
3706 static bool use_vm_log() {
3707   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3708       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3709       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3710       PrintAssembly || TraceDeoptimization || TraceDependencies ||
3711       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3712     return true;
3713   }
3714 
3715 #ifdef COMPILER1
3716   if (PrintC1Statistics) {
3717     return true;
3718   }
3719 #endif // COMPILER1
3720 
3721 #ifdef COMPILER2
3722   if (PrintOptoAssembly || PrintOptoStatistics) {
3723     return true;
3724   }
3725 #endif // COMPILER2
3726 
3727   return false;
3728 }
3729 
3730 #endif // PRODUCT
3731 
3732 bool Arguments::args_contains_vm_options_file_arg(const JavaVMInitArgs* args) {
3733   for (int index = 0; index < args->nOptions; index++) {
3734     const JavaVMOption* option = args->options + index;
3735     const char* tail;
3736     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3737       return true;
3738     }
3739   }
3740   return false;
3741 }
3742 
3743 jint Arguments::insert_vm_options_file(const JavaVMInitArgs* args,
3744                                        const char* vm_options_file,
3745                                        const int vm_options_file_pos,
3746                                        ScopedVMInitArgs* vm_options_file_args,
3747                                        ScopedVMInitArgs* args_out) {
3748   jint code = parse_vm_options_file(vm_options_file, vm_options_file_args);
3749   if (code != JNI_OK) {
3750     return code;
3751   }
3752 
3753   if (vm_options_file_args->get()->nOptions < 1) {
3754     return JNI_OK;
3755   }
3756 
3757   if (args_contains_vm_options_file_arg(vm_options_file_args->get())) {
3758     jio_fprintf(defaultStream::error_stream(),
3759                 "A VM options file may not refer to a VM options file. "
3760                 "Specification of '-XX:VMOptionsFile=<file-name>' in the "
3761                 "options file '%s' in options container '%s' is an error.\n",
3762                 vm_options_file_args->vm_options_file_arg(),
3763                 vm_options_file_args->container_name());
3764     return JNI_EINVAL;
3765   }
3766 
3767   return args_out->insert(args, vm_options_file_args->get(),
3768                           vm_options_file_pos);
3769 }
3770 
3771 // Expand -XX:VMOptionsFile found in args_in as needed.
3772 // mod_args and args_out parameters may return values as needed.
3773 jint Arguments::expand_vm_options_as_needed(const JavaVMInitArgs* args_in,
3774                                             ScopedVMInitArgs* mod_args,
3775                                             JavaVMInitArgs** args_out) {
3776   jint code = match_special_option_and_act(args_in, mod_args);
3777   if (code != JNI_OK) {
3778     return code;
3779   }
3780 
3781   if (mod_args->is_set()) {
3782     // args_in contains -XX:VMOptionsFile and mod_args contains the
3783     // original options from args_in along with the options expanded
3784     // from the VMOptionsFile. Return a short-hand to the caller.
3785     *args_out = mod_args->get();
3786   } else {
3787     *args_out = (JavaVMInitArgs *)args_in;  // no changes so use args_in
3788   }
3789   return JNI_OK;
3790 }
3791 
3792 jint Arguments::match_special_option_and_act(const JavaVMInitArgs* args,
3793                                              ScopedVMInitArgs* args_out) {
3794   // Remaining part of option string
3795   const char* tail;
3796   ScopedVMInitArgs vm_options_file_args(args_out->container_name());
3797 
3798   for (int index = 0; index < args->nOptions; index++) {
3799     const JavaVMOption* option = args->options + index;
3800     if (ArgumentsExt::process_options(option)) {
3801       continue;
3802     }
3803     if (match_option(option, "-XX:Flags=", &tail)) {
3804       Arguments::set_jvm_flags_file(tail);
3805       continue;
3806     }
3807     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3808       if (vm_options_file_args.found_vm_options_file_arg()) {
3809         jio_fprintf(defaultStream::error_stream(),
3810                     "The option '%s' is already specified in the options "
3811                     "container '%s' so the specification of '%s' in the "
3812                     "same options container is an error.\n",
3813                     vm_options_file_args.vm_options_file_arg(),
3814                     vm_options_file_args.container_name(),
3815                     option->optionString);
3816         return JNI_EINVAL;
3817       }
3818       vm_options_file_args.set_vm_options_file_arg(option->optionString);
3819       // If there's a VMOptionsFile, parse that
3820       jint code = insert_vm_options_file(args, tail, index,
3821                                          &vm_options_file_args, args_out);
3822       if (code != JNI_OK) {
3823         return code;
3824       }
3825       args_out->set_vm_options_file_arg(vm_options_file_args.vm_options_file_arg());
3826       if (args_out->is_set()) {
3827         // The VMOptions file inserted some options so switch 'args'
3828         // to the new set of options, and continue processing which
3829         // preserves "last option wins" semantics.
3830         args = args_out->get();
3831         // The first option from the VMOptionsFile replaces the
3832         // current option.  So we back track to process the
3833         // replacement option.
3834         index--;
3835       }
3836       continue;
3837     }
3838     if (match_option(option, "-XX:+PrintVMOptions")) {
3839       PrintVMOptions = true;
3840       continue;
3841     }
3842     if (match_option(option, "-XX:-PrintVMOptions")) {
3843       PrintVMOptions = false;
3844       continue;
3845     }
3846     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
3847       IgnoreUnrecognizedVMOptions = true;
3848       continue;
3849     }
3850     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
3851       IgnoreUnrecognizedVMOptions = false;
3852       continue;
3853     }
3854     if (match_option(option, "-XX:+PrintFlagsInitial")) {
3855       CommandLineFlags::printFlags(tty, false);
3856       vm_exit(0);
3857     }
3858     if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
3859 #if INCLUDE_NMT
3860       // The launcher did not setup nmt environment variable properly.
3861       if (!MemTracker::check_launcher_nmt_support(tail)) {
3862         warning("Native Memory Tracking did not setup properly, using wrong launcher?");
3863       }
3864 
3865       // Verify if nmt option is valid.
3866       if (MemTracker::verify_nmt_option()) {
3867         // Late initialization, still in single-threaded mode.
3868         if (MemTracker::tracking_level() >= NMT_summary) {
3869           MemTracker::init();
3870         }
3871       } else {
3872         vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
3873       }
3874       continue;
3875 #else
3876       jio_fprintf(defaultStream::error_stream(),
3877         "Native Memory Tracking is not supported in this VM\n");
3878       return JNI_ERR;
3879 #endif
3880     }
3881 
3882 #ifndef PRODUCT
3883     if (match_option(option, "-XX:+PrintFlagsWithComments")) {
3884       CommandLineFlags::printFlags(tty, true);
3885       vm_exit(0);
3886     }
3887 #endif
3888 
3889     if (match_option(option, "-XX:+UseAppCDS")) {
3890       Flag* flag = Flag::find_flag("SharedArchiveFile", 17, true, true);
3891       if (flag->is_diagnostic()) {
3892         flag->clear_diagnostic();
3893       }
3894       continue;
3895     }
3896   }
3897   return JNI_OK;
3898 }
3899 
3900 static void print_options(const JavaVMInitArgs *args) {
3901   const char* tail;
3902   for (int index = 0; index < args->nOptions; index++) {
3903     const JavaVMOption *option = args->options + index;
3904     if (match_option(option, "-XX:", &tail)) {
3905       logOption(tail);
3906     }
3907   }
3908 }
3909 
3910 bool Arguments::handle_deprecated_print_gc_flags() {
3911   if (PrintGC) {
3912     log_warning(gc)("-XX:+PrintGC is deprecated. Will use -Xlog:gc instead.");
3913   }
3914   if (PrintGCDetails) {
3915     log_warning(gc)("-XX:+PrintGCDetails is deprecated. Will use -Xlog:gc* instead.");
3916   }
3917 
3918   if (_gc_log_filename != NULL) {
3919     // -Xloggc was used to specify a filename
3920     const char* gc_conf = PrintGCDetails ? "gc*" : "gc";
3921 
3922     LogTarget(Error, logging) target;
3923     LogStream errstream(target);
3924     return LogConfiguration::parse_log_arguments(_gc_log_filename, gc_conf, NULL, NULL, &errstream);
3925   } else if (PrintGC || PrintGCDetails) {
3926     LogConfiguration::configure_stdout(LogLevel::Info, !PrintGCDetails, LOG_TAGS(gc));
3927   }
3928   return true;
3929 }
3930 
3931 void Arguments::handle_extra_cms_flags(const char* msg) {
3932   SpecialFlag flag;
3933   const char *flag_name = "UseConcMarkSweepGC";
3934   if (lookup_special_flag(flag_name, flag)) {
3935     handle_aliases_and_deprecation(flag_name, /* print warning */ true);
3936     warning("%s", msg);
3937   }
3938 }
3939 
3940 // Parse entry point called from JNI_CreateJavaVM
3941 
3942 jint Arguments::parse(const JavaVMInitArgs* initial_cmd_args) {
3943   assert(verify_special_jvm_flags(), "deprecated and obsolete flag table inconsistent");
3944 
3945   // Initialize ranges, constraints and writeables
3946   CommandLineFlagRangeList::init();
3947   CommandLineFlagConstraintList::init();
3948   CommandLineFlagWriteableList::init();
3949 
3950   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
3951   const char* hotspotrc = ".hotspotrc";
3952   bool settings_file_specified = false;
3953   bool needs_hotspotrc_warning = false;
3954   ScopedVMInitArgs initial_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
3955   ScopedVMInitArgs initial_java_options_args("env_var='_JAVA_OPTIONS'");
3956 
3957   // Pointers to current working set of containers
3958   JavaVMInitArgs* cur_cmd_args;
3959   JavaVMInitArgs* cur_java_options_args;
3960   JavaVMInitArgs* cur_java_tool_options_args;
3961 
3962   // Containers for modified/expanded options
3963   ScopedVMInitArgs mod_cmd_args("cmd_line_args");
3964   ScopedVMInitArgs mod_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
3965   ScopedVMInitArgs mod_java_options_args("env_var='_JAVA_OPTIONS'");
3966 
3967 
3968   jint code =
3969       parse_java_tool_options_environment_variable(&initial_java_tool_options_args);
3970   if (code != JNI_OK) {
3971     return code;
3972   }
3973 
3974   code = parse_java_options_environment_variable(&initial_java_options_args);
3975   if (code != JNI_OK) {
3976     return code;
3977   }
3978 
3979   code = expand_vm_options_as_needed(initial_java_tool_options_args.get(),
3980                                      &mod_java_tool_options_args,
3981                                      &cur_java_tool_options_args);
3982   if (code != JNI_OK) {
3983     return code;
3984   }
3985 
3986   code = expand_vm_options_as_needed(initial_cmd_args,
3987                                      &mod_cmd_args,
3988                                      &cur_cmd_args);
3989   if (code != JNI_OK) {
3990     return code;
3991   }
3992 
3993   code = expand_vm_options_as_needed(initial_java_options_args.get(),
3994                                      &mod_java_options_args,
3995                                      &cur_java_options_args);
3996   if (code != JNI_OK) {
3997     return code;
3998   }
3999 
4000   const char* flags_file = Arguments::get_jvm_flags_file();
4001   settings_file_specified = (flags_file != NULL);
4002 
4003   if (IgnoreUnrecognizedVMOptions) {
4004     cur_cmd_args->ignoreUnrecognized = true;
4005     cur_java_tool_options_args->ignoreUnrecognized = true;
4006     cur_java_options_args->ignoreUnrecognized = true;
4007   }
4008 
4009   // Parse specified settings file
4010   if (settings_file_specified) {
4011     if (!process_settings_file(flags_file, true,
4012                                cur_cmd_args->ignoreUnrecognized)) {
4013       return JNI_EINVAL;
4014     }
4015   } else {
4016 #ifdef ASSERT
4017     // Parse default .hotspotrc settings file
4018     if (!process_settings_file(".hotspotrc", false,
4019                                cur_cmd_args->ignoreUnrecognized)) {
4020       return JNI_EINVAL;
4021     }
4022 #else
4023     struct stat buf;
4024     if (os::stat(hotspotrc, &buf) == 0) {
4025       needs_hotspotrc_warning = true;
4026     }
4027 #endif
4028   }
4029 
4030   if (PrintVMOptions) {
4031     print_options(cur_java_tool_options_args);
4032     print_options(cur_cmd_args);
4033     print_options(cur_java_options_args);
4034   }
4035 
4036   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
4037   jint result = parse_vm_init_args(cur_java_tool_options_args,
4038                                    cur_java_options_args,
4039                                    cur_cmd_args);
4040 
4041   if (result != JNI_OK) {
4042     return result;
4043   }
4044 
4045   // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
4046   SharedArchivePath = get_shared_archive_path();
4047   if (SharedArchivePath == NULL) {
4048     return JNI_ENOMEM;
4049   }
4050 
4051   // Set up VerifySharedSpaces
4052   if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
4053     VerifySharedSpaces = true;
4054   }
4055 
4056   // Delay warning until here so that we've had a chance to process
4057   // the -XX:-PrintWarnings flag
4058   if (needs_hotspotrc_warning) {
4059     warning("%s file is present but has been ignored.  "
4060             "Run with -XX:Flags=%s to load the file.",
4061             hotspotrc, hotspotrc);
4062   }
4063 
4064   if (needs_module_property_warning) {
4065     warning("Ignoring system property options whose names match the '-Djdk.module.*'."
4066             " names that are reserved for internal use.");
4067   }
4068 
4069 #if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
4070   UNSUPPORTED_OPTION(UseLargePages);
4071 #endif
4072 
4073   ArgumentsExt::report_unsupported_options();
4074 
4075 #ifndef PRODUCT
4076   if (TraceBytecodesAt != 0) {
4077     TraceBytecodes = true;
4078   }
4079   if (CountCompiledCalls) {
4080     if (UseCounterDecay) {
4081       warning("UseCounterDecay disabled because CountCalls is set");
4082       UseCounterDecay = false;
4083     }
4084   }
4085 #endif // PRODUCT
4086 
4087   if (ScavengeRootsInCode == 0) {
4088     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
4089       warning("Forcing ScavengeRootsInCode non-zero");
4090     }
4091     ScavengeRootsInCode = 1;
4092   }
4093 
4094   if (!handle_deprecated_print_gc_flags()) {
4095     return JNI_EINVAL;
4096   }
4097 
4098   // Set object alignment values.
4099   set_object_alignment();
4100 
4101 #if !INCLUDE_CDS
4102   if (DumpSharedSpaces || RequireSharedSpaces) {
4103     jio_fprintf(defaultStream::error_stream(),
4104       "Shared spaces are not supported in this VM\n");
4105     return JNI_ERR;
4106   }
4107   if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) ||
4108       log_is_enabled(Info, cds)) {
4109     warning("Shared spaces are not supported in this VM");
4110     FLAG_SET_DEFAULT(UseSharedSpaces, false);
4111     LogConfiguration::configure_stdout(LogLevel::Off, true, LOG_TAGS(cds));
4112   }
4113   no_shared_spaces("CDS Disabled");
4114 #endif // INCLUDE_CDS
4115 
4116   return JNI_OK;
4117 }
4118 
4119 jint Arguments::apply_ergo() {
4120   // Set flags based on ergonomics.
4121   jint result = set_ergonomics_flags();
4122   if (result != JNI_OK) return result;
4123 
4124 #if INCLUDE_JVMCI
4125   set_jvmci_specific_flags();
4126 #endif
4127 
4128   set_shared_spaces_flags();
4129 
4130   if (TieredCompilation) {
4131     set_tiered_flags();
4132   } else {
4133     int max_compilation_policy_choice = 1;
4134 #ifdef COMPILER2
4135     if (is_server_compilation_mode_vm()) {
4136       max_compilation_policy_choice = 2;
4137     }
4138 #endif
4139     // Check if the policy is valid.
4140     if (CompilationPolicyChoice >= max_compilation_policy_choice) {
4141       vm_exit_during_initialization(
4142         "Incompatible compilation policy selected", NULL);
4143     }
4144     // Scale CompileThreshold
4145     // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves CompileThreshold unchanged.
4146     if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
4147       FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold));
4148     }
4149   }
4150 
4151 #ifdef COMPILER2
4152 #ifndef PRODUCT
4153   if (PrintIdealGraphLevel > 0) {
4154     FLAG_SET_ERGO(bool, PrintIdealGraph, true);
4155   }
4156 #endif
4157 #endif
4158 
4159   // Set heap size based on available physical memory
4160   set_heap_size();
4161 
4162   GCConfig::arguments()->initialize();
4163 
4164   // Initialize Metaspace flags and alignments
4165   Metaspace::ergo_initialize();
4166 
4167   // Set bytecode rewriting flags
4168   set_bytecode_flags();
4169 
4170   // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled
4171   jint code = set_aggressive_opts_flags();
4172   if (code != JNI_OK) {
4173     return code;
4174   }
4175 
4176   // Turn off biased locking for locking debug mode flags,
4177   // which are subtly different from each other but neither works with
4178   // biased locking
4179   if (UseHeavyMonitors
4180 #ifdef COMPILER1
4181       || !UseFastLocking
4182 #endif // COMPILER1
4183 #if INCLUDE_JVMCI
4184       || !JVMCIUseFastLocking
4185 #endif
4186     ) {
4187     if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
4188       // flag set to true on command line; warn the user that they
4189       // can't enable biased locking here
4190       warning("Biased Locking is not supported with locking debug flags"
4191               "; ignoring UseBiasedLocking flag." );
4192     }
4193     UseBiasedLocking = false;
4194   }
4195 
4196 #ifdef CC_INTERP
4197   // Clear flags not supported on zero.
4198   FLAG_SET_DEFAULT(ProfileInterpreter, false);
4199   FLAG_SET_DEFAULT(UseBiasedLocking, false);
4200   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
4201   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
4202 #endif // CC_INTERP
4203 
4204 #ifdef COMPILER2
4205   if (!EliminateLocks) {
4206     EliminateNestedLocks = false;
4207   }
4208   if (!Inline) {
4209     IncrementalInline = false;
4210   }
4211 #ifndef PRODUCT
4212   if (!IncrementalInline) {
4213     AlwaysIncrementalInline = false;
4214   }
4215 #endif
4216   if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
4217     // nothing to use the profiling, turn if off
4218     FLAG_SET_DEFAULT(TypeProfileLevel, 0);
4219   }
4220   if (FLAG_IS_DEFAULT(LoopStripMiningIterShortLoop)) {
4221     // blind guess
4222     LoopStripMiningIterShortLoop = LoopStripMiningIter / 10;
4223   }
4224 #endif
4225 
4226   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
4227     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
4228     DebugNonSafepoints = true;
4229   }
4230 
4231   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
4232     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
4233   }
4234 
4235   if (UseOnStackReplacement && !UseLoopCounter) {
4236     warning("On-stack-replacement requires loop counters; enabling loop counters");
4237     FLAG_SET_DEFAULT(UseLoopCounter, true);
4238   }
4239 
4240 #ifndef PRODUCT
4241   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
4242     if (use_vm_log()) {
4243       LogVMOutput = true;
4244     }
4245   }
4246 #endif // PRODUCT
4247 
4248   if (PrintCommandLineFlags) {
4249     CommandLineFlags::printSetFlags(tty);
4250   }
4251 
4252   // Apply CPU specific policy for the BiasedLocking
4253   if (UseBiasedLocking) {
4254     if (!VM_Version::use_biased_locking() &&
4255         !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
4256       UseBiasedLocking = false;
4257     }
4258   }
4259 #ifdef COMPILER2
4260   if (!UseBiasedLocking || EmitSync != 0) {
4261     UseOptoBiasInlining = false;
4262   }
4263 #endif
4264 
4265   // ThreadLocalHandshakesConstraintFunc handles the constraints.
4266   if (FLAG_IS_DEFAULT(ThreadLocalHandshakes) || !SafepointMechanism::supports_thread_local_poll()) {
4267     log_debug(ergo)("ThreadLocalHandshakes %s", ThreadLocalHandshakes ? "enabled." : "disabled.");
4268   } else {
4269     log_info(ergo)("ThreadLocalHandshakes %s", ThreadLocalHandshakes ? "enabled." : "disabled.");
4270   }
4271 
4272   return JNI_OK;
4273 }
4274 
4275 jint Arguments::adjust_after_os() {
4276   if (UseNUMA) {
4277     if (!FLAG_IS_DEFAULT(AllocateHeapAt)) {
4278       FLAG_SET_ERGO(bool, UseNUMA, false);
4279     } else if (UseParallelGC || UseParallelOldGC) {
4280       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4281          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4282       }
4283     }
4284     // UseNUMAInterleaving is set to ON for all collectors and
4285     // platforms when UseNUMA is set to ON. NUMA-aware collectors
4286     // such as the parallel collector for Linux and Solaris will
4287     // interleave old gen and survivor spaces on top of NUMA
4288     // allocation policy for the eden space.
4289     // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
4290     // all platforms and ParallelGC on Windows will interleave all
4291     // of the heap spaces across NUMA nodes.
4292     if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
4293       FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
4294     }
4295   }
4296   return JNI_OK;
4297 }
4298 
4299 int Arguments::PropertyList_count(SystemProperty* pl) {
4300   int count = 0;
4301   while(pl != NULL) {
4302     count++;
4303     pl = pl->next();
4304   }
4305   return count;
4306 }
4307 
4308 // Return the number of readable properties.
4309 int Arguments::PropertyList_readable_count(SystemProperty* pl) {
4310   int count = 0;
4311   while(pl != NULL) {
4312     if (pl->is_readable()) {
4313       count++;
4314     }
4315     pl = pl->next();
4316   }
4317   return count;
4318 }
4319 
4320 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4321   assert(key != NULL, "just checking");
4322   SystemProperty* prop;
4323   for (prop = pl; prop != NULL; prop = prop->next()) {
4324     if (strcmp(key, prop->key()) == 0) return prop->value();
4325   }
4326   return NULL;
4327 }
4328 
4329 // Return the value of the requested property provided that it is a readable property.
4330 const char* Arguments::PropertyList_get_readable_value(SystemProperty *pl, const char* key) {
4331   assert(key != NULL, "just checking");
4332   SystemProperty* prop;
4333   // Return the property value if the keys match and the property is not internal or
4334   // it's the special internal property "jdk.boot.class.path.append".
4335   for (prop = pl; prop != NULL; prop = prop->next()) {
4336     if (strcmp(key, prop->key()) == 0) {
4337       if (!prop->internal()) {
4338         return prop->value();
4339       } else if (strcmp(key, "jdk.boot.class.path.append") == 0) {
4340         return prop->value();
4341       } else {
4342         // Property is internal and not jdk.boot.class.path.append so return NULL.
4343         return NULL;
4344       }
4345     }
4346   }
4347   return NULL;
4348 }
4349 
4350 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
4351   int count = 0;
4352   const char* ret_val = NULL;
4353 
4354   while(pl != NULL) {
4355     if(count >= index) {
4356       ret_val = pl->key();
4357       break;
4358     }
4359     count++;
4360     pl = pl->next();
4361   }
4362 
4363   return ret_val;
4364 }
4365 
4366 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
4367   int count = 0;
4368   char* ret_val = NULL;
4369 
4370   while(pl != NULL) {
4371     if(count >= index) {
4372       ret_val = pl->value();
4373       break;
4374     }
4375     count++;
4376     pl = pl->next();
4377   }
4378 
4379   return ret_val;
4380 }
4381 
4382 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4383   SystemProperty* p = *plist;
4384   if (p == NULL) {
4385     *plist = new_p;
4386   } else {
4387     while (p->next() != NULL) {
4388       p = p->next();
4389     }
4390     p->set_next(new_p);
4391   }
4392 }
4393 
4394 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v,
4395                                  bool writeable, bool internal) {
4396   if (plist == NULL)
4397     return;
4398 
4399   SystemProperty* new_p = new SystemProperty(k, v, writeable, internal);
4400   PropertyList_add(plist, new_p);
4401 }
4402 
4403 void Arguments::PropertyList_add(SystemProperty *element) {
4404   PropertyList_add(&_system_properties, element);
4405 }
4406 
4407 // This add maintains unique property key in the list.
4408 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v,
4409                                         PropertyAppendable append, PropertyWriteable writeable,
4410                                         PropertyInternal internal) {
4411   if (plist == NULL)
4412     return;
4413 
4414   // If property key exist then update with new value.
4415   SystemProperty* prop;
4416   for (prop = *plist; prop != NULL; prop = prop->next()) {
4417     if (strcmp(k, prop->key()) == 0) {
4418       if (append == AppendProperty) {
4419         prop->append_value(v);
4420       } else {
4421         prop->set_value(v);
4422       }
4423       return;
4424     }
4425   }
4426 
4427   PropertyList_add(plist, k, v, writeable == WriteableProperty, internal == InternalProperty);
4428 }
4429 
4430 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4431 // Returns true if all of the source pointed by src has been copied over to
4432 // the destination buffer pointed by buf. Otherwise, returns false.
4433 // Notes:
4434 // 1. If the length (buflen) of the destination buffer excluding the
4435 // NULL terminator character is not long enough for holding the expanded
4436 // pid characters, it also returns false instead of returning the partially
4437 // expanded one.
4438 // 2. The passed in "buflen" should be large enough to hold the null terminator.
4439 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4440                                 char* buf, size_t buflen) {
4441   const char* p = src;
4442   char* b = buf;
4443   const char* src_end = &src[srclen];
4444   char* buf_end = &buf[buflen - 1];
4445 
4446   while (p < src_end && b < buf_end) {
4447     if (*p == '%') {
4448       switch (*(++p)) {
4449       case '%':         // "%%" ==> "%"
4450         *b++ = *p++;
4451         break;
4452       case 'p':  {       //  "%p" ==> current process id
4453         // buf_end points to the character before the last character so
4454         // that we could write '\0' to the end of the buffer.
4455         size_t buf_sz = buf_end - b + 1;
4456         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4457 
4458         // if jio_snprintf fails or the buffer is not long enough to hold
4459         // the expanded pid, returns false.
4460         if (ret < 0 || ret >= (int)buf_sz) {
4461           return false;
4462         } else {
4463           b += ret;
4464           assert(*b == '\0', "fail in copy_expand_pid");
4465           if (p == src_end && b == buf_end + 1) {
4466             // reach the end of the buffer.
4467             return true;
4468           }
4469         }
4470         p++;
4471         break;
4472       }
4473       default :
4474         *b++ = '%';
4475       }
4476     } else {
4477       *b++ = *p++;
4478     }
4479   }
4480   *b = '\0';
4481   return (p == src_end); // return false if not all of the source was copied
4482 }