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