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