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