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