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