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