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