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