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