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