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