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