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