arguments.cpp 165.8 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25
#include "precompiled.hpp"
26
#include "classfile/classLoader.hpp"
27
#include "classfile/javaAssertions.hpp"
28
#include "classfile/symbolTable.hpp"
29 30 31
#include "compiler/compilerOracle.hpp"
#include "memory/allocation.inline.hpp"
#include "memory/cardTableRS.hpp"
32
#include "memory/genCollectedHeap.hpp"
33 34 35 36 37
#include "memory/referenceProcessor.hpp"
#include "memory/universe.inline.hpp"
#include "oops/oop.inline.hpp"
#include "prims/jvmtiExport.hpp"
#include "runtime/arguments.hpp"
38
#include "runtime/arguments_ext.hpp"
39 40 41
#include "runtime/globals_extension.hpp"
#include "runtime/java.hpp"
#include "services/management.hpp"
Z
zgu 已提交
42
#include "services/memTracker.hpp"
43
#include "utilities/defaultStream.hpp"
44
#include "utilities/macros.hpp"
45
#include "utilities/stringUtils.hpp"
46 47 48 49 50 51 52 53 54 55
#include "utilities/taskqueue.hpp"
#ifdef TARGET_OS_FAMILY_linux
# include "os_linux.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_solaris
# include "os_solaris.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_windows
# include "os_windows.inline.hpp"
#endif
56 57 58
#ifdef TARGET_OS_FAMILY_aix
# include "os_aix.inline.hpp"
#endif
N
never 已提交
59 60 61
#ifdef TARGET_OS_FAMILY_bsd
# include "os_bsd.inline.hpp"
#endif
62
#if INCLUDE_ALL_GCS
63
#include "gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp"
64 65
#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
#include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"
66
#endif // INCLUDE_ALL_GCS
D
duke 已提交
67

68
// Note: This is a special bug reporting site for the JVM
69 70 71 72 73
#ifdef VENDOR_URL_VM_BUG
# define DEFAULT_VENDOR_URL_BUG VENDOR_URL_VM_BUG
#else
# define DEFAULT_VENDOR_URL_BUG "http://bugreport.java.com/bugreport/crash.jsp"
#endif
D
duke 已提交
74 75
#define DEFAULT_JAVA_LAUNCHER  "generic"

76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
// Disable options not supported in this release, with a warning if they
// were explicitly requested on the command-line
#define UNSUPPORTED_OPTION(opt, description)                    \
do {                                                            \
  if (opt) {                                                    \
    if (FLAG_IS_CMDLINE(opt)) {                                 \
      warning(description " is disabled in this release.");     \
    }                                                           \
    FLAG_SET_DEFAULT(opt, false);                               \
  }                                                             \
} while(0)

#define UNSUPPORTED_GC_OPTION(gc)                                     \
do {                                                                  \
  if (gc) {                                                           \
    if (FLAG_IS_CMDLINE(gc)) {                                        \
      warning(#gc " is not supported in this VM.  Using Serial GC."); \
    }                                                                 \
    FLAG_SET_DEFAULT(gc, false);                                      \
  }                                                                   \
} while(0)

D
duke 已提交
98 99 100 101 102 103 104 105
char**  Arguments::_jvm_flags_array             = NULL;
int     Arguments::_num_jvm_flags               = 0;
char**  Arguments::_jvm_args_array              = NULL;
int     Arguments::_num_jvm_args                = 0;
char*  Arguments::_java_command                 = NULL;
SystemProperty* Arguments::_system_properties   = NULL;
const char*  Arguments::_gc_log_filename        = NULL;
bool   Arguments::_has_profile                  = false;
106
size_t Arguments::_conservative_max_heap_alignment = 0;
D
duke 已提交
107
uintx  Arguments::_min_heap_size                = 0;
108 109
uintx  Arguments::_min_heap_free_ratio          = 0;
uintx  Arguments::_max_heap_free_ratio          = 0;
D
duke 已提交
110 111 112 113 114 115
Arguments::Mode Arguments::_mode                = _mixed;
bool   Arguments::_java_compiler                = false;
bool   Arguments::_xdebug_mode                  = false;
const char*  Arguments::_java_vendor_url_bug    = DEFAULT_VENDOR_URL_BUG;
const char*  Arguments::_sun_java_launcher      = DEFAULT_JAVA_LAUNCHER;
int    Arguments::_sun_java_launcher_pid        = -1;
116
bool   Arguments::_created_by_gamma_launcher    = false;
D
duke 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217

// These parameters are reset in method parse_vm_init_args(JavaVMInitArgs*)
bool   Arguments::_AlwaysCompileLoopMethods     = AlwaysCompileLoopMethods;
bool   Arguments::_UseOnStackReplacement        = UseOnStackReplacement;
bool   Arguments::_BackgroundCompilation        = BackgroundCompilation;
bool   Arguments::_ClipInlining                 = ClipInlining;

char*  Arguments::SharedArchivePath             = NULL;

AgentLibraryList Arguments::_libraryList;
AgentLibraryList Arguments::_agentList;

abort_hook_t     Arguments::_abort_hook         = NULL;
exit_hook_t      Arguments::_exit_hook          = NULL;
vfprintf_hook_t  Arguments::_vfprintf_hook      = NULL;


SystemProperty *Arguments::_java_ext_dirs = NULL;
SystemProperty *Arguments::_java_endorsed_dirs = NULL;
SystemProperty *Arguments::_sun_boot_library_path = NULL;
SystemProperty *Arguments::_java_library_path = NULL;
SystemProperty *Arguments::_java_home = NULL;
SystemProperty *Arguments::_java_class_path = NULL;
SystemProperty *Arguments::_sun_boot_class_path = NULL;

char* Arguments::_meta_index_path = NULL;
char* Arguments::_meta_index_dir = NULL;

// Check if head of 'option' matches 'name', and sets 'tail' remaining part of option string

static bool match_option(const JavaVMOption *option, const char* name,
                         const char** tail) {
  int len = (int)strlen(name);
  if (strncmp(option->optionString, name, len) == 0) {
    *tail = option->optionString + len;
    return true;
  } else {
    return false;
  }
}

static void logOption(const char* opt) {
  if (PrintVMOptions) {
    jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);
  }
}

// Process java launcher properties.
void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
  // See if sun.java.launcher or sun.java.launcher.pid is defined.
  // Must do this before setting up other system properties,
  // as some of them may depend on launcher type.
  for (int index = 0; index < args->nOptions; index++) {
    const JavaVMOption* option = args->options + index;
    const char* tail;

    if (match_option(option, "-Dsun.java.launcher=", &tail)) {
      process_java_launcher_argument(tail, option->extraInfo);
      continue;
    }
    if (match_option(option, "-Dsun.java.launcher.pid=", &tail)) {
      _sun_java_launcher_pid = atoi(tail);
      continue;
    }
  }
}

// Initialize system properties key and value.
void Arguments::init_system_properties() {

  PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
                                                                 "Java Virtual Machine Specification",  false));
  PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(),  false));
  PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(),  false));
  PropertyList_add(&_system_properties, new SystemProperty("java.vm.info", VM_Version::vm_info_string(),  true));

  // following are JVMTI agent writeable properties.
  // Properties values are set to NULL and they are
  // os specific they are initialized in os::init_system_properties_values().
  _java_ext_dirs = new SystemProperty("java.ext.dirs", NULL,  true);
  _java_endorsed_dirs = new SystemProperty("java.endorsed.dirs", NULL,  true);
  _sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL,  true);
  _java_library_path = new SystemProperty("java.library.path", NULL,  true);
  _java_home =  new SystemProperty("java.home", NULL,  true);
  _sun_boot_class_path = new SystemProperty("sun.boot.class.path", NULL,  true);

  _java_class_path = new SystemProperty("java.class.path", "",  true);

  // Add to System Property list.
  PropertyList_add(&_system_properties, _java_ext_dirs);
  PropertyList_add(&_system_properties, _java_endorsed_dirs);
  PropertyList_add(&_system_properties, _sun_boot_library_path);
  PropertyList_add(&_system_properties, _java_library_path);
  PropertyList_add(&_system_properties, _java_home);
  PropertyList_add(&_system_properties, _java_class_path);
  PropertyList_add(&_system_properties, _sun_boot_class_path);

  // Set OS specific system properties values
  os::init_system_properties_values();
}

218 219 220

  // Update/Initialize System properties after JDK version number is known
void Arguments::init_version_specific_system_properties() {
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
  enum { bufsz = 16 };
  char buffer[bufsz];
  const char* spec_vendor = "Sun Microsystems Inc.";
  uint32_t spec_version = 0;

  if (JDK_Version::is_gte_jdk17x_version()) {
    spec_vendor = "Oracle Corporation";
    spec_version = JDK_Version::current().major_version();
  }
  jio_snprintf(buffer, bufsz, "1." UINT32_FORMAT, spec_version);

  PropertyList_add(&_system_properties,
      new SystemProperty("java.vm.specification.vendor",  spec_vendor, false));
  PropertyList_add(&_system_properties,
      new SystemProperty("java.vm.specification.version", buffer, false));
  PropertyList_add(&_system_properties,
      new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(),  false));
238 239
}

K
kamg 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
/**
 * Provide a slightly more user-friendly way of eliminating -XX flags.
 * When a flag is eliminated, it can be added to this list in order to
 * continue accepting this flag on the command-line, while issuing a warning
 * and ignoring the value.  Once the JDK version reaches the 'accept_until'
 * limit, we flatly refuse to admit the existence of the flag.  This allows
 * a flag to die correctly over JDK releases using HSX.
 */
typedef struct {
  const char* name;
  JDK_Version obsoleted_in; // when the flag went away
  JDK_Version accept_until; // which version to start denying the existence
} ObsoleteFlag;

static ObsoleteFlag obsolete_jvm_flags[] = {
  { "UseTrainGC",                    JDK_Version::jdk(5), JDK_Version::jdk(7) },
  { "UseSpecialLargeObjectHandling", JDK_Version::jdk(5), JDK_Version::jdk(7) },
  { "UseOversizedCarHandling",       JDK_Version::jdk(5), JDK_Version::jdk(7) },
  { "TraceCarAllocation",            JDK_Version::jdk(5), JDK_Version::jdk(7) },
  { "PrintTrainGCProcessingStats",   JDK_Version::jdk(5), JDK_Version::jdk(7) },
  { "LogOfCarSpaceSize",             JDK_Version::jdk(5), JDK_Version::jdk(7) },
  { "OversizedCarThreshold",         JDK_Version::jdk(5), JDK_Version::jdk(7) },
  { "MinTickInterval",               JDK_Version::jdk(5), JDK_Version::jdk(7) },
  { "DefaultTickInterval",           JDK_Version::jdk(5), JDK_Version::jdk(7) },
  { "MaxTickInterval",               JDK_Version::jdk(5), JDK_Version::jdk(7) },
  { "DelayTickAdjustment",           JDK_Version::jdk(5), JDK_Version::jdk(7) },
  { "ProcessingToTenuringRatio",     JDK_Version::jdk(5), JDK_Version::jdk(7) },
  { "MinTrainLength",                JDK_Version::jdk(5), JDK_Version::jdk(7) },
  { "AppendRatio",         JDK_Version::jdk_update(6,10), JDK_Version::jdk(7) },
P
phh 已提交
269 270 271
  { "DefaultMaxRAM",       JDK_Version::jdk_update(6,18), JDK_Version::jdk(7) },
  { "DefaultInitialRAMFraction",
                           JDK_Version::jdk_update(6,18), JDK_Version::jdk(7) },
272 273
  { "UseDepthFirstScavengeOrder",
                           JDK_Version::jdk_update(6,22), JDK_Version::jdk(7) },
274 275 276 277
  { "HandlePromotionFailure",
                           JDK_Version::jdk_update(6,24), JDK_Version::jdk(8) },
  { "MaxLiveObjectEvacuationRatio",
                           JDK_Version::jdk_update(6,24), JDK_Version::jdk(8) },
278
  { "ForceSharedSpaces",   JDK_Version::jdk_update(6,25), JDK_Version::jdk(8) },
279 280 281 282 283 284
  { "UseParallelOldGCCompacting",
                           JDK_Version::jdk_update(6,27), JDK_Version::jdk(8) },
  { "UseParallelDensePrefixUpdate",
                           JDK_Version::jdk_update(6,27), JDK_Version::jdk(8) },
  { "UseParallelOldGCDensePrefix",
                           JDK_Version::jdk_update(6,27), JDK_Version::jdk(8) },
285
  { "AllowTransitionalJSR292",       JDK_Version::jdk(7), JDK_Version::jdk(8) },
286
  { "UseCompressedStrings",          JDK_Version::jdk(7), JDK_Version::jdk(8) },
287 288 289 290 291 292 293 294 295 296 297 298
  { "CMSPermGenPrecleaningEnabled", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
  { "CMSTriggerPermRatio", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
  { "CMSInitiatingPermOccupancyFraction", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
  { "AdaptivePermSizeWeight", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
  { "PermGenPadding", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
  { "PermMarkSweepDeadRatio", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
  { "PermSize", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
  { "MaxPermSize", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
  { "MinPermHeapExpansion", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
  { "MaxPermHeapExpansion", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
  { "CMSRevisitStackSize",           JDK_Version::jdk(8), JDK_Version::jdk(9) },
  { "PrintRevisitStats",             JDK_Version::jdk(8), JDK_Version::jdk(9) },
299
  { "UseVectoredExceptions",         JDK_Version::jdk(8), JDK_Version::jdk(9) },
300
  { "UseSplitVerifier",              JDK_Version::jdk(8), JDK_Version::jdk(9) },
301 302 303
  { "UseISM",                        JDK_Version::jdk(8), JDK_Version::jdk(9) },
  { "UsePermISM",                    JDK_Version::jdk(8), JDK_Version::jdk(9) },
  { "UseMPSS",                       JDK_Version::jdk(8), JDK_Version::jdk(9) },
304
  { "UseStringCache",                JDK_Version::jdk(8), JDK_Version::jdk(9) },
305 306
  { "UseOldInlining",                JDK_Version::jdk_update(8, 20), JDK_Version::jdk(10) },
  { "AutoShutdownNMT",               JDK_Version::jdk_update(8, 40), JDK_Version::jdk(10) },
N
neliasso 已提交
307
  { "CompilationRepeat",             JDK_Version::jdk(8), JDK_Version::jdk(9) },
308
  { "SegmentedHeapDumpThreshold",    JDK_Version::jdk_update(8, 252), JDK_Version::jdk(10) },
309 310 311 312
#ifdef PRODUCT
  { "DesiredMethodLimit",
                           JDK_Version::jdk_update(7, 2), JDK_Version::jdk(8) },
#endif // PRODUCT
K
kamg 已提交
313 314 315 316 317 318 319 320
  { NULL, JDK_Version(0), JDK_Version(0) }
};

// Returns true if the flag is obsolete and fits into the range specified
// for being ignored.  In the case that the flag is ignored, the 'version'
// value is filled in with the version number when the flag became
// obsolete so that that value can be displayed to the user.
bool Arguments::is_newly_obsolete(const char *s, JDK_Version* version) {
D
duke 已提交
321
  int i = 0;
K
kamg 已提交
322 323 324
  assert(version != NULL, "Must provide a version buffer");
  while (obsolete_jvm_flags[i].name != NULL) {
    const ObsoleteFlag& flag_status = obsolete_jvm_flags[i];
D
duke 已提交
325 326
    // <flag>=xxx form
    // [-|+]<flag> form
K
kamg 已提交
327
    if ((strncmp(flag_status.name, s, strlen(flag_status.name)) == 0) ||
D
duke 已提交
328
        ((s[0] == '+' || s[0] == '-') &&
K
kamg 已提交
329 330 331 332 333
        (strncmp(flag_status.name, &s[1], strlen(flag_status.name)) == 0))) {
      if (JDK_Version::current().compare(flag_status.accept_until) == -1) {
          *version = flag_status.obsoleted_in;
          return true;
      }
D
duke 已提交
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
    }
    i++;
  }
  return false;
}

// Constructs the system class path (aka boot class path) from the following
// components, in order:
//
//     prefix           // from -Xbootclasspath/p:...
//     endorsed         // the expansion of -Djava.endorsed.dirs=...
//     base             // from os::get_system_properties() or -Xbootclasspath=
//     suffix           // from -Xbootclasspath/a:...
//
// java.endorsed.dirs is a list of directories; any jar or zip files in the
// directories are added to the sysclasspath just before the base.
//
// This could be AllStatic, but it isn't needed after argument processing is
// complete.
class SysClassPath: public StackObj {
public:
  SysClassPath(const char* base);
  ~SysClassPath();

  inline void set_base(const char* base);
  inline void add_prefix(const char* prefix);
360
  inline void add_suffix_to_prefix(const char* suffix);
D
duke 已提交
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
  inline void add_suffix(const char* suffix);
  inline void reset_path(const char* base);

  // Expand the jar/zip files in each directory listed by the java.endorsed.dirs
  // property.  Must be called after all command-line arguments have been
  // processed (in particular, -Djava.endorsed.dirs=...) and before calling
  // combined_path().
  void expand_endorsed();

  inline const char* get_base()     const { return _items[_scp_base]; }
  inline const char* get_prefix()   const { return _items[_scp_prefix]; }
  inline const char* get_suffix()   const { return _items[_scp_suffix]; }
  inline const char* get_endorsed() const { return _items[_scp_endorsed]; }

  // Combine all the components into a single c-heap-allocated string; caller
  // must free the string if/when no longer needed.
  char* combined_path();

private:
  // Utility routines.
  static char* add_to_path(const char* path, const char* str, bool prepend);
  static char* add_jars_to_path(char* path, const char* directory);

  inline void reset_item_at(int index);

  // Array indices for the items that make up the sysclasspath.  All except the
  // base are allocated in the C heap and freed by this class.
  enum {
    _scp_prefix,        // from -Xbootclasspath/p:...
    _scp_endorsed,      // the expansion of -Djava.endorsed.dirs=...
    _scp_base,          // the default sysclasspath
    _scp_suffix,        // from -Xbootclasspath/a:...
    _scp_nitems         // the number of items, must be last.
  };

  const char* _items[_scp_nitems];
  DEBUG_ONLY(bool _expansion_done;)
};

SysClassPath::SysClassPath(const char* base) {
  memset(_items, 0, sizeof(_items));
  _items[_scp_base] = base;
  DEBUG_ONLY(_expansion_done = false;)
}

SysClassPath::~SysClassPath() {
  // Free everything except the base.
  for (int i = 0; i < _scp_nitems; ++i) {
    if (i != _scp_base) reset_item_at(i);
  }
  DEBUG_ONLY(_expansion_done = false;)
}

inline void SysClassPath::set_base(const char* base) {
  _items[_scp_base] = base;
}

inline void SysClassPath::add_prefix(const char* prefix) {
  _items[_scp_prefix] = add_to_path(_items[_scp_prefix], prefix, true);
}

422 423 424 425
inline void SysClassPath::add_suffix_to_prefix(const char* suffix) {
  _items[_scp_prefix] = add_to_path(_items[_scp_prefix], suffix, false);
}

D
duke 已提交
426 427 428 429 430 431 432
inline void SysClassPath::add_suffix(const char* suffix) {
  _items[_scp_suffix] = add_to_path(_items[_scp_suffix], suffix, false);
}

inline void SysClassPath::reset_item_at(int index) {
  assert(index < _scp_nitems && index != _scp_base, "just checking");
  if (_items[index] != NULL) {
Z
zgu 已提交
433
    FREE_C_HEAP_ARRAY(char, _items[index], mtInternal);
D
duke 已提交
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
    _items[index] = NULL;
  }
}

inline void SysClassPath::reset_path(const char* base) {
  // Clear the prefix and suffix.
  reset_item_at(_scp_prefix);
  reset_item_at(_scp_suffix);
  set_base(base);
}

//------------------------------------------------------------------------------

void SysClassPath::expand_endorsed() {
  assert(_items[_scp_endorsed] == NULL, "can only be called once.");

  const char* path = Arguments::get_property("java.endorsed.dirs");
  if (path == NULL) {
    path = Arguments::get_endorsed_dir();
    assert(path != NULL, "no default for java.endorsed.dirs");
  }

  char* expanded_path = NULL;
  const char separator = *os::path_separator();
  const char* const end = path + strlen(path);
  while (path < end) {
    const char* tmp_end = strchr(path, separator);
    if (tmp_end == NULL) {
      expanded_path = add_jars_to_path(expanded_path, path);
      path = end;
    } else {
Z
zgu 已提交
465
      char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);
D
duke 已提交
466 467 468
      memcpy(dirpath, path, tmp_end - path);
      dirpath[tmp_end - path] = '\0';
      expanded_path = add_jars_to_path(expanded_path, dirpath);
Z
zgu 已提交
469
      FREE_C_HEAP_ARRAY(char, dirpath, mtInternal);
D
duke 已提交
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
      path = tmp_end + 1;
    }
  }
  _items[_scp_endorsed] = expanded_path;
  DEBUG_ONLY(_expansion_done = true;)
}

// Combine the bootclasspath elements, some of which may be null, into a single
// c-heap-allocated string.
char* SysClassPath::combined_path() {
  assert(_items[_scp_base] != NULL, "empty default sysclasspath");
  assert(_expansion_done, "must call expand_endorsed() first.");

  size_t lengths[_scp_nitems];
  size_t total_len = 0;

  const char separator = *os::path_separator();

  // Get the lengths.
  int i;
  for (i = 0; i < _scp_nitems; ++i) {
    if (_items[i] != NULL) {
      lengths[i] = strlen(_items[i]);
      // Include space for the separator char (or a NULL for the last item).
      total_len += lengths[i] + 1;
    }
  }
  assert(total_len > 0, "empty sysclasspath not allowed");

  // Copy the _items to a single string.
Z
zgu 已提交
500
  char* cp = NEW_C_HEAP_ARRAY(char, total_len, mtInternal);
D
duke 已提交
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
  char* cp_tmp = cp;
  for (i = 0; i < _scp_nitems; ++i) {
    if (_items[i] != NULL) {
      memcpy(cp_tmp, _items[i], lengths[i]);
      cp_tmp += lengths[i];
      *cp_tmp++ = separator;
    }
  }
  *--cp_tmp = '\0';     // Replace the extra separator.
  return cp;
}

// Note:  path must be c-heap-allocated (or NULL); it is freed if non-null.
char*
SysClassPath::add_to_path(const char* path, const char* str, bool prepend) {
  char *cp;

  assert(str != NULL, "just checking");
  if (path == NULL) {
    size_t len = strlen(str) + 1;
Z
zgu 已提交
521
    cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);
D
duke 已提交
522 523 524 525 526 527 528 529
    memcpy(cp, str, len);                       // copy the trailing null
  } else {
    const char separator = *os::path_separator();
    size_t old_len = strlen(path);
    size_t str_len = strlen(str);
    size_t len = old_len + str_len + 2;

    if (prepend) {
Z
zgu 已提交
530
      cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);
D
duke 已提交
531 532 533 534 535
      char* cp_tmp = cp;
      memcpy(cp_tmp, str, str_len);
      cp_tmp += str_len;
      *cp_tmp = separator;
      memcpy(++cp_tmp, path, old_len + 1);      // copy the trailing null
Z
zgu 已提交
536
      FREE_C_HEAP_ARRAY(char, path, mtInternal);
D
duke 已提交
537
    } else {
Z
zgu 已提交
538
      cp = REALLOC_C_HEAP_ARRAY(char, path, len, mtInternal);
D
duke 已提交
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
      char* cp_tmp = cp + old_len;
      *cp_tmp = separator;
      memcpy(++cp_tmp, str, str_len + 1);       // copy the trailing null
    }
  }
  return cp;
}

// Scan the directory and append any jar or zip files found to path.
// Note:  path must be c-heap-allocated (or NULL); it is freed if non-null.
char* SysClassPath::add_jars_to_path(char* path, const char* directory) {
  DIR* dir = os::opendir(directory);
  if (dir == NULL) return path;

  char dir_sep[2] = { '\0', '\0' };
  size_t directory_len = strlen(directory);
  const char fileSep = *os::file_separator();
  if (directory[directory_len - 1] != fileSep) dir_sep[0] = fileSep;

  /* Scan the directory for jars/zips, appending them to path. */
  struct dirent *entry;
560
  while ((entry = os::readdir(dir)) != NULL) {
D
duke 已提交
561 562 563 564 565 566
    const char* name = entry->d_name;
    const char* ext = name + strlen(name) - 4;
    bool isJarOrZip = ext > name &&
      (os::file_name_strcmp(ext, ".jar") == 0 ||
       os::file_name_strcmp(ext, ".zip") == 0);
    if (isJarOrZip) {
S
shshahma 已提交
567 568 569
      size_t length = directory_len + 2 + strlen(name);
      char* jarpath = NEW_C_HEAP_ARRAY(char, length, mtInternal);
      jio_snprintf(jarpath, length, "%s%s%s", directory, dir_sep, name);
D
duke 已提交
570
      path = add_to_path(path, jarpath, false);
Z
zgu 已提交
571
      FREE_C_HEAP_ARRAY(char, jarpath, mtInternal);
D
duke 已提交
572 573 574 575 576 577 578
    }
  }
  os::closedir(dir);
  return path;
}

// Parses a memory size specification string.
579 580
static bool atomull(const char *s, julong* result) {
  julong n = 0;
581
  int args_read = sscanf(s, JULONG_FORMAT, &n);
D
duke 已提交
582 583 584 585 586 587 588 589 590 591 592 593 594
  if (args_read != 1) {
    return false;
  }
  while (*s != '\0' && isdigit(*s)) {
    s++;
  }
  // 4705540: illegal if more characters are found after the first non-digit
  if (strlen(s) > 1) {
    return false;
  }
  switch (*s) {
    case 'T': case 't':
      *result = n * G * K;
595 596
      // Check for overflow.
      if (*result/((julong)G * K) != n) return false;
D
duke 已提交
597 598 599
      return true;
    case 'G': case 'g':
      *result = n * G;
600
      if (*result/G != n) return false;
D
duke 已提交
601 602 603
      return true;
    case 'M': case 'm':
      *result = n * M;
604
      if (*result/M != n) return false;
D
duke 已提交
605 606 607
      return true;
    case 'K': case 'k':
      *result = n * K;
608
      if (*result/K != n) return false;
D
duke 已提交
609 610 611 612 613 614 615 616 617
      return true;
    case '\0':
      *result = n;
      return true;
    default:
      return false;
  }
}

618
Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size) {
D
duke 已提交
619 620
  if (size < min_size) return arg_too_small;
  // Check that size will fit in a size_t (only relevant on 32-bit)
621
  if (size > max_uintx) return arg_too_big;
D
duke 已提交
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
  return arg_in_range;
}

// Describe an argument out of range error
void Arguments::describe_range_error(ArgsRange errcode) {
  switch(errcode) {
  case arg_too_big:
    jio_fprintf(defaultStream::error_stream(),
                "The specified size exceeds the maximum "
                "representable size.\n");
    break;
  case arg_too_small:
  case arg_unreadable:
  case arg_in_range:
    // do nothing for now
    break;
  default:
    ShouldNotReachHere();
  }
}

643
static bool set_bool_flag(char* name, bool value, Flag::Flags origin) {
D
duke 已提交
644 645 646
  return CommandLineFlags::boolAtPut(name, &value, origin);
}

647
static bool set_fp_numeric_flag(char* name, char* value, Flag::Flags origin) {
D
duke 已提交
648 649 650 651 652 653 654 655 656 657 658
  double v;
  if (sscanf(value, "%lf", &v) != 1) {
    return false;
  }

  if (CommandLineFlags::doubleAtPut(name, &v, origin)) {
    return true;
  }
  return false;
}

659
static bool set_numeric_flag(char* name, char* value, Flag::Flags origin) {
660
  julong v;
D
duke 已提交
661 662
  intx intx_v;
  bool is_neg = false;
663
  // Check the sign first since atomull() parses only unsigned values.
D
duke 已提交
664 665 666 667 668 669 670
  if (*value == '-') {
    if (!CommandLineFlags::intxAt(name, &intx_v)) {
      return false;
    }
    value++;
    is_neg = true;
  }
671
  if (!atomull(value, &v)) {
D
duke 已提交
672 673 674 675 676 677 678 679 680 681 682 683 684
    return false;
  }
  intx_v = (intx) v;
  if (is_neg) {
    intx_v = -intx_v;
  }
  if (CommandLineFlags::intxAtPut(name, &intx_v, origin)) {
    return true;
  }
  uintx uintx_v = (uintx) v;
  if (!is_neg && CommandLineFlags::uintxAtPut(name, &uintx_v, origin)) {
    return true;
  }
P
phh 已提交
685 686 687 688
  uint64_t uint64_t_v = (uint64_t) v;
  if (!is_neg && CommandLineFlags::uint64_tAtPut(name, &uint64_t_v, origin)) {
    return true;
  }
D
duke 已提交
689 690 691
  return false;
}

692
static bool set_string_flag(char* name, const char* value, Flag::Flags origin) {
D
duke 已提交
693 694
  if (!CommandLineFlags::ccstrAtPut(name, &value, origin))  return false;
  // Contract:  CommandLineFlags always returns a pointer that needs freeing.
Z
zgu 已提交
695
  FREE_C_HEAP_ARRAY(char, value, mtInternal);
D
duke 已提交
696 697 698
  return true;
}

699
static bool append_to_string_flag(char* name, const char* new_value, Flag::Flags origin) {
D
duke 已提交
700 701 702 703 704 705 706 707 708 709 710
  const char* old_value = "";
  if (!CommandLineFlags::ccstrAt(name, &old_value))  return false;
  size_t old_len = old_value != NULL ? strlen(old_value) : 0;
  size_t new_len = strlen(new_value);
  const char* value;
  char* free_this_too = NULL;
  if (old_len == 0) {
    value = new_value;
  } else if (new_len == 0) {
    value = old_value;
  } else {
S
shshahma 已提交
711 712
    size_t length = old_len + 1 + new_len + 1;
    char* buf = NEW_C_HEAP_ARRAY(char, length, mtInternal);
D
duke 已提交
713
    // each new setting adds another LINE to the switch:
S
shshahma 已提交
714
    jio_snprintf(buf, length, "%s\n%s", old_value, new_value);
D
duke 已提交
715 716 717 718 719
    value = buf;
    free_this_too = buf;
  }
  (void) CommandLineFlags::ccstrAtPut(name, &value, origin);
  // CommandLineFlags always returns a pointer that needs freeing.
Z
zgu 已提交
720
  FREE_C_HEAP_ARRAY(char, value, mtInternal);
D
duke 已提交
721 722
  if (free_this_too != NULL) {
    // CommandLineFlags made its own copy, so I must delete my own temp. buffer.
Z
zgu 已提交
723
    FREE_C_HEAP_ARRAY(char, free_this_too, mtInternal);
D
duke 已提交
724 725 726 727
  }
  return true;
}

728
bool Arguments::parse_argument(const char* arg, Flag::Flags origin) {
D
duke 已提交
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794

  // range of acceptable characters spelled out for portability reasons
#define NAME_RANGE  "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"
#define BUFLEN 255
  char name[BUFLEN+1];
  char dummy;

  if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
    return set_bool_flag(name, false, origin);
  }
  if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
    return set_bool_flag(name, true, origin);
  }

  char punct;
  if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {
    const char* value = strchr(arg, '=') + 1;
    Flag* flag = Flag::find_flag(name, strlen(name));
    if (flag != NULL && flag->is_ccstr()) {
      if (flag->ccstr_accumulates()) {
        return append_to_string_flag(name, value, origin);
      } else {
        if (value[0] == '\0') {
          value = NULL;
        }
        return set_string_flag(name, value, origin);
      }
    }
  }

  if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {
    const char* value = strchr(arg, '=') + 1;
    // -XX:Foo:=xxx will reset the string flag to the given value.
    if (value[0] == '\0') {
      value = NULL;
    }
    return set_string_flag(name, value, origin);
  }

#define SIGNED_FP_NUMBER_RANGE "[-0123456789.]"
#define SIGNED_NUMBER_RANGE    "[-0123456789]"
#define        NUMBER_RANGE    "[0123456789]"
  char value[BUFLEN + 1];
  char value2[BUFLEN + 1];
  if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {
    // Looks like a floating-point number -- try again with more lenient format string
    if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {
      return set_fp_numeric_flag(name, value, origin);
    }
  }

#define VALUE_RANGE "[-kmgtKMGT0123456789]"
  if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_RANGE "%c", name, value, &dummy) == 2) {
    return set_numeric_flag(name, value, origin);
  }

  return false;
}

void Arguments::add_string(char*** bldarray, int* count, const char* arg) {
  assert(bldarray != NULL, "illegal argument");

  if (arg == NULL) {
    return;
  }

795
  int new_count = *count + 1;
D
duke 已提交
796 797 798

  // expand the array and add arg to the last element
  if (*bldarray == NULL) {
799
    *bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtInternal);
D
duke 已提交
800
  } else {
801
    *bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtInternal);
D
duke 已提交
802
  }
803 804
  (*bldarray)[*count] = strdup(arg);
  *count = new_count;
D
duke 已提交
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
}

void Arguments::build_jvm_args(const char* arg) {
  add_string(&_jvm_args_array, &_num_jvm_args, arg);
}

void Arguments::build_jvm_flags(const char* arg) {
  add_string(&_jvm_flags_array, &_num_jvm_flags, arg);
}

// utility function to return a string that concatenates all
// strings in a given char** array
const char* Arguments::build_resource_string(char** args, int count) {
  if (args == NULL || count == 0) {
    return NULL;
  }
S
shshahma 已提交
821 822 823
  size_t length = 0;
  for (int i = 0; i < count; i++) {
    length += strlen(args[i]) + 1; // add 1 for a space or NULL terminating character
D
duke 已提交
824 825
  }
  char* s = NEW_RESOURCE_ARRAY(char, length);
S
shshahma 已提交
826 827 828 829 830 831
  char* dst = s;
  for (int j = 0; j < count; j++) {
    size_t offset = strlen(args[j]) + 1; // add 1 for a space or NULL terminating character
    jio_snprintf(dst, length, "%s ", args[j]); // jio_snprintf will replace the last space character with NULL character
    dst += offset;
    length -= offset;
D
duke 已提交
832 833 834 835 836 837 838 839 840 841 842 843 844
  }
  return (const char*) s;
}

void Arguments::print_on(outputStream* st) {
  st->print_cr("VM Arguments:");
  if (num_jvm_flags() > 0) {
    st->print("jvm_flags: "); print_jvm_flags_on(st);
  }
  if (num_jvm_args() > 0) {
    st->print("jvm_args: "); print_jvm_args_on(st);
  }
  st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");
845 846 847 848
  if (_java_class_path != NULL) {
    char* path = _java_class_path->value();
    st->print_cr("java_class_path (initial): %s", strlen(path) == 0 ? "<not set>" : path );
  }
D
duke 已提交
849 850 851 852 853 854 855 856
  st->print_cr("Launcher Type: %s", _sun_java_launcher);
}

void Arguments::print_jvm_flags_on(outputStream* st) {
  if (_num_jvm_flags > 0) {
    for (int i=0; i < _num_jvm_flags; i++) {
      st->print("%s ", _jvm_flags_array[i]);
    }
857
    st->cr();
D
duke 已提交
858 859 860 861 862 863 864 865
  }
}

void Arguments::print_jvm_args_on(outputStream* st) {
  if (_num_jvm_args > 0) {
    for (int i=0; i < _num_jvm_args; i++) {
      st->print("%s ", _jvm_args_array[i]);
    }
866
    st->cr();
D
duke 已提交
867 868 869
  }
}

K
kamg 已提交
870
bool Arguments::process_argument(const char* arg,
871
    jboolean ignore_unrecognized, Flag::Flags origin) {
K
kamg 已提交
872 873

  JDK_Version since = JDK_Version();
D
duke 已提交
874

875 876
  if (parse_argument(arg, origin) || ignore_unrecognized) {
    return true;
D
duke 已提交
877
  }
878

879 880
  bool has_plus_minus = (*arg == '+' || *arg == '-');
  const char* const argname = has_plus_minus ? arg + 1 : arg;
881 882 883 884 885 886 887
  if (is_newly_obsolete(arg, &since)) {
    char version[256];
    since.to_string(version, sizeof(version));
    warning("ignoring option %s; support was removed in %s", argname, version);
    return true;
  }

888 889 890
  // For locked flags, report a custom error message if available.
  // Otherwise, report the standard unrecognized VM option.

891 892 893 894 895 896 897 898
  size_t arg_len;
  const char* equal_sign = strchr(argname, '=');
  if (equal_sign == NULL) {
    arg_len = strlen(argname);
  } else {
    arg_len = equal_sign - argname;
  }

899
  Flag* found_flag = Flag::find_flag((const char*)argname, arg_len, true, true);
900
  if (found_flag != NULL) {
901
    char locked_message_buf[BUFLEN];
902
    found_flag->get_locked_message(locked_message_buf, BUFLEN);
903
    if (strlen(locked_message_buf) == 0) {
904 905 906 907 908 909 910 911 912 913
      if (found_flag->is_bool() && !has_plus_minus) {
        jio_fprintf(defaultStream::error_stream(),
          "Missing +/- setting for VM option '%s'\n", argname);
      } else if (!found_flag->is_bool() && has_plus_minus) {
        jio_fprintf(defaultStream::error_stream(),
          "Unexpected +/- setting in VM option '%s'\n", argname);
      } else {
        jio_fprintf(defaultStream::error_stream(),
          "Improperly specified VM option '%s'\n", argname);
      }
914 915 916
    } else {
      jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);
    }
917 918 919
  } else {
    jio_fprintf(defaultStream::error_stream(),
                "Unrecognized VM option '%s'\n", argname);
920 921 922 923 924
    Flag* fuzzy_matched = Flag::fuzzy_match((const char*)argname, arg_len, true);
    if (fuzzy_matched != NULL) {
      jio_fprintf(defaultStream::error_stream(),
                  "Did you mean '%s%s%s'?\n",
                  (fuzzy_matched->is_bool()) ? "(+/-)" : "",
925
                  fuzzy_matched->_name,
926 927
                  (fuzzy_matched->is_bool()) ? "" : "=<value>");
    }
928 929
  }

930 931
  // allow for commandline "commenting out" options like -XX:#+Verbose
  return arg[0] == '#';
D
duke 已提交
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
}

bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
  FILE* stream = fopen(file_name, "rb");
  if (stream == NULL) {
    if (should_exist) {
      jio_fprintf(defaultStream::error_stream(),
                  "Could not open settings file %s\n", file_name);
      return false;
    } else {
      return true;
    }
  }

  char token[1024];
  int  pos = 0;

  bool in_white_space = true;
  bool in_comment     = false;
  bool in_quote       = false;
  char quote_c        = 0;
  bool result         = true;

  int c = getc(stream);
K
kamg 已提交
956
  while(c != EOF && pos < (int)(sizeof(token)-1)) {
D
duke 已提交
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
    if (in_white_space) {
      if (in_comment) {
        if (c == '\n') in_comment = false;
      } else {
        if (c == '#') in_comment = true;
        else if (!isspace(c)) {
          in_white_space = false;
          token[pos++] = c;
        }
      }
    } else {
      if (c == '\n' || (!in_quote && isspace(c))) {
        // token ends at newline, or at unquoted whitespace
        // this allows a way to include spaces in string-valued options
        token[pos] = '\0';
        logOption(token);
973
        result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
D
duke 已提交
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
        build_jvm_flags(token);
        pos = 0;
        in_white_space = true;
        in_quote = false;
      } else if (!in_quote && (c == '\'' || c == '"')) {
        in_quote = true;
        quote_c = c;
      } else if (in_quote && (c == quote_c)) {
        in_quote = false;
      } else {
        token[pos++] = c;
      }
    }
    c = getc(stream);
  }
  if (pos > 0) {
    token[pos] = '\0';
991
    result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
D
duke 已提交
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
    build_jvm_flags(token);
  }
  fclose(stream);
  return result;
}

//=============================================================================================================
// Parsing of properties (-D)

const char* Arguments::get_property(const char* key) {
  return PropertyList_get_value(system_properties(), key);
}

bool Arguments::add_property(const char* prop) {
  const char* eq = strchr(prop, '=');
  char* key;
  // ns must be static--its address may be stored in a SystemProperty object.
  const static char ns[1] = {0};
  char* value = (char *)ns;

  size_t key_len = (eq == NULL) ? strlen(prop) : (eq - prop);
Z
zgu 已提交
1013
  key = AllocateHeap(key_len + 1, mtInternal);
D
duke 已提交
1014 1015 1016 1017 1018
  strncpy(key, prop, key_len);
  key[key_len] = '\0';

  if (eq != NULL) {
    size_t value_len = strlen(prop) - key_len - 1;
Z
zgu 已提交
1019
    value = AllocateHeap(value_len + 1, mtInternal);
D
duke 已提交
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
    strncpy(value, &prop[key_len + 1], value_len + 1);
  }

  if (strcmp(key, "java.compiler") == 0) {
    process_java_compiler_argument(value);
    FreeHeap(key);
    if (eq != NULL) {
      FreeHeap(value);
    }
    return true;
P
phh 已提交
1030
  } else if (strcmp(key, "sun.java.command") == 0) {
D
duke 已提交
1031 1032
    _java_command = value;

1033
    // Record value in Arguments, but let it get passed to Java.
P
phh 已提交
1034
  } else if (strcmp(key, "sun.java.launcher.pid") == 0) {
D
duke 已提交
1035 1036 1037 1038 1039 1040 1041 1042
    // launcher.pid property is private and is processed
    // in process_sun_java_launcher_properties();
    // the sun.java.launcher property is passed on to the java application
    FreeHeap(key);
    if (eq != NULL) {
      FreeHeap(value);
    }
    return true;
P
phh 已提交
1043
  } else if (strcmp(key, "java.vendor.url.bug") == 0) {
D
duke 已提交
1044 1045 1046
    // save it in _java_vendor_url_bug, so JVM fatal error handler can access
    // its value without going through the property list or making a Java call.
    _java_vendor_url_bug = value;
P
phh 已提交
1047 1048 1049
  } else if (strcmp(key, "sun.boot.library.path") == 0) {
    PropertyList_unique_add(&_system_properties, key, value, true);
    return true;
D
duke 已提交
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
  }
  // Create new property and add at the end of the list
  PropertyList_unique_add(&_system_properties, key, value);
  return true;
}

//===========================================================================================================
// Setting int/mixed/comp mode flags

void Arguments::set_mode_flags(Mode mode) {
  // Set up default values for all flags.
  // If you add a flag to any of the branches below,
  // add a default value for it here.
  set_java_compiler(false);
  _mode                      = mode;

  // Ensure Agent_OnLoad has the correct initial values.
  // This may not be the final mode; mode may change later in onload phase.
  PropertyList_unique_add(&_system_properties, "java.vm.info",
1069
                          (char*)VM_Version::vm_info_string(), false);
D
duke 已提交
1070 1071 1072 1073 1074

  UseInterpreter             = true;
  UseCompiler                = true;
  UseLoopCounter             = true;

1075 1076 1077
#ifndef ZERO
  // Turn these off for mixed and comp.  Leave them on for Zero.
  if (FLAG_IS_DEFAULT(UseFastAccessorMethods)) {
1078
    UseFastAccessorMethods = (mode == _int);
1079 1080
  }
  if (FLAG_IS_DEFAULT(UseFastEmptyMethods)) {
1081
    UseFastEmptyMethods = (mode == _int);
1082 1083 1084
  }
#endif

D
duke 已提交
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
  // Default values may be platform/compiler dependent -
  // use the saved values
  ClipInlining               = Arguments::_ClipInlining;
  AlwaysCompileLoopMethods   = Arguments::_AlwaysCompileLoopMethods;
  UseOnStackReplacement      = Arguments::_UseOnStackReplacement;
  BackgroundCompilation      = Arguments::_BackgroundCompilation;

  // Change from defaults based on mode
  switch (mode) {
  default:
    ShouldNotReachHere();
    break;
  case _int:
    UseCompiler              = false;
    UseLoopCounter           = false;
    AlwaysCompileLoopMethods = false;
    UseOnStackReplacement    = false;
    break;
  case _mixed:
    // same as default
    break;
  case _comp:
    UseInterpreter           = false;
    BackgroundCompilation    = false;
    ClipInlining             = false;
1110 1111 1112 1113 1114 1115 1116
    // Be much more aggressive in tiered mode with -Xcomp and exercise C2 more.
    // We will first compile a level 3 version (C1 with full profiling), then do one invocation of it and
    // compile a level 4 (C2) and then continue executing it.
    if (TieredCompilation) {
      Tier3InvokeNotifyFreqLog = 0;
      Tier4InvocationThreshold = 0;
    }
D
duke 已提交
1117 1118 1119 1120
    break;
  }
}

1121
#if defined(COMPILER2) || defined(_LP64) || !INCLUDE_CDS
D
duke 已提交
1122 1123 1124
// Conflict: required to use shared spaces (-Xshare:on), but
// incompatible command line options were chosen.

1125
static void no_shared_spaces(const char* message) {
D
duke 已提交
1126 1127 1128
  if (RequireSharedSpaces) {
    jio_fprintf(defaultStream::error_stream(),
      "Class data sharing is inconsistent with other specified options.\n");
1129
    vm_exit_during_initialization("Unable to use shared archive.", message);
D
duke 已提交
1130 1131 1132 1133
  } else {
    FLAG_SET_DEFAULT(UseSharedSpaces, false);
  }
}
1134
#endif
D
duke 已提交
1135

I
iveresov 已提交
1136
void Arguments::set_tiered_flags() {
1137
  // With tiered, set default policy to AdvancedThresholdPolicy, which is 3.
I
iveresov 已提交
1138
  if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {
1139
    FLAG_SET_DEFAULT(CompilationPolicyChoice, 3);
I
iveresov 已提交
1140 1141 1142 1143 1144
  }
  if (CompilationPolicyChoice < 2) {
    vm_exit_during_initialization(
      "Incompatible compilation policy selected", NULL);
  }
1145
  // Increase the code cache size - tiered compiles a lot more.
I
iveresov 已提交
1146
  if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1147
    FLAG_SET_DEFAULT(ReservedCodeCacheSize, ReservedCodeCacheSize * 5);
I
iveresov 已提交
1148
  }
1149 1150 1151 1152
  if (!UseInterpreter) { // -Xcomp
    Tier3InvokeNotifyFreqLog = 0;
    Tier4InvocationThreshold = 0;
  }
I
iveresov 已提交
1153 1154
}

1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
/**
 * Returns the minimum number of compiler threads needed to run the JVM. The following
 * configurations are possible.
 *
 * 1) The JVM is build using an interpreter only. As a result, the minimum number of
 *    compiler threads is 0.
 * 2) The JVM is build using the compiler(s) and tiered compilation is disabled. As
 *    a result, either C1 or C2 is used, so the minimum number of compiler threads is 1.
 * 3) The JVM is build using the compiler(s) and tiered compilation is enabled. However,
 *    the option "TieredStopAtLevel < CompLevel_full_optimization". As a result, only
 *    C1 can be used, so the minimum number of compiler threads is 1.
 * 4) The JVM is build using the compilers and tiered compilation is enabled. The option
 *    'TieredStopAtLevel = CompLevel_full_optimization' (the default value). As a result,
 *    the minimum number of compiler threads is 2.
 */
int Arguments::get_min_number_of_compiler_threads() {
#if !defined(COMPILER1) && !defined(COMPILER2) && !defined(SHARK)
  return 0;   // case 1
#else
  if (!TieredCompilation || (TieredStopAtLevel < CompLevel_full_optimization)) {
    return 1; // case 2 or case 3
  }
  return 2;   // case 4 (tiered)
#endif
}

1181
#if INCLUDE_ALL_GCS
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
static void disable_adaptive_size_policy(const char* collector_name) {
  if (UseAdaptiveSizePolicy) {
    if (FLAG_IS_CMDLINE(UseAdaptiveSizePolicy)) {
      warning("disabling UseAdaptiveSizePolicy; it is incompatible with %s.",
              collector_name);
    }
    FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false);
  }
}

D
duke 已提交
1192
void Arguments::set_parnew_gc_flags() {
P
phh 已提交
1193
  assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC && !UseG1GC,
1194 1195
         "control point invariant");
  assert(UseParNewGC, "Error");
D
duke 已提交
1196

1197 1198
  // Turn off AdaptiveSizePolicy for parnew until it is complete.
  disable_adaptive_size_policy("UseParNewGC");
1199

1200 1201 1202 1203 1204 1205 1206
  if (FLAG_IS_DEFAULT(ParallelGCThreads)) {
    FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
    assert(ParallelGCThreads > 0, "We should always have at least one thread by default");
  } else if (ParallelGCThreads == 0) {
    jio_fprintf(defaultStream::error_stream(),
        "The ParNew GC can not be combined with -XX:ParallelGCThreads=0\n");
    vm_exit(1);
D
duke 已提交
1207 1208
  }

1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
  // By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 respectively,
  // these settings are default for Parallel Scavenger. For ParNew+Tenured configuration
  // we set them to 1024 and 1024.
  // See CR 6362902.
  if (FLAG_IS_DEFAULT(YoungPLABSize)) {
    FLAG_SET_DEFAULT(YoungPLABSize, (intx)1024);
  }
  if (FLAG_IS_DEFAULT(OldPLABSize)) {
    FLAG_SET_DEFAULT(OldPLABSize, (intx)1024);
  }

  // AlwaysTenure flag should make ParNew promote all at first collection.
  // See CR 6362902.
  if (AlwaysTenure) {
    FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0);
  }
  // When using compressed oops, we use local overflow stacks,
  // rather than using a global overflow list chained through
  // the klass word of the object's pre-image.
  if (UseCompressedOops && !ParGCUseLocalOverflow) {
    if (!FLAG_IS_DEFAULT(ParGCUseLocalOverflow)) {
      warning("Forcing +ParGCUseLocalOverflow: needed if using compressed references");
1231
    }
1232
    FLAG_SET_DEFAULT(ParGCUseLocalOverflow, true);
D
duke 已提交
1233
  }
1234
  assert(ParGCUseLocalOverflow || !UseCompressedOops, "Error");
D
duke 已提交
1235 1236 1237 1238 1239 1240 1241
}

// Adjust some sizes to suit CMS and/or ParNew needs; these work well on
// sparc/solaris for certain applications, but would gain from
// further optimization and tuning efforts, and would almost
// certainly gain from analysis of platform and environment.
void Arguments::set_cms_and_parnew_gc_flags() {
P
phh 已提交
1242
  assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC, "Error");
1243 1244
  assert(UseConcMarkSweepGC, "CMS is expected to be on here");

D
duke 已提交
1245 1246
  // If we are using CMS, we prefer to UseParNewGC,
  // unless explicitly forbidden.
1247
  if (FLAG_IS_DEFAULT(UseParNewGC)) {
1248
    FLAG_SET_ERGO(bool, UseParNewGC, true);
D
duke 已提交
1249 1250
  }

1251
  // Turn off AdaptiveSizePolicy by default for cms until it is complete.
1252
  disable_adaptive_size_policy("UseConcMarkSweepGC");
D
duke 已提交
1253 1254 1255

  // In either case, adjust ParallelGCThreads and/or UseParNewGC
  // as needed.
1256 1257
  if (UseParNewGC) {
    set_parnew_gc_flags();
D
duke 已提交
1258 1259
  }

1260 1261 1262
  size_t max_heap = align_size_down(MaxHeapSize,
                                    CardTableRS::ct_max_alignment_constraint());

D
duke 已提交
1263
  // Now make adjustments for CMS
1264 1265 1266 1267 1268
  intx   tenuring_default = (intx)6;
  size_t young_gen_per_worker = CMSYoungGenPerWorker;

  // Preferred young gen size for "short" pauses:
  // upper bound depends on # of threads and NewRatio.
D
duke 已提交
1269 1270 1271
  const uintx parallel_gc_threads =
    (ParallelGCThreads == 0 ? 1 : ParallelGCThreads);
  const size_t preferred_max_new_size_unaligned =
1272 1273
    MIN2(max_heap/(NewRatio+1), ScaleForWordSize(young_gen_per_worker * parallel_gc_threads));
  size_t preferred_max_new_size =
D
duke 已提交
1274 1275 1276
    align_size_up(preferred_max_new_size_unaligned, os::vm_page_size());

  // Unless explicitly requested otherwise, size young gen
1277
  // for "short" pauses ~ CMSYoungGenPerWorker*ParallelGCThreads
1278 1279 1280 1281 1282 1283 1284 1285

  // If either MaxNewSize or NewRatio is set on the command line,
  // assume the user is trying to set the size of the young gen.
  if (FLAG_IS_DEFAULT(MaxNewSize) && FLAG_IS_DEFAULT(NewRatio)) {

    // Set MaxNewSize to our calculated preferred_max_new_size unless
    // NewSize was set on the command line and it is larger than
    // preferred_max_new_size.
D
duke 已提交
1286
    if (!FLAG_IS_DEFAULT(NewSize)) {   // NewSize explicitly set at command-line
1287
      FLAG_SET_ERGO(uintx, MaxNewSize, MAX2(NewSize, preferred_max_new_size));
D
duke 已提交
1288
    } else {
1289
      FLAG_SET_ERGO(uintx, MaxNewSize, preferred_max_new_size);
D
duke 已提交
1290
    }
P
phh 已提交
1291
    if (PrintGCDetails && Verbose) {
1292
      // Too early to use gclog_or_tty
1293
      tty->print_cr("CMS ergo set MaxNewSize: " SIZE_FORMAT, MaxNewSize);
1294 1295 1296
    }

    // Code along this path potentially sets NewSize and OldSize
P
phh 已提交
1297
    if (PrintGCDetails && Verbose) {
1298 1299 1300 1301
      // Too early to use gclog_or_tty
      tty->print_cr("CMS set min_heap_size: " SIZE_FORMAT
           " initial_heap_size:  " SIZE_FORMAT
           " max_heap: " SIZE_FORMAT,
P
phh 已提交
1302
           min_heap_size(), InitialHeapSize, max_heap);
1303
    }
1304 1305 1306 1307 1308
    size_t min_new = preferred_max_new_size;
    if (FLAG_IS_CMDLINE(NewSize)) {
      min_new = NewSize;
    }
    if (max_heap > min_new && min_heap_size() > min_new) {
D
duke 已提交
1309 1310 1311
      // Unless explicitly requested otherwise, make young gen
      // at least min_new, and at most preferred_max_new_size.
      if (FLAG_IS_DEFAULT(NewSize)) {
1312 1313
        FLAG_SET_ERGO(uintx, NewSize, MAX2(NewSize, min_new));
        FLAG_SET_ERGO(uintx, NewSize, MIN2(preferred_max_new_size, NewSize));
P
phh 已提交
1314
        if (PrintGCDetails && Verbose) {
1315
          // Too early to use gclog_or_tty
1316
          tty->print_cr("CMS ergo set NewSize: " SIZE_FORMAT, NewSize);
1317
        }
D
duke 已提交
1318 1319
      }
      // Unless explicitly requested otherwise, size old gen
1320
      // so it's NewRatio x of NewSize.
D
duke 已提交
1321 1322
      if (FLAG_IS_DEFAULT(OldSize)) {
        if (max_heap > NewSize) {
1323
          FLAG_SET_ERGO(uintx, OldSize, MIN2(NewRatio*NewSize, max_heap - NewSize));
P
phh 已提交
1324
          if (PrintGCDetails && Verbose) {
1325
            // Too early to use gclog_or_tty
1326
            tty->print_cr("CMS ergo set OldSize: " SIZE_FORMAT, OldSize);
1327
          }
D
duke 已提交
1328 1329 1330 1331 1332 1333 1334 1335
        }
      }
    }
  }
  // Unless explicitly requested otherwise, definitely
  // promote all objects surviving "tenuring_default" scavenges.
  if (FLAG_IS_DEFAULT(MaxTenuringThreshold) &&
      FLAG_IS_DEFAULT(SurvivorRatio)) {
1336
    FLAG_SET_ERGO(uintx, MaxTenuringThreshold, tenuring_default);
D
duke 已提交
1337 1338 1339 1340 1341 1342
  }
  // If we decided above (or user explicitly requested)
  // `promote all' (via MaxTenuringThreshold := 0),
  // prefer minuscule survivor spaces so as not to waste
  // space for (non-existent) survivors
  if (FLAG_IS_DEFAULT(SurvivorRatio) && MaxTenuringThreshold == 0) {
1343
    FLAG_SET_ERGO(uintx, SurvivorRatio, MAX2((uintx)1024, SurvivorRatio));
D
duke 已提交
1344 1345 1346 1347 1348 1349 1350 1351
  }
  // If OldPLABSize is set and CMSParPromoteBlocksToClaim is not,
  // set CMSParPromoteBlocksToClaim equal to OldPLABSize.
  // This is done in order to make ParNew+CMS configuration to work
  // with YoungPLABSize and OldPLABSize options.
  // See CR 6362902.
  if (!FLAG_IS_DEFAULT(OldPLABSize)) {
    if (FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim)) {
1352 1353 1354 1355 1356
      // OldPLABSize is not the default value but CMSParPromoteBlocksToClaim
      // is.  In this situtation let CMSParPromoteBlocksToClaim follow
      // the value (either from the command line or ergonomics) of
      // OldPLABSize.  Following OldPLABSize is an ergonomics decision.
      FLAG_SET_ERGO(uintx, CMSParPromoteBlocksToClaim, OldPLABSize);
1357
    } else {
D
duke 已提交
1358 1359 1360 1361
      // OldPLABSize and CMSParPromoteBlocksToClaim are both set.
      // CMSParPromoteBlocksToClaim is a collector-specific flag, so
      // we'll let it to take precedence.
      jio_fprintf(defaultStream::error_stream(),
1362 1363 1364
                  "Both OldPLABSize and CMSParPromoteBlocksToClaim"
                  " options are specified for the CMS collector."
                  " CMSParPromoteBlocksToClaim will take precedence.\n");
D
duke 已提交
1365 1366
    }
  }
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
  if (!FLAG_IS_DEFAULT(ResizeOldPLAB) && !ResizeOldPLAB) {
    // OldPLAB sizing manually turned off: Use a larger default setting,
    // unless it was manually specified. This is because a too-low value
    // will slow down scavenges.
    if (FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim)) {
      FLAG_SET_ERGO(uintx, CMSParPromoteBlocksToClaim, 50); // default value before 6631166
    }
  }
  // Overwrite OldPLABSize which is the variable we will internally use everywhere.
  FLAG_SET_ERGO(uintx, OldPLABSize, CMSParPromoteBlocksToClaim);
  // If either of the static initialization defaults have changed, note this
  // modification.
  if (!FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim) || !FLAG_IS_DEFAULT(OldPLABWeight)) {
    CFLS_LAB::modify_initialization(OldPLABSize, OldPLABWeight);
  }
P
poonam 已提交
1382

1383 1384
  if (PrintGCDetails && Verbose) {
    tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
1385 1386
      (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
    tty->print_cr("ConcGCThreads: %u", (uint) ConcGCThreads);
1387
  }
D
duke 已提交
1388
}
1389
#endif // INCLUDE_ALL_GCS
D
duke 已提交
1390

1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
void set_object_alignment() {
  // Object alignment.
  assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
  MinObjAlignmentInBytes     = ObjectAlignmentInBytes;
  assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
  MinObjAlignment            = MinObjAlignmentInBytes / HeapWordSize;
  assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
  MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;

  LogMinObjAlignmentInBytes  = exact_log2(ObjectAlignmentInBytes);
  LogMinObjAlignment         = LogMinObjAlignmentInBytes - LogHeapWordSize;

  // Oop encoding heap max
  OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;

1406
#if INCLUDE_ALL_GCS
1407 1408
  // Set CMS global values
  CompactibleFreeListSpace::set_cms_values();
1409
#endif // INCLUDE_ALL_GCS
1410 1411 1412 1413 1414 1415
}

bool verify_object_alignment() {
  // Object alignment.
  if (!is_power_of_2(ObjectAlignmentInBytes)) {
    jio_fprintf(defaultStream::error_stream(),
1416 1417
                "error: ObjectAlignmentInBytes=%d must be power of 2\n",
                (int)ObjectAlignmentInBytes);
1418 1419 1420 1421
    return false;
  }
  if ((int)ObjectAlignmentInBytes < BytesPerLong) {
    jio_fprintf(defaultStream::error_stream(),
1422 1423 1424 1425 1426 1427 1428 1429 1430
                "error: ObjectAlignmentInBytes=%d must be greater or equal %d\n",
                (int)ObjectAlignmentInBytes, BytesPerLong);
    return false;
  }
  // It does not make sense to have big object alignment
  // since a space lost due to alignment will be greater
  // then a saved space from compressed oops.
  if ((int)ObjectAlignmentInBytes > 256) {
    jio_fprintf(defaultStream::error_stream(),
1431
                "error: ObjectAlignmentInBytes=%d must not be greater than 256\n",
1432 1433 1434 1435 1436 1437
                (int)ObjectAlignmentInBytes);
    return false;
  }
  // In case page size is very small.
  if ((int)ObjectAlignmentInBytes >= os::vm_page_size()) {
    jio_fprintf(defaultStream::error_stream(),
1438
                "error: ObjectAlignmentInBytes=%d must be less than page size %d\n",
1439
                (int)ObjectAlignmentInBytes, os::vm_page_size());
1440 1441
    return false;
  }
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
  if(SurvivorAlignmentInBytes == 0) {
    SurvivorAlignmentInBytes = ObjectAlignmentInBytes;
  } else {
    if (!is_power_of_2(SurvivorAlignmentInBytes)) {
      jio_fprintf(defaultStream::error_stream(),
            "error: SurvivorAlignmentInBytes=%d must be power of 2\n",
            (int)SurvivorAlignmentInBytes);
      return false;
    }
    if (SurvivorAlignmentInBytes < ObjectAlignmentInBytes) {
      jio_fprintf(defaultStream::error_stream(),
          "error: SurvivorAlignmentInBytes=%d must be greater than ObjectAlignmentInBytes=%d \n",
          (int)SurvivorAlignmentInBytes, (int)ObjectAlignmentInBytes);
      return false;
    }
  }
1458 1459 1460
  return true;
}

1461
size_t Arguments::max_heap_for_compressed_oops() {
1462
  // Avoid sign flip.
1463
  assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
1464 1465 1466 1467 1468
  // We need to fit both the NULL page and the heap into the memory budget, while
  // keeping alignment constraints of the heap. To guarantee the latter, as the
  // NULL page is located before the heap, we pad the NULL page to the conservative
  // maximum alignment that the GC may ever impose upon the heap.
  size_t displacement_due_to_null_page = align_size_up_(os::vm_page_size(),
1469
                                                        _conservative_max_heap_alignment);
1470 1471

  LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
P
phh 已提交
1472
  NOT_LP64(ShouldNotReachHere(); return 0);
1473 1474
}

D
duke 已提交
1475 1476 1477 1478 1479 1480 1481
bool Arguments::should_auto_select_low_pause_collector() {
  if (UseAutoGCSelectPolicy &&
      !FLAG_IS_DEFAULT(MaxGCPauseMillis) &&
      (MaxGCPauseMillis <= AutoGCSelectPauseMillis)) {
    if (PrintGCDetails) {
      // Cannot use gclog_or_tty yet.
      tty->print_cr("Automatic selection of the low pause collector"
1482
       " based on pause goal of %d (ms)", (int) MaxGCPauseMillis);
D
duke 已提交
1483 1484 1485 1486 1487 1488
    }
    return true;
  }
  return false;
}

1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
void Arguments::set_use_compressed_oops() {
#ifndef ZERO
#ifdef _LP64
  // MaxHeapSize is not set up properly at this point, but
  // the only value that can override MaxHeapSize if we are
  // to use UseCompressedOops is InitialHeapSize.
  size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);

  if (max_heap_size <= max_heap_for_compressed_oops()) {
#if !defined(COMPILER1) || defined(TIERED)
    if (FLAG_IS_DEFAULT(UseCompressedOops)) {
      FLAG_SET_ERGO(bool, UseCompressedOops, true);
    }
#endif
#ifdef _WIN64
    if (UseLargePages && UseCompressedOops) {
      // Cannot allocate guard pages for implicit checks in indexed addressing
      // mode, when large pages are specified on windows.
      // This flag could be switched ON if narrow oop base address is set to 0,
      // see code in Universe::initialize_heap().
      Universe::set_narrow_oop_use_implicit_null_checks(false);
    }
#endif //  _WIN64
  } else {
    if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
      warning("Max heap size too large for Compressed Oops");
      FLAG_SET_DEFAULT(UseCompressedOops, false);
1516
      FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1517 1518 1519 1520 1521 1522
    }
  }
#endif // _LP64
#endif // ZERO
}

1523 1524 1525 1526 1527 1528

// NOTE: set_use_compressed_klass_ptrs() must be called after calling
// set_use_compressed_oops().
void Arguments::set_use_compressed_klass_ptrs() {
#ifndef ZERO
#ifdef _LP64
1529
  // UseCompressedOops must be on for UseCompressedClassPointers to be on.
1530
  if (!UseCompressedOops) {
1531 1532
    if (UseCompressedClassPointers) {
      warning("UseCompressedClassPointers requires UseCompressedOops");
1533
    }
1534
    FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1535
  } else {
1536 1537 1538 1539 1540 1541 1542 1543 1544
    // Turn on UseCompressedClassPointers too
    if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
      FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);
    }
    // Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
    if (UseCompressedClassPointers) {
      if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
        warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
        FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1545 1546 1547 1548 1549 1550 1551
      }
    }
  }
#endif // _LP64
#endif // !ZERO
}

1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
void Arguments::set_conservative_max_heap_alignment() {
  // The conservative maximum required alignment for the heap is the maximum of
  // the alignments imposed by several sources: any requirements from the heap
  // itself, the collector policy and the maximum page size we may run the VM
  // with.
  size_t heap_alignment = GenCollectedHeap::conservative_max_heap_alignment();
#if INCLUDE_ALL_GCS
  if (UseParallelGC) {
    heap_alignment = ParallelScavengeHeap::conservative_max_heap_alignment();
  } else if (UseG1GC) {
    heap_alignment = G1CollectedHeap::conservative_max_heap_alignment();
  }
#endif // INCLUDE_ALL_GCS
1565 1566 1567 1568
  _conservative_max_heap_alignment = MAX4(heap_alignment,
                                          (size_t)os::vm_allocation_granularity(),
                                          os::max_page_size(),
                                          CollectorPolicy::compute_heap_alignment());
1569 1570
}

1571
void Arguments::select_gc_ergonomically() {
1572
  if (os::is_server_class_machine()) {
1573 1574 1575 1576
    if (should_auto_select_low_pause_collector()) {
      FLAG_SET_ERGO(bool, UseConcMarkSweepGC, true);
    } else {
      FLAG_SET_ERGO(bool, UseParallelGC, true);
1577
    }
D
duke 已提交
1578
  }
1579 1580 1581 1582
}

void Arguments::select_gc() {
  if (!gc_selected()) {
1583
    select_gc_ergonomically();
1584 1585 1586 1587 1588 1589
  }
}

void Arguments::set_ergonomics_flags() {
  select_gc();

1590 1591 1592 1593 1594 1595 1596 1597
#ifdef COMPILER2
  // Shared spaces work fine with other GCs but causes bytecode rewriting
  // to be disabled, which hurts interpreter performance and decreases
  // server performance.  When -server is specified, keep the default off
  // unless it is asked for.  Future work: either add bytecode rewriting
  // at link time, or rewrite bytecodes in non-shared methods.
  if (!DumpSharedSpaces && !RequireSharedSpaces &&
      (FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {
1598
    no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");
1599 1600
  }
#endif
1601

1602 1603
  set_conservative_max_heap_alignment();

1604
#ifndef ZERO
1605
#ifdef _LP64
1606
  set_use_compressed_oops();
1607 1608 1609 1610 1611

  // set_use_compressed_klass_ptrs() must be called after calling
  // set_use_compressed_oops().
  set_use_compressed_klass_ptrs();

1612 1613 1614
  // Also checks that certain machines are slower with compressed oops
  // in vm_version initialization code.
#endif // _LP64
1615
#endif // !ZERO
D
duke 已提交
1616 1617 1618
}

void Arguments::set_parallel_gc_flags() {
1619
  assert(UseParallelGC || UseParallelOldGC, "Error");
1620 1621 1622
  // Enable ParallelOld unless it was explicitly disabled (cmd line or rc file).
  if (FLAG_IS_DEFAULT(UseParallelOldGC)) {
    FLAG_SET_DEFAULT(UseParallelOldGC, true);
D
duke 已提交
1623
  }
1624
  FLAG_SET_DEFAULT(UseParallelGC, true);
D
duke 已提交
1625 1626 1627

  // If no heap maximum was requested explicitly, use some reasonable fraction
  // of the physical memory, up to a maximum of 1GB.
1628 1629 1630 1631 1632 1633 1634
  FLAG_SET_DEFAULT(ParallelGCThreads,
                   Abstract_VM_Version::parallel_worker_threads());
  if (ParallelGCThreads == 0) {
    jio_fprintf(defaultStream::error_stream(),
        "The Parallel GC can not be combined with -XX:ParallelGCThreads=0\n");
    vm_exit(1);
  }
1635

1636 1637 1638 1639 1640
  if (UseAdaptiveSizePolicy) {
    // We don't want to limit adaptive heap sizing's freedom to adjust the heap
    // unless the user actually sets these flags.
    if (FLAG_IS_DEFAULT(MinHeapFreeRatio)) {
      FLAG_SET_DEFAULT(MinHeapFreeRatio, 0);
1641
      _min_heap_free_ratio = MinHeapFreeRatio;
1642 1643 1644
    }
    if (FLAG_IS_DEFAULT(MaxHeapFreeRatio)) {
      FLAG_SET_DEFAULT(MaxHeapFreeRatio, 100);
1645
      _max_heap_free_ratio = MaxHeapFreeRatio;
1646 1647
    }
  }
1648 1649 1650 1651 1652 1653 1654 1655

  // If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
  // SurvivorRatio has been set, reset their default values to SurvivorRatio +
  // 2.  By doing this we make SurvivorRatio also work for Parallel Scavenger.
  // See CR 6362902 for details.
  if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
    if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
       FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
D
duke 已提交
1656
    }
1657 1658 1659 1660
    if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
      FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
    }
  }
D
duke 已提交
1661

1662 1663 1664 1665 1666 1667
  if (UseParallelOldGC) {
    // Par compact uses lower default values since they are treated as
    // minimums.  These are different defaults because of the different
    // interpretation and are not ergonomically set.
    if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
      FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
D
duke 已提交
1668 1669 1670 1671
    }
  }
}

1672 1673 1674 1675 1676 1677 1678 1679
void Arguments::set_g1_gc_flags() {
  assert(UseG1GC, "Error");
#ifdef COMPILER1
  FastTLABRefill = false;
#endif
  FLAG_SET_DEFAULT(ParallelGCThreads,
                     Abstract_VM_Version::parallel_worker_threads());
  if (ParallelGCThreads == 0) {
1680 1681
    vm_exit_during_initialization("The flag -XX:+UseG1GC can not be combined with -XX:ParallelGCThreads=0", NULL);
    }
J
johnc 已提交
1682

1683 1684 1685 1686 1687 1688
#if INCLUDE_ALL_GCS
  if (G1ConcRefinementThreads == 0) {
    FLAG_SET_DEFAULT(G1ConcRefinementThreads, ParallelGCThreads);
  }
#endif

1689 1690 1691 1692 1693 1694
  // MarkStackSize will be set (if it hasn't been set by the user)
  // when concurrent marking is initialized.
  // Its value will be based upon the number of parallel marking threads.
  // But we do set the maximum mark stack size here.
  if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {
    FLAG_SET_DEFAULT(MarkStackSizeMax, 128 * TASKQUEUE_SIZE);
1695
  }
T
tonyp 已提交
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705

  if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {
    // In G1, we want the default GC overhead goal to be higher than
    // say in PS. So we set it here to 10%. Otherwise the heap might
    // be expanded more aggressively than we would like it to. In
    // fact, even 10% seems to not be high enough in some cases
    // (especially small GC stress tests that the main thing they do
    // is allocation). We might consider increase it further.
    FLAG_SET_DEFAULT(GCTimeRatio, 9);
  }
1706 1707 1708

  if (PrintGCDetails && Verbose) {
    tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
1709 1710
      (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
    tty->print_cr("ConcGCThreads: %u", (uint) ConcGCThreads);
1711
  }
1712 1713
}

1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
#if !INCLUDE_ALL_GCS
#ifdef ASSERT
static bool verify_serial_gc_flags() {
  return (UseSerialGC &&
        !(UseParNewGC || (UseConcMarkSweepGC || CMSIncrementalMode) || UseG1GC ||
          UseParallelGC || UseParallelOldGC));
}
#endif // ASSERT
#endif // INCLUDE_ALL_GCS

void Arguments::set_gc_specific_flags() {
#if INCLUDE_ALL_GCS
  // Set per-collector flags
  if (UseParallelGC || UseParallelOldGC) {
    set_parallel_gc_flags();
  } else if (UseConcMarkSweepGC) { // Should be done before ParNew check below
    set_cms_and_parnew_gc_flags();
  } else if (UseParNewGC) {  // Skipped if CMS is set above
    set_parnew_gc_flags();
  } else if (UseG1GC) {
    set_g1_gc_flags();
  }
  check_deprecated_gcs();
  check_deprecated_gc_flags();
  if (AssumeMP && !UseSerialGC) {
    if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) {
      warning("If the number of processors is expected to increase from one, then"
              " you should configure the number of parallel GC threads appropriately"
              " using -XX:ParallelGCThreads=N");
    }
  }
  if (MinHeapFreeRatio == 100) {
    // Keeping the heap 100% free is hard ;-) so limit it to 99%.
    FLAG_SET_ERGO(uintx, MinHeapFreeRatio, 99);
  }
1749 1750 1751 1752 1753 1754 1755

  // If class unloading is disabled, also disable concurrent class unloading.
  if (!ClassUnloading) {
    FLAG_SET_CMDLINE(bool, CMSClassUnloadingEnabled, false);
    FLAG_SET_CMDLINE(bool, ClassUnloadingWithConcurrentMark, false);
    FLAG_SET_CMDLINE(bool, ExplicitGCInvokesConcurrentAndUnloadsClasses, false);
  }
1756 1757 1758 1759 1760
#else // INCLUDE_ALL_GCS
  assert(verify_serial_gc_flags(), "SerialGC unset");
#endif // INCLUDE_ALL_GCS
}

1761 1762 1763 1764 1765 1766 1767 1768 1769
julong Arguments::limit_by_allocatable_memory(julong limit) {
  julong max_allocatable;
  julong result = limit;
  if (os::has_allocatable_memory_limit(&max_allocatable)) {
    result = MIN2(result, max_allocatable / MaxVirtMemFraction);
  }
  return result;
}

P
phh 已提交
1770 1771 1772 1773 1774 1775
void Arguments::set_heap_size() {
  if (!FLAG_IS_DEFAULT(DefaultMaxRAMFraction)) {
    // Deprecated flag
    FLAG_SET_CMDLINE(uintx, MaxRAMFraction, DefaultMaxRAMFraction);
  }

1776
  julong phys_mem =
P
phh 已提交
1777 1778 1779
    FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
                            : (julong)MaxRAM;

1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
  // Experimental support for CGroup memory limits
  if (UseCGroupMemoryLimitForHeap) {
    // This is a rough indicator that a CGroup limit may be in force
    // for this process
    const char* lim_file = "/sys/fs/cgroup/memory/memory.limit_in_bytes";
    FILE *fp = fopen(lim_file, "r");
    if (fp != NULL) {
      julong cgroup_max = 0;
      int ret = fscanf(fp, JULONG_FORMAT, &cgroup_max);
      if (ret == 1 && cgroup_max > 0) {
        // If unlimited, cgroup_max will be a very large, but unspecified
        // value, so use initial phys_mem as a limit
        if (PrintGCDetails && Verbose) {
          // Cannot use gclog_or_tty yet.
          tty->print_cr("Setting phys_mem to the min of cgroup limit ("
                        JULONG_FORMAT "MB) and initial phys_mem ("
                        JULONG_FORMAT "MB)", cgroup_max/M, phys_mem/M);
        }
        phys_mem = MIN2(cgroup_max, phys_mem);
      } else {
        warning("Unable to read/parse cgroup memory limit from %s: %s",
                lim_file, errno != 0 ? strerror(errno) : "unknown error");
      }
      fclose(fp);
    } else {
      warning("Unable to open cgroup memory limit file %s (%s)", lim_file, strerror(errno));
    }
  }

1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821
  // Convert Fraction to Precentage values
  if (FLAG_IS_DEFAULT(MaxRAMPercentage) &&
      !FLAG_IS_DEFAULT(MaxRAMFraction))
    MaxRAMPercentage = 100.0 / MaxRAMFraction;

   if (FLAG_IS_DEFAULT(MinRAMPercentage) &&
       !FLAG_IS_DEFAULT(MinRAMFraction))
     MinRAMPercentage = 100.0 / MinRAMFraction;

   if (FLAG_IS_DEFAULT(InitialRAMPercentage) &&
       !FLAG_IS_DEFAULT(InitialRAMFraction))
     InitialRAMPercentage = 100.0 / InitialRAMFraction;

P
phh 已提交
1822 1823 1824
  // If the maximum heap size has not been set with -Xmx,
  // then set it as fraction of the size of physical memory,
  // respecting the maximum and minimum sizes of the heap.
1825
  if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1826 1827 1828
    julong reasonable_max = (julong)((phys_mem * MaxRAMPercentage) / 100);
    const julong reasonable_min = (julong)((phys_mem * MinRAMPercentage) / 100);
    if (reasonable_min < MaxHeapSize) {
P
phh 已提交
1829
      // Small physical memory, so use a minimum fraction of it for the heap
1830
      reasonable_max = reasonable_min;
P
phh 已提交
1831 1832 1833 1834 1835
    } else {
      // Not-small physical memory, so require a heap at least
      // as large as MaxHeapSize
      reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
    }
1836

P
phh 已提交
1837 1838 1839 1840 1841 1842
    if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
      // Limit the heap size to ErgoHeapSizeLimit
      reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
    }
    if (UseCompressedOops) {
      // Limit the heap size to the maximum possible when using compressed oops
1843 1844 1845 1846 1847 1848 1849
      julong max_coop_heap = (julong)max_heap_for_compressed_oops();
      if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
        // Heap should be above HeapBaseMinAddress to get zero based compressed oops
        // but it should be not less than default MaxHeapSize.
        max_coop_heap -= HeapBaseMinAddress;
      }
      reasonable_max = MIN2(reasonable_max, max_coop_heap);
1850
    }
1851
    reasonable_max = limit_by_allocatable_memory(reasonable_max);
P
phh 已提交
1852 1853 1854 1855

    if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
      // An initial heap size was specified on the command line,
      // so be sure that the maximum size is consistent.  Done
1856
      // after call to limit_by_allocatable_memory because that
P
phh 已提交
1857 1858 1859 1860
      // method might reduce the allocation size.
      reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
    }

1861 1862
    if (PrintGCDetails && Verbose) {
      // Cannot use gclog_or_tty yet.
1863
      tty->print_cr("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
1864
    }
P
phh 已提交
1865 1866 1867
    FLAG_SET_ERGO(uintx, MaxHeapSize, (uintx)reasonable_max);
  }

1868 1869 1870
  // If the minimum or initial heap_size have not been set or requested to be set
  // ergonomically, set them accordingly.
  if (InitialHeapSize == 0 || min_heap_size() == 0) {
1871 1872 1873 1874
    julong reasonable_minimum = (julong)(OldSize + NewSize);

    reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);

1875
    reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
1876

1877
    if (InitialHeapSize == 0) {
1878
      julong reasonable_initial = (julong)((phys_mem * InitialRAMPercentage) / 100);
P
phh 已提交
1879

1880 1881
      reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());
      reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
P
phh 已提交
1882

1883
      reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
P
phh 已提交
1884

1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
      if (PrintGCDetails && Verbose) {
        // Cannot use gclog_or_tty yet.
        tty->print_cr("  Initial heap size " SIZE_FORMAT, (uintx)reasonable_initial);
      }
      FLAG_SET_ERGO(uintx, InitialHeapSize, (uintx)reasonable_initial);
    }
    // If the minimum heap size has not been set (via -Xms),
    // synchronize with InitialHeapSize to avoid errors with the default value.
    if (min_heap_size() == 0) {
      set_min_heap_size(MIN2((uintx)reasonable_minimum, InitialHeapSize));
      if (PrintGCDetails && Verbose) {
        // Cannot use gclog_or_tty yet.
        tty->print_cr("  Minimum heap size " SIZE_FORMAT, min_heap_size());
      }
P
phh 已提交
1899
    }
1900 1901 1902
  }
}

1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
// This option inspects the machine and attempts to set various
// parameters to be optimal for long-running, memory allocation
// intensive jobs.  It is intended for machines with large
// amounts of cpu and memory.
jint Arguments::set_aggressive_heap_flags() {
  // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
  // VM, but we may not be able to represent the total physical memory
  // available (like having 8gb of memory on a box but using a 32bit VM).
  // Thus, we need to make sure we're using a julong for intermediate
  // calculations.
  julong initHeapSize;
  julong total_memory = os::physical_memory();

  if (total_memory < (julong) 256 * M) {
    jio_fprintf(defaultStream::error_stream(),
            "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
    vm_exit(1);
  }

  // The heap size is half of available memory, or (at most)
  // all of possible memory less 160mb (leaving room for the OS
  // when using ISM).  This is the maximum; because adaptive sizing
  // is turned on below, the actual space used may be smaller.

  initHeapSize = MIN2(total_memory / (julong) 2,
                      total_memory - (julong) 160 * M);

  initHeapSize = limit_by_allocatable_memory(initHeapSize);

  if (FLAG_IS_DEFAULT(MaxHeapSize)) {
    FLAG_SET_CMDLINE(uintx, MaxHeapSize, initHeapSize);
    FLAG_SET_CMDLINE(uintx, InitialHeapSize, initHeapSize);
    // Currently the minimum size and the initial heap sizes are the same.
    set_min_heap_size(initHeapSize);
  }
  if (FLAG_IS_DEFAULT(NewSize)) {
    // Make the young generation 3/8ths of the total heap.
    FLAG_SET_CMDLINE(uintx, NewSize,
            ((julong) MaxHeapSize / (julong) 8) * (julong) 3);
    FLAG_SET_CMDLINE(uintx, MaxNewSize, NewSize);
  }

#ifndef _ALLBSD_SOURCE  // UseLargePages is not yet supported on BSD.
  FLAG_SET_DEFAULT(UseLargePages, true);
#endif

  // Increase some data structure sizes for efficiency
  FLAG_SET_CMDLINE(uintx, BaseFootPrintEstimate, MaxHeapSize);
  FLAG_SET_CMDLINE(bool, ResizeTLAB, false);
  FLAG_SET_CMDLINE(uintx, TLABSize, 256 * K);

  // See the OldPLABSize comment below, but replace 'after promotion'
  // with 'after copying'.  YoungPLABSize is the size of the survivor
  // space per-gc-thread buffers.  The default is 4kw.
  FLAG_SET_CMDLINE(uintx, YoungPLABSize, 256 * K);     // Note: this is in words

  // OldPLABSize is the size of the buffers in the old gen that
  // UseParallelGC uses to promote live data that doesn't fit in the
  // survivor spaces.  At any given time, there's one for each gc thread.
  // The default size is 1kw. These buffers are rarely used, since the
  // survivor spaces are usually big enough.  For specjbb, however, there
  // are occasions when there's lots of live data in the young gen
  // and we end up promoting some of it.  We don't have a definite
  // explanation for why bumping OldPLABSize helps, but the theory
  // is that a bigger PLAB results in retaining something like the
  // original allocation order after promotion, which improves mutator
  // locality.  A minor effect may be that larger PLABs reduce the
  // number of PLAB allocation events during gc.  The value of 8kw
  // was arrived at by experimenting with specjbb.
  FLAG_SET_CMDLINE(uintx, OldPLABSize, 8 * K);      // Note: this is in words

  // Enable parallel GC and adaptive generation sizing
  FLAG_SET_CMDLINE(bool, UseParallelGC, true);

  // Encourage steady state memory management
  FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100);

  // This appears to improve mutator locality
  FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);

  // Get around early Solaris scheduling bug
  // (affinity vs other jobs on system)
  // but disallow DR and offlining (5008695).
  FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true);

  return JNI_OK;
}

D
duke 已提交
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
// This must be called after ergonomics because we want bytecode rewriting
// if the server compiler is used, or if UseSharedSpaces is disabled.
void Arguments::set_bytecode_flags() {
  // Better not attempt to store into a read-only space.
  if (UseSharedSpaces) {
    FLAG_SET_DEFAULT(RewriteBytecodes, false);
    FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
  }

  if (!RewriteBytecodes) {
    FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
  }
}

// Aggressive optimization flags  -XX:+AggressiveOpts
void Arguments::set_aggressive_opts_flags() {
2007
#ifdef COMPILER2
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
  if (AggressiveUnboxing) {
    if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
      FLAG_SET_DEFAULT(EliminateAutoBox, true);
    } else if (!EliminateAutoBox) {
      // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
      AggressiveUnboxing = false;
    }
    if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
      FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
    } else if (!DoEscapeAnalysis) {
      // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
      AggressiveUnboxing = false;
    }
  }
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031
  if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
    if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
      FLAG_SET_DEFAULT(EliminateAutoBox, true);
    }
    if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
      FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
    }

    // Feed the cache size setting into the JDK
    char buffer[1024];
S
shshahma 已提交
2032
    jio_snprintf(buffer, 1024, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
2033 2034
    add_property(buffer);
  }
2035 2036 2037
  if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
    FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
  }
2038 2039
#endif

D
duke 已提交
2040
  if (AggressiveOpts) {
S
sbohne 已提交
2041 2042 2043 2044
// Sample flag setting code
//    if (FLAG_IS_DEFAULT(EliminateZeroing)) {
//      FLAG_SET_DEFAULT(EliminateZeroing, true);
//    }
D
duke 已提交
2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
  }
}

//===========================================================================================================
// Parsing of java.compiler property

void Arguments::process_java_compiler_argument(char* arg) {
  // For backwards compatibility, Djava.compiler=NONE or ""
  // causes us to switch to -Xint mode UNLESS -Xdebug
  // is also specified.
  if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
    set_java_compiler(true);    // "-Djava.compiler[=...]" most recently seen.
  }
}

void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
  _sun_java_launcher = strdup(launcher);
2062 2063 2064
  if (strcmp("gamma", _sun_java_launcher) == 0) {
    _created_by_gamma_launcher = true;
  }
D
duke 已提交
2065 2066 2067 2068 2069 2070 2071
}

bool Arguments::created_by_java_launcher() {
  assert(_sun_java_launcher != NULL, "property must have value");
  return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
}

2072 2073 2074 2075
bool Arguments::created_by_gamma_launcher() {
  return _created_by_gamma_launcher;
}

D
duke 已提交
2076 2077 2078
//===========================================================================================================
// Parsing of main arguments

2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092
bool Arguments::verify_interval(uintx val, uintx min,
                                uintx max, const char* name) {
  // Returns true iff value is in the inclusive interval [min..max]
  // false, otherwise.
  if (val >= min && val <= max) {
    return true;
  }
  jio_fprintf(defaultStream::error_stream(),
              "%s of " UINTX_FORMAT " is invalid; must be between " UINTX_FORMAT
              " and " UINTX_FORMAT "\n",
              name, val, min, max);
  return false;
}

2093
bool Arguments::verify_min_value(intx val, intx min, const char* name) {
2094
  // Returns true if given value is at least specified min threshold
2095 2096 2097 2098 2099
  // false, otherwise.
  if (val >= min ) {
      return true;
  }
  jio_fprintf(defaultStream::error_stream(),
2100
              "%s of " INTX_FORMAT " is invalid; must be at least " INTX_FORMAT "\n",
2101 2102 2103 2104
              name, val, min);
  return false;
}

D
duke 已提交
2105
bool Arguments::verify_percentage(uintx value, const char* name) {
2106
  if (is_percentage(value)) {
D
duke 已提交
2107 2108 2109 2110 2111 2112 2113 2114
    return true;
  }
  jio_fprintf(defaultStream::error_stream(),
              "%s of " UINTX_FORMAT " is invalid; must be between 0 and 100\n",
              name, value);
  return false;
}

2115 2116 2117
// check if do gclog rotation
// +UseGCLogFileRotation is a must,
// no gc log rotation when log file not supplied or
2118
// NumberOfGCLogFiles is 0
2119 2120
void check_gclog_consistency() {
  if (UseGCLogFileRotation) {
2121
    if ((Arguments::gc_log_filename() == NULL) || (NumberOfGCLogFiles == 0)) {
2122
      jio_fprintf(defaultStream::output_stream(),
2123 2124
                  "To enable GC log rotation, use -Xloggc:<filename> -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=<num_of_files>\n"
                  "where num_of_file > 0\n"
2125 2126 2127 2128 2129
                  "GC log rotation is turned off\n");
      UseGCLogFileRotation = false;
    }
  }

2130 2131 2132 2133
  if (UseGCLogFileRotation && (GCLogFileSize != 0) && (GCLogFileSize < 8*K)) {
    FLAG_SET_CMDLINE(uintx, GCLogFileSize, 8*K);
    jio_fprintf(defaultStream::output_stream(),
                "GCLogFileSize changed to minimum 8K\n");
2134 2135 2136
  }
}

2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181
// This function is called for -Xloggc:<filename>, it can be used
// to check if a given file name(or string) conforms to the following
// specification:
// A valid string only contains "[A-Z][a-z][0-9].-_%[p|t]"
// %p and %t only allowed once. We only limit usage of filename not path
bool is_filename_valid(const char *file_name) {
  const char* p = file_name;
  char file_sep = os::file_separator()[0];
  const char* cp;
  // skip prefix path
  for (cp = file_name; *cp != '\0'; cp++) {
    if (*cp == '/' || *cp == file_sep) {
      p = cp + 1;
    }
  }

  int count_p = 0;
  int count_t = 0;
  while (*p != '\0') {
    if ((*p >= '0' && *p <= '9') ||
        (*p >= 'A' && *p <= 'Z') ||
        (*p >= 'a' && *p <= 'z') ||
         *p == '-'               ||
         *p == '_'               ||
         *p == '.') {
       p++;
       continue;
    }
    if (*p == '%') {
      if(*(p + 1) == 'p') {
        p += 2;
        count_p ++;
        continue;
      }
      if (*(p + 1) == 't') {
        p += 2;
        count_t ++;
        continue;
      }
    }
    return false;
  }
  return count_p < 2 && count_t < 2;
}

2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
bool Arguments::verify_MinHeapFreeRatio(FormatBuffer<80>& err_msg, uintx min_heap_free_ratio) {
  if (!is_percentage(min_heap_free_ratio)) {
    err_msg.print("MinHeapFreeRatio must have a value between 0 and 100");
    return false;
  }
  if (min_heap_free_ratio > MaxHeapFreeRatio) {
    err_msg.print("MinHeapFreeRatio (" UINTX_FORMAT ") must be less than or "
                  "equal to MaxHeapFreeRatio (" UINTX_FORMAT ")", min_heap_free_ratio,
                  MaxHeapFreeRatio);
    return false;
  }
2193 2194
  // This does not set the flag itself, but stores the value in a safe place for later usage.
  _min_heap_free_ratio = min_heap_free_ratio;
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
  return true;
}

bool Arguments::verify_MaxHeapFreeRatio(FormatBuffer<80>& err_msg, uintx max_heap_free_ratio) {
  if (!is_percentage(max_heap_free_ratio)) {
    err_msg.print("MaxHeapFreeRatio must have a value between 0 and 100");
    return false;
  }
  if (max_heap_free_ratio < MinHeapFreeRatio) {
    err_msg.print("MaxHeapFreeRatio (" UINTX_FORMAT ") must be greater than or "
                  "equal to MinHeapFreeRatio (" UINTX_FORMAT ")", max_heap_free_ratio,
                  MinHeapFreeRatio);
    return false;
  }
2209 2210
  // This does not set the flag itself, but stores the value in a safe place for later usage.
  _max_heap_free_ratio = max_heap_free_ratio;
2211 2212 2213
  return true;
}

2214
// Check consistency of GC selection
2215
bool Arguments::check_gc_consistency() {
2216
  check_gclog_consistency();
2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228
  bool status = true;
  // Ensure that the user has not selected conflicting sets
  // of collectors. [Note: this check is merely a user convenience;
  // collectors over-ride each other so that only a non-conflicting
  // set is selected; however what the user gets is not what they
  // may have expected from the combination they asked for. It's
  // better to reduce user confusion by not allowing them to
  // select conflicting combinations.
  uint i = 0;
  if (UseSerialGC)                       i++;
  if (UseConcMarkSweepGC || UseParNewGC) i++;
  if (UseParallelGC || UseParallelOldGC) i++;
2229
  if (UseG1GC)                           i++;
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
  if (i > 1) {
    jio_fprintf(defaultStream::error_stream(),
                "Conflicting collector combinations in option list; "
                "please refer to the release notes for the combinations "
                "allowed\n");
    status = false;
  }
  return status;
}

2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251
void Arguments::check_deprecated_gcs() {
  if (UseConcMarkSweepGC && !UseParNewGC) {
    warning("Using the DefNew young collector with the CMS collector is deprecated "
        "and will likely be removed in a future release");
  }

  if (UseParNewGC && !UseConcMarkSweepGC) {
    // !UseConcMarkSweepGC means that we are using serial old gc. Unfortunately we don't
    // set up UseSerialGC properly, so that can't be used in the check here.
    warning("Using the ParNew young collector with the Serial old collector is deprecated "
        "and will likely be removed in a future release");
  }
2252 2253 2254 2255

  if (CMSIncrementalMode) {
    warning("Using incremental CMS is deprecated and will likely be removed in a future release");
  }
2256 2257
}

T
tamao 已提交
2258 2259 2260 2261 2262
void Arguments::check_deprecated_gc_flags() {
  if (FLAG_IS_CMDLINE(MaxGCMinorPauseMillis)) {
    warning("Using MaxGCMinorPauseMillis as minor pause goal is deprecated"
            "and will likely be removed in future release");
  }
2263 2264 2265 2266
  if (FLAG_IS_CMDLINE(DefaultMaxRAMFraction)) {
    warning("DefaultMaxRAMFraction is deprecated and will likely be removed in a future release. "
        "Use MaxRAMFraction instead.");
  }
2267 2268 2269 2270 2271 2272 2273 2274 2275
  if (FLAG_IS_CMDLINE(UseCMSCompactAtFullCollection)) {
    warning("UseCMSCompactAtFullCollection is deprecated and will likely be removed in a future release.");
  }
  if (FLAG_IS_CMDLINE(CMSFullGCsBeforeCompaction)) {
    warning("CMSFullGCsBeforeCompaction is deprecated and will likely be removed in a future release.");
  }
  if (FLAG_IS_CMDLINE(UseCMSCollectionPassing)) {
    warning("UseCMSCollectionPassing is deprecated and will likely be removed in a future release.");
  }
T
tamao 已提交
2276 2277
}

2278 2279 2280 2281 2282 2283
// Check stack pages settings
bool Arguments::check_stack_pages()
{
  bool status = true;
  status = status && verify_min_value(StackYellowPages, 1, "StackYellowPages");
  status = status && verify_min_value(StackRedPages, 1, "StackRedPages");
2284 2285
  // greater stack shadow pages can't generate instruction to bang stack
  status = status && verify_interval(StackShadowPages, 1, 50, "StackShadowPages");
2286 2287 2288
  return status;
}

D
duke 已提交
2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315
// Check the consistency of vm_init_args
bool Arguments::check_vm_args_consistency() {
  // Method for adding checks for flag consistency.
  // The intent is to warn the user of all possible conflicts,
  // before returning an error.
  // Note: Needs platform-dependent factoring.
  bool status = true;

  // Allow both -XX:-UseStackBanging and -XX:-UseBoundThreads in non-product
  // builds so the cost of stack banging can be measured.
#if (defined(PRODUCT) && defined(SOLARIS))
  if (!UseBoundThreads && !UseStackBanging) {
    jio_fprintf(defaultStream::error_stream(),
                "-UseStackBanging conflicts with -UseBoundThreads\n");

     status = false;
  }
#endif

  if (TLABRefillWasteFraction == 0) {
    jio_fprintf(defaultStream::error_stream(),
                "TLABRefillWasteFraction should be a denominator, "
                "not " SIZE_FORMAT "\n",
                TLABRefillWasteFraction);
    status = false;
  }

2316
  status = status && verify_interval(AdaptiveSizePolicyWeight, 0, 100,
D
duke 已提交
2317
                              "AdaptiveSizePolicyWeight");
2318
  status = status && verify_percentage(ThresholdTolerance, "ThresholdTolerance");
D
duke 已提交
2319

2320 2321
  // Divide by bucket size to prevent a large size from causing rollover when
  // calculating amount of memory needed to be allocated for the String table.
2322
  status = status && verify_interval(StringTableSize, minimumStringTableSize,
2323 2324
    (max_uintx / StringTable::bucket_size()), "StringTable size");

2325 2326 2327
  status = status && verify_interval(SymbolTableSize, minimumSymbolTableSize,
    (max_uintx / SymbolTable::bucket_size()), "SymbolTable size");

2328 2329 2330 2331
  {
    // Using "else if" below to avoid printing two error messages if min > max.
    // This will also prevent us from reporting both min>100 and max>100 at the
    // same time, but that is less annoying than printing two identical errors IMHO.
2332
    FormatBuffer<80> err_msg("%s","");
2333 2334 2335 2336 2337 2338 2339
    if (!verify_MinHeapFreeRatio(err_msg, MinHeapFreeRatio)) {
      jio_fprintf(defaultStream::error_stream(), "%s\n", err_msg.buffer());
      status = false;
    } else if (!verify_MaxHeapFreeRatio(err_msg, MaxHeapFreeRatio)) {
      jio_fprintf(defaultStream::error_stream(), "%s\n", err_msg.buffer());
      status = false;
    }
D
duke 已提交
2340 2341
  }

2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359
  // Min/MaxMetaspaceFreeRatio
  status = status && verify_percentage(MinMetaspaceFreeRatio, "MinMetaspaceFreeRatio");
  status = status && verify_percentage(MaxMetaspaceFreeRatio, "MaxMetaspaceFreeRatio");

  if (MinMetaspaceFreeRatio > MaxMetaspaceFreeRatio) {
    jio_fprintf(defaultStream::error_stream(),
                "MinMetaspaceFreeRatio (%s" UINTX_FORMAT ") must be less than or "
                "equal to MaxMetaspaceFreeRatio (%s" UINTX_FORMAT ")\n",
                FLAG_IS_DEFAULT(MinMetaspaceFreeRatio) ? "Default: " : "",
                MinMetaspaceFreeRatio,
                FLAG_IS_DEFAULT(MaxMetaspaceFreeRatio) ? "Default: " : "",
                MaxMetaspaceFreeRatio);
    status = false;
  }

  // Trying to keep 100% free is not practical
  MinMetaspaceFreeRatio = MIN2(MinMetaspaceFreeRatio, (uintx) 99);

D
duke 已提交
2360 2361 2362 2363
  if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {
    MarkSweepAlwaysCompactCount = 1;  // Move objects every gc.
  }

2364 2365 2366
  if (UseParallelOldGC && ParallelOldGCSplitALot) {
    // Settings to encourage splitting.
    if (!FLAG_IS_CMDLINE(NewRatio)) {
2367
      FLAG_SET_CMDLINE(uintx, NewRatio, 2);
2368 2369 2370 2371 2372 2373
    }
    if (!FLAG_IS_CMDLINE(ScavengeBeforeFullGC)) {
      FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
    }
  }

2374 2375
  status = status && verify_percentage(GCHeapFreeLimit, "GCHeapFreeLimit");
  status = status && verify_percentage(GCTimeLimit, "GCTimeLimit");
D
duke 已提交
2376 2377 2378 2379 2380
  if (GCTimeLimit == 100) {
    // Turn off gc-overhead-limit-exceeded checks
    FLAG_SET_DEFAULT(UseGCOverheadLimit, false);
  }

2381
  status = status && check_gc_consistency();
2382
  status = status && check_stack_pages();
D
duke 已提交
2383 2384 2385 2386 2387 2388 2389 2390 2391

  if (CMSIncrementalMode) {
    if (!UseConcMarkSweepGC) {
      jio_fprintf(defaultStream::error_stream(),
                  "error:  invalid argument combination.\n"
                  "The CMS collector (-XX:+UseConcMarkSweepGC) must be "
                  "selected in order\nto use CMSIncrementalMode.\n");
      status = false;
    } else {
2392
      status = status && verify_percentage(CMSIncrementalDutyCycle,
D
duke 已提交
2393
                                  "CMSIncrementalDutyCycle");
2394
      status = status && verify_percentage(CMSIncrementalDutyCycleMin,
D
duke 已提交
2395
                                  "CMSIncrementalDutyCycleMin");
2396
      status = status && verify_percentage(CMSIncrementalSafetyFactor,
D
duke 已提交
2397
                                  "CMSIncrementalSafetyFactor");
2398
      status = status && verify_percentage(CMSIncrementalOffset,
D
duke 已提交
2399
                                  "CMSIncrementalOffset");
2400
      status = status && verify_percentage(CMSExpAvgFactor,
D
duke 已提交
2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418
                                  "CMSExpAvgFactor");
      // If it was not set on the command line, set
      // CMSInitiatingOccupancyFraction to 1 so icms can initiate cycles early.
      if (CMSInitiatingOccupancyFraction < 0) {
        FLAG_SET_DEFAULT(CMSInitiatingOccupancyFraction, 1);
      }
    }
  }

  // CMS space iteration, which FLSVerifyAllHeapreferences entails,
  // insists that we hold the requisite locks so that the iteration is
  // MT-safe. For the verification at start-up and shut-down, we don't
  // yet have a good way of acquiring and releasing these locks,
  // which are not visible at the CollectedHeap level. We want to
  // be able to acquire these locks and then do the iteration rather
  // than just disable the lock verification. This will be fixed under
  // bug 4788986.
  if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {
2419
    if (VerifyDuringStartup) {
D
duke 已提交
2420 2421
      warning("Heap verification at start-up disabled "
              "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2422
      VerifyDuringStartup = false; // Disable verification at start-up
D
duke 已提交
2423
    }
2424

D
duke 已提交
2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
    if (VerifyBeforeExit) {
      warning("Heap verification at shutdown disabled "
              "(due to current incompatibility with FLSVerifyAllHeapReferences)");
      VerifyBeforeExit = false; // Disable verification at shutdown
    }
  }

  // Note: only executed in non-PRODUCT mode
  if (!UseAsyncConcMarkSweepGC &&
      (ExplicitGCInvokesConcurrent ||
       ExplicitGCInvokesConcurrentAndUnloadsClasses)) {
    jio_fprintf(defaultStream::error_stream(),
2437
                "error: +ExplicitGCInvokesConcurrent[AndUnloadsClasses] conflicts"
D
duke 已提交
2438 2439 2440 2441
                " with -UseAsyncConcMarkSweepGC");
    status = false;
  }

2442 2443
  status = status && verify_min_value(ParGCArrayScanChunk, 1, "ParGCArrayScanChunk");

2444
#if INCLUDE_ALL_GCS
2445
  if (UseG1GC) {
2446 2447 2448 2449
    status = status && verify_percentage(G1NewSizePercent, "G1NewSizePercent");
    status = status && verify_percentage(G1MaxNewSizePercent, "G1MaxNewSizePercent");
    status = status && verify_interval(G1NewSizePercent, 0, G1MaxNewSizePercent, "G1NewSizePercent");

2450 2451
    status = status && verify_percentage(InitiatingHeapOccupancyPercent,
                                         "InitiatingHeapOccupancyPercent");
2452 2453 2454 2455
    status = status && verify_min_value(G1RefProcDrainInterval, 1,
                                        "G1RefProcDrainInterval");
    status = status && verify_min_value((intx)G1ConcMarkStepDurationMillis, 1,
                                        "G1ConcMarkStepDurationMillis");
2456 2457
    status = status && verify_interval(G1ConcRSHotCardLimit, 0, max_jubyte,
                                       "G1ConcRSHotCardLimit");
J
jmasa 已提交
2458
    status = status && verify_interval(G1ConcRSLogCacheSize, 0, 27,
2459
                                       "G1ConcRSLogCacheSize");
P
pliden 已提交
2460 2461
    status = status && verify_interval(StringDeduplicationAgeThreshold, 1, markOopDesc::max_age,
                                       "StringDeduplicationAgeThreshold");
2462
  }
2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508
  if (UseConcMarkSweepGC) {
    status = status && verify_min_value(CMSOldPLABNumRefills, 1, "CMSOldPLABNumRefills");
    status = status && verify_min_value(CMSOldPLABToleranceFactor, 1, "CMSOldPLABToleranceFactor");
    status = status && verify_min_value(CMSOldPLABMax, 1, "CMSOldPLABMax");
    status = status && verify_interval(CMSOldPLABMin, 1, CMSOldPLABMax, "CMSOldPLABMin");

    status = status && verify_min_value(CMSYoungGenPerWorker, 1, "CMSYoungGenPerWorker");

    status = status && verify_min_value(CMSSamplingGrain, 1, "CMSSamplingGrain");
    status = status && verify_interval(CMS_SweepWeight, 0, 100, "CMS_SweepWeight");
    status = status && verify_interval(CMS_FLSWeight, 0, 100, "CMS_FLSWeight");

    status = status && verify_interval(FLSCoalescePolicy, 0, 4, "FLSCoalescePolicy");

    status = status && verify_min_value(CMSRescanMultiple, 1, "CMSRescanMultiple");
    status = status && verify_min_value(CMSConcMarkMultiple, 1, "CMSConcMarkMultiple");

    status = status && verify_interval(CMSPrecleanIter, 0, 9, "CMSPrecleanIter");
    status = status && verify_min_value(CMSPrecleanDenominator, 1, "CMSPrecleanDenominator");
    status = status && verify_interval(CMSPrecleanNumerator, 0, CMSPrecleanDenominator - 1, "CMSPrecleanNumerator");

    status = status && verify_percentage(CMSBootstrapOccupancy, "CMSBootstrapOccupancy");

    status = status && verify_min_value(CMSPrecleanThreshold, 100, "CMSPrecleanThreshold");

    status = status && verify_percentage(CMSScheduleRemarkEdenPenetration, "CMSScheduleRemarkEdenPenetration");
    status = status && verify_min_value(CMSScheduleRemarkSamplingRatio, 1, "CMSScheduleRemarkSamplingRatio");
    status = status && verify_min_value(CMSBitMapYieldQuantum, 1, "CMSBitMapYieldQuantum");
    status = status && verify_percentage(CMSTriggerRatio, "CMSTriggerRatio");
    status = status && verify_percentage(CMSIsTooFullPercentage, "CMSIsTooFullPercentage");
  }

  if (UseParallelGC || UseParallelOldGC) {
    status = status && verify_interval(ParallelOldDeadWoodLimiterMean, 0, 100, "ParallelOldDeadWoodLimiterMean");
    status = status && verify_interval(ParallelOldDeadWoodLimiterStdDev, 0, 100, "ParallelOldDeadWoodLimiterStdDev");

    status = status && verify_percentage(YoungGenerationSizeIncrement, "YoungGenerationSizeIncrement");
    status = status && verify_percentage(TenuredGenerationSizeIncrement, "TenuredGenerationSizeIncrement");

    status = status && verify_min_value(YoungGenerationSizeSupplementDecay, 1, "YoungGenerationSizeSupplementDecay");
    status = status && verify_min_value(TenuredGenerationSizeSupplementDecay, 1, "TenuredGenerationSizeSupplementDecay");

    status = status && verify_min_value(ParGCCardsPerStrideChunk, 1, "ParGCCardsPerStrideChunk");

    status = status && verify_min_value(ParallelOldGCSplitInterval, 0, "ParallelOldGCSplitInterval");
  }
2509
#endif // INCLUDE_ALL_GCS
2510

2511 2512 2513 2514 2515 2516 2517 2518 2519 2520
  status = status && verify_interval(RefDiscoveryPolicy,
                                     ReferenceProcessor::DiscoveryPolicyMin,
                                     ReferenceProcessor::DiscoveryPolicyMax,
                                     "RefDiscoveryPolicy");

  // Limit the lower bound of this flag to 1 as it is used in a division
  // expression.
  status = status && verify_interval(TLABWasteTargetPercent,
                                     1, 100, "TLABWasteTargetPercent");

2521 2522
  status = status && verify_object_alignment();

2523 2524
  status = status && verify_interval(CompressedClassSpaceSize, 1*M, 3*G,
                                      "CompressedClassSpaceSize");
2525

2526 2527
  status = status && verify_interval(MarkStackSizeMax,
                                  1, (max_jint - 1), "MarkStackSizeMax");
2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539
  status = status && verify_interval(NUMAChunkResizeWeight, 0, 100, "NUMAChunkResizeWeight");

  status = status && verify_min_value(LogEventsBufferEntries, 1, "LogEventsBufferEntries");

  status = status && verify_min_value(HeapSizePerGCThread, (uintx) os::vm_page_size(), "HeapSizePerGCThread");

  status = status && verify_min_value(GCTaskTimeStampEntries, 1, "GCTaskTimeStampEntries");

  status = status && verify_percentage(ParallelGCBufferWastePct, "ParallelGCBufferWastePct");
  status = status && verify_interval(TargetPLABWastePct, 1, 100, "TargetPLABWastePct");

  status = status && verify_min_value(ParGCStridesPerThread, 1, "ParGCStridesPerThread");
2540

2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561
  status = status && verify_min_value(MinRAMFraction, 1, "MinRAMFraction");
  status = status && verify_min_value(InitialRAMFraction, 1, "InitialRAMFraction");
  status = status && verify_min_value(MaxRAMFraction, 1, "MaxRAMFraction");
  status = status && verify_min_value(DefaultMaxRAMFraction, 1, "DefaultMaxRAMFraction");

  status = status && verify_interval(AdaptiveTimeWeight, 0, 100, "AdaptiveTimeWeight");
  status = status && verify_min_value(AdaptiveSizeDecrementScaleFactor, 1, "AdaptiveSizeDecrementScaleFactor");

  status = status && verify_interval(TLABAllocationWeight, 0, 100, "TLABAllocationWeight");
  status = status && verify_min_value(MinTLABSize, 1, "MinTLABSize");
  status = status && verify_min_value(TLABRefillWasteFraction, 1, "TLABRefillWasteFraction");

  status = status && verify_percentage(YoungGenerationSizeSupplement, "YoungGenerationSizeSupplement");
  status = status && verify_percentage(TenuredGenerationSizeSupplement, "TenuredGenerationSizeSupplement");

  // the "age" field in the oop header is 4 bits; do not want to pull in markOop.hpp
  // just for that, so hardcode here.
  status = status && verify_interval(MaxTenuringThreshold, 0, 15, "MaxTenuringThreshold");
  status = status && verify_interval(InitialTenuringThreshold, 0, MaxTenuringThreshold, "MaxTenuringThreshold");
  status = status && verify_percentage(TargetSurvivorRatio, "TargetSurvivorRatio");
  status = status && verify_percentage(MarkSweepDeadRatio, "MarkSweepDeadRatio");
2562

2563
  status = status && verify_min_value(MarkSweepAlwaysCompactCount, 1, "MarkSweepAlwaysCompactCount");
2564 2565 2566
#ifdef COMPILER1
  status = status && verify_min_value(ValueMapInitialSize, 1, "ValueMapInitialSize");
#endif
2567

2568 2569
  if (PrintNMTStatistics) {
#if INCLUDE_NMT
2570
    if (MemTracker::tracking_level() == NMT_off) {
2571 2572 2573 2574 2575 2576
#endif // INCLUDE_NMT
      warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
      PrintNMTStatistics = false;
#if INCLUDE_NMT
    }
#endif
2577 2578
  }

2579 2580 2581 2582 2583 2584
  // Need to limit the extent of the padding to reasonable size.
  // 8K is well beyond the reasonable HW cache line size, even with the
  // aggressive prefetching, while still leaving the room for segregating
  // among the distinct pages.
  if (ContendedPaddingWidth < 0 || ContendedPaddingWidth > 8192) {
    jio_fprintf(defaultStream::error_stream(),
2585
                "ContendedPaddingWidth=" INTX_FORMAT " must be in between %d and %d\n",
2586 2587 2588 2589 2590 2591 2592 2593
                ContendedPaddingWidth, 0, 8192);
    status = false;
  }

  // Need to enforce the padding not to break the existing field alignments.
  // It is sufficient to check against the largest type size.
  if ((ContendedPaddingWidth % BytesPerLong) != 0) {
    jio_fprintf(defaultStream::error_stream(),
2594
                "ContendedPaddingWidth=" INTX_FORMAT " must be a multiple of %d\n",
2595 2596 2597 2598
                ContendedPaddingWidth, BytesPerLong);
    status = false;
  }

2599 2600 2601 2602
  // Check lower bounds of the code cache
  // Template Interpreter code is approximately 3X larger in debug builds.
  uint min_code_cache_size = (CodeCacheMinimumUseSpace DEBUG_ONLY(* 3)) + CodeCacheMinimumFreeSpace;
  if (InitialCodeCacheSize < (uintx)os::vm_page_size()) {
2603
    jio_fprintf(defaultStream::error_stream(),
2604 2605 2606 2607
                "Invalid InitialCodeCacheSize=%dK. Must be at least %dK.\n", InitialCodeCacheSize/K,
                os::vm_page_size()/K);
    status = false;
  } else if (ReservedCodeCacheSize < InitialCodeCacheSize) {
2608
    jio_fprintf(defaultStream::error_stream(),
2609
                "Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",
2610 2611
                ReservedCodeCacheSize/K, InitialCodeCacheSize/K);
    status = false;
2612 2613 2614 2615 2616
  } else if (ReservedCodeCacheSize < min_code_cache_size) {
    jio_fprintf(defaultStream::error_stream(),
                "Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,
                min_code_cache_size/K);
    status = false;
2617 2618 2619 2620 2621 2622
  } else if (ReservedCodeCacheSize > 2*G) {
    // Code cache size larger than MAXINT is not supported.
    jio_fprintf(defaultStream::error_stream(),
                "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,
                (2*G)/M);
    status = false;
2623
  }
2624 2625 2626 2627

  status &= verify_interval(NmethodSweepFraction, 1, ReservedCodeCacheSize/K, "NmethodSweepFraction");
  status &= verify_interval(NmethodSweepActivity, 0, 2000, "NmethodSweepActivity");

2628 2629 2630 2631
  if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {
    warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");
  }

2632
#ifdef COMPILER1
T
twisti 已提交
2633
  status &= verify_interval(SafepointPollOffset, 0, os::vm_page_size() - BytesPerWord, "SafepointPollOffset");
2634
#endif
T
twisti 已提交
2635

2636 2637 2638 2639 2640
  int min_number_of_compiler_threads = get_min_number_of_compiler_threads();
  // The default CICompilerCount's value is CI_COMPILER_COUNT.
  assert(min_number_of_compiler_threads <= CI_COMPILER_COUNT, "minimum should be less or equal default number");
  // Check the minimum number of compiler threads
  status &=verify_min_value(CICompilerCount, min_number_of_compiler_threads, "CICompilerCount");
2641

D
duke 已提交
2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689
  return status;
}

bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
  const char* option_type) {
  if (ignore) return false;

  const char* spacer = " ";
  if (option_type == NULL) {
    option_type = ++spacer; // Set both to the empty string.
  }

  if (os::obsolete_option(option)) {
    jio_fprintf(defaultStream::error_stream(),
                "Obsolete %s%soption: %s\n", option_type, spacer,
      option->optionString);
    return false;
  } else {
    jio_fprintf(defaultStream::error_stream(),
                "Unrecognized %s%soption: %s\n", option_type, spacer,
      option->optionString);
    return true;
  }
}

static const char* user_assertion_options[] = {
  "-da", "-ea", "-disableassertions", "-enableassertions", 0
};

static const char* system_assertion_options[] = {
  "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
};

// Return true if any of the strings in null-terminated array 'names' matches.
// If tail_allowed is true, then the tail must begin with a colon; otherwise,
// the option must match exactly.
static bool match_option(const JavaVMOption* option, const char** names, const char** tail,
  bool tail_allowed) {
  for (/* empty */; *names != NULL; ++names) {
    if (match_option(option, *names, tail)) {
      if (**tail == '\0' || tail_allowed && **tail == ':') {
        return true;
      }
    }
  }
  return false;
}

2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712
bool Arguments::parse_uintx(const char* value,
                            uintx* uintx_arg,
                            uintx min_size) {

  // Check the sign first since atomull() parses only unsigned values.
  bool value_is_positive = !(*value == '-');

  if (value_is_positive) {
    julong n;
    bool good_return = atomull(value, &n);
    if (good_return) {
      bool above_minimum = n >= min_size;
      bool value_is_too_large = n > max_uintx;

      if (above_minimum && !value_is_too_large) {
        *uintx_arg = n;
        return true;
      }
    }
  }
  return false;
}

D
duke 已提交
2713
Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2714 2715 2716
                                                  julong* long_arg,
                                                  julong min_size) {
  if (!atomull(s, long_arg)) return arg_unreadable;
D
duke 已提交
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732
  return check_memory_size(*long_arg, min_size);
}

// Parse JavaVMInitArgs structure

jint Arguments::parse_vm_init_args(const JavaVMInitArgs* args) {
  // For components of the system classpath.
  SysClassPath scp(Arguments::get_sysclasspath());
  bool scp_assembly_required = false;

  // Save default settings for some mode flags
  Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
  Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
  Arguments::_ClipInlining             = ClipInlining;
  Arguments::_BackgroundCompilation    = BackgroundCompilation;

2733 2734 2735
  // Setup flags for mixed which is the default
  set_mode_flags(_mixed);

D
duke 已提交
2736 2737 2738 2739 2740 2741 2742
  // Parse JAVA_TOOL_OPTIONS environment variable (if present)
  jint result = parse_java_tool_options_environment_variable(&scp, &scp_assembly_required);
  if (result != JNI_OK) {
    return result;
  }

  // Parse JavaVMInitArgs structure passed in
2743
  result = parse_each_vm_init_arg(args, &scp, &scp_assembly_required, Flag::COMMAND_LINE);
D
duke 已提交
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753
  if (result != JNI_OK) {
    return result;
  }

  // Parse _JAVA_OPTIONS environment variable (if present) (mimics classic VM)
  result = parse_java_options_environment_variable(&scp, &scp_assembly_required);
  if (result != JNI_OK) {
    return result;
  }

2754 2755 2756 2757 2758 2759 2760 2761
  // We need to ensure processor and memory resources have been properly
  // configured - which may rely on arguments we just processed - before
  // doing the final argument processing. Any argument processing that
  // needs to know about processor and memory resources must occur after
  // this point.

  os::init_container_support();

D
duke 已提交
2762 2763 2764 2765 2766 2767 2768 2769 2770
  // Do final processing now that all arguments have been parsed
  result = finalize_vm_init_args(&scp, scp_assembly_required);
  if (result != JNI_OK) {
    return result;
  }

  return JNI_OK;
}

2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819
// Checks if name in command-line argument -agent{lib,path}:name[=options]
// represents a valid HPROF of JDWP agent.  is_path==true denotes that we
// are dealing with -agentpath (case where name is a path), otherwise with
// -agentlib
bool valid_hprof_or_jdwp_agent(char *name, bool is_path) {
  char *_name;
  const char *_hprof = "hprof", *_jdwp = "jdwp";
  size_t _len_hprof, _len_jdwp, _len_prefix;

  if (is_path) {
    if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
      return false;
    }

    _name++;  // skip past last path separator
    _len_prefix = strlen(JNI_LIB_PREFIX);

    if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
      return false;
    }

    _name += _len_prefix;
    _len_hprof = strlen(_hprof);
    _len_jdwp = strlen(_jdwp);

    if (strncmp(_name, _hprof, _len_hprof) == 0) {
      _name += _len_hprof;
    }
    else if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
      _name += _len_jdwp;
    }
    else {
      return false;
    }

    if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
      return false;
    }

    return true;
  }

  if (strcmp(name, _hprof) == 0 || strcmp(name, _jdwp) == 0) {
    return true;
  }

  return false;
}

D
duke 已提交
2820 2821 2822
jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args,
                                       SysClassPath* scp_p,
                                       bool* scp_assembly_required_p,
2823
                                       Flag::Flags origin) {
D
duke 已提交
2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883
  // Remaining part of option string
  const char* tail;

  // iterate over arguments
  for (int index = 0; index < args->nOptions; index++) {
    bool is_absolute_path = false;  // for -agentpath vs -agentlib

    const JavaVMOption* option = args->options + index;

    if (!match_option(option, "-Djava.class.path", &tail) &&
        !match_option(option, "-Dsun.java.command", &tail) &&
        !match_option(option, "-Dsun.java.launcher", &tail)) {

        // add all jvm options to the jvm_args string. This string
        // is used later to set the java.vm.args PerfData string constant.
        // the -Djava.class.path and the -Dsun.java.command options are
        // omitted from jvm_args string as each have their own PerfData
        // string constant object.
        build_jvm_args(option->optionString);
    }

    // -verbose:[class/gc/jni]
    if (match_option(option, "-verbose", &tail)) {
      if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
        FLAG_SET_CMDLINE(bool, TraceClassLoading, true);
        FLAG_SET_CMDLINE(bool, TraceClassUnloading, true);
      } else if (!strcmp(tail, ":gc")) {
        FLAG_SET_CMDLINE(bool, PrintGC, true);
      } else if (!strcmp(tail, ":jni")) {
        FLAG_SET_CMDLINE(bool, PrintJNIResolving, true);
      }
    // -da / -ea / -disableassertions / -enableassertions
    // These accept an optional class/package name separated by a colon, e.g.,
    // -da:java.lang.Thread.
    } else if (match_option(option, user_assertion_options, &tail, true)) {
      bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
      if (*tail == '\0') {
        JavaAssertions::setUserClassDefault(enable);
      } else {
        assert(*tail == ':', "bogus match by match_option()");
        JavaAssertions::addOption(tail + 1, enable);
      }
    // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
    } else if (match_option(option, system_assertion_options, &tail, false)) {
      bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
      JavaAssertions::setSystemClassDefault(enable);
    // -bootclasspath:
    } else if (match_option(option, "-Xbootclasspath:", &tail)) {
      scp_p->reset_path(tail);
      *scp_assembly_required_p = true;
    // -bootclasspath/a:
    } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
      scp_p->add_suffix(tail);
      *scp_assembly_required_p = true;
    // -bootclasspath/p:
    } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
      scp_p->add_prefix(tail);
      *scp_assembly_required_p = true;
    // -Xrun
    } else if (match_option(option, "-Xrun", &tail)) {
2884
      if (tail != NULL) {
D
duke 已提交
2885 2886
        const char* pos = strchr(tail, ':');
        size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
Z
zgu 已提交
2887
        char* name = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
D
duke 已提交
2888 2889 2890 2891 2892
        name[len] = '\0';

        char *options = NULL;
        if(pos != NULL) {
          size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
Z
zgu 已提交
2893
          options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtInternal), pos+1, len2);
D
duke 已提交
2894
        }
2895
#if !INCLUDE_JVMTI
D
duke 已提交
2896
        if ((strcmp(name, "hprof") == 0) || (strcmp(name, "jdwp") == 0)) {
2897 2898 2899 2900
          jio_fprintf(defaultStream::error_stream(),
            "Profiling and debugging agents are not supported in this VM\n");
          return JNI_ERR;
        }
2901
#endif // !INCLUDE_JVMTI
2902
        add_init_library(name, options);
D
duke 已提交
2903 2904 2905 2906 2907 2908 2909
      }
    // -agentlib and -agentpath
    } else if (match_option(option, "-agentlib:", &tail) ||
          (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
      if(tail != NULL) {
        const char* pos = strchr(tail, '=');
        size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
Z
zgu 已提交
2910
        char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
D
duke 已提交
2911 2912 2913 2914
        name[len] = '\0';

        char *options = NULL;
        if(pos != NULL) {
S
shshahma 已提交
2915 2916 2917
          size_t length = strlen(pos + 1) + 1;
          options = NEW_C_HEAP_ARRAY(char, length, mtInternal);
          jio_snprintf(options, length, "%s", pos + 1);
D
duke 已提交
2918
        }
2919
#if !INCLUDE_JVMTI
2920
        if (valid_hprof_or_jdwp_agent(name, is_absolute_path)) {
2921 2922 2923 2924
          jio_fprintf(defaultStream::error_stream(),
            "Profiling and debugging agents are not supported in this VM\n");
          return JNI_ERR;
        }
2925
#endif // !INCLUDE_JVMTI
D
duke 已提交
2926 2927 2928 2929
        add_init_agent(name, options, is_absolute_path);
      }
    // -javaagent
    } else if (match_option(option, "-javaagent:", &tail)) {
2930
#if !INCLUDE_JVMTI
2931 2932 2933
      jio_fprintf(defaultStream::error_stream(),
        "Instrumentation agents are not supported in this VM\n");
      return JNI_ERR;
2934
#else
D
duke 已提交
2935
      if(tail != NULL) {
S
shshahma 已提交
2936 2937 2938
        size_t length = strlen(tail) + 1;
        char *options = NEW_C_HEAP_ARRAY(char, length, mtInternal);
        jio_snprintf(options, length, "%s", tail);
D
duke 已提交
2939 2940
        add_init_agent("instrument", options, false);
      }
2941
#endif // !INCLUDE_JVMTI
D
duke 已提交
2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963
    // -Xnoclassgc
    } else if (match_option(option, "-Xnoclassgc", &tail)) {
      FLAG_SET_CMDLINE(bool, ClassUnloading, false);
    // -Xincgc: i-CMS
    } else if (match_option(option, "-Xincgc", &tail)) {
      FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true);
      FLAG_SET_CMDLINE(bool, CMSIncrementalMode, true);
    // -Xnoincgc: no i-CMS
    } else if (match_option(option, "-Xnoincgc", &tail)) {
      FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false);
      FLAG_SET_CMDLINE(bool, CMSIncrementalMode, false);
    // -Xconcgc
    } else if (match_option(option, "-Xconcgc", &tail)) {
      FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true);
    // -Xnoconcgc
    } else if (match_option(option, "-Xnoconcgc", &tail)) {
      FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false);
    // -Xbatch
    } else if (match_option(option, "-Xbatch", &tail)) {
      FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
    // -Xmn for compatibility with other JVM vendors
    } else if (match_option(option, "-Xmn", &tail)) {
2964 2965
      julong long_initial_young_size = 0;
      ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
D
duke 已提交
2966 2967
      if (errcode != arg_in_range) {
        jio_fprintf(defaultStream::error_stream(),
2968
                    "Invalid initial young generation size: %s\n", option->optionString);
D
duke 已提交
2969 2970 2971
        describe_range_error(errcode);
        return JNI_EINVAL;
      }
2972 2973
      FLAG_SET_CMDLINE(uintx, MaxNewSize, (uintx)long_initial_young_size);
      FLAG_SET_CMDLINE(uintx, NewSize, (uintx)long_initial_young_size);
D
duke 已提交
2974 2975
    // -Xms
    } else if (match_option(option, "-Xms", &tail)) {
2976
      julong long_initial_heap_size = 0;
2977 2978
      // an initial heap size of 0 means automatically determine
      ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);
D
duke 已提交
2979 2980 2981 2982 2983 2984
      if (errcode != arg_in_range) {
        jio_fprintf(defaultStream::error_stream(),
                    "Invalid initial heap size: %s\n", option->optionString);
        describe_range_error(errcode);
        return JNI_EINVAL;
      }
2985
      set_min_heap_size((uintx)long_initial_heap_size);
D
duke 已提交
2986
      // Currently the minimum size and the initial heap sizes are the same.
2987 2988
      // Can be overridden with -XX:InitialHeapSize.
      FLAG_SET_CMDLINE(uintx, InitialHeapSize, (uintx)long_initial_heap_size);
D
duke 已提交
2989
    // -Xmx
2990
    } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2991
      julong long_max_heap_size = 0;
D
duke 已提交
2992 2993 2994 2995 2996 2997 2998
      ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
      if (errcode != arg_in_range) {
        jio_fprintf(defaultStream::error_stream(),
                    "Invalid maximum heap size: %s\n", option->optionString);
        describe_range_error(errcode);
        return JNI_EINVAL;
      }
P
phh 已提交
2999
      FLAG_SET_CMDLINE(uintx, MaxHeapSize, (uintx)long_max_heap_size);
D
duke 已提交
3000 3001
    // Xmaxf
    } else if (match_option(option, "-Xmaxf", &tail)) {
3002 3003
      char* err;
      int maxf = (int)(strtod(tail, &err) * 100);
3004
      if (*err != '\0' || *tail == '\0' || maxf < 0 || maxf > 100) {
D
duke 已提交
3005 3006 3007 3008 3009 3010 3011 3012 3013
        jio_fprintf(defaultStream::error_stream(),
                    "Bad max heap free percentage size: %s\n",
                    option->optionString);
        return JNI_EINVAL;
      } else {
        FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf);
      }
    // Xminf
    } else if (match_option(option, "-Xminf", &tail)) {
3014 3015
      char* err;
      int minf = (int)(strtod(tail, &err) * 100);
3016
      if (*err != '\0' || *tail == '\0' || minf < 0 || minf > 100) {
D
duke 已提交
3017 3018 3019 3020 3021 3022 3023 3024 3025
        jio_fprintf(defaultStream::error_stream(),
                    "Bad min heap free percentage size: %s\n",
                    option->optionString);
        return JNI_EINVAL;
      } else {
        FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf);
      }
    // -Xss
    } else if (match_option(option, "-Xss", &tail)) {
3026
      julong long_ThreadStackSize = 0;
D
duke 已提交
3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039
      ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);
      if (errcode != arg_in_range) {
        jio_fprintf(defaultStream::error_stream(),
                    "Invalid thread stack size: %s\n", option->optionString);
        describe_range_error(errcode);
        return JNI_EINVAL;
      }
      // Internally track ThreadStackSize in units of 1024 bytes.
      FLAG_SET_CMDLINE(intx, ThreadStackSize,
                              round_to((int)long_ThreadStackSize, K) / K);
    // -Xoss
    } else if (match_option(option, "-Xoss", &tail)) {
          // HotSpot does not have separate native and Java stacks, ignore silently for compatibility
3040 3041 3042 3043 3044 3045 3046 3047 3048 3049
    } else if (match_option(option, "-XX:CodeCacheExpansionSize=", &tail)) {
      julong long_CodeCacheExpansionSize = 0;
      ArgsRange errcode = parse_memory_size(tail, &long_CodeCacheExpansionSize, os::vm_page_size());
      if (errcode != arg_in_range) {
        jio_fprintf(defaultStream::error_stream(),
                   "Invalid argument: %s. Must be at least %luK.\n", option->optionString,
                   os::vm_page_size()/K);
        return JNI_EINVAL;
      }
      FLAG_SET_CMDLINE(uintx, CodeCacheExpansionSize, (uintx)long_CodeCacheExpansionSize);
3050 3051
    } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
               match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
3052
      julong long_ReservedCodeCacheSize = 0;
3053

3054
      ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
D
duke 已提交
3055 3056
      if (errcode != arg_in_range) {
        jio_fprintf(defaultStream::error_stream(),
3057
                    "Invalid maximum code cache size: %s.\n", option->optionString);
D
duke 已提交
3058 3059 3060
        return JNI_EINVAL;
      }
      FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize);
3061 3062 3063 3064 3065 3066 3067 3068 3069 3070
      //-XX:IncreaseFirstTierCompileThresholdAt=
      } else if (match_option(option, "-XX:IncreaseFirstTierCompileThresholdAt=", &tail)) {
        uintx uint_IncreaseFirstTierCompileThresholdAt = 0;
        if (!parse_uintx(tail, &uint_IncreaseFirstTierCompileThresholdAt, 0) || uint_IncreaseFirstTierCompileThresholdAt > 99) {
          jio_fprintf(defaultStream::error_stream(),
                      "Invalid value for IncreaseFirstTierCompileThresholdAt: %s. Should be between 0 and 99.\n",
                      option->optionString);
          return JNI_EINVAL;
        }
        FLAG_SET_CMDLINE(uintx, IncreaseFirstTierCompileThresholdAt, (uintx)uint_IncreaseFirstTierCompileThresholdAt);
D
duke 已提交
3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093
    // -green
    } else if (match_option(option, "-green", &tail)) {
      jio_fprintf(defaultStream::error_stream(),
                  "Green threads support not available\n");
          return JNI_EINVAL;
    // -native
    } else if (match_option(option, "-native", &tail)) {
          // HotSpot always uses native threads, ignore silently for compatibility
    // -Xsqnopause
    } else if (match_option(option, "-Xsqnopause", &tail)) {
          // EVM option, ignore silently for compatibility
    // -Xrs
    } else if (match_option(option, "-Xrs", &tail)) {
          // Classic/EVM option, new functionality
      FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true);
    } else if (match_option(option, "-Xusealtsigs", &tail)) {
          // change default internal VM signals used - lower case for back compat
      FLAG_SET_CMDLINE(bool, UseAltSigs, true);
    // -Xoptimize
    } else if (match_option(option, "-Xoptimize", &tail)) {
          // EVM option, ignore silently for compatibility
    // -Xprof
    } else if (match_option(option, "-Xprof", &tail)) {
3094
#if INCLUDE_FPROF
D
duke 已提交
3095
      _has_profile = true;
3096
#else // INCLUDE_FPROF
3097 3098 3099
      jio_fprintf(defaultStream::error_stream(),
        "Flat profiling is not supported in this VM.\n");
      return JNI_ERR;
3100
#endif // INCLUDE_FPROF
D
duke 已提交
3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116
    // -Xconcurrentio
    } else if (match_option(option, "-Xconcurrentio", &tail)) {
      FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true);
      FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
      FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1);
      FLAG_SET_CMDLINE(bool, UseTLAB, false);
      FLAG_SET_CMDLINE(uintx, NewSizeThreadIncrease, 16 * K);  // 20Kb per thread added to new generation

      // -Xinternalversion
    } else if (match_option(option, "-Xinternalversion", &tail)) {
      jio_fprintf(defaultStream::output_stream(), "%s\n",
                  VM_Version::internal_vm_info_string());
      vm_exit(0);
#ifndef PRODUCT
    // -Xprintflags
    } else if (match_option(option, "-Xprintflags", &tail)) {
F
fparain 已提交
3117
      CommandLineFlags::printFlags(tty, false);
D
duke 已提交
3118 3119 3120 3121
      vm_exit(0);
#endif
    // -D
    } else if (match_option(option, "-D", &tail)) {
3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138
      if (CheckEndorsedAndExtDirs) {
        if (match_option(option, "-Djava.endorsed.dirs=", &tail)) {
          // abort if -Djava.endorsed.dirs is set
          jio_fprintf(defaultStream::output_stream(),
            "-Djava.endorsed.dirs will not be supported in a future release.\n"
            "Refer to JEP 220 for details (http://openjdk.java.net/jeps/220).\n");
          return JNI_EINVAL;
        }
        if (match_option(option, "-Djava.ext.dirs=", &tail)) {
          // abort if -Djava.ext.dirs is set
          jio_fprintf(defaultStream::output_stream(),
            "-Djava.ext.dirs will not be supported in a future release.\n"
            "Refer to JEP 220 for details (http://openjdk.java.net/jeps/220).\n");
          return JNI_EINVAL;
        }
      }

D
duke 已提交
3139 3140 3141 3142 3143
      if (!add_property(tail)) {
        return JNI_ENOMEM;
      }
      // Out of the box management support
      if (match_option(option, "-Dcom.sun.management", &tail)) {
3144
#if INCLUDE_MANAGEMENT
D
duke 已提交
3145
        FLAG_SET_CMDLINE(bool, ManagementServer, true);
3146
#else
3147 3148 3149
        jio_fprintf(defaultStream::output_stream(),
          "-Dcom.sun.management is not supported in this VM.\n");
        return JNI_ERR;
3150
#endif
D
duke 已提交
3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206
      }
    // -Xint
    } else if (match_option(option, "-Xint", &tail)) {
          set_mode_flags(_int);
    // -Xmixed
    } else if (match_option(option, "-Xmixed", &tail)) {
          set_mode_flags(_mixed);
    // -Xcomp
    } else if (match_option(option, "-Xcomp", &tail)) {
      // for testing the compiler; turn off all flags that inhibit compilation
          set_mode_flags(_comp);
    // -Xshare:dump
    } else if (match_option(option, "-Xshare:dump", &tail)) {
      FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true);
      set_mode_flags(_int);     // Prevent compilation, which creates objects
    // -Xshare:on
    } else if (match_option(option, "-Xshare:on", &tail)) {
      FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
      FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true);
    // -Xshare:auto
    } else if (match_option(option, "-Xshare:auto", &tail)) {
      FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
      FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);
    // -Xshare:off
    } else if (match_option(option, "-Xshare:off", &tail)) {
      FLAG_SET_CMDLINE(bool, UseSharedSpaces, false);
      FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);
    // -Xverify
    } else if (match_option(option, "-Xverify", &tail)) {
      if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
        FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true);
        FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);
      } else if (strcmp(tail, ":remote") == 0) {
        FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);
        FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);
      } else if (strcmp(tail, ":none") == 0) {
        FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);
        FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false);
      } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
        return JNI_EINVAL;
      }
    // -Xdebug
    } else if (match_option(option, "-Xdebug", &tail)) {
      // note this flag has been used, then ignore
      set_xdebug_mode(true);
    // -Xnoagent
    } else if (match_option(option, "-Xnoagent", &tail)) {
      // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
    } else if (match_option(option, "-Xboundthreads", &tail)) {
      // Bind user level threads to kernel threads (Solaris only)
      FLAG_SET_CMDLINE(bool, UseBoundThreads, true);
    } else if (match_option(option, "-Xloggc:", &tail)) {
      // Redirect GC output to the file. -Xloggc:<filename>
      // ostream_init_log(), when called will use this filename
      // to initialize a fileStream.
      _gc_log_filename = strdup(tail);
3207 3208 3209 3210 3211 3212 3213
     if (!is_filename_valid(_gc_log_filename)) {
       jio_fprintf(defaultStream::output_stream(),
                  "Invalid file name for use with -Xloggc: Filename can only contain the "
                  "characters [A-Z][a-z][0-9]-_.%%[p|t] but it has been %s\n"
                  "Note %%p or %%t can only be used once\n", _gc_log_filename);
        return JNI_EINVAL;
      }
D
duke 已提交
3214 3215 3216 3217 3218 3219
      FLAG_SET_CMDLINE(bool, PrintGC, true);
      FLAG_SET_CMDLINE(bool, PrintGCTimeStamps, true);

    // JNI hooks
    } else if (match_option(option, "-Xcheck", &tail)) {
      if (!strcmp(tail, ":jni")) {
3220 3221 3222
#if !INCLUDE_JNI_CHECK
        warning("JNI CHECKING is not supported in this VM");
#else
D
duke 已提交
3223
        CheckJNICalls = true;
3224
#endif // INCLUDE_JNI_CHECK
D
duke 已提交
3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273
      } else if (is_bad_option(option, args->ignoreUnrecognized,
                                     "check")) {
        return JNI_EINVAL;
      }
    } else if (match_option(option, "vfprintf", &tail)) {
      _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
    } else if (match_option(option, "exit", &tail)) {
      _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
    } else if (match_option(option, "abort", &tail)) {
      _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
    } else if (match_option(option, "-XX:+NeverTenure", &tail)) {
      // The last option must always win.
      FLAG_SET_CMDLINE(bool, AlwaysTenure, false);
      FLAG_SET_CMDLINE(bool, NeverTenure, true);
    } else if (match_option(option, "-XX:+AlwaysTenure", &tail)) {
      // The last option must always win.
      FLAG_SET_CMDLINE(bool, NeverTenure, false);
      FLAG_SET_CMDLINE(bool, AlwaysTenure, true);
    } else if (match_option(option, "-XX:+CMSPermGenSweepingEnabled", &tail) ||
               match_option(option, "-XX:-CMSPermGenSweepingEnabled", &tail)) {
      jio_fprintf(defaultStream::error_stream(),
        "Please use CMSClassUnloadingEnabled in place of "
        "CMSPermGenSweepingEnabled in the future\n");
    } else if (match_option(option, "-XX:+UseGCTimeLimit", &tail)) {
      FLAG_SET_CMDLINE(bool, UseGCOverheadLimit, true);
      jio_fprintf(defaultStream::error_stream(),
        "Please use -XX:+UseGCOverheadLimit in place of "
        "-XX:+UseGCTimeLimit in the future\n");
    } else if (match_option(option, "-XX:-UseGCTimeLimit", &tail)) {
      FLAG_SET_CMDLINE(bool, UseGCOverheadLimit, false);
      jio_fprintf(defaultStream::error_stream(),
        "Please use -XX:-UseGCOverheadLimit in place of "
        "-XX:-UseGCTimeLimit in the future\n");
    // The TLE options are for compatibility with 1.3 and will be
    // removed without notice in a future release.  These options
    // are not to be documented.
    } else if (match_option(option, "-XX:MaxTLERatio=", &tail)) {
      // No longer used.
    } else if (match_option(option, "-XX:+ResizeTLE", &tail)) {
      FLAG_SET_CMDLINE(bool, ResizeTLAB, true);
    } else if (match_option(option, "-XX:-ResizeTLE", &tail)) {
      FLAG_SET_CMDLINE(bool, ResizeTLAB, false);
    } else if (match_option(option, "-XX:+PrintTLE", &tail)) {
      FLAG_SET_CMDLINE(bool, PrintTLAB, true);
    } else if (match_option(option, "-XX:-PrintTLE", &tail)) {
      FLAG_SET_CMDLINE(bool, PrintTLAB, false);
    } else if (match_option(option, "-XX:TLEFragmentationRatio=", &tail)) {
      // No longer used.
    } else if (match_option(option, "-XX:TLESize=", &tail)) {
3274
      julong long_tlab_size = 0;
D
duke 已提交
3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295
      ArgsRange errcode = parse_memory_size(tail, &long_tlab_size, 1);
      if (errcode != arg_in_range) {
        jio_fprintf(defaultStream::error_stream(),
                    "Invalid TLAB size: %s\n", option->optionString);
        describe_range_error(errcode);
        return JNI_EINVAL;
      }
      FLAG_SET_CMDLINE(uintx, TLABSize, long_tlab_size);
    } else if (match_option(option, "-XX:TLEThreadRatio=", &tail)) {
      // No longer used.
    } else if (match_option(option, "-XX:+UseTLE", &tail)) {
      FLAG_SET_CMDLINE(bool, UseTLAB, true);
    } else if (match_option(option, "-XX:-UseTLE", &tail)) {
      FLAG_SET_CMDLINE(bool, UseTLAB, false);
    } else if (match_option(option, "-XX:+DisplayVMOutputToStderr", &tail)) {
      FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false);
      FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true);
    } else if (match_option(option, "-XX:+DisplayVMOutputToStdout", &tail)) {
      FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false);
      FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true);
    } else if (match_option(option, "-XX:+ExtendedDTraceProbes", &tail)) {
D
dcubed 已提交
3296
#if defined(DTRACE_ENABLED)
D
duke 已提交
3297 3298 3299 3300
      FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true);
      FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true);
      FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true);
      FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true);
D
dcubed 已提交
3301
#else // defined(DTRACE_ENABLED)
D
duke 已提交
3302
      jio_fprintf(defaultStream::error_stream(),
D
dcubed 已提交
3303
                  "ExtendedDTraceProbes flag is not applicable for this configuration\n");
D
duke 已提交
3304
      return JNI_EINVAL;
D
dcubed 已提交
3305
#endif // defined(DTRACE_ENABLED)
D
duke 已提交
3306
#ifdef ASSERT
3307
    } else if (match_option(option, "-XX:+FullGCALot", &tail)) {
D
duke 已提交
3308 3309 3310 3311
      FLAG_SET_CMDLINE(bool, FullGCALot, true);
      // disable scavenge before parallel mark-compact
      FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
#endif
3312
    } else if (match_option(option, "-XX:CMSParPromoteBlocksToClaim=", &tail)) {
D
duke 已提交
3313 3314 3315
      julong cms_blocks_to_claim = (julong)atol(tail);
      FLAG_SET_CMDLINE(uintx, CMSParPromoteBlocksToClaim, cms_blocks_to_claim);
      jio_fprintf(defaultStream::error_stream(),
3316 3317 3318 3319 3320 3321 3322
        "Please use -XX:OldPLABSize in place of "
        "-XX:CMSParPromoteBlocksToClaim in the future\n");
    } else if (match_option(option, "-XX:ParCMSPromoteBlocksToClaim=", &tail)) {
      julong cms_blocks_to_claim = (julong)atol(tail);
      FLAG_SET_CMDLINE(uintx, CMSParPromoteBlocksToClaim, cms_blocks_to_claim);
      jio_fprintf(defaultStream::error_stream(),
        "Please use -XX:OldPLABSize in place of "
D
duke 已提交
3323
        "-XX:ParCMSPromoteBlocksToClaim in the future\n");
3324
    } else if (match_option(option, "-XX:ParallelGCOldGenAllocBufferSize=", &tail)) {
3325
      julong old_plab_size = 0;
D
duke 已提交
3326 3327 3328 3329 3330 3331 3332
      ArgsRange errcode = parse_memory_size(tail, &old_plab_size, 1);
      if (errcode != arg_in_range) {
        jio_fprintf(defaultStream::error_stream(),
                    "Invalid old PLAB size: %s\n", option->optionString);
        describe_range_error(errcode);
        return JNI_EINVAL;
      }
3333
      FLAG_SET_CMDLINE(uintx, OldPLABSize, old_plab_size);
D
duke 已提交
3334 3335 3336
      jio_fprintf(defaultStream::error_stream(),
                  "Please use -XX:OldPLABSize in place of "
                  "-XX:ParallelGCOldGenAllocBufferSize in the future\n");
3337
    } else if (match_option(option, "-XX:ParallelGCToSpaceAllocBufferSize=", &tail)) {
3338
      julong young_plab_size = 0;
D
duke 已提交
3339 3340 3341 3342 3343 3344 3345
      ArgsRange errcode = parse_memory_size(tail, &young_plab_size, 1);
      if (errcode != arg_in_range) {
        jio_fprintf(defaultStream::error_stream(),
                    "Invalid young PLAB size: %s\n", option->optionString);
        describe_range_error(errcode);
        return JNI_EINVAL;
      }
3346
      FLAG_SET_CMDLINE(uintx, YoungPLABSize, young_plab_size);
D
duke 已提交
3347 3348 3349
      jio_fprintf(defaultStream::error_stream(),
                  "Please use -XX:YoungPLABSize in place of "
                  "-XX:ParallelGCToSpaceAllocBufferSize in the future\n");
3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380
    } else if (match_option(option, "-XX:CMSMarkStackSize=", &tail) ||
               match_option(option, "-XX:G1MarkStackSize=", &tail)) {
      julong stack_size = 0;
      ArgsRange errcode = parse_memory_size(tail, &stack_size, 1);
      if (errcode != arg_in_range) {
        jio_fprintf(defaultStream::error_stream(),
                    "Invalid mark stack size: %s\n", option->optionString);
        describe_range_error(errcode);
        return JNI_EINVAL;
      }
      FLAG_SET_CMDLINE(uintx, MarkStackSize, stack_size);
    } else if (match_option(option, "-XX:CMSMarkStackSizeMax=", &tail)) {
      julong max_stack_size = 0;
      ArgsRange errcode = parse_memory_size(tail, &max_stack_size, 1);
      if (errcode != arg_in_range) {
        jio_fprintf(defaultStream::error_stream(),
                    "Invalid maximum mark stack size: %s\n",
                    option->optionString);
        describe_range_error(errcode);
        return JNI_EINVAL;
      }
      FLAG_SET_CMDLINE(uintx, MarkStackSizeMax, max_stack_size);
    } else if (match_option(option, "-XX:ParallelMarkingThreads=", &tail) ||
               match_option(option, "-XX:ParallelCMSThreads=", &tail)) {
      uintx conc_threads = 0;
      if (!parse_uintx(tail, &conc_threads, 1)) {
        jio_fprintf(defaultStream::error_stream(),
                    "Invalid concurrent threads: %s\n", option->optionString);
        return JNI_EINVAL;
      }
      FLAG_SET_CMDLINE(uintx, ConcGCThreads, conc_threads);
3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391
    } else if (match_option(option, "-XX:MaxDirectMemorySize=", &tail)) {
      julong max_direct_memory_size = 0;
      ArgsRange errcode = parse_memory_size(tail, &max_direct_memory_size, 0);
      if (errcode != arg_in_range) {
        jio_fprintf(defaultStream::error_stream(),
                    "Invalid maximum direct memory size: %s\n",
                    option->optionString);
        describe_range_error(errcode);
        return JNI_EINVAL;
      }
      FLAG_SET_CMDLINE(uintx, MaxDirectMemorySize, max_direct_memory_size);
3392 3393 3394 3395 3396
    } else if (match_option(option, "-XX:+UseVMInterruptibleIO", &tail)) {
      // NOTE! In JDK 9, the UseVMInterruptibleIO flag will completely go
      //       away and will cause VM initialization failures!
      warning("-XX:+UseVMInterruptibleIO is obsolete and will be removed in a future release.");
      FLAG_SET_CMDLINE(bool, UseVMInterruptibleIO, true);
3397 3398
#if !INCLUDE_MANAGEMENT
    } else if (match_option(option, "-XX:+ManagementServer", &tail)) {
3399 3400 3401
        jio_fprintf(defaultStream::error_stream(),
          "ManagementServer is not supported in this VM.\n");
        return JNI_ERR;
3402
#endif // INCLUDE_MANAGEMENT
3403
    } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
D
duke 已提交
3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414
      // Skip -XX:Flags= since that case has already been handled
      if (strncmp(tail, "Flags=", strlen("Flags=")) != 0) {
        if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
          return JNI_EINVAL;
        }
      }
    // Unknown option
    } else if (is_bad_option(option, args->ignoreUnrecognized)) {
      return JNI_ERR;
    }
  }
3415

3416 3417 3418 3419 3420 3421 3422 3423 3424
  // PrintSharedArchiveAndExit will turn on
  //   -Xshare:on
  //   -XX:+TraceClassPaths
  if (PrintSharedArchiveAndExit) {
    FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
    FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true);
    FLAG_SET_CMDLINE(bool, TraceClassPaths, true);
  }

3425 3426
  // Change the default value for flags  which have different default values
  // when working with older JDKs.
3427 3428 3429 3430 3431 3432
#ifdef LINUX
 if (JDK_Version::current().compare_major(6) <= 0 &&
      FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
    FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
  }
#endif // LINUX
3433
  fix_appclasspath();
D
duke 已提交
3434 3435 3436
  return JNI_OK;
}

3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477
// Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
//
// This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
// in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
// Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
// path is treated as the current directory.
//
// This causes problems with CDS, which requires that all directories specified in the classpath
// must be empty. In most cases, applications do NOT want to load classes from the current
// directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
// scripts compatible with CDS.
void Arguments::fix_appclasspath() {
  if (IgnoreEmptyClassPaths) {
    const char separator = *os::path_separator();
    const char* src = _java_class_path->value();

    // skip over all the leading empty paths
    while (*src == separator) {
      src ++;
    }

    char* copy = AllocateHeap(strlen(src) + 1, mtInternal);
    strncpy(copy, src, strlen(src) + 1);

    // trim all trailing empty paths
    for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
      *tail = '\0';
    }

    char from[3] = {separator, separator, '\0'};
    char to  [2] = {separator, '\0'};
    while (StringUtils::replace_no_expand(copy, from, to) > 0) {
      // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
      // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
    }

    _java_class_path->set_value(copy);
    FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
  }

  if (!PrintSharedArchiveAndExit) {
3478
    ClassLoader::trace_class_path(tty, "[classpath: ", _java_class_path->value());
3479 3480 3481
  }
}

3482 3483 3484 3485 3486 3487
static bool has_jar_files(const char* directory) {
  DIR* dir = os::opendir(directory);
  if (dir == NULL) return false;

  struct dirent *entry;
  bool hasJarFile = false;
3488
  while (!hasJarFile && (entry = os::readdir(dir)) != NULL) {
3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573
    const char* name = entry->d_name;
    const char* ext = name + strlen(name) - 4;
    hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);
  }
  os::closedir(dir);
  return hasJarFile ;
}

// returns the number of directories in the given path containing JAR files
// If the skip argument is not NULL, it will skip that directory
static int check_non_empty_dirs(const char* path, const char* type, const char* skip) {
  const char separator = *os::path_separator();
  const char* const end = path + strlen(path);
  int nonEmptyDirs = 0;
  while (path < end) {
    const char* tmp_end = strchr(path, separator);
    if (tmp_end == NULL) {
      if ((skip == NULL || strcmp(path, skip) != 0) && has_jar_files(path)) {
        nonEmptyDirs++;
        jio_fprintf(defaultStream::output_stream(),
          "Non-empty %s directory: %s\n", type, path);
      }
      path = end;
    } else {
      char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);
      memcpy(dirpath, path, tmp_end - path);
      dirpath[tmp_end - path] = '\0';
      if ((skip == NULL || strcmp(dirpath, skip) != 0) && has_jar_files(dirpath)) {
        nonEmptyDirs++;
        jio_fprintf(defaultStream::output_stream(),
          "Non-empty %s directory: %s\n", type, dirpath);
      }
      FREE_C_HEAP_ARRAY(char, dirpath, mtInternal);
      path = tmp_end + 1;
    }
  }
  return nonEmptyDirs;
}

// Returns true if endorsed standards override mechanism and extension mechanism
// are not used.
static bool check_endorsed_and_ext_dirs() {
  if (!CheckEndorsedAndExtDirs)
    return true;

  char endorsedDir[JVM_MAXPATHLEN];
  char extDir[JVM_MAXPATHLEN];
  const char* fileSep = os::file_separator();
  jio_snprintf(endorsedDir, sizeof(endorsedDir), "%s%slib%sendorsed",
               Arguments::get_java_home(), fileSep, fileSep);
  jio_snprintf(extDir, sizeof(extDir), "%s%slib%sext",
               Arguments::get_java_home(), fileSep, fileSep);

  // check endorsed directory
  int nonEmptyDirs = check_non_empty_dirs(Arguments::get_endorsed_dir(), "endorsed", NULL);

  // check the extension directories but skip the default lib/ext directory
  nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs(), "extension", extDir);

  // List of JAR files installed in the default lib/ext directory.
  // -XX:+CheckEndorsedAndExtDirs checks if any non-JDK file installed
  static const char* jdk_ext_jars[] = {
      "access-bridge-32.jar",
      "access-bridge-64.jar",
      "access-bridge.jar",
      "cldrdata.jar",
      "dnsns.jar",
      "jaccess.jar",
      "jfxrt.jar",
      "localedata.jar",
      "nashorn.jar",
      "sunec.jar",
      "sunjce_provider.jar",
      "sunmscapi.jar",
      "sunpkcs11.jar",
      "ucrypto.jar",
      "zipfs.jar",
      NULL
  };

  // check if the default lib/ext directory has any non-JDK jar files; if so, error
  DIR* dir = os::opendir(extDir);
  if (dir != NULL) {
    int num_ext_jars = 0;
    struct dirent *entry;
3574
    while ((entry = os::readdir(dir)) != NULL) {
3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608
      const char* name = entry->d_name;
      const char* ext = name + strlen(name) - 4;
      if (ext > name && (os::file_name_strcmp(ext, ".jar") == 0)) {
        bool is_jdk_jar = false;
        const char* jarfile = NULL;
        for (int i=0; (jarfile = jdk_ext_jars[i]) != NULL; i++) {
          if (os::file_name_strcmp(name, jarfile) == 0) {
            is_jdk_jar = true;
            break;
          }
        }
        if (!is_jdk_jar) {
          jio_fprintf(defaultStream::output_stream(),
            "%s installed in <JAVA_HOME>/lib/ext\n", name);
          num_ext_jars++;
        }
      }
    }
    os::closedir(dir);
    if (num_ext_jars > 0) {
      nonEmptyDirs += 1;
    }
  }

  // check if the default lib/endorsed directory exists; if so, error
  dir = os::opendir(endorsedDir);
  if (dir != NULL) {
    jio_fprintf(defaultStream::output_stream(), "<JAVA_HOME>/lib/endorsed exists\n");
    os::closedir(dir);
    nonEmptyDirs += 1;
  }

  if (nonEmptyDirs > 0) {
    jio_fprintf(defaultStream::output_stream(),
3609
      "Endorsed standards override mechanism and extension mechanism "
3610 3611 3612 3613 3614 3615 3616 3617
      "will not be supported in a future release.\n"
      "Refer to JEP 220 for details (http://openjdk.java.net/jeps/220).\n");
    return false;
  }

  return true;
}

D
duke 已提交
3618 3619 3620 3621 3622 3623 3624 3625 3626
jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_required) {
  // This must be done after all -D arguments have been processed.
  scp_p->expand_endorsed();

  if (scp_assembly_required || scp_p->get_endorsed() != NULL) {
    // Assemble the bootclasspath elements into the final path.
    Arguments::set_sysclasspath(scp_p->combined_path());
  }

3627 3628 3629 3630
  if (!check_endorsed_and_ext_dirs()) {
    return JNI_ERR;
  }

3631 3632 3633 3634 3635 3636 3637 3638 3639
  // This must be done after all arguments have been processed
  // and the container support has been initialized since AggressiveHeap
  // relies on the amount of total memory available.
  if (AggressiveHeap) {
    jint result = set_aggressive_heap_flags();
    if (result != JNI_OK) {
      return result;
    }
  }
D
duke 已提交
3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651
  // This must be done after all arguments have been processed.
  // java_compiler() true means set to "NONE" or empty.
  if (java_compiler() && !xdebug_mode()) {
    // For backwards compatibility, we switch to interpreted mode if
    // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
    // not specified.
    set_mode_flags(_int);
  }
  if (CompileThreshold == 0) {
    set_mode_flags(_int);
  }

3652 3653 3654 3655 3656
  // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
  if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
    FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
  }

D
duke 已提交
3657 3658 3659 3660 3661 3662 3663 3664 3665
#ifndef COMPILER2
  // Don't degrade server performance for footprint
  if (FLAG_IS_DEFAULT(UseLargePages) &&
      MaxHeapSize < LargePageHeapSizeThreshold) {
    // No need for large granularity pages w/small heaps.
    // Note that large pages are enabled/disabled for both the
    // Java heap and the code cache.
    FLAG_SET_DEFAULT(UseLargePages, false);
  }
3666

D
duke 已提交
3667 3668 3669 3670 3671 3672
#else
  if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
    FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
  }
#endif

3673 3674 3675 3676 3677
#ifndef TIERED
  // Tiered compilation is undefined.
  UNSUPPORTED_OPTION(TieredCompilation, "TieredCompilation");
#endif

3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690
  // If we are running in a headless jre, force java.awt.headless property
  // to be true unless the property has already been set.
  // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.
  if (os::is_headless_jre()) {
    const char* headless = Arguments::get_property("java.awt.headless");
    if (headless == NULL) {
      char envbuffer[128];
      if (!os::getenv("JAVA_AWT_HEADLESS", envbuffer, sizeof(envbuffer))) {
        if (!add_property("java.awt.headless=true")) {
          return JNI_ENOMEM;
        }
      } else {
        char buffer[256];
S
shshahma 已提交
3691
        jio_snprintf(buffer, 256, "java.awt.headless=%s", envbuffer);
3692 3693 3694 3695 3696 3697 3698
        if (!add_property(buffer)) {
          return JNI_ENOMEM;
        }
      }
    }
  }

3699
  if (!check_vm_args_consistency()) {
D
duke 已提交
3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770
    return JNI_ERR;
  }

  return JNI_OK;
}

jint Arguments::parse_java_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
  return parse_options_environment_variable("_JAVA_OPTIONS", scp_p,
                                            scp_assembly_required_p);
}

jint Arguments::parse_java_tool_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
  return parse_options_environment_variable("JAVA_TOOL_OPTIONS", scp_p,
                                            scp_assembly_required_p);
}

jint Arguments::parse_options_environment_variable(const char* name, SysClassPath* scp_p, bool* scp_assembly_required_p) {
  const int N_MAX_OPTIONS = 64;
  const int OPTION_BUFFER_SIZE = 1024;
  char buffer[OPTION_BUFFER_SIZE];

  // The variable will be ignored if it exceeds the length of the buffer.
  // Don't check this variable if user has special privileges
  // (e.g. unix su command).
  if (os::getenv(name, buffer, sizeof(buffer)) &&
      !os::have_special_privileges()) {
    JavaVMOption options[N_MAX_OPTIONS];      // Construct option array
    jio_fprintf(defaultStream::error_stream(),
                "Picked up %s: %s\n", name, buffer);
    char* rd = buffer;                        // pointer to the input string (rd)
    int i;
    for (i = 0; i < N_MAX_OPTIONS;) {         // repeat for all options in the input string
      while (isspace(*rd)) rd++;              // skip whitespace
      if (*rd == 0) break;                    // we re done when the input string is read completely

      // The output, option string, overwrites the input string.
      // Because of quoting, the pointer to the option string (wrt) may lag the pointer to
      // input string (rd).
      char* wrt = rd;

      options[i++].optionString = wrt;        // Fill in option
      while (*rd != 0 && !isspace(*rd)) {     // unquoted strings terminate with a space or NULL
        if (*rd == '\'' || *rd == '"') {      // handle a quoted string
          int quote = *rd;                    // matching quote to look for
          rd++;                               // don't copy open quote
          while (*rd != quote) {              // include everything (even spaces) up until quote
            if (*rd == 0) {                   // string termination means unmatched string
              jio_fprintf(defaultStream::error_stream(),
                          "Unmatched quote in %s\n", name);
              return JNI_ERR;
            }
            *wrt++ = *rd++;                   // copy to option string
          }
          rd++;                               // don't copy close quote
        } else {
          *wrt++ = *rd++;                     // copy to option string
        }
      }
      // Need to check if we're done before writing a NULL,
      // because the write could be to the byte that rd is pointing to.
      if (*rd++ == 0) {
        *wrt = 0;
        break;
      }
      *wrt = 0;                               // Zero terminate option
    }
    // Construct JavaVMInitArgs structure and parse as if it was part of the command line
    JavaVMInitArgs vm_args;
    vm_args.version = JNI_VERSION_1_2;
    vm_args.options = options;
    vm_args.nOptions = i;
3771
    vm_args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
D
duke 已提交
3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782

    if (PrintVMOptions) {
      const char* tail;
      for (int i = 0; i < vm_args.nOptions; i++) {
        const JavaVMOption *option = vm_args.options + i;
        if (match_option(option, "-XX:", &tail)) {
          logOption(tail);
        }
      }
    }

3783
    return(parse_each_vm_init_arg(&vm_args, scp_p, scp_assembly_required_p, Flag::ENVIRON_VAR));
D
duke 已提交
3784 3785 3786 3787
  }
  return JNI_OK;
}

3788
void Arguments::set_shared_spaces_flags() {
3789
  if (DumpSharedSpaces) {
J
jiangli 已提交
3790 3791 3792 3793 3794 3795 3796 3797
    if (FailOverToOldVerifier) {
      // Don't fall back to the old verifier on verification failure. If a
      // class fails verification with the split verifier, it might fail the
      // CDS runtime verifier constraint check. In that case, we don't want
      // to share the class. We only archive classes that pass the split verifier.
      FLAG_SET_DEFAULT(FailOverToOldVerifier, false);
    }

3798 3799 3800 3801
    if (RequireSharedSpaces) {
      warning("cannot dump shared archive while using shared archive");
    }
    UseSharedSpaces = false;
3802
#ifdef _LP64
3803
    if (!UseCompressedOops || !UseCompressedClassPointers) {
3804
      vm_exit_during_initialization(
3805
        "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
3806 3807
    }
  } else {
3808
    if (!UseCompressedOops || !UseCompressedClassPointers) {
3809
      no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
3810 3811
    }
#endif
3812
  }
3813
}
3814

3815
#if !INCLUDE_ALL_GCS
3816 3817 3818 3819 3820 3821 3822 3823 3824
static void force_serial_gc() {
  FLAG_SET_DEFAULT(UseSerialGC, true);
  FLAG_SET_DEFAULT(CMSIncrementalMode, false);  // special CMS suboption
  UNSUPPORTED_GC_OPTION(UseG1GC);
  UNSUPPORTED_GC_OPTION(UseParallelGC);
  UNSUPPORTED_GC_OPTION(UseParallelOldGC);
  UNSUPPORTED_GC_OPTION(UseConcMarkSweepGC);
  UNSUPPORTED_GC_OPTION(UseParNewGC);
}
3825
#endif // INCLUDE_ALL_GCS
3826

3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853
// Sharing support
// Construct the path to the archive
static char* get_shared_archive_path() {
  char *shared_archive_path;
  if (SharedArchiveFile == NULL) {
    char jvm_path[JVM_MAXPATHLEN];
    os::jvm_path(jvm_path, sizeof(jvm_path));
    char *end = strrchr(jvm_path, *os::file_separator());
    if (end != NULL) *end = '\0';
    size_t jvm_path_len = strlen(jvm_path);
    size_t file_sep_len = strlen(os::file_separator());
    shared_archive_path = NEW_C_HEAP_ARRAY(char, jvm_path_len +
        file_sep_len + 20, mtInternal);
    if (shared_archive_path != NULL) {
      strncpy(shared_archive_path, jvm_path, jvm_path_len + 1);
      strncat(shared_archive_path, os::file_separator(), file_sep_len);
      strncat(shared_archive_path, "classes.jsa", 11);
    }
  } else {
    shared_archive_path = NEW_C_HEAP_ARRAY(char, strlen(SharedArchiveFile) + 1, mtInternal);
    if (shared_archive_path != NULL) {
      strncpy(shared_archive_path, SharedArchiveFile, strlen(SharedArchiveFile) + 1);
    }
  }
  return shared_archive_path;
}

3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880
#ifndef PRODUCT
// Determine whether LogVMOutput should be implicitly turned on.
static bool use_vm_log() {
  if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
      PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
      PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
      PrintAssembly || TraceDeoptimization || TraceDependencies ||
      (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
    return true;
  }

#ifdef COMPILER1
  if (PrintC1Statistics) {
    return true;
  }
#endif // COMPILER1

#ifdef COMPILER2
  if (PrintOptoAssembly || PrintOptoStatistics) {
    return true;
  }
#endif // COMPILER2

  return false;
}
#endif // PRODUCT

D
duke 已提交
3881 3882 3883 3884 3885 3886 3887 3888
// Parse entry point called from JNI_CreateJavaVM

jint Arguments::parse(const JavaVMInitArgs* args) {

  // Remaining part of option string
  const char* tail;

  // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
3889
  const char* hotspotrc = ".hotspotrc";
D
duke 已提交
3890
  bool settings_file_specified = false;
3891 3892
  bool needs_hotspotrc_warning = false;

3893 3894
  ArgumentsExt::process_options(args);

3895
  const char* flags_file;
D
duke 已提交
3896 3897 3898 3899
  int index;
  for (index = 0; index < args->nOptions; index++) {
    const JavaVMOption *option = args->options + index;
    if (match_option(option, "-XX:Flags=", &tail)) {
3900
      flags_file = tail;
D
duke 已提交
3901 3902 3903 3904 3905
      settings_file_specified = true;
    }
    if (match_option(option, "-XX:+PrintVMOptions", &tail)) {
      PrintVMOptions = true;
    }
3906 3907 3908
    if (match_option(option, "-XX:-PrintVMOptions", &tail)) {
      PrintVMOptions = false;
    }
3909 3910 3911 3912 3913 3914
    if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions", &tail)) {
      IgnoreUnrecognizedVMOptions = true;
    }
    if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions", &tail)) {
      IgnoreUnrecognizedVMOptions = false;
    }
3915
    if (match_option(option, "-XX:+PrintFlagsInitial", &tail)) {
F
fparain 已提交
3916
      CommandLineFlags::printFlags(tty, false);
3917 3918
      vm_exit(0);
    }
3919
    if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
3920
#if INCLUDE_NMT
3921
      // The launcher did not setup nmt environment variable properly.
3922 3923 3924
      if (!MemTracker::check_launcher_nmt_support(tail)) {
        warning("Native Memory Tracking did not setup properly, using wrong launcher?");
      }
3925 3926 3927 3928 3929 3930 3931 3932 3933 3934

      // Verify if nmt option is valid.
      if (MemTracker::verify_nmt_option()) {
        // Late initialization, still in single-threaded mode.
        if (MemTracker::tracking_level() >= NMT_summary) {
          MemTracker::init();
        }
      } else {
        vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
      }
3935 3936 3937 3938
#else
      jio_fprintf(defaultStream::error_stream(),
        "Native Memory Tracking is not supported in this VM\n");
      return JNI_ERR;
3939
#endif
3940
    }
Z
zgu 已提交
3941

3942 3943 3944

#ifndef PRODUCT
    if (match_option(option, "-XX:+PrintFlagsWithComments", &tail)) {
F
fparain 已提交
3945
      CommandLineFlags::printFlags(tty, true);
3946 3947 3948
      vm_exit(0);
    }
#endif
3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960
  }

  if (IgnoreUnrecognizedVMOptions) {
    // uncast const to modify the flag args->ignoreUnrecognized
    *(jboolean*)(&args->ignoreUnrecognized) = true;
  }

  // Parse specified settings file
  if (settings_file_specified) {
    if (!process_settings_file(flags_file, true, args->ignoreUnrecognized)) {
      return JNI_EINVAL;
    }
3961
  } else {
3962
#ifdef ASSERT
3963
    // Parse default .hotspotrc settings file
D
duke 已提交
3964 3965 3966
    if (!process_settings_file(".hotspotrc", false, args->ignoreUnrecognized)) {
      return JNI_EINVAL;
    }
3967 3968 3969 3970 3971
#else
    struct stat buf;
    if (os::stat(hotspotrc, &buf) == 0) {
      needs_hotspotrc_warning = true;
    }
3972
#endif
3973
  }
D
duke 已提交
3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989

  if (PrintVMOptions) {
    for (index = 0; index < args->nOptions; index++) {
      const JavaVMOption *option = args->options + index;
      if (match_option(option, "-XX:", &tail)) {
        logOption(tail);
      }
    }
  }

  // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
  jint result = parse_vm_init_args(args);
  if (result != JNI_OK) {
    return result;
  }

3990 3991 3992 3993 3994 3995
  // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
  SharedArchivePath = get_shared_archive_path();
  if (SharedArchivePath == NULL) {
    return JNI_ENOMEM;
  }

J
jiangli 已提交
3996 3997 3998 3999 4000
  // Set up VerifySharedSpaces
  if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
    VerifySharedSpaces = true;
  }

4001 4002 4003 4004 4005 4006 4007 4008
  // Delay warning until here so that we've had a chance to process
  // the -XX:-PrintWarnings flag
  if (needs_hotspotrc_warning) {
    warning("%s file is present but has been ignored.  "
            "Run with -XX:Flags=%s to load the file.",
            hotspotrc, hotspotrc);
  }

4009 4010 4011 4012
#ifdef _ALLBSD_SOURCE  // UseLargePages is not yet supported on BSD.
  UNSUPPORTED_OPTION(UseLargePages, "-XX:+UseLargePages");
#endif

4013 4014 4015 4016 4017
#if INCLUDE_ALL_GCS
  #if (defined JAVASE_EMBEDDED || defined ARM)
    UNSUPPORTED_OPTION(UseG1GC, "G1 GC");
  #endif
#endif
4018

D
duke 已提交
4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030
#ifndef PRODUCT
  if (TraceBytecodesAt != 0) {
    TraceBytecodes = true;
  }
  if (CountCompiledCalls) {
    if (UseCounterDecay) {
      warning("UseCounterDecay disabled because CountCalls is set");
      UseCounterDecay = false;
    }
  }
#endif // PRODUCT

4031 4032 4033 4034 4035 4036 4037
  // JSR 292 is not supported before 1.7
  if (!JDK_Version::is_gte_jdk17x_version()) {
    if (EnableInvokeDynamic) {
      if (!FLAG_IS_DEFAULT(EnableInvokeDynamic)) {
        warning("JSR 292 is not supported before 1.7.  Disabling support.");
      }
      EnableInvokeDynamic = false;
4038 4039
    }
  }
4040 4041

  if (EnableInvokeDynamic && ScavengeRootsInCode == 0) {
4042
    if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
4043
      warning("forcing ScavengeRootsInCode non-zero because EnableInvokeDynamic is true");
4044 4045 4046
    }
    ScavengeRootsInCode = 1;
  }
4047

D
duke 已提交
4048 4049 4050 4051 4052
  if (PrintGCDetails) {
    // Turn on -verbose:gc options as well
    PrintGC = true;
  }

4053 4054 4055 4056 4057 4058 4059 4060
  if (!JDK_Version::is_gte_jdk18x_version()) {
    // To avoid changing the log format for 7 updates this flag is only
    // true by default in JDK8 and above.
    if (FLAG_IS_DEFAULT(PrintGCCause)) {
      FLAG_SET_DEFAULT(PrintGCCause, false);
    }
  }

4061 4062 4063
  // Set object alignment values.
  set_object_alignment();

4064
#if !INCLUDE_ALL_GCS
P
phh 已提交
4065
  force_serial_gc();
4066
#endif // INCLUDE_ALL_GCS
4067
#if !INCLUDE_CDS
4068 4069 4070 4071 4072
  if (DumpSharedSpaces || RequireSharedSpaces) {
    jio_fprintf(defaultStream::error_stream(),
      "Shared spaces are not supported in this VM\n");
    return JNI_ERR;
  }
4073
  if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {
4074 4075 4076 4077
    warning("Shared spaces are not supported in this VM");
    FLAG_SET_DEFAULT(UseSharedSpaces, false);
    FLAG_SET_DEFAULT(PrintSharedSpaces, false);
  }
4078
  no_shared_spaces("CDS Disabled");
4079
#endif // INCLUDE_CDS
D
duke 已提交
4080

4081 4082 4083 4084 4085
  return JNI_OK;
}

jint Arguments::apply_ergo() {

D
duke 已提交
4086 4087 4088
  // Set flags based on ergonomics.
  set_ergonomics_flags();

4089
  set_shared_spaces_flags();
4090

4091 4092 4093 4094 4095 4096 4097 4098 4099 4100
#if defined(SPARC)
  // BIS instructions require 'membar' instruction regardless of the number
  // of CPUs because in virtualized/container environments which might use only 1
  // CPU, BIS instructions may produce incorrect results.

  if (FLAG_IS_DEFAULT(AssumeMP)) {
    FLAG_SET_DEFAULT(AssumeMP, true);
  }
#endif

4101
  // Check the GC selections again.
4102
  if (!check_gc_consistency()) {
4103 4104 4105
    return JNI_EINVAL;
  }

I
iveresov 已提交
4106 4107 4108 4109 4110 4111 4112 4113 4114
  if (TieredCompilation) {
    set_tiered_flags();
  } else {
    // Check if the policy is valid. Policies 0 and 1 are valid for non-tiered setup.
    if (CompilationPolicyChoice >= 2) {
      vm_exit_during_initialization(
        "Incompatible compilation policy selected", NULL);
    }
  }
4115 4116 4117 4118 4119
  // Set NmethodSweepFraction after the size of the code cache is adapted (in case of tiered)
  if (FLAG_IS_DEFAULT(NmethodSweepFraction)) {
    FLAG_SET_DEFAULT(NmethodSweepFraction, 1 + ReservedCodeCacheSize / (16 * M));
  }

I
iveresov 已提交
4120

4121 4122
  // Set heap size based on available physical memory
  set_heap_size();
4123

4124
  ArgumentsExt::set_gc_specific_flags();
D
duke 已提交
4125

4126 4127 4128
  // Initialize Metaspace flags and alignments.
  Metaspace::ergo_initialize();

D
duke 已提交
4129 4130 4131 4132 4133 4134
  // Set bytecode rewriting flags
  set_bytecode_flags();

  // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled.
  set_aggressive_opts_flags();

4135 4136 4137
  // Turn off biased locking for locking debug mode flags,
  // which are subtlely different from each other but neither works with
  // biased locking.
4138 4139 4140 4141 4142
  if (UseHeavyMonitors
#ifdef COMPILER1
      || !UseFastLocking
#endif // COMPILER1
    ) {
4143 4144 4145 4146 4147 4148 4149 4150 4151
    if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
      // flag set to true on command line; warn the user that they
      // can't enable biased locking here
      warning("Biased Locking is not supported with locking debug flags"
              "; ignoring UseBiasedLocking flag." );
    }
    UseBiasedLocking = false;
  }

4152 4153
#ifdef ZERO
  // Clear flags not supported on zero.
T
twisti 已提交
4154
  FLAG_SET_DEFAULT(ProfileInterpreter, false);
D
duke 已提交
4155
  FLAG_SET_DEFAULT(UseBiasedLocking, false);
T
twisti 已提交
4156
  LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
4157
  LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
T
twisti 已提交
4158 4159
#endif // CC_INTERP

4160
#ifdef COMPILER2
K
kvn 已提交
4161 4162 4163
  if (!EliminateLocks) {
    EliminateNestedLocks = false;
  }
R
roland 已提交
4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175
  if (!Inline) {
    IncrementalInline = false;
  }
#ifndef PRODUCT
  if (!IncrementalInline) {
    AlwaysIncrementalInline = false;
  }
#endif
  if (IncrementalInline && FLAG_IS_DEFAULT(MaxNodeLimit)) {
    // incremental inlining: bump MaxNodeLimit
    FLAG_SET_DEFAULT(MaxNodeLimit, (intx)75000);
  }
4176 4177 4178 4179
  if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
    // nothing to use the profiling, turn if off
    FLAG_SET_DEFAULT(TypeProfileLevel, 0);
  }
4180 4181
#endif

4182 4183 4184 4185 4186
  if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
    warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
    DebugNonSafepoints = true;
  }

4187 4188 4189 4190
  if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
    warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
  }

4191 4192 4193 4194 4195
  if (UseOnStackReplacement && !UseLoopCounter) {
    warning("On-stack-replacement requires loop counters; enabling loop counters");
    FLAG_SET_DEFAULT(UseLoopCounter, true);
  }

4196 4197 4198 4199 4200 4201 4202
#ifndef PRODUCT
  if (CompileTheWorld) {
    // Force NmethodSweeper to sweep whole CodeCache each time.
    if (FLAG_IS_DEFAULT(NmethodSweepFraction)) {
      NmethodSweepFraction = 1;
    }
  }
4203 4204 4205 4206 4207 4208 4209

  if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
    if (use_vm_log()) {
      LogVMOutput = true;
    }
  }
#endif // PRODUCT
4210

D
duke 已提交
4211
  if (PrintCommandLineFlags) {
F
fparain 已提交
4212
    CommandLineFlags::printSetFlags(tty);
D
duke 已提交
4213 4214
  }

4215 4216 4217 4218 4219 4220 4221
  // Apply CPU specific policy for the BiasedLocking
  if (UseBiasedLocking) {
    if (!VM_Version::use_biased_locking() &&
        !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
      UseBiasedLocking = false;
    }
  }
4222 4223 4224 4225 4226
#ifdef COMPILER2
  if (!UseBiasedLocking || EmitSync != 0) {
    UseOptoBiasInlining = false;
  }
#endif
4227

4228 4229 4230 4231 4232 4233 4234 4235 4236 4237
  // set PauseAtExit if the gamma launcher was used and a debugger is attached
  // but only if not already set on the commandline
  if (Arguments::created_by_gamma_launcher() && os::is_debugger_attached()) {
    bool set = false;
    CommandLineFlags::wasSetOnCmdline("PauseAtExit", &set);
    if (!set) {
      FLAG_SET_DEFAULT(PauseAtExit, true);
    }
  }

D
duke 已提交
4238 4239 4240
  return JNI_OK;
}

4241
jint Arguments::adjust_after_os() {
4242 4243
  if (UseNUMA) {
    if (UseParallelGC || UseParallelOldGC) {
4244
      if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4245
         FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4246
      }
4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257
    }
    // UseNUMAInterleaving is set to ON for all collectors and
    // platforms when UseNUMA is set to ON. NUMA-aware collectors
    // such as the parallel collector for Linux and Solaris will
    // interleave old gen and survivor spaces on top of NUMA
    // allocation policy for the eden space.
    // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
    // all platforms and ParallelGC on Windows will interleave all
    // of the heap spaces across NUMA nodes.
    if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
      FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
4258 4259 4260 4261 4262
    }
  }
  return JNI_OK;
}

D
duke 已提交
4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333
int Arguments::PropertyList_count(SystemProperty* pl) {
  int count = 0;
  while(pl != NULL) {
    count++;
    pl = pl->next();
  }
  return count;
}

const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
  assert(key != NULL, "just checking");
  SystemProperty* prop;
  for (prop = pl; prop != NULL; prop = prop->next()) {
    if (strcmp(key, prop->key()) == 0) return prop->value();
  }
  return NULL;
}

const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
  int count = 0;
  const char* ret_val = NULL;

  while(pl != NULL) {
    if(count >= index) {
      ret_val = pl->key();
      break;
    }
    count++;
    pl = pl->next();
  }

  return ret_val;
}

char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
  int count = 0;
  char* ret_val = NULL;

  while(pl != NULL) {
    if(count >= index) {
      ret_val = pl->value();
      break;
    }
    count++;
    pl = pl->next();
  }

  return ret_val;
}

void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
  SystemProperty* p = *plist;
  if (p == NULL) {
    *plist = new_p;
  } else {
    while (p->next() != NULL) {
      p = p->next();
    }
    p->set_next(new_p);
  }
}

void Arguments::PropertyList_add(SystemProperty** plist, const char* k, char* v) {
  if (plist == NULL)
    return;

  SystemProperty* new_p = new SystemProperty(k, v, true);
  PropertyList_add(plist, new_p);
}

// This add maintains unique property key in the list.
P
phh 已提交
4334
void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, char* v, jboolean append) {
D
duke 已提交
4335 4336 4337 4338 4339 4340 4341
  if (plist == NULL)
    return;

  // If property key exist then update with new value.
  SystemProperty* prop;
  for (prop = *plist; prop != NULL; prop = prop->next()) {
    if (strcmp(k, prop->key()) == 0) {
P
phh 已提交
4342 4343 4344 4345 4346
      if (append) {
        prop->append_value(v);
      } else {
        prop->set_value(v);
      }
D
duke 已提交
4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406
      return;
    }
  }

  PropertyList_add(plist, k, v);
}

// Copies src into buf, replacing "%%" with "%" and "%p" with pid
// Returns true if all of the source pointed by src has been copied over to
// the destination buffer pointed by buf. Otherwise, returns false.
// Notes:
// 1. If the length (buflen) of the destination buffer excluding the
// NULL terminator character is not long enough for holding the expanded
// pid characters, it also returns false instead of returning the partially
// expanded one.
// 2. The passed in "buflen" should be large enough to hold the null terminator.
bool Arguments::copy_expand_pid(const char* src, size_t srclen,
                                char* buf, size_t buflen) {
  const char* p = src;
  char* b = buf;
  const char* src_end = &src[srclen];
  char* buf_end = &buf[buflen - 1];

  while (p < src_end && b < buf_end) {
    if (*p == '%') {
      switch (*(++p)) {
      case '%':         // "%%" ==> "%"
        *b++ = *p++;
        break;
      case 'p':  {       //  "%p" ==> current process id
        // buf_end points to the character before the last character so
        // that we could write '\0' to the end of the buffer.
        size_t buf_sz = buf_end - b + 1;
        int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());

        // if jio_snprintf fails or the buffer is not long enough to hold
        // the expanded pid, returns false.
        if (ret < 0 || ret >= (int)buf_sz) {
          return false;
        } else {
          b += ret;
          assert(*b == '\0', "fail in copy_expand_pid");
          if (p == src_end && b == buf_end + 1) {
            // reach the end of the buffer.
            return true;
          }
        }
        p++;
        break;
      }
      default :
        *b++ = '%';
      }
    } else {
      *b++ = *p++;
    }
  }
  *b = '\0';
  return (p == src_end); // return false if not all of the source was copied
}