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