1 /*
2 * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "classfile/classLoader.hpp"
27 #include "classfile/javaAssertions.hpp"
28 #include "classfile/stringTable.hpp"
29 #include "classfile/symbolTable.hpp"
30 #include "compiler/compilerOracle.hpp"
31 #include "gc/shared/cardTableRS.hpp"
32 #include "gc/shared/genCollectedHeap.hpp"
33 #include "gc/shared/referenceProcessor.hpp"
34 #include "gc/shared/taskqueue.hpp"
35 #include "memory/allocation.inline.hpp"
36 #include "memory/universe.inline.hpp"
37 #include "oops/oop.inline.hpp"
38 #include "prims/jvmtiExport.hpp"
39 #include "runtime/arguments.hpp"
40 #include "runtime/arguments_ext.hpp"
41 #include "runtime/globals_extension.hpp"
42 #include "runtime/java.hpp"
43 #include "runtime/os.hpp"
44 #include "runtime/vm_version.hpp"
45 #include "services/management.hpp"
46 #include "services/memTracker.hpp"
47 #include "utilities/defaultStream.hpp"
48 #include "utilities/macros.hpp"
49 #include "utilities/stringUtils.hpp"
50 #if INCLUDE_ALL_GCS
51 #include "gc/cms/compactibleFreeListSpace.hpp"
52 #include "gc/g1/g1CollectedHeap.inline.hpp"
53 #include "gc/parallel/parallelScavengeHeap.hpp"
54 #endif // INCLUDE_ALL_GCS
55
56 // Note: This is a special bug reporting site for the JVM
57 #define DEFAULT_VENDOR_URL_BUG "http://bugreport.java.com/bugreport/crash.jsp"
58 #define DEFAULT_JAVA_LAUNCHER "generic"
59
60 #define UNSUPPORTED_GC_OPTION(gc) \
61 do { \
62 if (gc) { \
63 if (FLAG_IS_CMDLINE(gc)) { \
64 warning(#gc " is not supported in this VM. Using Serial GC."); \
65 } \
66 FLAG_SET_DEFAULT(gc, false); \
67 } \
68 } while(0)
69
70 char** Arguments::_jvm_flags_array = NULL;
71 int Arguments::_num_jvm_flags = 0;
72 char** Arguments::_jvm_args_array = NULL;
73 int Arguments::_num_jvm_args = 0;
74 char* Arguments::_java_command = NULL;
75 SystemProperty* Arguments::_system_properties = NULL;
76 const char* Arguments::_gc_log_filename = NULL;
77 bool Arguments::_has_profile = false;
78 size_t Arguments::_conservative_max_heap_alignment = 0;
79 size_t Arguments::_min_heap_size = 0;
80 uintx Arguments::_min_heap_free_ratio = 0;
81 uintx Arguments::_max_heap_free_ratio = 0;
82 Arguments::Mode Arguments::_mode = _mixed;
83 bool Arguments::_java_compiler = false;
84 bool Arguments::_xdebug_mode = false;
85 const char* Arguments::_java_vendor_url_bug = DEFAULT_VENDOR_URL_BUG;
86 const char* Arguments::_sun_java_launcher = DEFAULT_JAVA_LAUNCHER;
87 int Arguments::_sun_java_launcher_pid = -1;
88 bool Arguments::_sun_java_launcher_is_altjvm = false;
89
90 // These parameters are reset in method parse_vm_init_args(JavaVMInitArgs*)
91 bool Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
92 bool Arguments::_UseOnStackReplacement = UseOnStackReplacement;
93 bool Arguments::_BackgroundCompilation = BackgroundCompilation;
94 bool Arguments::_ClipInlining = ClipInlining;
95 intx Arguments::_Tier3InvokeNotifyFreqLog = Tier3InvokeNotifyFreqLog;
96 intx Arguments::_Tier4InvocationThreshold = Tier4InvocationThreshold;
97
98 char* Arguments::SharedArchivePath = NULL;
99
100 AgentLibraryList Arguments::_libraryList;
101 AgentLibraryList Arguments::_agentList;
102
103 abort_hook_t Arguments::_abort_hook = NULL;
104 exit_hook_t Arguments::_exit_hook = NULL;
105 vfprintf_hook_t Arguments::_vfprintf_hook = NULL;
106
107
108 SystemProperty *Arguments::_sun_boot_library_path = NULL;
109 SystemProperty *Arguments::_java_library_path = NULL;
110 SystemProperty *Arguments::_java_home = NULL;
111 SystemProperty *Arguments::_java_class_path = NULL;
112 SystemProperty *Arguments::_sun_boot_class_path = NULL;
113
114 char* Arguments::_ext_dirs = NULL;
115
116 // Check if head of 'option' matches 'name', and sets 'tail' to the remaining
117 // part of the option string.
118 static bool match_option(const JavaVMOption *option, const char* name,
119 const char** tail) {
120 int len = (int)strlen(name);
121 if (strncmp(option->optionString, name, len) == 0) {
122 *tail = option->optionString + len;
123 return true;
124 } else {
125 return false;
126 }
127 }
128
129 // Check if 'option' matches 'name'. No "tail" is allowed.
130 static bool match_option(const JavaVMOption *option, const char* name) {
131 const char* tail = NULL;
132 bool result = match_option(option, name, &tail);
133 if (tail != NULL && *tail == '\0') {
134 return result;
135 } else {
136 return false;
137 }
138 }
139
140 // Return true if any of the strings in null-terminated array 'names' matches.
141 // If tail_allowed is true, then the tail must begin with a colon; otherwise,
142 // the option must match exactly.
143 static bool match_option(const JavaVMOption* option, const char** names, const char** tail,
144 bool tail_allowed) {
145 for (/* empty */; *names != NULL; ++names) {
146 if (match_option(option, *names, tail)) {
147 if (**tail == '\0' || tail_allowed && **tail == ':') {
148 return true;
149 }
150 }
151 }
152 return false;
153 }
154
155 static void logOption(const char* opt) {
156 if (PrintVMOptions) {
157 jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);
158 }
159 }
160
161 // Process java launcher properties.
162 void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
163 // See if sun.java.launcher, sun.java.launcher.is_altjvm or
164 // sun.java.launcher.pid is defined.
165 // Must do this before setting up other system properties,
166 // as some of them may depend on launcher type.
167 for (int index = 0; index < args->nOptions; index++) {
168 const JavaVMOption* option = args->options + index;
169 const char* tail;
170
171 if (match_option(option, "-Dsun.java.launcher=", &tail)) {
172 process_java_launcher_argument(tail, option->extraInfo);
173 continue;
174 }
175 if (match_option(option, "-Dsun.java.launcher.is_altjvm=", &tail)) {
176 if (strcmp(tail, "true") == 0) {
177 _sun_java_launcher_is_altjvm = true;
178 }
179 continue;
180 }
181 if (match_option(option, "-Dsun.java.launcher.pid=", &tail)) {
182 _sun_java_launcher_pid = atoi(tail);
183 continue;
184 }
185 }
186 }
187
188 // Initialize system properties key and value.
189 void Arguments::init_system_properties() {
190
191 PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
192 "Java Virtual Machine Specification", false));
193 PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(), false));
194 PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(), false));
195 PropertyList_add(&_system_properties, new SystemProperty("java.vm.info", VM_Version::vm_info_string(), true));
196
197 // Following are JVMTI agent writable properties.
198 // Properties values are set to NULL and they are
199 // os specific they are initialized in os::init_system_properties_values().
200 _sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL, true);
201 _java_library_path = new SystemProperty("java.library.path", NULL, true);
202 _java_home = new SystemProperty("java.home", NULL, true);
203 _sun_boot_class_path = new SystemProperty("sun.boot.class.path", NULL, true);
204
205 _java_class_path = new SystemProperty("java.class.path", "", true);
206
207 // Add to System Property list.
208 PropertyList_add(&_system_properties, _sun_boot_library_path);
209 PropertyList_add(&_system_properties, _java_library_path);
210 PropertyList_add(&_system_properties, _java_home);
211 PropertyList_add(&_system_properties, _java_class_path);
212 PropertyList_add(&_system_properties, _sun_boot_class_path);
213
214 // Set OS specific system properties values
215 os::init_system_properties_values();
216 }
217
218
219 // Update/Initialize System properties after JDK version number is known
220 void Arguments::init_version_specific_system_properties() {
221 enum { bufsz = 16 };
222 char buffer[bufsz];
223 const char* spec_vendor = "Oracle Corporation";
224 uint32_t spec_version_major = 0;
225
226 spec_version_major = JDK_Version::current().major_version();
227 jio_snprintf(buffer, bufsz, UINT32_FORMAT, spec_version_major);
228
229 PropertyList_add(&_system_properties,
230 new SystemProperty("java.vm.specification.vendor", spec_vendor, false));
231 PropertyList_add(&_system_properties,
232 new SystemProperty("java.vm.specification.version", buffer, false));
233 PropertyList_add(&_system_properties,
234 new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(), false));
235 }
236
237 /**
238 * Provide a slightly more user-friendly way of eliminating -XX flags.
239 * When a flag is eliminated, it can be added to this list in order to
240 * continue accepting this flag on the command-line, while issuing a warning
241 * and ignoring the value. Once the JDK version reaches the 'accept_until'
242 * limit, we flatly refuse to admit the existence of the flag. This allows
243 * a flag to die correctly over JDK releases using HSX.
244 * But now that HSX is no longer supported only options with a future
245 * accept_until value need to be listed, and the list can be pruned
246 * on each major release.
247 */
248 typedef struct {
249 const char* name;
250 JDK_Version obsoleted_in; // when the flag went away
251 JDK_Version accept_until; // which version to start denying the existence
252 } ObsoleteFlag;
253
254 static ObsoleteFlag obsolete_jvm_flags[] = {
255 { "UseOldInlining", JDK_Version::jdk(9), JDK_Version::jdk(10) },
256 { "SafepointPollOffset", JDK_Version::jdk(9), JDK_Version::jdk(10) },
257 { "UseBoundThreads", JDK_Version::jdk(9), JDK_Version::jdk(10) },
258 { "DefaultThreadPriority", JDK_Version::jdk(9), JDK_Version::jdk(10) },
259 { "NoYieldsInMicrolock", JDK_Version::jdk(9), JDK_Version::jdk(10) },
260 { "BackEdgeThreshold", JDK_Version::jdk(9), JDK_Version::jdk(10) },
261 { "UseNewReflection", JDK_Version::jdk(9), JDK_Version::jdk(10) },
262 { "ReflectionWrapResolutionErrors",JDK_Version::jdk(9), JDK_Version::jdk(10) },
263 { "VerifyReflectionBytecodes", JDK_Version::jdk(9), JDK_Version::jdk(10) },
264 { "AutoShutdownNMT", JDK_Version::jdk(9), JDK_Version::jdk(10) },
265 { "NmethodSweepFraction", JDK_Version::jdk(9), JDK_Version::jdk(10) },
266 { "NmethodSweepCheckInterval", JDK_Version::jdk(9), JDK_Version::jdk(10) },
267 { "CodeCacheMinimumFreeSpace", JDK_Version::jdk(9), JDK_Version::jdk(10) },
268 #ifndef ZERO
269 { "UseFastAccessorMethods", JDK_Version::jdk(9), JDK_Version::jdk(10) },
270 { "UseFastEmptyMethods", JDK_Version::jdk(9), JDK_Version::jdk(10) },
271 #endif // ZERO
272 { "UseCompilerSafepoints", JDK_Version::jdk(9), JDK_Version::jdk(10) },
273 { "AdaptiveSizePausePolicy", JDK_Version::jdk(9), JDK_Version::jdk(10) },
274 { "ParallelGCRetainPLAB", JDK_Version::jdk(9), JDK_Version::jdk(10) },
275 { NULL, JDK_Version(0), JDK_Version(0) }
276 };
277
278 // Returns true if the flag is obsolete and fits into the range specified
279 // for being ignored. In the case that the flag is ignored, the 'version'
280 // value is filled in with the version number when the flag became
281 // obsolete so that that value can be displayed to the user.
282 bool Arguments::is_newly_obsolete(const char *s, JDK_Version* version) {
283 int i = 0;
284 assert(version != NULL, "Must provide a version buffer");
285 while (obsolete_jvm_flags[i].name != NULL) {
286 const ObsoleteFlag& flag_status = obsolete_jvm_flags[i];
287 // <flag>=xxx form
288 // [-|+]<flag> form
289 size_t len = strlen(flag_status.name);
290 if ((strncmp(flag_status.name, s, len) == 0) &&
291 (strlen(s) == len)){
292 if (JDK_Version::current().compare(flag_status.accept_until) == -1) {
293 *version = flag_status.obsoleted_in;
294 return true;
295 }
296 }
297 i++;
298 }
299 return false;
300 }
301
302 // Constructs the system class path (aka boot class path) from the following
303 // components, in order:
304 //
305 // prefix // from -Xbootclasspath/p:...
306 // base // from os::get_system_properties() or -Xbootclasspath=
307 // suffix // from -Xbootclasspath/a:...
308 //
309 // This could be AllStatic, but it isn't needed after argument processing is
310 // complete.
311 class SysClassPath: public StackObj {
312 public:
313 SysClassPath(const char* base);
314 ~SysClassPath();
315
316 inline void set_base(const char* base);
317 inline void add_prefix(const char* prefix);
318 inline void add_suffix_to_prefix(const char* suffix);
319 inline void add_suffix(const char* suffix);
320 inline void reset_path(const char* base);
321
322 inline const char* get_base() const { return _items[_scp_base]; }
323 inline const char* get_prefix() const { return _items[_scp_prefix]; }
324 inline const char* get_suffix() const { return _items[_scp_suffix]; }
325
326 // Combine all the components into a single c-heap-allocated string; caller
327 // must free the string if/when no longer needed.
328 char* combined_path();
329
330 private:
331 // Utility routines.
332 static char* add_to_path(const char* path, const char* str, bool prepend);
333 static char* add_jars_to_path(char* path, const char* directory);
334
335 inline void reset_item_at(int index);
336
337 // Array indices for the items that make up the sysclasspath. All except the
338 // base are allocated in the C heap and freed by this class.
339 enum {
340 _scp_prefix, // from -Xbootclasspath/p:...
341 _scp_base, // the default sysclasspath
342 _scp_suffix, // from -Xbootclasspath/a:...
343 _scp_nitems // the number of items, must be last.
344 };
345
346 const char* _items[_scp_nitems];
347 };
348
349 SysClassPath::SysClassPath(const char* base) {
350 memset(_items, 0, sizeof(_items));
351 _items[_scp_base] = base;
352 }
353
354 SysClassPath::~SysClassPath() {
355 // Free everything except the base.
356 for (int i = 0; i < _scp_nitems; ++i) {
357 if (i != _scp_base) reset_item_at(i);
358 }
359 }
360
361 inline void SysClassPath::set_base(const char* base) {
362 _items[_scp_base] = base;
363 }
364
365 inline void SysClassPath::add_prefix(const char* prefix) {
366 _items[_scp_prefix] = add_to_path(_items[_scp_prefix], prefix, true);
367 }
368
369 inline void SysClassPath::add_suffix_to_prefix(const char* suffix) {
370 _items[_scp_prefix] = add_to_path(_items[_scp_prefix], suffix, false);
371 }
372
373 inline void SysClassPath::add_suffix(const char* suffix) {
374 _items[_scp_suffix] = add_to_path(_items[_scp_suffix], suffix, false);
375 }
376
377 inline void SysClassPath::reset_item_at(int index) {
378 assert(index < _scp_nitems && index != _scp_base, "just checking");
379 if (_items[index] != NULL) {
380 FREE_C_HEAP_ARRAY(char, _items[index]);
381 _items[index] = NULL;
382 }
383 }
384
385 inline void SysClassPath::reset_path(const char* base) {
386 // Clear the prefix and suffix.
387 reset_item_at(_scp_prefix);
388 reset_item_at(_scp_suffix);
389 set_base(base);
390 }
391
392 //------------------------------------------------------------------------------
393
394
395 // Combine the bootclasspath elements, some of which may be null, into a single
396 // c-heap-allocated string.
397 char* SysClassPath::combined_path() {
398 assert(_items[_scp_base] != NULL, "empty default sysclasspath");
399
400 size_t lengths[_scp_nitems];
401 size_t total_len = 0;
402
403 const char separator = *os::path_separator();
404
405 // Get the lengths.
406 int i;
407 for (i = 0; i < _scp_nitems; ++i) {
408 if (_items[i] != NULL) {
409 lengths[i] = strlen(_items[i]);
410 // Include space for the separator char (or a NULL for the last item).
411 total_len += lengths[i] + 1;
412 }
413 }
414 assert(total_len > 0, "empty sysclasspath not allowed");
415
416 // Copy the _items to a single string.
417 char* cp = NEW_C_HEAP_ARRAY(char, total_len, mtInternal);
418 char* cp_tmp = cp;
419 for (i = 0; i < _scp_nitems; ++i) {
420 if (_items[i] != NULL) {
421 memcpy(cp_tmp, _items[i], lengths[i]);
422 cp_tmp += lengths[i];
423 *cp_tmp++ = separator;
424 }
425 }
426 *--cp_tmp = '\0'; // Replace the extra separator.
427 return cp;
428 }
429
430 // Note: path must be c-heap-allocated (or NULL); it is freed if non-null.
431 char*
432 SysClassPath::add_to_path(const char* path, const char* str, bool prepend) {
433 char *cp;
434
435 assert(str != NULL, "just checking");
436 if (path == NULL) {
437 size_t len = strlen(str) + 1;
438 cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);
439 memcpy(cp, str, len); // copy the trailing null
440 } else {
441 const char separator = *os::path_separator();
442 size_t old_len = strlen(path);
443 size_t str_len = strlen(str);
444 size_t len = old_len + str_len + 2;
445
446 if (prepend) {
447 cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);
448 char* cp_tmp = cp;
449 memcpy(cp_tmp, str, str_len);
450 cp_tmp += str_len;
451 *cp_tmp = separator;
452 memcpy(++cp_tmp, path, old_len + 1); // copy the trailing null
453 FREE_C_HEAP_ARRAY(char, path);
454 } else {
455 cp = REALLOC_C_HEAP_ARRAY(char, path, len, mtInternal);
456 char* cp_tmp = cp + old_len;
457 *cp_tmp = separator;
458 memcpy(++cp_tmp, str, str_len + 1); // copy the trailing null
459 }
460 }
461 return cp;
462 }
463
464 // Scan the directory and append any jar or zip files found to path.
465 // Note: path must be c-heap-allocated (or NULL); it is freed if non-null.
466 char* SysClassPath::add_jars_to_path(char* path, const char* directory) {
467 DIR* dir = os::opendir(directory);
468 if (dir == NULL) return path;
469
470 char dir_sep[2] = { '\0', '\0' };
471 size_t directory_len = strlen(directory);
472 const char fileSep = *os::file_separator();
473 if (directory[directory_len - 1] != fileSep) dir_sep[0] = fileSep;
474
475 /* Scan the directory for jars/zips, appending them to path. */
476 struct dirent *entry;
477 char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtInternal);
478 while ((entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
479 const char* name = entry->d_name;
480 const char* ext = name + strlen(name) - 4;
481 bool isJarOrZip = ext > name &&
482 (os::file_name_strcmp(ext, ".jar") == 0 ||
483 os::file_name_strcmp(ext, ".zip") == 0);
484 if (isJarOrZip) {
485 char* jarpath = NEW_C_HEAP_ARRAY(char, directory_len + 2 + strlen(name), mtInternal);
486 sprintf(jarpath, "%s%s%s", directory, dir_sep, name);
487 path = add_to_path(path, jarpath, false);
488 FREE_C_HEAP_ARRAY(char, jarpath);
489 }
490 }
491 FREE_C_HEAP_ARRAY(char, dbuf);
492 os::closedir(dir);
493 return path;
494 }
495
496 // Parses a memory size specification string.
497 static bool atomull(const char *s, julong* result) {
498 julong n = 0;
499 int args_read = 0;
500 bool is_hex = false;
501 // Skip leading 0[xX] for hexadecimal
502 if (*s =='0' && (*(s+1) == 'x' || *(s+1) == 'X')) {
503 s += 2;
504 is_hex = true;
505 args_read = sscanf(s, JULONG_FORMAT_X, &n);
506 } else {
507 args_read = sscanf(s, JULONG_FORMAT, &n);
508 }
509 if (args_read != 1) {
510 return false;
511 }
512 while (*s != '\0' && (isdigit(*s) || (is_hex && isxdigit(*s)))) {
513 s++;
514 }
515 // 4705540: illegal if more characters are found after the first non-digit
516 if (strlen(s) > 1) {
517 return false;
518 }
519 switch (*s) {
520 case 'T': case 't':
521 *result = n * G * K;
522 // Check for overflow.
523 if (*result/((julong)G * K) != n) return false;
524 return true;
525 case 'G': case 'g':
526 *result = n * G;
527 if (*result/G != n) return false;
528 return true;
529 case 'M': case 'm':
530 *result = n * M;
531 if (*result/M != n) return false;
532 return true;
533 case 'K': case 'k':
534 *result = n * K;
535 if (*result/K != n) return false;
536 return true;
537 case '\0':
538 *result = n;
539 return true;
540 default:
541 return false;
542 }
543 }
544
545 Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size) {
546 if (size < min_size) return arg_too_small;
547 // Check that size will fit in a size_t (only relevant on 32-bit)
548 if (size > max_uintx) return arg_too_big;
549 return arg_in_range;
550 }
551
552 // Describe an argument out of range error
553 void Arguments::describe_range_error(ArgsRange errcode) {
554 switch(errcode) {
555 case arg_too_big:
556 jio_fprintf(defaultStream::error_stream(),
557 "The specified size exceeds the maximum "
558 "representable size.\n");
559 break;
560 case arg_too_small:
561 case arg_unreadable:
562 case arg_in_range:
563 // do nothing for now
564 break;
565 default:
566 ShouldNotReachHere();
567 }
568 }
569
570 static bool set_bool_flag(char* name, bool value, Flag::Flags origin) {
571 return CommandLineFlags::boolAtPut(name, &value, origin);
572 }
573
574 static bool set_fp_numeric_flag(char* name, char* value, Flag::Flags origin) {
575 double v;
576 if (sscanf(value, "%lf", &v) != 1) {
577 return false;
578 }
579
580 if (CommandLineFlags::doubleAtPut(name, &v, origin)) {
581 return true;
582 }
583 return false;
584 }
585
586 static bool set_numeric_flag(char* name, char* value, Flag::Flags origin) {
587 julong v;
588 intx intx_v;
589 bool is_neg = false;
590 // Check the sign first since atomull() parses only unsigned values.
591 if (*value == '-') {
592 if (!CommandLineFlags::intxAt(name, &intx_v)) {
593 return false;
594 }
595 value++;
596 is_neg = true;
597 }
598 if (!atomull(value, &v)) {
599 return false;
600 }
601 intx_v = (intx) v;
602 if (is_neg) {
603 intx_v = -intx_v;
604 }
605 if (CommandLineFlags::intxAtPut(name, &intx_v, origin)) {
606 return true;
607 }
608 uintx uintx_v = (uintx) v;
609 if (!is_neg && CommandLineFlags::uintxAtPut(name, &uintx_v, origin)) {
610 return true;
611 }
612 uint64_t uint64_t_v = (uint64_t) v;
613 if (!is_neg && CommandLineFlags::uint64_tAtPut(name, &uint64_t_v, origin)) {
614 return true;
615 }
616 size_t size_t_v = (size_t) v;
617 if (!is_neg && CommandLineFlags::size_tAtPut(name, &size_t_v, origin)) {
618 return true;
619 }
620 return false;
621 }
622
623 static bool set_string_flag(char* name, const char* value, Flag::Flags origin) {
624 if (!CommandLineFlags::ccstrAtPut(name, &value, origin)) return false;
625 // Contract: CommandLineFlags always returns a pointer that needs freeing.
626 FREE_C_HEAP_ARRAY(char, value);
627 return true;
628 }
629
630 static bool append_to_string_flag(char* name, const char* new_value, Flag::Flags origin) {
631 const char* old_value = "";
632 if (!CommandLineFlags::ccstrAt(name, &old_value)) return false;
633 size_t old_len = old_value != NULL ? strlen(old_value) : 0;
634 size_t new_len = strlen(new_value);
635 const char* value;
636 char* free_this_too = NULL;
637 if (old_len == 0) {
638 value = new_value;
639 } else if (new_len == 0) {
640 value = old_value;
641 } else {
642 char* buf = NEW_C_HEAP_ARRAY(char, old_len + 1 + new_len + 1, mtInternal);
643 // each new setting adds another LINE to the switch:
644 sprintf(buf, "%s\n%s", old_value, new_value);
645 value = buf;
646 free_this_too = buf;
647 }
648 (void) CommandLineFlags::ccstrAtPut(name, &value, origin);
649 // CommandLineFlags always returns a pointer that needs freeing.
650 FREE_C_HEAP_ARRAY(char, value);
651 if (free_this_too != NULL) {
652 // CommandLineFlags made its own copy, so I must delete my own temp. buffer.
653 FREE_C_HEAP_ARRAY(char, free_this_too);
654 }
655 return true;
656 }
657
658 bool Arguments::parse_argument(const char* arg, Flag::Flags origin) {
659
660 // range of acceptable characters spelled out for portability reasons
661 #define NAME_RANGE "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"
662 #define BUFLEN 255
663 char name[BUFLEN+1];
664 char dummy;
665
666 if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
667 return set_bool_flag(name, false, origin);
668 }
669 if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
670 return set_bool_flag(name, true, origin);
671 }
672
673 char punct;
674 if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {
675 const char* value = strchr(arg, '=') + 1;
676 Flag* flag = Flag::find_flag(name, strlen(name));
677 if (flag != NULL && flag->is_ccstr()) {
678 if (flag->ccstr_accumulates()) {
679 return append_to_string_flag(name, value, origin);
680 } else {
681 if (value[0] == '\0') {
682 value = NULL;
683 }
684 return set_string_flag(name, value, origin);
685 }
686 }
687 }
688
689 if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {
690 const char* value = strchr(arg, '=') + 1;
691 // -XX:Foo:=xxx will reset the string flag to the given value.
692 if (value[0] == '\0') {
693 value = NULL;
694 }
695 return set_string_flag(name, value, origin);
696 }
697
698 #define SIGNED_FP_NUMBER_RANGE "[-0123456789.]"
699 #define SIGNED_NUMBER_RANGE "[-0123456789]"
700 #define NUMBER_RANGE "[0123456789]"
701 char value[BUFLEN + 1];
702 char value2[BUFLEN + 1];
703 if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {
704 // Looks like a floating-point number -- try again with more lenient format string
705 if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {
706 return set_fp_numeric_flag(name, value, origin);
707 }
708 }
709
710 #define VALUE_RANGE "[-kmgtxKMGTX0123456789abcdefABCDEF]"
711 if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_RANGE "%c", name, value, &dummy) == 2) {
712 return set_numeric_flag(name, value, origin);
713 }
714
715 return false;
716 }
717
718 void Arguments::add_string(char*** bldarray, int* count, const char* arg) {
719 assert(bldarray != NULL, "illegal argument");
720
721 if (arg == NULL) {
722 return;
723 }
724
725 int new_count = *count + 1;
726
727 // expand the array and add arg to the last element
728 if (*bldarray == NULL) {
729 *bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtInternal);
730 } else {
731 *bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtInternal);
732 }
733 (*bldarray)[*count] = os::strdup_check_oom(arg);
734 *count = new_count;
735 }
736
737 void Arguments::build_jvm_args(const char* arg) {
738 add_string(&_jvm_args_array, &_num_jvm_args, arg);
739 }
740
741 void Arguments::build_jvm_flags(const char* arg) {
742 add_string(&_jvm_flags_array, &_num_jvm_flags, arg);
743 }
744
745 // utility function to return a string that concatenates all
746 // strings in a given char** array
747 const char* Arguments::build_resource_string(char** args, int count) {
748 if (args == NULL || count == 0) {
749 return NULL;
750 }
751 size_t length = strlen(args[0]) + 1; // add 1 for the null terminator
752 for (int i = 1; i < count; i++) {
753 length += strlen(args[i]) + 1; // add 1 for a space
754 }
755 char* s = NEW_RESOURCE_ARRAY(char, length);
756 strcpy(s, args[0]);
757 for (int j = 1; j < count; j++) {
758 strcat(s, " ");
759 strcat(s, args[j]);
760 }
761 return (const char*) s;
762 }
763
764 void Arguments::print_on(outputStream* st) {
765 st->print_cr("VM Arguments:");
766 if (num_jvm_flags() > 0) {
767 st->print("jvm_flags: "); print_jvm_flags_on(st);
768 }
769 if (num_jvm_args() > 0) {
770 st->print("jvm_args: "); print_jvm_args_on(st);
771 }
772 st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");
773 if (_java_class_path != NULL) {
774 char* path = _java_class_path->value();
775 st->print_cr("java_class_path (initial): %s", strlen(path) == 0 ? "<not set>" : path );
776 }
777 st->print_cr("Launcher Type: %s", _sun_java_launcher);
778 }
779
780 void Arguments::print_jvm_flags_on(outputStream* st) {
781 if (_num_jvm_flags > 0) {
782 for (int i=0; i < _num_jvm_flags; i++) {
783 st->print("%s ", _jvm_flags_array[i]);
784 }
785 st->cr();
786 }
787 }
788
789 void Arguments::print_jvm_args_on(outputStream* st) {
790 if (_num_jvm_args > 0) {
791 for (int i=0; i < _num_jvm_args; i++) {
792 st->print("%s ", _jvm_args_array[i]);
793 }
794 st->cr();
795 }
796 }
797
798 bool Arguments::process_argument(const char* arg,
799 jboolean ignore_unrecognized, Flag::Flags origin) {
800
801 JDK_Version since = JDK_Version();
802
803 if (parse_argument(arg, origin) || ignore_unrecognized) {
804 return true;
805 }
806
807 // Determine if the flag has '+', '-', or '=' characters.
808 bool has_plus_minus = (*arg == '+' || *arg == '-');
809 const char* const argname = has_plus_minus ? arg + 1 : arg;
810
811 size_t arg_len;
812 const char* equal_sign = strchr(argname, '=');
813 if (equal_sign == NULL) {
814 arg_len = strlen(argname);
815 } else {
816 arg_len = equal_sign - argname;
817 }
818
819 // Construct a string which consists only of the argument name without '+', '-', or '='.
820 char stripped_argname[256];
821 strncpy(stripped_argname, argname, arg_len);
822 stripped_argname[arg_len] = '\0'; //strncpy doesn't null terminate.
823
824 if (is_newly_obsolete(stripped_argname, &since)) {
825 char version[256];
826 since.to_string(version, sizeof(version));
827 warning("ignoring option %s; support was removed in %s", stripped_argname, version);
828 return true;
829 }
830
831 // For locked flags, report a custom error message if available.
832 // Otherwise, report the standard unrecognized VM option.
833 Flag* found_flag = Flag::find_flag((const char*)argname, arg_len, true, true);
834 if (found_flag != NULL) {
835 char locked_message_buf[BUFLEN];
836 found_flag->get_locked_message(locked_message_buf, BUFLEN);
837 if (strlen(locked_message_buf) == 0) {
838 if (found_flag->is_bool() && !has_plus_minus) {
839 jio_fprintf(defaultStream::error_stream(),
840 "Missing +/- setting for VM option '%s'\n", argname);
841 } else if (!found_flag->is_bool() && has_plus_minus) {
842 jio_fprintf(defaultStream::error_stream(),
843 "Unexpected +/- setting in VM option '%s'\n", argname);
844 } else {
845 jio_fprintf(defaultStream::error_stream(),
846 "Improperly specified VM option '%s'\n", argname);
847 }
848 } else {
849 jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);
850 }
851 } else {
852 jio_fprintf(defaultStream::error_stream(),
853 "Unrecognized VM option '%s'\n", argname);
854 Flag* fuzzy_matched = Flag::fuzzy_match((const char*)argname, arg_len, true);
855 if (fuzzy_matched != NULL) {
856 jio_fprintf(defaultStream::error_stream(),
857 "Did you mean '%s%s%s'? ",
858 (fuzzy_matched->is_bool()) ? "(+/-)" : "",
859 fuzzy_matched->_name,
860 (fuzzy_matched->is_bool()) ? "" : "=<value>");
861 }
862 }
863
864 // allow for commandline "commenting out" options like -XX:#+Verbose
865 return arg[0] == '#';
866 }
867
868 bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
869 FILE* stream = fopen(file_name, "rb");
870 if (stream == NULL) {
871 if (should_exist) {
872 jio_fprintf(defaultStream::error_stream(),
873 "Could not open settings file %s\n", file_name);
874 return false;
875 } else {
876 return true;
877 }
878 }
879
880 char token[1024];
881 int pos = 0;
882
883 bool in_white_space = true;
884 bool in_comment = false;
885 bool in_quote = false;
886 char quote_c = 0;
887 bool result = true;
888
889 int c = getc(stream);
890 while(c != EOF && pos < (int)(sizeof(token)-1)) {
891 if (in_white_space) {
892 if (in_comment) {
893 if (c == '\n') in_comment = false;
894 } else {
895 if (c == '#') in_comment = true;
896 else if (!isspace(c)) {
897 in_white_space = false;
898 token[pos++] = c;
899 }
900 }
901 } else {
902 if (c == '\n' || (!in_quote && isspace(c))) {
903 // token ends at newline, or at unquoted whitespace
904 // this allows a way to include spaces in string-valued options
905 token[pos] = '\0';
906 logOption(token);
907 result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
908 build_jvm_flags(token);
909 pos = 0;
910 in_white_space = true;
911 in_quote = false;
912 } else if (!in_quote && (c == '\'' || c == '"')) {
913 in_quote = true;
914 quote_c = c;
915 } else if (in_quote && (c == quote_c)) {
916 in_quote = false;
917 } else {
918 token[pos++] = c;
919 }
920 }
921 c = getc(stream);
922 }
923 if (pos > 0) {
924 token[pos] = '\0';
925 result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
926 build_jvm_flags(token);
927 }
928 fclose(stream);
929 return result;
930 }
931
932 //=============================================================================================================
933 // Parsing of properties (-D)
934
935 const char* Arguments::get_property(const char* key) {
936 return PropertyList_get_value(system_properties(), key);
937 }
938
939 bool Arguments::add_property(const char* prop) {
940 const char* eq = strchr(prop, '=');
941 char* key;
942 // ns must be static--its address may be stored in a SystemProperty object.
943 const static char ns[1] = {0};
944 char* value = (char *)ns;
945
946 size_t key_len = (eq == NULL) ? strlen(prop) : (eq - prop);
947 key = AllocateHeap(key_len + 1, mtInternal);
948 strncpy(key, prop, key_len);
949 key[key_len] = '\0';
950
951 if (eq != NULL) {
952 size_t value_len = strlen(prop) - key_len - 1;
953 value = AllocateHeap(value_len + 1, mtInternal);
954 strncpy(value, &prop[key_len + 1], value_len + 1);
955 }
956
957 if (strcmp(key, "java.compiler") == 0) {
958 process_java_compiler_argument(value);
959 FreeHeap(key);
960 if (eq != NULL) {
961 FreeHeap(value);
962 }
963 return true;
964 } else if (strcmp(key, "sun.java.command") == 0) {
965 _java_command = value;
966
967 // Record value in Arguments, but let it get passed to Java.
968 } else if (strcmp(key, "sun.java.launcher.is_altjvm") == 0 ||
969 strcmp(key, "sun.java.launcher.pid") == 0) {
970 // sun.java.launcher.is_altjvm and sun.java.launcher.pid property are
971 // private and are processed in process_sun_java_launcher_properties();
972 // the sun.java.launcher property is passed on to the java application
973 FreeHeap(key);
974 if (eq != NULL) {
975 FreeHeap(value);
976 }
977 return true;
978 } else if (strcmp(key, "java.vendor.url.bug") == 0) {
979 // save it in _java_vendor_url_bug, so JVM fatal error handler can access
980 // its value without going through the property list or making a Java call.
981 _java_vendor_url_bug = value;
982 } else if (strcmp(key, "sun.boot.library.path") == 0) {
983 PropertyList_unique_add(&_system_properties, key, value, true);
984 return true;
985 }
986 // Create new property and add at the end of the list
987 PropertyList_unique_add(&_system_properties, key, value);
988 return true;
989 }
990
991 //===========================================================================================================
992 // Setting int/mixed/comp mode flags
993
994 void Arguments::set_mode_flags(Mode mode) {
995 // Set up default values for all flags.
996 // If you add a flag to any of the branches below,
997 // add a default value for it here.
998 set_java_compiler(false);
999 _mode = mode;
1000
1001 // Ensure Agent_OnLoad has the correct initial values.
1002 // This may not be the final mode; mode may change later in onload phase.
1003 PropertyList_unique_add(&_system_properties, "java.vm.info",
1004 (char*)VM_Version::vm_info_string(), false);
1005
1006 UseInterpreter = true;
1007 UseCompiler = true;
1008 UseLoopCounter = true;
1009
1010 // Default values may be platform/compiler dependent -
1011 // use the saved values
1012 ClipInlining = Arguments::_ClipInlining;
1013 AlwaysCompileLoopMethods = Arguments::_AlwaysCompileLoopMethods;
1014 UseOnStackReplacement = Arguments::_UseOnStackReplacement;
1015 BackgroundCompilation = Arguments::_BackgroundCompilation;
1016 if (TieredCompilation) {
1017 if (FLAG_IS_DEFAULT(Tier3InvokeNotifyFreqLog)) {
1018 Tier3InvokeNotifyFreqLog = Arguments::_Tier3InvokeNotifyFreqLog;
1019 }
1020 if (FLAG_IS_DEFAULT(Tier4InvocationThreshold)) {
1021 Tier4InvocationThreshold = Arguments::_Tier4InvocationThreshold;
1022 }
1023 }
1024
1025 // Change from defaults based on mode
1026 switch (mode) {
1027 default:
1028 ShouldNotReachHere();
1029 break;
1030 case _int:
1031 UseCompiler = false;
1032 UseLoopCounter = false;
1033 AlwaysCompileLoopMethods = false;
1034 UseOnStackReplacement = false;
1035 break;
1036 case _mixed:
1037 // same as default
1038 break;
1039 case _comp:
1040 UseInterpreter = false;
1041 BackgroundCompilation = false;
1042 ClipInlining = false;
1043 // Be much more aggressive in tiered mode with -Xcomp and exercise C2 more.
1044 // We will first compile a level 3 version (C1 with full profiling), then do one invocation of it and
1045 // compile a level 4 (C2) and then continue executing it.
1046 if (TieredCompilation) {
1047 Tier3InvokeNotifyFreqLog = 0;
1048 Tier4InvocationThreshold = 0;
1049 }
1050 break;
1051 }
1052 }
1053
1054 #if defined(COMPILER2) || defined(_LP64) || !INCLUDE_CDS
1055 // Conflict: required to use shared spaces (-Xshare:on), but
1056 // incompatible command line options were chosen.
1057
1058 static void no_shared_spaces(const char* message) {
1059 if (RequireSharedSpaces) {
1060 jio_fprintf(defaultStream::error_stream(),
1061 "Class data sharing is inconsistent with other specified options.\n");
1062 vm_exit_during_initialization("Unable to use shared archive.", message);
1063 } else {
1064 FLAG_SET_DEFAULT(UseSharedSpaces, false);
1065 }
1066 }
1067 #endif
1068
1069 // Returns threshold scaled with the value of scale.
1070 // If scale < 0.0, threshold is returned without scaling.
1071 intx Arguments::scaled_compile_threshold(intx threshold, double scale) {
1072 if (scale == 1.0 || scale < 0.0) {
1073 return threshold;
1074 } else {
1075 return (intx)(threshold * scale);
1076 }
1077 }
1078
1079 // Returns freq_log scaled with the value of scale.
1080 // Returned values are in the range of [0, InvocationCounter::number_of_count_bits + 1].
1081 // If scale < 0.0, freq_log is returned without scaling.
1082 intx Arguments::scaled_freq_log(intx freq_log, double scale) {
1083 // Check if scaling is necessary or if negative value was specified.
1084 if (scale == 1.0 || scale < 0.0) {
1085 return freq_log;
1086 }
1087 // Check values to avoid calculating log2 of 0.
1088 if (scale == 0.0 || freq_log == 0) {
1089 return 0;
1090 }
1091 // Determine the maximum notification frequency value currently supported.
1092 // The largest mask value that the interpreter/C1 can handle is
1093 // of length InvocationCounter::number_of_count_bits. Mask values are always
1094 // one bit shorter then the value of the notification frequency. Set
1095 // max_freq_bits accordingly.
1096 intx max_freq_bits = InvocationCounter::number_of_count_bits + 1;
1097 intx scaled_freq = scaled_compile_threshold((intx)1 << freq_log, scale);
1098 if (scaled_freq == 0) {
1099 // Return 0 right away to avoid calculating log2 of 0.
1100 return 0;
1101 } else if (scaled_freq > nth_bit(max_freq_bits)) {
1102 return max_freq_bits;
1103 } else {
1104 return log2_intptr(scaled_freq);
1105 }
1106 }
1107
1108 void Arguments::set_tiered_flags() {
1109 // With tiered, set default policy to AdvancedThresholdPolicy, which is 3.
1110 if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {
1111 FLAG_SET_DEFAULT(CompilationPolicyChoice, 3);
1112 }
1113 if (CompilationPolicyChoice < 2) {
1114 vm_exit_during_initialization(
1115 "Incompatible compilation policy selected", NULL);
1116 }
1117 // Increase the code cache size - tiered compiles a lot more.
1118 if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1119 FLAG_SET_ERGO(uintx, ReservedCodeCacheSize,
1120 MIN2(CODE_CACHE_DEFAULT_LIMIT, ReservedCodeCacheSize * 5));
1121 }
1122 // Enable SegmentedCodeCache if TieredCompilation is enabled and ReservedCodeCacheSize >= 240M
1123 if (FLAG_IS_DEFAULT(SegmentedCodeCache) && ReservedCodeCacheSize >= 240*M) {
1124 FLAG_SET_ERGO(bool, SegmentedCodeCache, true);
1125
1126 if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1127 // Multiply sizes by 5 but fix NonNMethodCodeHeapSize (distribute among non-profiled and profiled code heap)
1128 if (FLAG_IS_DEFAULT(ProfiledCodeHeapSize)) {
1129 FLAG_SET_ERGO(uintx, ProfiledCodeHeapSize, ProfiledCodeHeapSize * 5 + NonNMethodCodeHeapSize * 2);
1130 }
1131 if (FLAG_IS_DEFAULT(NonProfiledCodeHeapSize)) {
1132 FLAG_SET_ERGO(uintx, NonProfiledCodeHeapSize, NonProfiledCodeHeapSize * 5 + NonNMethodCodeHeapSize * 2);
1133 }
1134 // Check consistency of code heap sizes
1135 if ((NonNMethodCodeHeapSize + NonProfiledCodeHeapSize + ProfiledCodeHeapSize) != ReservedCodeCacheSize) {
1136 jio_fprintf(defaultStream::error_stream(),
1137 "Invalid code heap sizes: NonNMethodCodeHeapSize(%dK) + ProfiledCodeHeapSize(%dK) + NonProfiledCodeHeapSize(%dK) = %dK. Must be equal to ReservedCodeCacheSize = %uK.\n",
1138 NonNMethodCodeHeapSize/K, ProfiledCodeHeapSize/K, NonProfiledCodeHeapSize/K,
1139 (NonNMethodCodeHeapSize + ProfiledCodeHeapSize + NonProfiledCodeHeapSize)/K, ReservedCodeCacheSize/K);
1140 vm_exit(1);
1141 }
1142 }
1143 }
1144 if (!UseInterpreter) { // -Xcomp
1145 Tier3InvokeNotifyFreqLog = 0;
1146 Tier4InvocationThreshold = 0;
1147 }
1148
1149 if (CompileThresholdScaling < 0) {
1150 vm_exit_during_initialization("Negative value specified for CompileThresholdScaling", NULL);
1151 }
1152
1153 // Scale tiered compilation thresholds.
1154 // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves compilation thresholds unchanged.
1155 if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
1156 FLAG_SET_ERGO(intx, Tier0InvokeNotifyFreqLog, scaled_freq_log(Tier0InvokeNotifyFreqLog));
1157 FLAG_SET_ERGO(intx, Tier0BackedgeNotifyFreqLog, scaled_freq_log(Tier0BackedgeNotifyFreqLog));
1158
1159 FLAG_SET_ERGO(intx, Tier3InvocationThreshold, scaled_compile_threshold(Tier3InvocationThreshold));
1160 FLAG_SET_ERGO(intx, Tier3MinInvocationThreshold, scaled_compile_threshold(Tier3MinInvocationThreshold));
1161 FLAG_SET_ERGO(intx, Tier3CompileThreshold, scaled_compile_threshold(Tier3CompileThreshold));
1162 FLAG_SET_ERGO(intx, Tier3BackEdgeThreshold, scaled_compile_threshold(Tier3BackEdgeThreshold));
1163
1164 // Tier2{Invocation,MinInvocation,Compile,Backedge}Threshold should be scaled here
1165 // once these thresholds become supported.
1166
1167 FLAG_SET_ERGO(intx, Tier2InvokeNotifyFreqLog, scaled_freq_log(Tier2InvokeNotifyFreqLog));
1168 FLAG_SET_ERGO(intx, Tier2BackedgeNotifyFreqLog, scaled_freq_log(Tier2BackedgeNotifyFreqLog));
1169
1170 FLAG_SET_ERGO(intx, Tier3InvokeNotifyFreqLog, scaled_freq_log(Tier3InvokeNotifyFreqLog));
1171 FLAG_SET_ERGO(intx, Tier3BackedgeNotifyFreqLog, scaled_freq_log(Tier3BackedgeNotifyFreqLog));
1172
1173 FLAG_SET_ERGO(intx, Tier23InlineeNotifyFreqLog, scaled_freq_log(Tier23InlineeNotifyFreqLog));
1174
1175 FLAG_SET_ERGO(intx, Tier4InvocationThreshold, scaled_compile_threshold(Tier4InvocationThreshold));
1176 FLAG_SET_ERGO(intx, Tier4MinInvocationThreshold, scaled_compile_threshold(Tier4MinInvocationThreshold));
1177 FLAG_SET_ERGO(intx, Tier4CompileThreshold, scaled_compile_threshold(Tier4CompileThreshold));
1178 FLAG_SET_ERGO(intx, Tier4BackEdgeThreshold, scaled_compile_threshold(Tier4BackEdgeThreshold));
1179 }
1180 }
1181
1182 /**
1183 * Returns the minimum number of compiler threads needed to run the JVM. The following
1184 * configurations are possible.
1185 *
1186 * 1) The JVM is build using an interpreter only. As a result, the minimum number of
1187 * compiler threads is 0.
1188 * 2) The JVM is build using the compiler(s) and tiered compilation is disabled. As
1189 * a result, either C1 or C2 is used, so the minimum number of compiler threads is 1.
1190 * 3) The JVM is build using the compiler(s) and tiered compilation is enabled. However,
1191 * the option "TieredStopAtLevel < CompLevel_full_optimization". As a result, only
1192 * C1 can be used, so the minimum number of compiler threads is 1.
1193 * 4) The JVM is build using the compilers and tiered compilation is enabled. The option
1194 * 'TieredStopAtLevel = CompLevel_full_optimization' (the default value). As a result,
1195 * the minimum number of compiler threads is 2.
1196 */
1197 int Arguments::get_min_number_of_compiler_threads() {
1198 #if !defined(COMPILER1) && !defined(COMPILER2) && !defined(SHARK)
1199 return 0; // case 1
1200 #else
1201 if (!TieredCompilation || (TieredStopAtLevel < CompLevel_full_optimization)) {
1202 return 1; // case 2 or case 3
1203 }
1204 return 2; // case 4 (tiered)
1205 #endif
1206 }
1207
1208 #if INCLUDE_ALL_GCS
1209 static void disable_adaptive_size_policy(const char* collector_name) {
1210 if (UseAdaptiveSizePolicy) {
1211 if (FLAG_IS_CMDLINE(UseAdaptiveSizePolicy)) {
1212 warning("disabling UseAdaptiveSizePolicy; it is incompatible with %s.",
1213 collector_name);
1214 }
1215 FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false);
1216 }
1217 }
1218
1219 void Arguments::set_parnew_gc_flags() {
1220 assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC && !UseG1GC,
1221 "control point invariant");
1222 assert(UseConcMarkSweepGC, "CMS is expected to be on here");
1223 assert(UseParNewGC, "ParNew should always be used with CMS");
1224
1225 if (FLAG_IS_DEFAULT(ParallelGCThreads)) {
1226 FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1227 assert(ParallelGCThreads > 0, "We should always have at least one thread by default");
1228 } else if (ParallelGCThreads == 0) {
1229 jio_fprintf(defaultStream::error_stream(),
1230 "The ParNew GC can not be combined with -XX:ParallelGCThreads=0\n");
1231 vm_exit(1);
1232 }
1233
1234 // By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 respectively,
1235 // these settings are default for Parallel Scavenger. For ParNew+Tenured configuration
1236 // we set them to 1024 and 1024.
1237 // See CR 6362902.
1238 if (FLAG_IS_DEFAULT(YoungPLABSize)) {
1239 FLAG_SET_DEFAULT(YoungPLABSize, (intx)1024);
1240 }
1241 if (FLAG_IS_DEFAULT(OldPLABSize)) {
1242 FLAG_SET_DEFAULT(OldPLABSize, (intx)1024);
1243 }
1244
1245 // When using compressed oops, we use local overflow stacks,
1246 // rather than using a global overflow list chained through
1247 // the klass word of the object's pre-image.
1248 if (UseCompressedOops && !ParGCUseLocalOverflow) {
1249 if (!FLAG_IS_DEFAULT(ParGCUseLocalOverflow)) {
1250 warning("Forcing +ParGCUseLocalOverflow: needed if using compressed references");
1251 }
1252 FLAG_SET_DEFAULT(ParGCUseLocalOverflow, true);
1253 }
1254 assert(ParGCUseLocalOverflow || !UseCompressedOops, "Error");
1255 }
1256
1257 // Adjust some sizes to suit CMS and/or ParNew needs; these work well on
1258 // sparc/solaris for certain applications, but would gain from
1259 // further optimization and tuning efforts, and would almost
1260 // certainly gain from analysis of platform and environment.
1261 void Arguments::set_cms_and_parnew_gc_flags() {
1262 assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC, "Error");
1263 assert(UseConcMarkSweepGC, "CMS is expected to be on here");
1264 assert(UseParNewGC, "ParNew should always be used with CMS");
1265
1266 // Turn off AdaptiveSizePolicy by default for cms until it is complete.
1267 disable_adaptive_size_policy("UseConcMarkSweepGC");
1268
1269 set_parnew_gc_flags();
1270
1271 size_t max_heap = align_size_down(MaxHeapSize,
1272 CardTableRS::ct_max_alignment_constraint());
1273
1274 // Now make adjustments for CMS
1275 intx tenuring_default = (intx)6;
1276 size_t young_gen_per_worker = CMSYoungGenPerWorker;
1277
1278 // Preferred young gen size for "short" pauses:
1279 // upper bound depends on # of threads and NewRatio.
1280 const uintx parallel_gc_threads =
1281 (ParallelGCThreads == 0 ? 1 : ParallelGCThreads);
1282 const size_t preferred_max_new_size_unaligned =
1283 MIN2(max_heap/(NewRatio+1), ScaleForWordSize(young_gen_per_worker * parallel_gc_threads));
1284 size_t preferred_max_new_size =
1285 align_size_up(preferred_max_new_size_unaligned, os::vm_page_size());
1286
1287 // Unless explicitly requested otherwise, size young gen
1288 // for "short" pauses ~ CMSYoungGenPerWorker*ParallelGCThreads
1289
1290 // If either MaxNewSize or NewRatio is set on the command line,
1291 // assume the user is trying to set the size of the young gen.
1292 if (FLAG_IS_DEFAULT(MaxNewSize) && FLAG_IS_DEFAULT(NewRatio)) {
1293
1294 // Set MaxNewSize to our calculated preferred_max_new_size unless
1295 // NewSize was set on the command line and it is larger than
1296 // preferred_max_new_size.
1297 if (!FLAG_IS_DEFAULT(NewSize)) { // NewSize explicitly set at command-line
1298 FLAG_SET_ERGO(size_t, MaxNewSize, MAX2(NewSize, preferred_max_new_size));
1299 } else {
1300 FLAG_SET_ERGO(size_t, MaxNewSize, preferred_max_new_size);
1301 }
1302 if (PrintGCDetails && Verbose) {
1303 // Too early to use gclog_or_tty
1304 tty->print_cr("CMS ergo set MaxNewSize: " SIZE_FORMAT, MaxNewSize);
1305 }
1306
1307 // Code along this path potentially sets NewSize and OldSize
1308 if (PrintGCDetails && Verbose) {
1309 // Too early to use gclog_or_tty
1310 tty->print_cr("CMS set min_heap_size: " SIZE_FORMAT
1311 " initial_heap_size: " SIZE_FORMAT
1312 " max_heap: " SIZE_FORMAT,
1313 min_heap_size(), InitialHeapSize, max_heap);
1314 }
1315 size_t min_new = preferred_max_new_size;
1316 if (FLAG_IS_CMDLINE(NewSize)) {
1317 min_new = NewSize;
1318 }
1319 if (max_heap > min_new && min_heap_size() > min_new) {
1320 // Unless explicitly requested otherwise, make young gen
1321 // at least min_new, and at most preferred_max_new_size.
1322 if (FLAG_IS_DEFAULT(NewSize)) {
1323 FLAG_SET_ERGO(size_t, NewSize, MAX2(NewSize, min_new));
1324 FLAG_SET_ERGO(size_t, NewSize, MIN2(preferred_max_new_size, NewSize));
1325 if (PrintGCDetails && Verbose) {
1326 // Too early to use gclog_or_tty
1327 tty->print_cr("CMS ergo set NewSize: " SIZE_FORMAT, NewSize);
1328 }
1329 }
1330 // Unless explicitly requested otherwise, size old gen
1331 // so it's NewRatio x of NewSize.
1332 if (FLAG_IS_DEFAULT(OldSize)) {
1333 if (max_heap > NewSize) {
1334 FLAG_SET_ERGO(size_t, OldSize, MIN2(NewRatio*NewSize, max_heap - NewSize));
1335 if (PrintGCDetails && Verbose) {
1336 // Too early to use gclog_or_tty
1337 tty->print_cr("CMS ergo set OldSize: " SIZE_FORMAT, OldSize);
1338 }
1339 }
1340 }
1341 }
1342 }
1343 // Unless explicitly requested otherwise, definitely
1344 // promote all objects surviving "tenuring_default" scavenges.
1345 if (FLAG_IS_DEFAULT(MaxTenuringThreshold) &&
1346 FLAG_IS_DEFAULT(SurvivorRatio)) {
1347 FLAG_SET_ERGO(uintx, MaxTenuringThreshold, tenuring_default);
1348 }
1349 // If we decided above (or user explicitly requested)
1350 // `promote all' (via MaxTenuringThreshold := 0),
1351 // prefer minuscule survivor spaces so as not to waste
1352 // space for (non-existent) survivors
1353 if (FLAG_IS_DEFAULT(SurvivorRatio) && MaxTenuringThreshold == 0) {
1354 FLAG_SET_ERGO(uintx, SurvivorRatio, MAX2((uintx)1024, SurvivorRatio));
1355 }
1356
1357 // OldPLABSize is interpreted in CMS as not the size of the PLAB in words,
1358 // but rather the number of free blocks of a given size that are used when
1359 // replenishing the local per-worker free list caches.
1360 if (FLAG_IS_DEFAULT(OldPLABSize)) {
1361 if (!FLAG_IS_DEFAULT(ResizeOldPLAB) && !ResizeOldPLAB) {
1362 // OldPLAB sizing manually turned off: Use a larger default setting,
1363 // unless it was manually specified. This is because a too-low value
1364 // will slow down scavenges.
1365 FLAG_SET_ERGO(size_t, OldPLABSize, CFLS_LAB::_default_static_old_plab_size); // default value before 6631166
1366 } else {
1367 FLAG_SET_DEFAULT(OldPLABSize, CFLS_LAB::_default_dynamic_old_plab_size); // old CMSParPromoteBlocksToClaim default
1368 }
1369 }
1370
1371 // If either of the static initialization defaults have changed, note this
1372 // modification.
1373 if (!FLAG_IS_DEFAULT(OldPLABSize) || !FLAG_IS_DEFAULT(OldPLABWeight)) {
1374 CFLS_LAB::modify_initialization(OldPLABSize, OldPLABWeight);
1375 }
1376 if (PrintGCDetails && Verbose) {
1377 tty->print_cr("MarkStackSize: %uk MarkStackSizeMax: %uk",
1378 (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1379 tty->print_cr("ConcGCThreads: %u", (uint) ConcGCThreads);
1380 }
1381 }
1382 #endif // INCLUDE_ALL_GCS
1383
1384 void set_object_alignment() {
1385 // Object alignment.
1386 assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
1387 MinObjAlignmentInBytes = ObjectAlignmentInBytes;
1388 assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
1389 MinObjAlignment = MinObjAlignmentInBytes / HeapWordSize;
1390 assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
1391 MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
1392
1393 LogMinObjAlignmentInBytes = exact_log2(ObjectAlignmentInBytes);
1394 LogMinObjAlignment = LogMinObjAlignmentInBytes - LogHeapWordSize;
1395
1396 // Oop encoding heap max
1397 OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
1398
1399 #if INCLUDE_ALL_GCS
1400 // Set CMS global values
1401 CompactibleFreeListSpace::set_cms_values();
1402 #endif // INCLUDE_ALL_GCS
1403 }
1404
1405 bool verify_object_alignment() {
1406 // Object alignment.
1407 if (!is_power_of_2(ObjectAlignmentInBytes)) {
1408 jio_fprintf(defaultStream::error_stream(),
1409 "error: ObjectAlignmentInBytes=%d must be power of 2\n",
1410 (int)ObjectAlignmentInBytes);
1411 return false;
1412 }
1413 if ((int)ObjectAlignmentInBytes < BytesPerLong) {
1414 jio_fprintf(defaultStream::error_stream(),
1415 "error: ObjectAlignmentInBytes=%d must be greater or equal %d\n",
1416 (int)ObjectAlignmentInBytes, BytesPerLong);
1417 return false;
1418 }
1419 // It does not make sense to have big object alignment
1420 // since a space lost due to alignment will be greater
1421 // then a saved space from compressed oops.
1422 if ((int)ObjectAlignmentInBytes > 256) {
1423 jio_fprintf(defaultStream::error_stream(),
1424 "error: ObjectAlignmentInBytes=%d must not be greater than 256\n",
1425 (int)ObjectAlignmentInBytes);
1426 return false;
1427 }
1428 // In case page size is very small.
1429 if ((int)ObjectAlignmentInBytes >= os::vm_page_size()) {
1430 jio_fprintf(defaultStream::error_stream(),
1431 "error: ObjectAlignmentInBytes=%d must be less than page size %d\n",
1432 (int)ObjectAlignmentInBytes, os::vm_page_size());
1433 return false;
1434 }
1435 if(SurvivorAlignmentInBytes == 0) {
1436 SurvivorAlignmentInBytes = ObjectAlignmentInBytes;
1437 } else {
1438 if (!is_power_of_2(SurvivorAlignmentInBytes)) {
1439 jio_fprintf(defaultStream::error_stream(),
1440 "error: SurvivorAlignmentInBytes=%d must be power of 2\n",
1441 (int)SurvivorAlignmentInBytes);
1442 return false;
1443 }
1444 if (SurvivorAlignmentInBytes < ObjectAlignmentInBytes) {
1445 jio_fprintf(defaultStream::error_stream(),
1446 "error: SurvivorAlignmentInBytes=%d must be greater than ObjectAlignmentInBytes=%d \n",
1447 (int)SurvivorAlignmentInBytes, (int)ObjectAlignmentInBytes);
1448 return false;
1449 }
1450 }
1451 return true;
1452 }
1453
1454 size_t Arguments::max_heap_for_compressed_oops() {
1455 // Avoid sign flip.
1456 assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
1457 // We need to fit both the NULL page and the heap into the memory budget, while
1458 // keeping alignment constraints of the heap. To guarantee the latter, as the
1459 // NULL page is located before the heap, we pad the NULL page to the conservative
1460 // maximum alignment that the GC may ever impose upon the heap.
1461 size_t displacement_due_to_null_page = align_size_up_(os::vm_page_size(),
1462 _conservative_max_heap_alignment);
1463
1464 LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
1465 NOT_LP64(ShouldNotReachHere(); return 0);
1466 }
1467
1468 bool Arguments::should_auto_select_low_pause_collector() {
1469 if (UseAutoGCSelectPolicy &&
1470 !FLAG_IS_DEFAULT(MaxGCPauseMillis) &&
1471 (MaxGCPauseMillis <= AutoGCSelectPauseMillis)) {
1472 if (PrintGCDetails) {
1473 // Cannot use gclog_or_tty yet.
1474 tty->print_cr("Automatic selection of the low pause collector"
1475 " based on pause goal of %d (ms)", (int) MaxGCPauseMillis);
1476 }
1477 return true;
1478 }
1479 return false;
1480 }
1481
1482 void Arguments::set_use_compressed_oops() {
1483 #ifndef ZERO
1484 #ifdef _LP64
1485 // MaxHeapSize is not set up properly at this point, but
1486 // the only value that can override MaxHeapSize if we are
1487 // to use UseCompressedOops is InitialHeapSize.
1488 size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);
1489
1490 if (max_heap_size <= max_heap_for_compressed_oops()) {
1491 #if !defined(COMPILER1) || defined(TIERED)
1492 if (FLAG_IS_DEFAULT(UseCompressedOops)) {
1493 FLAG_SET_ERGO(bool, UseCompressedOops, true);
1494 }
1495 #endif
1496 } else {
1497 if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
1498 warning("Max heap size too large for Compressed Oops");
1499 FLAG_SET_DEFAULT(UseCompressedOops, false);
1500 FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1501 }
1502 }
1503 #endif // _LP64
1504 #endif // ZERO
1505 }
1506
1507
1508 // NOTE: set_use_compressed_klass_ptrs() must be called after calling
1509 // set_use_compressed_oops().
1510 void Arguments::set_use_compressed_klass_ptrs() {
1511 #ifndef ZERO
1512 #ifdef _LP64
1513 // UseCompressedOops must be on for UseCompressedClassPointers to be on.
1514 if (!UseCompressedOops) {
1515 if (UseCompressedClassPointers) {
1516 warning("UseCompressedClassPointers requires UseCompressedOops");
1517 }
1518 FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1519 } else {
1520 // Turn on UseCompressedClassPointers too
1521 if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
1522 FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);
1523 }
1524 // Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
1525 if (UseCompressedClassPointers) {
1526 if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
1527 warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
1528 FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1529 }
1530 }
1531 }
1532 #endif // _LP64
1533 #endif // !ZERO
1534 }
1535
1536 void Arguments::set_conservative_max_heap_alignment() {
1537 // The conservative maximum required alignment for the heap is the maximum of
1538 // the alignments imposed by several sources: any requirements from the heap
1539 // itself, the collector policy and the maximum page size we may run the VM
1540 // with.
1541 size_t heap_alignment = GenCollectedHeap::conservative_max_heap_alignment();
1542 #if INCLUDE_ALL_GCS
1543 if (UseParallelGC) {
1544 heap_alignment = ParallelScavengeHeap::conservative_max_heap_alignment();
1545 } else if (UseG1GC) {
1546 heap_alignment = G1CollectedHeap::conservative_max_heap_alignment();
1547 }
1548 #endif // INCLUDE_ALL_GCS
1549 _conservative_max_heap_alignment = MAX4(heap_alignment,
1550 (size_t)os::vm_allocation_granularity(),
1551 os::max_page_size(),
1552 CollectorPolicy::compute_heap_alignment());
1553 }
1554
1555 void Arguments::select_gc_ergonomically() {
1556 if (os::is_server_class_machine()) {
1557 if (should_auto_select_low_pause_collector()) {
1558 FLAG_SET_ERGO(bool, UseConcMarkSweepGC, true);
1559 } else {
1560 FLAG_SET_ERGO(bool, UseParallelGC, true);
1561 }
1562 } else {
1563 FLAG_SET_ERGO(bool, UseSerialGC, true);
1564 }
1565 }
1566
1567 void Arguments::select_gc() {
1568 if (!gc_selected()) {
1569 select_gc_ergonomically();
1570 guarantee(gc_selected(), "No GC selected");
1571 }
1572 }
1573
1574 void Arguments::set_ergonomics_flags() {
1575 select_gc();
1576
1577 #ifdef COMPILER2
1578 // Shared spaces work fine with other GCs but causes bytecode rewriting
1579 // to be disabled, which hurts interpreter performance and decreases
1580 // server performance. When -server is specified, keep the default off
1581 // unless it is asked for. Future work: either add bytecode rewriting
1582 // at link time, or rewrite bytecodes in non-shared methods.
1583 if (!DumpSharedSpaces && !RequireSharedSpaces &&
1584 (FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {
1585 no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");
1586 }
1587 #endif
1588
1589 set_conservative_max_heap_alignment();
1590
1591 #ifndef ZERO
1592 #ifdef _LP64
1593 set_use_compressed_oops();
1594
1595 // set_use_compressed_klass_ptrs() must be called after calling
1596 // set_use_compressed_oops().
1597 set_use_compressed_klass_ptrs();
1598
1599 // Also checks that certain machines are slower with compressed oops
1600 // in vm_version initialization code.
1601 #endif // _LP64
1602 #endif // !ZERO
1603 }
1604
1605 void Arguments::set_parallel_gc_flags() {
1606 assert(UseParallelGC || UseParallelOldGC, "Error");
1607 // Enable ParallelOld unless it was explicitly disabled (cmd line or rc file).
1608 if (FLAG_IS_DEFAULT(UseParallelOldGC)) {
1609 FLAG_SET_DEFAULT(UseParallelOldGC, true);
1610 }
1611 FLAG_SET_DEFAULT(UseParallelGC, true);
1612
1613 // If no heap maximum was requested explicitly, use some reasonable fraction
1614 // of the physical memory, up to a maximum of 1GB.
1615 FLAG_SET_DEFAULT(ParallelGCThreads,
1616 Abstract_VM_Version::parallel_worker_threads());
1617 if (ParallelGCThreads == 0) {
1618 jio_fprintf(defaultStream::error_stream(),
1619 "The Parallel GC can not be combined with -XX:ParallelGCThreads=0\n");
1620 vm_exit(1);
1621 }
1622
1623 if (UseAdaptiveSizePolicy) {
1624 // We don't want to limit adaptive heap sizing's freedom to adjust the heap
1625 // unless the user actually sets these flags.
1626 if (FLAG_IS_DEFAULT(MinHeapFreeRatio)) {
1627 FLAG_SET_DEFAULT(MinHeapFreeRatio, 0);
1628 _min_heap_free_ratio = MinHeapFreeRatio;
1629 }
1630 if (FLAG_IS_DEFAULT(MaxHeapFreeRatio)) {
1631 FLAG_SET_DEFAULT(MaxHeapFreeRatio, 100);
1632 _max_heap_free_ratio = MaxHeapFreeRatio;
1633 }
1634 }
1635
1636 // If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
1637 // SurvivorRatio has been set, reset their default values to SurvivorRatio +
1638 // 2. By doing this we make SurvivorRatio also work for Parallel Scavenger.
1639 // See CR 6362902 for details.
1640 if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
1641 if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
1642 FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
1643 }
1644 if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
1645 FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
1646 }
1647 }
1648
1649 if (UseParallelOldGC) {
1650 // Par compact uses lower default values since they are treated as
1651 // minimums. These are different defaults because of the different
1652 // interpretation and are not ergonomically set.
1653 if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
1654 FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
1655 }
1656 }
1657 }
1658
1659 void Arguments::set_g1_gc_flags() {
1660 assert(UseG1GC, "Error");
1661 #ifdef COMPILER1
1662 FastTLABRefill = false;
1663 #endif
1664 FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1665 if (ParallelGCThreads == 0) {
1666 assert(!FLAG_IS_DEFAULT(ParallelGCThreads), "The default value for ParallelGCThreads should not be 0.");
1667 vm_exit_during_initialization("The flag -XX:+UseG1GC can not be combined with -XX:ParallelGCThreads=0", NULL);
1668 }
1669
1670 #if INCLUDE_ALL_GCS
1671 if (G1ConcRefinementThreads == 0) {
1672 FLAG_SET_DEFAULT(G1ConcRefinementThreads, ParallelGCThreads);
1673 }
1674 #endif
1675
1676 // MarkStackSize will be set (if it hasn't been set by the user)
1677 // when concurrent marking is initialized.
1678 // Its value will be based upon the number of parallel marking threads.
1679 // But we do set the maximum mark stack size here.
1680 if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {
1681 FLAG_SET_DEFAULT(MarkStackSizeMax, 128 * TASKQUEUE_SIZE);
1682 }
1683
1684 if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {
1685 // In G1, we want the default GC overhead goal to be higher than
1686 // say in PS. So we set it here to 10%. Otherwise the heap might
1687 // be expanded more aggressively than we would like it to. In
1688 // fact, even 10% seems to not be high enough in some cases
1689 // (especially small GC stress tests that the main thing they do
1690 // is allocation). We might consider increase it further.
1691 FLAG_SET_DEFAULT(GCTimeRatio, 9);
1692 }
1693
1694 if (PrintGCDetails && Verbose) {
1695 tty->print_cr("MarkStackSize: %uk MarkStackSizeMax: %uk",
1696 (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1697 tty->print_cr("ConcGCThreads: %u", (uint) ConcGCThreads);
1698 }
1699 }
1700
1701 #if !INCLUDE_ALL_GCS
1702 #ifdef ASSERT
1703 static bool verify_serial_gc_flags() {
1704 return (UseSerialGC &&
1705 !(UseParNewGC || (UseConcMarkSweepGC) || UseG1GC ||
1706 UseParallelGC || UseParallelOldGC));
1707 }
1708 #endif // ASSERT
1709 #endif // INCLUDE_ALL_GCS
1710
1711 void Arguments::set_gc_specific_flags() {
1712 #if INCLUDE_ALL_GCS
1713 // Set per-collector flags
1714 if (UseParallelGC || UseParallelOldGC) {
1715 set_parallel_gc_flags();
1716 } else if (UseConcMarkSweepGC) {
1717 set_cms_and_parnew_gc_flags();
1718 } else if (UseG1GC) {
1719 set_g1_gc_flags();
1720 }
1721 check_deprecated_gc_flags();
1722 if (AssumeMP && !UseSerialGC) {
1723 if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) {
1724 warning("If the number of processors is expected to increase from one, then"
1725 " you should configure the number of parallel GC threads appropriately"
1726 " using -XX:ParallelGCThreads=N");
1727 }
1728 }
1729 if (MinHeapFreeRatio == 100) {
1730 // Keeping the heap 100% free is hard ;-) so limit it to 99%.
1731 FLAG_SET_ERGO(uintx, MinHeapFreeRatio, 99);
1732 }
1733 #else // INCLUDE_ALL_GCS
1734 assert(verify_serial_gc_flags(), "SerialGC unset");
1735 #endif // INCLUDE_ALL_GCS
1736 }
1737
1738 julong Arguments::limit_by_allocatable_memory(julong limit) {
1739 julong max_allocatable;
1740 julong result = limit;
1741 if (os::has_allocatable_memory_limit(&max_allocatable)) {
1742 result = MIN2(result, max_allocatable / MaxVirtMemFraction);
1743 }
1744 return result;
1745 }
1746
1747 // Use static initialization to get the default before parsing
1748 static const size_t DefaultHeapBaseMinAddress = HeapBaseMinAddress;
1749
1750 void Arguments::set_heap_size() {
1751 if (!FLAG_IS_DEFAULT(DefaultMaxRAMFraction)) {
1752 // Deprecated flag
1753 FLAG_SET_CMDLINE(uintx, MaxRAMFraction, DefaultMaxRAMFraction);
1754 }
1755
1756 const julong phys_mem =
1757 FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
1758 : (julong)MaxRAM;
1759
1760 // If the maximum heap size has not been set with -Xmx,
1761 // then set it as fraction of the size of physical memory,
1762 // respecting the maximum and minimum sizes of the heap.
1763 if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1764 julong reasonable_max = phys_mem / MaxRAMFraction;
1765
1766 if (phys_mem <= MaxHeapSize * MinRAMFraction) {
1767 // Small physical memory, so use a minimum fraction of it for the heap
1768 reasonable_max = phys_mem / MinRAMFraction;
1769 } else {
1770 // Not-small physical memory, so require a heap at least
1771 // as large as MaxHeapSize
1772 reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
1773 }
1774 if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
1775 // Limit the heap size to ErgoHeapSizeLimit
1776 reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
1777 }
1778 if (UseCompressedOops) {
1779 // Limit the heap size to the maximum possible when using compressed oops
1780 julong max_coop_heap = (julong)max_heap_for_compressed_oops();
1781
1782 // HeapBaseMinAddress can be greater than default but not less than.
1783 if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
1784 if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
1785 // matches compressed oops printing flags
1786 if (PrintCompressedOopsMode || (PrintMiscellaneous && Verbose)) {
1787 jio_fprintf(defaultStream::error_stream(),
1788 "HeapBaseMinAddress must be at least " SIZE_FORMAT
1789 " (" SIZE_FORMAT "G) which is greater than value given "
1790 SIZE_FORMAT "\n",
1791 DefaultHeapBaseMinAddress,
1792 DefaultHeapBaseMinAddress/G,
1793 HeapBaseMinAddress);
1794 }
1795 FLAG_SET_ERGO(size_t, HeapBaseMinAddress, DefaultHeapBaseMinAddress);
1796 }
1797 }
1798
1799 if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
1800 // Heap should be above HeapBaseMinAddress to get zero based compressed oops
1801 // but it should be not less than default MaxHeapSize.
1802 max_coop_heap -= HeapBaseMinAddress;
1803 }
1804 reasonable_max = MIN2(reasonable_max, max_coop_heap);
1805 }
1806 reasonable_max = limit_by_allocatable_memory(reasonable_max);
1807
1808 if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
1809 // An initial heap size was specified on the command line,
1810 // so be sure that the maximum size is consistent. Done
1811 // after call to limit_by_allocatable_memory because that
1812 // method might reduce the allocation size.
1813 reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
1814 }
1815
1816 if (PrintGCDetails && Verbose) {
1817 // Cannot use gclog_or_tty yet.
1818 tty->print_cr(" Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
1819 }
1820 FLAG_SET_ERGO(size_t, MaxHeapSize, (size_t)reasonable_max);
1821 }
1822
1823 // If the minimum or initial heap_size have not been set or requested to be set
1824 // ergonomically, set them accordingly.
1825 if (InitialHeapSize == 0 || min_heap_size() == 0) {
1826 julong reasonable_minimum = (julong)(OldSize + NewSize);
1827
1828 reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
1829
1830 reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
1831
1832 if (InitialHeapSize == 0) {
1833 julong reasonable_initial = phys_mem / InitialRAMFraction;
1834
1835 reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());
1836 reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
1837
1838 reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
1839
1840 if (PrintGCDetails && Verbose) {
1841 // Cannot use gclog_or_tty yet.
1842 tty->print_cr(" Initial heap size " SIZE_FORMAT, (size_t)reasonable_initial);
1843 }
1844 FLAG_SET_ERGO(size_t, InitialHeapSize, (size_t)reasonable_initial);
1845 }
1846 // If the minimum heap size has not been set (via -Xms),
1847 // synchronize with InitialHeapSize to avoid errors with the default value.
1848 if (min_heap_size() == 0) {
1849 set_min_heap_size(MIN2((size_t)reasonable_minimum, InitialHeapSize));
1850 if (PrintGCDetails && Verbose) {
1851 // Cannot use gclog_or_tty yet.
1852 tty->print_cr(" Minimum heap size " SIZE_FORMAT, min_heap_size());
1853 }
1854 }
1855 }
1856 }
1857
1858 // This must be called after ergonomics.
1859 void Arguments::set_bytecode_flags() {
1860 if (!RewriteBytecodes) {
1861 FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
1862 }
1863 }
1864
1865 // Aggressive optimization flags -XX:+AggressiveOpts
1866 void Arguments::set_aggressive_opts_flags() {
1867 #ifdef COMPILER2
1868 if (AggressiveUnboxing) {
1869 if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1870 FLAG_SET_DEFAULT(EliminateAutoBox, true);
1871 } else if (!EliminateAutoBox) {
1872 // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
1873 AggressiveUnboxing = false;
1874 }
1875 if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
1876 FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
1877 } else if (!DoEscapeAnalysis) {
1878 // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
1879 AggressiveUnboxing = false;
1880 }
1881 }
1882 if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1883 if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
1884 FLAG_SET_DEFAULT(EliminateAutoBox, true);
1885 }
1886 if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
1887 FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
1888 }
1889
1890 // Feed the cache size setting into the JDK
1891 char buffer[1024];
1892 sprintf(buffer, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
1893 add_property(buffer);
1894 }
1895 if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
1896 FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
1897 }
1898 #endif
1899
1900 if (AggressiveOpts) {
1901 // Sample flag setting code
1902 // if (FLAG_IS_DEFAULT(EliminateZeroing)) {
1903 // FLAG_SET_DEFAULT(EliminateZeroing, true);
1904 // }
1905 }
1906 }
1907
1908 //===========================================================================================================
1909 // Parsing of java.compiler property
1910
1911 void Arguments::process_java_compiler_argument(char* arg) {
1912 // For backwards compatibility, Djava.compiler=NONE or ""
1913 // causes us to switch to -Xint mode UNLESS -Xdebug
1914 // is also specified.
1915 if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
1916 set_java_compiler(true); // "-Djava.compiler[=...]" most recently seen.
1917 }
1918 }
1919
1920 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
1921 _sun_java_launcher = os::strdup_check_oom(launcher);
1922 }
1923
1924 bool Arguments::created_by_java_launcher() {
1925 assert(_sun_java_launcher != NULL, "property must have value");
1926 return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
1927 }
1928
1929 bool Arguments::sun_java_launcher_is_altjvm() {
1930 return _sun_java_launcher_is_altjvm;
1931 }
1932
1933 //===========================================================================================================
1934 // Parsing of main arguments
1935
1936 bool Arguments::verify_interval(uintx val, uintx min,
1937 uintx max, const char* name) {
1938 // Returns true iff value is in the inclusive interval [min..max]
1939 // false, otherwise.
1940 if (val >= min && val <= max) {
1941 return true;
1942 }
1943 jio_fprintf(defaultStream::error_stream(),
1944 "%s of " UINTX_FORMAT " is invalid; must be between " UINTX_FORMAT
1945 " and " UINTX_FORMAT "\n",
1946 name, val, min, max);
1947 return false;
1948 }
1949
1950 bool Arguments::verify_min_value(intx val, intx min, const char* name) {
1951 // Returns true if given value is at least specified min threshold
1952 // false, otherwise.
1953 if (val >= min ) {
1954 return true;
1955 }
1956 jio_fprintf(defaultStream::error_stream(),
1957 "%s of " INTX_FORMAT " is invalid; must be at least " INTX_FORMAT "\n",
1958 name, val, min);
1959 return false;
1960 }
1961
1962 bool Arguments::verify_percentage(uintx value, const char* name) {
1963 if (is_percentage(value)) {
1964 return true;
1965 }
1966 jio_fprintf(defaultStream::error_stream(),
1967 "%s of " UINTX_FORMAT " is invalid; must be between 0 and 100\n",
1968 name, value);
1969 return false;
1970 }
1971
1972 // check if do gclog rotation
1973 // +UseGCLogFileRotation is a must,
1974 // no gc log rotation when log file not supplied or
1975 // NumberOfGCLogFiles is 0
1976 void check_gclog_consistency() {
1977 if (UseGCLogFileRotation) {
1978 if ((Arguments::gc_log_filename() == NULL) || (NumberOfGCLogFiles == 0)) {
1979 jio_fprintf(defaultStream::output_stream(),
1980 "To enable GC log rotation, use -Xloggc:<filename> -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=<num_of_files>\n"
1981 "where num_of_file > 0\n"
1982 "GC log rotation is turned off\n");
1983 UseGCLogFileRotation = false;
1984 }
1985 }
1986
1987 if (UseGCLogFileRotation && (GCLogFileSize != 0) && (GCLogFileSize < 8*K)) {
1988 FLAG_SET_CMDLINE(size_t, GCLogFileSize, 8*K);
1989 jio_fprintf(defaultStream::output_stream(),
1990 "GCLogFileSize changed to minimum 8K\n");
1991 }
1992 }
1993
1994 // This function is called for -Xloggc:<filename>, it can be used
1995 // to check if a given file name(or string) conforms to the following
1996 // specification:
1997 // A valid string only contains "[A-Z][a-z][0-9].-_%[p|t]"
1998 // %p and %t only allowed once. We only limit usage of filename not path
1999 bool is_filename_valid(const char *file_name) {
2000 const char* p = file_name;
2001 char file_sep = os::file_separator()[0];
2002 const char* cp;
2003 // skip prefix path
2004 for (cp = file_name; *cp != '\0'; cp++) {
2005 if (*cp == '/' || *cp == file_sep) {
2006 p = cp + 1;
2007 }
2008 }
2009
2010 int count_p = 0;
2011 int count_t = 0;
2012 while (*p != '\0') {
2013 if ((*p >= '0' && *p <= '9') ||
2014 (*p >= 'A' && *p <= 'Z') ||
2015 (*p >= 'a' && *p <= 'z') ||
2016 *p == '-' ||
2017 *p == '_' ||
2018 *p == '.') {
2019 p++;
2020 continue;
2021 }
2022 if (*p == '%') {
2023 if(*(p + 1) == 'p') {
2024 p += 2;
2025 count_p ++;
2026 continue;
2027 }
2028 if (*(p + 1) == 't') {
2029 p += 2;
2030 count_t ++;
2031 continue;
2032 }
2033 }
2034 return false;
2035 }
2036 return count_p < 2 && count_t < 2;
2037 }
2038
2039 bool Arguments::verify_MinHeapFreeRatio(FormatBuffer<80>& err_msg, uintx min_heap_free_ratio) {
2040 if (!is_percentage(min_heap_free_ratio)) {
2041 err_msg.print("MinHeapFreeRatio must have a value between 0 and 100");
2042 return false;
2043 }
2044 if (min_heap_free_ratio > MaxHeapFreeRatio) {
2045 err_msg.print("MinHeapFreeRatio (" UINTX_FORMAT ") must be less than or "
2046 "equal to MaxHeapFreeRatio (" UINTX_FORMAT ")", min_heap_free_ratio,
2047 MaxHeapFreeRatio);
2048 return false;
2049 }
2050 // This does not set the flag itself, but stores the value in a safe place for later usage.
2051 _min_heap_free_ratio = min_heap_free_ratio;
2052 return true;
2053 }
2054
2055 bool Arguments::verify_MaxHeapFreeRatio(FormatBuffer<80>& err_msg, uintx max_heap_free_ratio) {
2056 if (!is_percentage(max_heap_free_ratio)) {
2057 err_msg.print("MaxHeapFreeRatio must have a value between 0 and 100");
2058 return false;
2059 }
2060 if (max_heap_free_ratio < MinHeapFreeRatio) {
2061 err_msg.print("MaxHeapFreeRatio (" UINTX_FORMAT ") must be greater than or "
2062 "equal to MinHeapFreeRatio (" UINTX_FORMAT ")", max_heap_free_ratio,
2063 MinHeapFreeRatio);
2064 return false;
2065 }
2066 // This does not set the flag itself, but stores the value in a safe place for later usage.
2067 _max_heap_free_ratio = max_heap_free_ratio;
2068 return true;
2069 }
2070
2071 // Check consistency of GC selection
2072 bool Arguments::check_gc_consistency() {
2073 check_gclog_consistency();
2074 // Ensure that the user has not selected conflicting sets
2075 // of collectors.
2076 uint i = 0;
2077 if (UseSerialGC) i++;
2078 if (UseConcMarkSweepGC) i++;
2079 if (UseParallelGC || UseParallelOldGC) i++;
2080 if (UseG1GC) i++;
2081 if (i > 1) {
2082 jio_fprintf(defaultStream::error_stream(),
2083 "Conflicting collector combinations in option list; "
2084 "please refer to the release notes for the combinations "
2085 "allowed\n");
2086 return false;
2087 }
2088
2089 if (UseConcMarkSweepGC && !UseParNewGC) {
2090 jio_fprintf(defaultStream::error_stream(),
2091 "It is not possible to combine the DefNew young collector with the CMS collector.\n");
2092 return false;
2093 }
2094
2095 if (UseParNewGC && !UseConcMarkSweepGC) {
2096 jio_fprintf(defaultStream::error_stream(),
2097 "It is not possible to combine the ParNew young collector with any collector other than CMS.\n");
2098 return false;
2099 }
2100
2101 return true;
2102 }
2103
2104 void Arguments::check_deprecated_gc_flags() {
2105 if (FLAG_IS_CMDLINE(UseParNewGC)) {
2106 warning("The UseParNewGC flag is deprecated and will likely be removed in a future release");
2107 }
2108 if (FLAG_IS_CMDLINE(MaxGCMinorPauseMillis)) {
2109 warning("Using MaxGCMinorPauseMillis as minor pause goal is deprecated"
2110 "and will likely be removed in future release");
2111 }
2112 if (FLAG_IS_CMDLINE(DefaultMaxRAMFraction)) {
2113 warning("DefaultMaxRAMFraction is deprecated and will likely be removed in a future release. "
2114 "Use MaxRAMFraction instead.");
2115 }
2116 }
2117
2118 // Check stack pages settings
2119 bool Arguments::check_stack_pages()
2120 {
2121 bool status = true;
2122 status = status && verify_min_value(StackYellowPages, 1, "StackYellowPages");
2123 status = status && verify_min_value(StackRedPages, 1, "StackRedPages");
2124 // greater stack shadow pages can't generate instruction to bang stack
2125 status = status && verify_interval(StackShadowPages, 1, 50, "StackShadowPages");
2126 return status;
2127 }
2128
2129 // Check the consistency of vm_init_args
2130 bool Arguments::check_vm_args_consistency() {
2131 // Method for adding checks for flag consistency.
2132 // The intent is to warn the user of all possible conflicts,
2133 // before returning an error.
2134 // Note: Needs platform-dependent factoring.
2135 bool status = true;
2136
2137 if (TLABRefillWasteFraction == 0) {
2138 jio_fprintf(defaultStream::error_stream(),
2139 "TLABRefillWasteFraction should be a denominator, "
2140 "not " SIZE_FORMAT "\n",
2141 TLABRefillWasteFraction);
2142 status = false;
2143 }
2144
2145 status = status && verify_interval(AdaptiveSizePolicyWeight, 0, 100,
2146 "AdaptiveSizePolicyWeight");
2147 status = status && verify_percentage(ThresholdTolerance, "ThresholdTolerance");
2148
2149 // Divide by bucket size to prevent a large size from causing rollover when
2150 // calculating amount of memory needed to be allocated for the String table.
2151 status = status && verify_interval(StringTableSize, minimumStringTableSize,
2152 (max_uintx / StringTable::bucket_size()), "StringTable size");
2153
2154 status = status && verify_interval(SymbolTableSize, minimumSymbolTableSize,
2155 (max_uintx / SymbolTable::bucket_size()), "SymbolTable size");
2156
2157 {
2158 // Using "else if" below to avoid printing two error messages if min > max.
2159 // This will also prevent us from reporting both min>100 and max>100 at the
2160 // same time, but that is less annoying than printing two identical errors IMHO.
2161 FormatBuffer<80> err_msg("%s","");
2162 if (!verify_MinHeapFreeRatio(err_msg, MinHeapFreeRatio)) {
2163 jio_fprintf(defaultStream::error_stream(), "%s\n", err_msg.buffer());
2164 status = false;
2165 } else if (!verify_MaxHeapFreeRatio(err_msg, MaxHeapFreeRatio)) {
2166 jio_fprintf(defaultStream::error_stream(), "%s\n", err_msg.buffer());
2167 status = false;
2168 }
2169 }
2170
2171 // Min/MaxMetaspaceFreeRatio
2172 status = status && verify_percentage(MinMetaspaceFreeRatio, "MinMetaspaceFreeRatio");
2173 status = status && verify_percentage(MaxMetaspaceFreeRatio, "MaxMetaspaceFreeRatio");
2174
2175 if (MinMetaspaceFreeRatio > MaxMetaspaceFreeRatio) {
2176 jio_fprintf(defaultStream::error_stream(),
2177 "MinMetaspaceFreeRatio (%s" UINTX_FORMAT ") must be less than or "
2178 "equal to MaxMetaspaceFreeRatio (%s" UINTX_FORMAT ")\n",
2179 FLAG_IS_DEFAULT(MinMetaspaceFreeRatio) ? "Default: " : "",
2180 MinMetaspaceFreeRatio,
2181 FLAG_IS_DEFAULT(MaxMetaspaceFreeRatio) ? "Default: " : "",
2182 MaxMetaspaceFreeRatio);
2183 status = false;
2184 }
2185
2186 // Trying to keep 100% free is not practical
2187 MinMetaspaceFreeRatio = MIN2(MinMetaspaceFreeRatio, (uintx) 99);
2188
2189 if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {
2190 MarkSweepAlwaysCompactCount = 1; // Move objects every gc.
2191 }
2192
2193 if (UseParallelOldGC && ParallelOldGCSplitALot) {
2194 // Settings to encourage splitting.
2195 if (!FLAG_IS_CMDLINE(NewRatio)) {
2196 FLAG_SET_CMDLINE(uintx, NewRatio, 2);
2197 }
2198 if (!FLAG_IS_CMDLINE(ScavengeBeforeFullGC)) {
2199 FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
2200 }
2201 }
2202
2203 if (!(UseParallelGC || UseParallelOldGC) && FLAG_IS_DEFAULT(ScavengeBeforeFullGC)) {
2204 FLAG_SET_DEFAULT(ScavengeBeforeFullGC, false);
2205 }
2206
2207 status = status && verify_percentage(GCHeapFreeLimit, "GCHeapFreeLimit");
2208 status = status && verify_percentage(GCTimeLimit, "GCTimeLimit");
2209 if (GCTimeLimit == 100) {
2210 // Turn off gc-overhead-limit-exceeded checks
2211 FLAG_SET_DEFAULT(UseGCOverheadLimit, false);
2212 }
2213
2214 status = status && check_gc_consistency();
2215 status = status && check_stack_pages();
2216
2217 status = status && verify_percentage(CMSIncrementalSafetyFactor,
2218 "CMSIncrementalSafetyFactor");
2219
2220 // CMS space iteration, which FLSVerifyAllHeapreferences entails,
2221 // insists that we hold the requisite locks so that the iteration is
2222 // MT-safe. For the verification at start-up and shut-down, we don't
2223 // yet have a good way of acquiring and releasing these locks,
2224 // which are not visible at the CollectedHeap level. We want to
2225 // be able to acquire these locks and then do the iteration rather
2226 // than just disable the lock verification. This will be fixed under
2227 // bug 4788986.
2228 if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {
2229 if (VerifyDuringStartup) {
2230 warning("Heap verification at start-up disabled "
2231 "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2232 VerifyDuringStartup = false; // Disable verification at start-up
2233 }
2234
2235 if (VerifyBeforeExit) {
2236 warning("Heap verification at shutdown disabled "
2237 "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2238 VerifyBeforeExit = false; // Disable verification at shutdown
2239 }
2240 }
2241
2242 // Note: only executed in non-PRODUCT mode
2243 if (!UseAsyncConcMarkSweepGC &&
2244 (ExplicitGCInvokesConcurrent ||
2245 ExplicitGCInvokesConcurrentAndUnloadsClasses)) {
2246 jio_fprintf(defaultStream::error_stream(),
2247 "error: +ExplicitGCInvokesConcurrent[AndUnloadsClasses] conflicts"
2248 " with -UseAsyncConcMarkSweepGC");
2249 status = false;
2250 }
2251
2252 status = status && verify_min_value(ParGCArrayScanChunk, 1, "ParGCArrayScanChunk");
2253
2254 #if INCLUDE_ALL_GCS
2255 if (UseG1GC) {
2256 status = status && verify_percentage(G1NewSizePercent, "G1NewSizePercent");
2257 status = status && verify_percentage(G1MaxNewSizePercent, "G1MaxNewSizePercent");
2258 status = status && verify_interval(G1NewSizePercent, 0, G1MaxNewSizePercent, "G1NewSizePercent");
2259
2260 status = status && verify_percentage(G1ConfidencePercent, "G1ConfidencePercent");
2261 status = status && verify_percentage(InitiatingHeapOccupancyPercent,
2262 "InitiatingHeapOccupancyPercent");
2263 status = status && verify_min_value(G1RefProcDrainInterval, 1,
2264 "G1RefProcDrainInterval");
2265 status = status && verify_min_value((intx)G1ConcMarkStepDurationMillis, 1,
2266 "G1ConcMarkStepDurationMillis");
2267 status = status && verify_interval(G1ConcRSHotCardLimit, 0, max_jubyte,
2268 "G1ConcRSHotCardLimit");
2269 status = status && verify_interval(G1ConcRSLogCacheSize, 0, 27,
2270 "G1ConcRSLogCacheSize");
2271 status = status && verify_interval(StringDeduplicationAgeThreshold, 1, markOopDesc::max_age,
2272 "StringDeduplicationAgeThreshold");
2273 }
2274 if (UseConcMarkSweepGC) {
2275 status = status && verify_min_value(CMSOldPLABNumRefills, 1, "CMSOldPLABNumRefills");
2276 status = status && verify_min_value(CMSOldPLABToleranceFactor, 1, "CMSOldPLABToleranceFactor");
2277 status = status && verify_min_value(CMSOldPLABMax, 1, "CMSOldPLABMax");
2278 status = status && verify_interval(CMSOldPLABMin, 1, CMSOldPLABMax, "CMSOldPLABMin");
2279
2280 status = status && verify_min_value(CMSYoungGenPerWorker, 1, "CMSYoungGenPerWorker");
2281
2282 status = status && verify_min_value(CMSSamplingGrain, 1, "CMSSamplingGrain");
2283 status = status && verify_interval(CMS_SweepWeight, 0, 100, "CMS_SweepWeight");
2284 status = status && verify_interval(CMS_FLSWeight, 0, 100, "CMS_FLSWeight");
2285
2286 status = status && verify_interval(FLSCoalescePolicy, 0, 4, "FLSCoalescePolicy");
2287
2288 status = status && verify_min_value(CMSRescanMultiple, 1, "CMSRescanMultiple");
2289 status = status && verify_min_value(CMSConcMarkMultiple, 1, "CMSConcMarkMultiple");
2290
2291 status = status && verify_interval(CMSPrecleanIter, 0, 9, "CMSPrecleanIter");
2292 status = status && verify_min_value(CMSPrecleanDenominator, 1, "CMSPrecleanDenominator");
2293 status = status && verify_interval(CMSPrecleanNumerator, 0, CMSPrecleanDenominator - 1, "CMSPrecleanNumerator");
2294
2295 status = status && verify_percentage(CMSBootstrapOccupancy, "CMSBootstrapOccupancy");
2296
2297 status = status && verify_min_value(CMSPrecleanThreshold, 100, "CMSPrecleanThreshold");
2298
2299 status = status && verify_percentage(CMSScheduleRemarkEdenPenetration, "CMSScheduleRemarkEdenPenetration");
2300 status = status && verify_min_value(CMSScheduleRemarkSamplingRatio, 1, "CMSScheduleRemarkSamplingRatio");
2301 status = status && verify_min_value(CMSBitMapYieldQuantum, 1, "CMSBitMapYieldQuantum");
2302 status = status && verify_percentage(CMSTriggerRatio, "CMSTriggerRatio");
2303 status = status && verify_percentage(CMSIsTooFullPercentage, "CMSIsTooFullPercentage");
2304 }
2305
2306 if (UseParallelGC || UseParallelOldGC) {
2307 status = status && verify_interval(ParallelOldDeadWoodLimiterMean, 0, 100, "ParallelOldDeadWoodLimiterMean");
2308 status = status && verify_interval(ParallelOldDeadWoodLimiterStdDev, 0, 100, "ParallelOldDeadWoodLimiterStdDev");
2309
2310 status = status && verify_percentage(YoungGenerationSizeIncrement, "YoungGenerationSizeIncrement");
2311 status = status && verify_percentage(TenuredGenerationSizeIncrement, "TenuredGenerationSizeIncrement");
2312
2313 status = status && verify_min_value(YoungGenerationSizeSupplementDecay, 1, "YoungGenerationSizeSupplementDecay");
2314 status = status && verify_min_value(TenuredGenerationSizeSupplementDecay, 1, "TenuredGenerationSizeSupplementDecay");
2315
2316 status = status && verify_min_value(ParGCCardsPerStrideChunk, 1, "ParGCCardsPerStrideChunk");
2317
2318 status = status && verify_min_value(ParallelOldGCSplitInterval, 0, "ParallelOldGCSplitInterval");
2319 }
2320 #endif // INCLUDE_ALL_GCS
2321
2322 status = status && verify_interval(RefDiscoveryPolicy,
2323 ReferenceProcessor::DiscoveryPolicyMin,
2324 ReferenceProcessor::DiscoveryPolicyMax,
2325 "RefDiscoveryPolicy");
2326
2327 // Limit the lower bound of this flag to 1 as it is used in a division
2328 // expression.
2329 status = status && verify_interval(TLABWasteTargetPercent,
2330 1, 100, "TLABWasteTargetPercent");
2331
2332 status = status && verify_object_alignment();
2333
2334 status = status && verify_interval(CompressedClassSpaceSize, 1*M, 3*G,
2335 "CompressedClassSpaceSize");
2336
2337 status = status && verify_interval(MarkStackSizeMax,
2338 1, (max_jint - 1), "MarkStackSizeMax");
2339 status = status && verify_interval(NUMAChunkResizeWeight, 0, 100, "NUMAChunkResizeWeight");
2340
2341 status = status && verify_min_value(LogEventsBufferEntries, 1, "LogEventsBufferEntries");
2342
2343 status = status && verify_min_value(HeapSizePerGCThread, (size_t) os::vm_page_size(), "HeapSizePerGCThread");
2344
2345 status = status && verify_min_value(GCTaskTimeStampEntries, 1, "GCTaskTimeStampEntries");
2346
2347 status = status && verify_percentage(ParallelGCBufferWastePct, "ParallelGCBufferWastePct");
2348 status = status && verify_interval(TargetPLABWastePct, 1, 100, "TargetPLABWastePct");
2349
2350 status = status && verify_min_value(ParGCStridesPerThread, 1, "ParGCStridesPerThread");
2351
2352 status = status && verify_min_value(MinRAMFraction, 1, "MinRAMFraction");
2353 status = status && verify_min_value(InitialRAMFraction, 1, "InitialRAMFraction");
2354 status = status && verify_min_value(MaxRAMFraction, 1, "MaxRAMFraction");
2355 status = status && verify_min_value(DefaultMaxRAMFraction, 1, "DefaultMaxRAMFraction");
2356
2357 status = status && verify_interval(AdaptiveTimeWeight, 0, 100, "AdaptiveTimeWeight");
2358 status = status && verify_min_value(AdaptiveSizeDecrementScaleFactor, 1, "AdaptiveSizeDecrementScaleFactor");
2359
2360 status = status && verify_interval(TLABAllocationWeight, 0, 100, "TLABAllocationWeight");
2361 status = status && verify_min_value(MinTLABSize, 1, "MinTLABSize");
2362 status = status && verify_min_value(TLABRefillWasteFraction, 1, "TLABRefillWasteFraction");
2363
2364 status = status && verify_percentage(YoungGenerationSizeSupplement, "YoungGenerationSizeSupplement");
2365 status = status && verify_percentage(TenuredGenerationSizeSupplement, "TenuredGenerationSizeSupplement");
2366
2367 status = status && verify_interval(MaxTenuringThreshold, 0, markOopDesc::max_age + 1, "MaxTenuringThreshold");
2368 status = status && verify_interval(InitialTenuringThreshold, 0, MaxTenuringThreshold, "InitialTenuringThreshold");
2369 status = status && verify_percentage(TargetSurvivorRatio, "TargetSurvivorRatio");
2370 status = status && verify_percentage(MarkSweepDeadRatio, "MarkSweepDeadRatio");
2371
2372 status = status && verify_min_value(MarkSweepAlwaysCompactCount, 1, "MarkSweepAlwaysCompactCount");
2373 #ifdef COMPILER1
2374 status = status && verify_min_value(ValueMapInitialSize, 1, "ValueMapInitialSize");
2375 #endif
2376 status = status && verify_min_value(HeapSearchSteps, 1, "HeapSearchSteps");
2377
2378 if (PrintNMTStatistics) {
2379 #if INCLUDE_NMT
2380 if (MemTracker::tracking_level() == NMT_off) {
2381 #endif // INCLUDE_NMT
2382 warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
2383 PrintNMTStatistics = false;
2384 #if INCLUDE_NMT
2385 }
2386 #endif
2387 }
2388
2389 // Need to limit the extent of the padding to reasonable size.
2390 // 8K is well beyond the reasonable HW cache line size, even with the
2391 // aggressive prefetching, while still leaving the room for segregating
2392 // among the distinct pages.
2393 if (ContendedPaddingWidth < 0 || ContendedPaddingWidth > 8192) {
2394 jio_fprintf(defaultStream::error_stream(),
2395 "ContendedPaddingWidth=" INTX_FORMAT " must be in between %d and %d\n",
2396 ContendedPaddingWidth, 0, 8192);
2397 status = false;
2398 }
2399
2400 // Need to enforce the padding not to break the existing field alignments.
2401 // It is sufficient to check against the largest type size.
2402 if ((ContendedPaddingWidth % BytesPerLong) != 0) {
2403 jio_fprintf(defaultStream::error_stream(),
2404 "ContendedPaddingWidth=" INTX_FORMAT " must be a multiple of %d\n",
2405 ContendedPaddingWidth, BytesPerLong);
2406 status = false;
2407 }
2408
2409 // Check lower bounds of the code cache
2410 // Template Interpreter code is approximately 3X larger in debug builds.
2411 uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
2412 if (InitialCodeCacheSize < (uintx)os::vm_page_size()) {
2413 jio_fprintf(defaultStream::error_stream(),
2414 "Invalid InitialCodeCacheSize=%dK. Must be at least %dK.\n", InitialCodeCacheSize/K,
2415 os::vm_page_size()/K);
2416 status = false;
2417 } else if (ReservedCodeCacheSize < InitialCodeCacheSize) {
2418 jio_fprintf(defaultStream::error_stream(),
2419 "Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",
2420 ReservedCodeCacheSize/K, InitialCodeCacheSize/K);
2421 status = false;
2422 } else if (ReservedCodeCacheSize < min_code_cache_size) {
2423 jio_fprintf(defaultStream::error_stream(),
2424 "Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,
2425 min_code_cache_size/K);
2426 status = false;
2427 } else if (ReservedCodeCacheSize > CODE_CACHE_SIZE_LIMIT) {
2428 // Code cache size larger than CODE_CACHE_SIZE_LIMIT is not supported.
2429 jio_fprintf(defaultStream::error_stream(),
2430 "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,
2431 CODE_CACHE_SIZE_LIMIT/M);
2432 status = false;
2433 } else if (NonNMethodCodeHeapSize < min_code_cache_size){
2434 jio_fprintf(defaultStream::error_stream(),
2435 "Invalid NonNMethodCodeHeapSize=%dK. Must be at least %uK.\n", NonNMethodCodeHeapSize/K,
2436 min_code_cache_size/K);
2437 status = false;
2438 } else if ((!FLAG_IS_DEFAULT(NonNMethodCodeHeapSize) || !FLAG_IS_DEFAULT(ProfiledCodeHeapSize) || !FLAG_IS_DEFAULT(NonProfiledCodeHeapSize))
2439 && (NonNMethodCodeHeapSize + NonProfiledCodeHeapSize + ProfiledCodeHeapSize) != ReservedCodeCacheSize) {
2440 jio_fprintf(defaultStream::error_stream(),
2441 "Invalid code heap sizes: NonNMethodCodeHeapSize(%dK) + ProfiledCodeHeapSize(%dK) + NonProfiledCodeHeapSize(%dK) = %dK. Must be equal to ReservedCodeCacheSize = %uK.\n",
2442 NonNMethodCodeHeapSize/K, ProfiledCodeHeapSize/K, NonProfiledCodeHeapSize/K,
2443 (NonNMethodCodeHeapSize + ProfiledCodeHeapSize + NonProfiledCodeHeapSize)/K, ReservedCodeCacheSize/K);
2444 status = false;
2445 }
2446
2447 status &= verify_interval(NmethodSweepActivity, 0, 2000, "NmethodSweepActivity");
2448 status &= verify_interval(CodeCacheMinBlockLength, 1, 100, "CodeCacheMinBlockLength");
2449 status &= verify_interval(CodeCacheSegmentSize, 1, 1024, "CodeCacheSegmentSize");
2450 status &= verify_interval(StartAggressiveSweepingAt, 0, 100, "StartAggressiveSweepingAt");
2451
2452
2453 int min_number_of_compiler_threads = get_min_number_of_compiler_threads();
2454 // The default CICompilerCount's value is CI_COMPILER_COUNT.
2455 assert(min_number_of_compiler_threads <= CI_COMPILER_COUNT, "minimum should be less or equal default number");
2456 // Check the minimum number of compiler threads
2457 status &=verify_min_value(CICompilerCount, min_number_of_compiler_threads, "CICompilerCount");
2458
2459 if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {
2460 warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");
2461 }
2462
2463 return status;
2464 }
2465
2466 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
2467 const char* option_type) {
2468 if (ignore) return false;
2469
2470 const char* spacer = " ";
2471 if (option_type == NULL) {
2472 option_type = ++spacer; // Set both to the empty string.
2473 }
2474
2475 if (os::obsolete_option(option)) {
2476 jio_fprintf(defaultStream::error_stream(),
2477 "Obsolete %s%soption: %s\n", option_type, spacer,
2478 option->optionString);
2479 return false;
2480 } else {
2481 jio_fprintf(defaultStream::error_stream(),
2482 "Unrecognized %s%soption: %s\n", option_type, spacer,
2483 option->optionString);
2484 return true;
2485 }
2486 }
2487
2488 static const char* user_assertion_options[] = {
2489 "-da", "-ea", "-disableassertions", "-enableassertions", 0
2490 };
2491
2492 static const char* system_assertion_options[] = {
2493 "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
2494 };
2495
2496 bool Arguments::parse_uintx(const char* value,
2497 uintx* uintx_arg,
2498 uintx min_size) {
2499
2500 // Check the sign first since atomull() parses only unsigned values.
2501 bool value_is_positive = !(*value == '-');
2502
2503 if (value_is_positive) {
2504 julong n;
2505 bool good_return = atomull(value, &n);
2506 if (good_return) {
2507 bool above_minimum = n >= min_size;
2508 bool value_is_too_large = n > max_uintx;
2509
2510 if (above_minimum && !value_is_too_large) {
2511 *uintx_arg = n;
2512 return true;
2513 }
2514 }
2515 }
2516 return false;
2517 }
2518
2519 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2520 julong* long_arg,
2521 julong min_size) {
2522 if (!atomull(s, long_arg)) return arg_unreadable;
2523 return check_memory_size(*long_arg, min_size);
2524 }
2525
2526 // Parse JavaVMInitArgs structure
2527
2528 jint Arguments::parse_vm_init_args(const JavaVMInitArgs* args) {
2529 // For components of the system classpath.
2530 SysClassPath scp(Arguments::get_sysclasspath());
2531 bool scp_assembly_required = false;
2532
2533 // Save default settings for some mode flags
2534 Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
2535 Arguments::_UseOnStackReplacement = UseOnStackReplacement;
2536 Arguments::_ClipInlining = ClipInlining;
2537 Arguments::_BackgroundCompilation = BackgroundCompilation;
2538 if (TieredCompilation) {
2539 Arguments::_Tier3InvokeNotifyFreqLog = Tier3InvokeNotifyFreqLog;
2540 Arguments::_Tier4InvocationThreshold = Tier4InvocationThreshold;
2541 }
2542
2543 // Setup flags for mixed which is the default
2544 set_mode_flags(_mixed);
2545
2546 // Parse JAVA_TOOL_OPTIONS environment variable (if present)
2547 jint result = parse_java_tool_options_environment_variable(&scp, &scp_assembly_required);
2548 if (result != JNI_OK) {
2549 return result;
2550 }
2551
2552 // Parse JavaVMInitArgs structure passed in
2553 result = parse_each_vm_init_arg(args, &scp, &scp_assembly_required, Flag::COMMAND_LINE);
2554 if (result != JNI_OK) {
2555 return result;
2556 }
2557
2558 // Parse _JAVA_OPTIONS environment variable (if present) (mimics classic VM)
2559 result = parse_java_options_environment_variable(&scp, &scp_assembly_required);
2560 if (result != JNI_OK) {
2561 return result;
2562 }
2563
2564 // Do final processing now that all arguments have been parsed
2565 result = finalize_vm_init_args(&scp, scp_assembly_required);
2566 if (result != JNI_OK) {
2567 return result;
2568 }
2569
2570 return JNI_OK;
2571 }
2572
2573 // Checks if name in command-line argument -agent{lib,path}:name[=options]
2574 // represents a valid HPROF of JDWP agent. is_path==true denotes that we
2575 // are dealing with -agentpath (case where name is a path), otherwise with
2576 // -agentlib
2577 bool valid_hprof_or_jdwp_agent(char *name, bool is_path) {
2578 char *_name;
2579 const char *_hprof = "hprof", *_jdwp = "jdwp";
2580 size_t _len_hprof, _len_jdwp, _len_prefix;
2581
2582 if (is_path) {
2583 if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
2584 return false;
2585 }
2586
2587 _name++; // skip past last path separator
2588 _len_prefix = strlen(JNI_LIB_PREFIX);
2589
2590 if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2591 return false;
2592 }
2593
2594 _name += _len_prefix;
2595 _len_hprof = strlen(_hprof);
2596 _len_jdwp = strlen(_jdwp);
2597
2598 if (strncmp(_name, _hprof, _len_hprof) == 0) {
2599 _name += _len_hprof;
2600 }
2601 else if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2602 _name += _len_jdwp;
2603 }
2604 else {
2605 return false;
2606 }
2607
2608 if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2609 return false;
2610 }
2611
2612 return true;
2613 }
2614
2615 if (strcmp(name, _hprof) == 0 || strcmp(name, _jdwp) == 0) {
2616 return true;
2617 }
2618
2619 return false;
2620 }
2621
2622 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args,
2623 SysClassPath* scp_p,
2624 bool* scp_assembly_required_p,
2625 Flag::Flags origin) {
2626 // Remaining part of option string
2627 const char* tail;
2628
2629 // iterate over arguments
2630 for (int index = 0; index < args->nOptions; index++) {
2631 bool is_absolute_path = false; // for -agentpath vs -agentlib
2632
2633 const JavaVMOption* option = args->options + index;
2634
2635 if (!match_option(option, "-Djava.class.path", &tail) &&
2636 !match_option(option, "-Dsun.java.command", &tail) &&
2637 !match_option(option, "-Dsun.java.launcher", &tail)) {
2638
2639 // add all jvm options to the jvm_args string. This string
2640 // is used later to set the java.vm.args PerfData string constant.
2641 // the -Djava.class.path and the -Dsun.java.command options are
2642 // omitted from jvm_args string as each have their own PerfData
2643 // string constant object.
2644 build_jvm_args(option->optionString);
2645 }
2646
2647 // -verbose:[class/gc/jni]
2648 if (match_option(option, "-verbose", &tail)) {
2649 if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2650 FLAG_SET_CMDLINE(bool, TraceClassLoading, true);
2651 FLAG_SET_CMDLINE(bool, TraceClassUnloading, true);
2652 } else if (!strcmp(tail, ":gc")) {
2653 FLAG_SET_CMDLINE(bool, PrintGC, true);
2654 } else if (!strcmp(tail, ":jni")) {
2655 FLAG_SET_CMDLINE(bool, PrintJNIResolving, true);
2656 }
2657 // -da / -ea / -disableassertions / -enableassertions
2658 // These accept an optional class/package name separated by a colon, e.g.,
2659 // -da:java.lang.Thread.
2660 } else if (match_option(option, user_assertion_options, &tail, true)) {
2661 bool enable = option->optionString[1] == 'e'; // char after '-' is 'e'
2662 if (*tail == '\0') {
2663 JavaAssertions::setUserClassDefault(enable);
2664 } else {
2665 assert(*tail == ':', "bogus match by match_option()");
2666 JavaAssertions::addOption(tail + 1, enable);
2667 }
2668 // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2669 } else if (match_option(option, system_assertion_options, &tail, false)) {
2670 bool enable = option->optionString[1] == 'e'; // char after '-' is 'e'
2671 JavaAssertions::setSystemClassDefault(enable);
2672 // -bootclasspath:
2673 } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2674 scp_p->reset_path(tail);
2675 *scp_assembly_required_p = true;
2676 // -bootclasspath/a:
2677 } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2678 scp_p->add_suffix(tail);
2679 *scp_assembly_required_p = true;
2680 // -bootclasspath/p:
2681 } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2682 scp_p->add_prefix(tail);
2683 *scp_assembly_required_p = true;
2684 // -Xrun
2685 } else if (match_option(option, "-Xrun", &tail)) {
2686 if (tail != NULL) {
2687 const char* pos = strchr(tail, ':');
2688 size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2689 char* name = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2690 name[len] = '\0';
2691
2692 char *options = NULL;
2693 if(pos != NULL) {
2694 size_t len2 = strlen(pos+1) + 1; // options start after ':'. Final zero must be copied.
2695 options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtInternal), pos+1, len2);
2696 }
2697 #if !INCLUDE_JVMTI
2698 if ((strcmp(name, "hprof") == 0) || (strcmp(name, "jdwp") == 0)) {
2699 jio_fprintf(defaultStream::error_stream(),
2700 "Profiling and debugging agents are not supported in this VM\n");
2701 return JNI_ERR;
2702 }
2703 #endif // !INCLUDE_JVMTI
2704 add_init_library(name, options);
2705 }
2706 // -agentlib and -agentpath
2707 } else if (match_option(option, "-agentlib:", &tail) ||
2708 (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2709 if(tail != NULL) {
2710 const char* pos = strchr(tail, '=');
2711 size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2712 char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2713 name[len] = '\0';
2714
2715 char *options = NULL;
2716 if(pos != NULL) {
2717 options = os::strdup_check_oom(pos + 1, mtInternal);
2718 }
2719 #if !INCLUDE_JVMTI
2720 if (valid_hprof_or_jdwp_agent(name, is_absolute_path)) {
2721 jio_fprintf(defaultStream::error_stream(),
2722 "Profiling and debugging agents are not supported in this VM\n");
2723 return JNI_ERR;
2724 }
2725 #endif // !INCLUDE_JVMTI
2726 add_init_agent(name, options, is_absolute_path);
2727 }
2728 // -javaagent
2729 } else if (match_option(option, "-javaagent:", &tail)) {
2730 #if !INCLUDE_JVMTI
2731 jio_fprintf(defaultStream::error_stream(),
2732 "Instrumentation agents are not supported in this VM\n");
2733 return JNI_ERR;
2734 #else
2735 if(tail != NULL) {
2736 char *options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(tail) + 1, mtInternal), tail);
2737 add_init_agent("instrument", options, false);
2738 }
2739 #endif // !INCLUDE_JVMTI
2740 // -Xnoclassgc
2741 } else if (match_option(option, "-Xnoclassgc")) {
2742 FLAG_SET_CMDLINE(bool, ClassUnloading, false);
2743 // -Xconcgc
2744 } else if (match_option(option, "-Xconcgc")) {
2745 FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true);
2746 // -Xnoconcgc
2747 } else if (match_option(option, "-Xnoconcgc")) {
2748 FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false);
2749 // -Xbatch
2750 } else if (match_option(option, "-Xbatch")) {
2751 FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
2752 // -Xmn for compatibility with other JVM vendors
2753 } else if (match_option(option, "-Xmn", &tail)) {
2754 julong long_initial_young_size = 0;
2755 ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2756 if (errcode != arg_in_range) {
2757 jio_fprintf(defaultStream::error_stream(),
2758 "Invalid initial young generation size: %s\n", option->optionString);
2759 describe_range_error(errcode);
2760 return JNI_EINVAL;
2761 }
2762 FLAG_SET_CMDLINE(size_t, MaxNewSize, (size_t)long_initial_young_size);
2763 FLAG_SET_CMDLINE(size_t, NewSize, (size_t)long_initial_young_size);
2764 // -Xms
2765 } else if (match_option(option, "-Xms", &tail)) {
2766 julong long_initial_heap_size = 0;
2767 // an initial heap size of 0 means automatically determine
2768 ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);
2769 if (errcode != arg_in_range) {
2770 jio_fprintf(defaultStream::error_stream(),
2771 "Invalid initial heap size: %s\n", option->optionString);
2772 describe_range_error(errcode);
2773 return JNI_EINVAL;
2774 }
2775 set_min_heap_size((size_t)long_initial_heap_size);
2776 // Currently the minimum size and the initial heap sizes are the same.
2777 // Can be overridden with -XX:InitialHeapSize.
2778 FLAG_SET_CMDLINE(size_t, InitialHeapSize, (size_t)long_initial_heap_size);
2779 // -Xmx
2780 } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2781 julong long_max_heap_size = 0;
2782 ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2783 if (errcode != arg_in_range) {
2784 jio_fprintf(defaultStream::error_stream(),
2785 "Invalid maximum heap size: %s\n", option->optionString);
2786 describe_range_error(errcode);
2787 return JNI_EINVAL;
2788 }
2789 FLAG_SET_CMDLINE(size_t, MaxHeapSize, (size_t)long_max_heap_size);
2790 // Xmaxf
2791 } else if (match_option(option, "-Xmaxf", &tail)) {
2792 char* err;
2793 int maxf = (int)(strtod(tail, &err) * 100);
2794 if (*err != '\0' || *tail == '\0' || maxf < 0 || maxf > 100) {
2795 jio_fprintf(defaultStream::error_stream(),
2796 "Bad max heap free percentage size: %s\n",
2797 option->optionString);
2798 return JNI_EINVAL;
2799 } else {
2800 FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf);
2801 }
2802 // Xminf
2803 } else if (match_option(option, "-Xminf", &tail)) {
2804 char* err;
2805 int minf = (int)(strtod(tail, &err) * 100);
2806 if (*err != '\0' || *tail == '\0' || minf < 0 || minf > 100) {
2807 jio_fprintf(defaultStream::error_stream(),
2808 "Bad min heap free percentage size: %s\n",
2809 option->optionString);
2810 return JNI_EINVAL;
2811 } else {
2812 FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf);
2813 }
2814 // -Xss
2815 } else if (match_option(option, "-Xss", &tail)) {
2816 julong long_ThreadStackSize = 0;
2817 ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);
2818 if (errcode != arg_in_range) {
2819 jio_fprintf(defaultStream::error_stream(),
2820 "Invalid thread stack size: %s\n", option->optionString);
2821 describe_range_error(errcode);
2822 return JNI_EINVAL;
2823 }
2824 // Internally track ThreadStackSize in units of 1024 bytes.
2825 FLAG_SET_CMDLINE(intx, ThreadStackSize,
2826 round_to((int)long_ThreadStackSize, K) / K);
2827 // -Xoss
2828 } else if (match_option(option, "-Xoss", &tail)) {
2829 // HotSpot does not have separate native and Java stacks, ignore silently for compatibility
2830 } else if (match_option(option, "-XX:CodeCacheExpansionSize=", &tail)) {
2831 julong long_CodeCacheExpansionSize = 0;
2832 ArgsRange errcode = parse_memory_size(tail, &long_CodeCacheExpansionSize, os::vm_page_size());
2833 if (errcode != arg_in_range) {
2834 jio_fprintf(defaultStream::error_stream(),
2835 "Invalid argument: %s. Must be at least %luK.\n", option->optionString,
2836 os::vm_page_size()/K);
2837 return JNI_EINVAL;
2838 }
2839 FLAG_SET_CMDLINE(uintx, CodeCacheExpansionSize, (uintx)long_CodeCacheExpansionSize);
2840 } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
2841 match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
2842 julong long_ReservedCodeCacheSize = 0;
2843
2844 ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
2845 if (errcode != arg_in_range) {
2846 jio_fprintf(defaultStream::error_stream(),
2847 "Invalid maximum code cache size: %s.\n", option->optionString);
2848 return JNI_EINVAL;
2849 }
2850 FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize);
2851 // -XX:NonNMethodCodeHeapSize=
2852 } else if (match_option(option, "-XX:NonNMethodCodeHeapSize=", &tail)) {
2853 julong long_NonNMethodCodeHeapSize = 0;
2854
2855 ArgsRange errcode = parse_memory_size(tail, &long_NonNMethodCodeHeapSize, 1);
2856 if (errcode != arg_in_range) {
2857 jio_fprintf(defaultStream::error_stream(),
2858 "Invalid maximum non-nmethod code heap size: %s.\n", option->optionString);
2859 return JNI_EINVAL;
2860 }
2861 FLAG_SET_CMDLINE(uintx, NonNMethodCodeHeapSize, (uintx)long_NonNMethodCodeHeapSize);
2862 // -XX:ProfiledCodeHeapSize=
2863 } else if (match_option(option, "-XX:ProfiledCodeHeapSize=", &tail)) {
2864 julong long_ProfiledCodeHeapSize = 0;
2865
2866 ArgsRange errcode = parse_memory_size(tail, &long_ProfiledCodeHeapSize, 1);
2867 if (errcode != arg_in_range) {
2868 jio_fprintf(defaultStream::error_stream(),
2869 "Invalid maximum profiled code heap size: %s.\n", option->optionString);
2870 return JNI_EINVAL;
2871 }
2872 FLAG_SET_CMDLINE(uintx, ProfiledCodeHeapSize, (uintx)long_ProfiledCodeHeapSize);
2873 // -XX:NonProfiledCodeHeapSizee=
2874 } else if (match_option(option, "-XX:NonProfiledCodeHeapSize=", &tail)) {
2875 julong long_NonProfiledCodeHeapSize = 0;
2876
2877 ArgsRange errcode = parse_memory_size(tail, &long_NonProfiledCodeHeapSize, 1);
2878 if (errcode != arg_in_range) {
2879 jio_fprintf(defaultStream::error_stream(),
2880 "Invalid maximum non-profiled code heap size: %s.\n", option->optionString);
2881 return JNI_EINVAL;
2882 }
2883 FLAG_SET_CMDLINE(uintx, NonProfiledCodeHeapSize, (uintx)long_NonProfiledCodeHeapSize);
2884 //-XX:IncreaseFirstTierCompileThresholdAt=
2885 } else if (match_option(option, "-XX:IncreaseFirstTierCompileThresholdAt=", &tail)) {
2886 uintx uint_IncreaseFirstTierCompileThresholdAt = 0;
2887 if (!parse_uintx(tail, &uint_IncreaseFirstTierCompileThresholdAt, 0) || uint_IncreaseFirstTierCompileThresholdAt > 99) {
2888 jio_fprintf(defaultStream::error_stream(),
2889 "Invalid value for IncreaseFirstTierCompileThresholdAt: %s. Should be between 0 and 99.\n",
2890 option->optionString);
2891 return JNI_EINVAL;
2892 }
2893 FLAG_SET_CMDLINE(uintx, IncreaseFirstTierCompileThresholdAt, (uintx)uint_IncreaseFirstTierCompileThresholdAt);
2894 // -green
2895 } else if (match_option(option, "-green")) {
2896 jio_fprintf(defaultStream::error_stream(),
2897 "Green threads support not available\n");
2898 return JNI_EINVAL;
2899 // -native
2900 } else if (match_option(option, "-native")) {
2901 // HotSpot always uses native threads, ignore silently for compatibility
2902 // -Xsqnopause
2903 } else if (match_option(option, "-Xsqnopause")) {
2904 // EVM option, ignore silently for compatibility
2905 // -Xrs
2906 } else if (match_option(option, "-Xrs")) {
2907 // Classic/EVM option, new functionality
2908 FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true);
2909 } else if (match_option(option, "-Xusealtsigs")) {
2910 // change default internal VM signals used - lower case for back compat
2911 FLAG_SET_CMDLINE(bool, UseAltSigs, true);
2912 // -Xoptimize
2913 } else if (match_option(option, "-Xoptimize")) {
2914 // EVM option, ignore silently for compatibility
2915 // -Xprof
2916 } else if (match_option(option, "-Xprof")) {
2917 #if INCLUDE_FPROF
2918 _has_profile = true;
2919 #else // INCLUDE_FPROF
2920 jio_fprintf(defaultStream::error_stream(),
2921 "Flat profiling is not supported in this VM.\n");
2922 return JNI_ERR;
2923 #endif // INCLUDE_FPROF
2924 // -Xconcurrentio
2925 } else if (match_option(option, "-Xconcurrentio")) {
2926 FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true);
2927 FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
2928 FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1);
2929 FLAG_SET_CMDLINE(bool, UseTLAB, false);
2930 FLAG_SET_CMDLINE(size_t, NewSizeThreadIncrease, 16 * K); // 20Kb per thread added to new generation
2931
2932 // -Xinternalversion
2933 } else if (match_option(option, "-Xinternalversion")) {
2934 jio_fprintf(defaultStream::output_stream(), "%s\n",
2935 VM_Version::internal_vm_info_string());
2936 vm_exit(0);
2937 #ifndef PRODUCT
2938 // -Xprintflags
2939 } else if (match_option(option, "-Xprintflags")) {
2940 CommandLineFlags::printFlags(tty, false);
2941 vm_exit(0);
2942 #endif
2943 // -D
2944 } else if (match_option(option, "-D", &tail)) {
2945 const char* value;
2946 if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
2947 *value!= '\0' && strcmp(value, "\"\"") != 0) {
2948 // abort if -Djava.endorsed.dirs is set
2949 jio_fprintf(defaultStream::output_stream(),
2950 "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
2951 "in modular form will be supported via the concept of upgradeable modules.\n", value);
2952 return JNI_EINVAL;
2953 }
2954 if (match_option(option, "-Djava.ext.dirs=", &value) &&
2955 *value != '\0' && strcmp(value, "\"\"") != 0) {
2956 // abort if -Djava.ext.dirs is set
2957 jio_fprintf(defaultStream::output_stream(),
2958 "-Djava.ext.dirs=%s is not supported. Use -classpath instead.\n", value);
2959 return JNI_EINVAL;
2960 }
2961
2962 if (!add_property(tail)) {
2963 return JNI_ENOMEM;
2964 }
2965 // Out of the box management support
2966 if (match_option(option, "-Dcom.sun.management", &tail)) {
2967 #if INCLUDE_MANAGEMENT
2968 FLAG_SET_CMDLINE(bool, ManagementServer, true);
2969 #else
2970 jio_fprintf(defaultStream::output_stream(),
2971 "-Dcom.sun.management is not supported in this VM.\n");
2972 return JNI_ERR;
2973 #endif
2974 }
2975 // -Xint
2976 } else if (match_option(option, "-Xint")) {
2977 set_mode_flags(_int);
2978 // -Xmixed
2979 } else if (match_option(option, "-Xmixed")) {
2980 set_mode_flags(_mixed);
2981 // -Xcomp
2982 } else if (match_option(option, "-Xcomp")) {
2983 // for testing the compiler; turn off all flags that inhibit compilation
2984 set_mode_flags(_comp);
2985 // -Xshare:dump
2986 } else if (match_option(option, "-Xshare:dump")) {
2987 FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true);
2988 set_mode_flags(_int); // Prevent compilation, which creates objects
2989 // -Xshare:on
2990 } else if (match_option(option, "-Xshare:on")) {
2991 FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
2992 FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true);
2993 // -Xshare:auto
2994 } else if (match_option(option, "-Xshare:auto")) {
2995 FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
2996 FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);
2997 // -Xshare:off
2998 } else if (match_option(option, "-Xshare:off")) {
2999 FLAG_SET_CMDLINE(bool, UseSharedSpaces, false);
3000 FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);
3001 // -Xverify
3002 } else if (match_option(option, "-Xverify", &tail)) {
3003 if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
3004 FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true);
3005 FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);
3006 } else if (strcmp(tail, ":remote") == 0) {
3007 FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);
3008 FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);
3009 } else if (strcmp(tail, ":none") == 0) {
3010 FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);
3011 FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false);
3012 } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
3013 return JNI_EINVAL;
3014 }
3015 // -Xdebug
3016 } else if (match_option(option, "-Xdebug")) {
3017 // note this flag has been used, then ignore
3018 set_xdebug_mode(true);
3019 // -Xnoagent
3020 } else if (match_option(option, "-Xnoagent")) {
3021 // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
3022 } else if (match_option(option, "-Xboundthreads")) {
3023 // Ignore silently for compatibility
3024 } else if (match_option(option, "-Xloggc:", &tail)) {
3025 // Redirect GC output to the file. -Xloggc:<filename>
3026 // ostream_init_log(), when called will use this filename
3027 // to initialize a fileStream.
3028 _gc_log_filename = os::strdup_check_oom(tail);
3029 if (!is_filename_valid(_gc_log_filename)) {
3030 jio_fprintf(defaultStream::output_stream(),
3031 "Invalid file name for use with -Xloggc: Filename can only contain the "
3032 "characters [A-Z][a-z][0-9]-_.%%[p|t] but it has been %s\n"
3033 "Note %%p or %%t can only be used once\n", _gc_log_filename);
3034 return JNI_EINVAL;
3035 }
3036 FLAG_SET_CMDLINE(bool, PrintGC, true);
3037 FLAG_SET_CMDLINE(bool, PrintGCTimeStamps, true);
3038
3039 // JNI hooks
3040 } else if (match_option(option, "-Xcheck", &tail)) {
3041 if (!strcmp(tail, ":jni")) {
3042 #if !INCLUDE_JNI_CHECK
3043 warning("JNI CHECKING is not supported in this VM");
3044 #else
3045 CheckJNICalls = true;
3046 #endif // INCLUDE_JNI_CHECK
3047 } else if (is_bad_option(option, args->ignoreUnrecognized,
3048 "check")) {
3049 return JNI_EINVAL;
3050 }
3051 } else if (match_option(option, "vfprintf")) {
3052 _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
3053 } else if (match_option(option, "exit")) {
3054 _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
3055 } else if (match_option(option, "abort")) {
3056 _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
3057 // -XX:+AggressiveHeap
3058 } else if (match_option(option, "-XX:+AggressiveHeap")) {
3059
3060 // This option inspects the machine and attempts to set various
3061 // parameters to be optimal for long-running, memory allocation
3062 // intensive jobs. It is intended for machines with large
3063 // amounts of cpu and memory.
3064
3065 // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
3066 // VM, but we may not be able to represent the total physical memory
3067 // available (like having 8gb of memory on a box but using a 32bit VM).
3068 // Thus, we need to make sure we're using a julong for intermediate
3069 // calculations.
3070 julong initHeapSize;
3071 julong total_memory = os::physical_memory();
3072
3073 if (total_memory < (julong)256*M) {
3074 jio_fprintf(defaultStream::error_stream(),
3075 "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
3076 vm_exit(1);
3077 }
3078
3079 // The heap size is half of available memory, or (at most)
3080 // all of possible memory less 160mb (leaving room for the OS
3081 // when using ISM). This is the maximum; because adaptive sizing
3082 // is turned on below, the actual space used may be smaller.
3083
3084 initHeapSize = MIN2(total_memory / (julong)2,
3085 total_memory - (julong)160*M);
3086
3087 initHeapSize = limit_by_allocatable_memory(initHeapSize);
3088
3089 if (FLAG_IS_DEFAULT(MaxHeapSize)) {
3090 FLAG_SET_CMDLINE(size_t, MaxHeapSize, initHeapSize);
3091 FLAG_SET_CMDLINE(size_t, InitialHeapSize, initHeapSize);
3092 // Currently the minimum size and the initial heap sizes are the same.
3093 set_min_heap_size(initHeapSize);
3094 }
3095 if (FLAG_IS_DEFAULT(NewSize)) {
3096 // Make the young generation 3/8ths of the total heap.
3097 FLAG_SET_CMDLINE(size_t, NewSize,
3098 ((julong)MaxHeapSize / (julong)8) * (julong)3);
3099 FLAG_SET_CMDLINE(size_t, MaxNewSize, NewSize);
3100 }
3101
3102 #if !defined(_ALLBSD_SOURCE) && !defined(AIX) // UseLargePages is not yet supported on BSD and AIX.
3103 FLAG_SET_DEFAULT(UseLargePages, true);
3104 #endif
3105
3106 // Increase some data structure sizes for efficiency
3107 FLAG_SET_CMDLINE(size_t, BaseFootPrintEstimate, MaxHeapSize);
3108 FLAG_SET_CMDLINE(bool, ResizeTLAB, false);
3109 FLAG_SET_CMDLINE(size_t, TLABSize, 256*K);
3110
3111 // See the OldPLABSize comment below, but replace 'after promotion'
3112 // with 'after copying'. YoungPLABSize is the size of the survivor
3113 // space per-gc-thread buffers. The default is 4kw.
3114 FLAG_SET_CMDLINE(size_t, YoungPLABSize, 256*K); // Note: this is in words
3115
3116 // OldPLABSize is the size of the buffers in the old gen that
3117 // UseParallelGC uses to promote live data that doesn't fit in the
3118 // survivor spaces. At any given time, there's one for each gc thread.
3119 // The default size is 1kw. These buffers are rarely used, since the
3120 // survivor spaces are usually big enough. For specjbb, however, there
3121 // are occasions when there's lots of live data in the young gen
3122 // and we end up promoting some of it. We don't have a definite
3123 // explanation for why bumping OldPLABSize helps, but the theory
3124 // is that a bigger PLAB results in retaining something like the
3125 // original allocation order after promotion, which improves mutator
3126 // locality. A minor effect may be that larger PLABs reduce the
3127 // number of PLAB allocation events during gc. The value of 8kw
3128 // was arrived at by experimenting with specjbb.
3129 FLAG_SET_CMDLINE(size_t, OldPLABSize, 8*K); // Note: this is in words
3130
3131 // Enable parallel GC and adaptive generation sizing
3132 FLAG_SET_CMDLINE(bool, UseParallelGC, true);
3133 FLAG_SET_DEFAULT(ParallelGCThreads,
3134 Abstract_VM_Version::parallel_worker_threads());
3135
3136 // Encourage steady state memory management
3137 FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100);
3138
3139 // This appears to improve mutator locality
3140 FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
3141
3142 // Get around early Solaris scheduling bug
3143 // (affinity vs other jobs on system)
3144 // but disallow DR and offlining (5008695).
3145 FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true);
3146
3147 // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
3148 // and the last option wins.
3149 } else if (match_option(option, "-XX:+NeverTenure")) {
3150 FLAG_SET_CMDLINE(bool, NeverTenure, true);
3151 FLAG_SET_CMDLINE(bool, AlwaysTenure, false);
3152 FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, markOopDesc::max_age + 1);
3153 } else if (match_option(option, "-XX:+AlwaysTenure")) {
3154 FLAG_SET_CMDLINE(bool, NeverTenure, false);
3155 FLAG_SET_CMDLINE(bool, AlwaysTenure, true);
3156 FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0);
3157 } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
3158 uintx max_tenuring_thresh = 0;
3159 if(!parse_uintx(tail, &max_tenuring_thresh, 0)) {
3160 jio_fprintf(defaultStream::error_stream(),
3161 "Improperly specified VM option 'MaxTenuringThreshold=%s'\n", tail);
3162 return JNI_EINVAL;
3163 }
3164 FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, max_tenuring_thresh);
3165
3166 if (MaxTenuringThreshold == 0) {
3167 FLAG_SET_CMDLINE(bool, NeverTenure, false);
3168 FLAG_SET_CMDLINE(bool, AlwaysTenure, true);
3169 } else {
3170 FLAG_SET_CMDLINE(bool, NeverTenure, false);
3171 FLAG_SET_CMDLINE(bool, AlwaysTenure, false);
3172 }
3173 } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
3174 FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false);
3175 FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true);
3176 } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
3177 FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false);
3178 FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true);
3179 } else if (match_option(option, "-XX:+ExtendedDTraceProbes")) {
3180 #if defined(DTRACE_ENABLED)
3181 FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true);
3182 FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true);
3183 FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true);
3184 FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true);
3185 #else // defined(DTRACE_ENABLED)
3186 jio_fprintf(defaultStream::error_stream(),
3187 "ExtendedDTraceProbes flag is not applicable for this configuration\n");
3188 return JNI_EINVAL;
3189 #endif // defined(DTRACE_ENABLED)
3190 #ifdef ASSERT
3191 } else if (match_option(option, "-XX:+FullGCALot")) {
3192 FLAG_SET_CMDLINE(bool, FullGCALot, true);
3193 // disable scavenge before parallel mark-compact
3194 FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
3195 #endif
3196 } else if (match_option(option, "-XX:CMSMarkStackSize=", &tail) ||
3197 match_option(option, "-XX:G1MarkStackSize=", &tail)) {
3198 julong stack_size = 0;
3199 ArgsRange errcode = parse_memory_size(tail, &stack_size, 1);
3200 if (errcode != arg_in_range) {
3201 jio_fprintf(defaultStream::error_stream(),
3202 "Invalid mark stack size: %s\n", option->optionString);
3203 describe_range_error(errcode);
3204 return JNI_EINVAL;
3205 }
3206 jio_fprintf(defaultStream::error_stream(),
3207 "Please use -XX:MarkStackSize in place of "
3208 "-XX:CMSMarkStackSize or -XX:G1MarkStackSize in the future\n");
3209 FLAG_SET_CMDLINE(size_t, MarkStackSize, stack_size);
3210 } else if (match_option(option, "-XX:CMSMarkStackSizeMax=", &tail)) {
3211 julong max_stack_size = 0;
3212 ArgsRange errcode = parse_memory_size(tail, &max_stack_size, 1);
3213 if (errcode != arg_in_range) {
3214 jio_fprintf(defaultStream::error_stream(),
3215 "Invalid maximum mark stack size: %s\n",
3216 option->optionString);
3217 describe_range_error(errcode);
3218 return JNI_EINVAL;
3219 }
3220 jio_fprintf(defaultStream::error_stream(),
3221 "Please use -XX:MarkStackSizeMax in place of "
3222 "-XX:CMSMarkStackSizeMax in the future\n");
3223 FLAG_SET_CMDLINE(size_t, MarkStackSizeMax, max_stack_size);
3224 } else if (match_option(option, "-XX:ParallelMarkingThreads=", &tail) ||
3225 match_option(option, "-XX:ParallelCMSThreads=", &tail)) {
3226 uintx conc_threads = 0;
3227 if (!parse_uintx(tail, &conc_threads, 1)) {
3228 jio_fprintf(defaultStream::error_stream(),
3229 "Invalid concurrent threads: %s\n", option->optionString);
3230 return JNI_EINVAL;
3231 }
3232 jio_fprintf(defaultStream::error_stream(),
3233 "Please use -XX:ConcGCThreads in place of "
3234 "-XX:ParallelMarkingThreads or -XX:ParallelCMSThreads in the future\n");
3235 FLAG_SET_CMDLINE(uintx, ConcGCThreads, conc_threads);
3236 } else if (match_option(option, "-XX:MaxDirectMemorySize=", &tail)) {
3237 julong max_direct_memory_size = 0;
3238 ArgsRange errcode = parse_memory_size(tail, &max_direct_memory_size, 0);
3239 if (errcode != arg_in_range) {
3240 jio_fprintf(defaultStream::error_stream(),
3241 "Invalid maximum direct memory size: %s\n",
3242 option->optionString);
3243 describe_range_error(errcode);
3244 return JNI_EINVAL;
3245 }
3246 FLAG_SET_CMDLINE(size_t, MaxDirectMemorySize, max_direct_memory_size);
3247 #if !INCLUDE_MANAGEMENT
3248 } else if (match_option(option, "-XX:+ManagementServer")) {
3249 jio_fprintf(defaultStream::error_stream(),
3250 "ManagementServer is not supported in this VM.\n");
3251 return JNI_ERR;
3252 #endif // INCLUDE_MANAGEMENT
3253 // CreateMinidumpOnCrash is removed, and replaced by CreateCoredumpOnCrash
3254 } else if (match_option(option, "-XX:+CreateMinidumpOnCrash")) {
3255 FLAG_SET_CMDLINE(bool, CreateCoredumpOnCrash, true);
3256 jio_fprintf(defaultStream::output_stream(),
3257 "CreateMinidumpOnCrash is replaced by CreateCoredumpOnCrash: CreateCoredumpOnCrash is on\n");
3258 } else if (match_option(option, "-XX:-CreateMinidumpOnCrash")) {
3259 FLAG_SET_CMDLINE(bool, CreateCoredumpOnCrash, false);
3260 jio_fprintf(defaultStream::output_stream(),
3261 "CreateMinidumpOnCrash is replaced by CreateCoredumpOnCrash: CreateCoredumpOnCrash is off\n");
3262 } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
3263 // Skip -XX:Flags= since that case has already been handled
3264 if (strncmp(tail, "Flags=", strlen("Flags=")) != 0) {
3265 if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
3266 return JNI_EINVAL;
3267 }
3268 }
3269 // Unknown option
3270 } else if (is_bad_option(option, args->ignoreUnrecognized)) {
3271 return JNI_ERR;
3272 }
3273 }
3274
3275 // PrintSharedArchiveAndExit will turn on
3276 // -Xshare:on
3277 // -XX:+TraceClassPaths
3278 if (PrintSharedArchiveAndExit) {
3279 FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
3280 FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true);
3281 FLAG_SET_CMDLINE(bool, TraceClassPaths, true);
3282 }
3283
3284 // Change the default value for flags which have different default values
3285 // when working with older JDKs.
3286 #ifdef LINUX
3287 if (JDK_Version::current().compare_major(6) <= 0 &&
3288 FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
3289 FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
3290 }
3291 #endif // LINUX
3292 fix_appclasspath();
3293 return JNI_OK;
3294 }
3295
3296 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
3297 //
3298 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
3299 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
3300 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
3301 // path is treated as the current directory.
3302 //
3303 // This causes problems with CDS, which requires that all directories specified in the classpath
3304 // must be empty. In most cases, applications do NOT want to load classes from the current
3305 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
3306 // scripts compatible with CDS.
3307 void Arguments::fix_appclasspath() {
3308 if (IgnoreEmptyClassPaths) {
3309 const char separator = *os::path_separator();
3310 const char* src = _java_class_path->value();
3311
3312 // skip over all the leading empty paths
3313 while (*src == separator) {
3314 src ++;
3315 }
3316
3317 char* copy = os::strdup_check_oom(src, mtInternal);
3318
3319 // trim all trailing empty paths
3320 for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
3321 *tail = '\0';
3322 }
3323
3324 char from[3] = {separator, separator, '\0'};
3325 char to [2] = {separator, '\0'};
3326 while (StringUtils::replace_no_expand(copy, from, to) > 0) {
3327 // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
3328 // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
3329 }
3330
3331 _java_class_path->set_value(copy);
3332 FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
3333 }
3334
3335 if (!PrintSharedArchiveAndExit) {
3336 ClassLoader::trace_class_path("[classpath: ", _java_class_path->value());
3337 }
3338 }
3339
3340 static bool has_jar_files(const char* directory) {
3341 DIR* dir = os::opendir(directory);
3342 if (dir == NULL) return false;
3343
3344 struct dirent *entry;
3345 char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtInternal);
3346 bool hasJarFile = false;
3347 while (!hasJarFile && (entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
3348 const char* name = entry->d_name;
3349 const char* ext = name + strlen(name) - 4;
3350 hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);
3351 }
3352 FREE_C_HEAP_ARRAY(char, dbuf);
3353 os::closedir(dir);
3354 return hasJarFile ;
3355 }
3356
3357 static int check_non_empty_dirs(const char* path) {
3358 const char separator = *os::path_separator();
3359 const char* const end = path + strlen(path);
3360 int nonEmptyDirs = 0;
3361 while (path < end) {
3362 const char* tmp_end = strchr(path, separator);
3363 if (tmp_end == NULL) {
3364 if (has_jar_files(path)) {
3365 nonEmptyDirs++;
3366 jio_fprintf(defaultStream::output_stream(),
3367 "Non-empty directory: %s\n", path);
3368 }
3369 path = end;
3370 } else {
3371 char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);
3372 memcpy(dirpath, path, tmp_end - path);
3373 dirpath[tmp_end - path] = '\0';
3374 if (has_jar_files(dirpath)) {
3375 nonEmptyDirs++;
3376 jio_fprintf(defaultStream::output_stream(),
3377 "Non-empty directory: %s\n", dirpath);
3378 }
3379 FREE_C_HEAP_ARRAY(char, dirpath);
3380 path = tmp_end + 1;
3381 }
3382 }
3383 return nonEmptyDirs;
3384 }
3385
3386 jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_required) {
3387 // check if the default lib/endorsed directory exists; if so, error
3388 char path[JVM_MAXPATHLEN];
3389 const char* fileSep = os::file_separator();
3390 sprintf(path, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
3391
3392 if (CheckEndorsedAndExtDirs) {
3393 int nonEmptyDirs = 0;
3394 // check endorsed directory
3395 nonEmptyDirs += check_non_empty_dirs(path);
3396 // check the extension directories
3397 nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs());
3398 if (nonEmptyDirs > 0) {
3399 return JNI_ERR;
3400 }
3401 }
3402
3403 DIR* dir = os::opendir(path);
3404 if (dir != NULL) {
3405 jio_fprintf(defaultStream::output_stream(),
3406 "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
3407 "in modular form will be supported via the concept of upgradeable modules.\n");
3408 os::closedir(dir);
3409 return JNI_ERR;
3410 }
3411
3412 sprintf(path, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
3413 dir = os::opendir(path);
3414 if (dir != NULL) {
3415 jio_fprintf(defaultStream::output_stream(),
3416 "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
3417 "Use -classpath instead.\n.");
3418 os::closedir(dir);
3419 return JNI_ERR;
3420 }
3421
3422 if (scp_assembly_required) {
3423 // Assemble the bootclasspath elements into the final path.
3424 Arguments::set_sysclasspath(scp_p->combined_path());
3425 }
3426
3427 // This must be done after all arguments have been processed.
3428 // java_compiler() true means set to "NONE" or empty.
3429 if (java_compiler() && !xdebug_mode()) {
3430 // For backwards compatibility, we switch to interpreted mode if
3431 // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
3432 // not specified.
3433 set_mode_flags(_int);
3434 }
3435
3436 // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
3437 // but like -Xint, leave compilation thresholds unaffected.
3438 // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
3439 if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
3440 set_mode_flags(_int);
3441 }
3442
3443 // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3444 if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3445 FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
3446 }
3447
3448 #ifndef COMPILER2
3449 // Don't degrade server performance for footprint
3450 if (FLAG_IS_DEFAULT(UseLargePages) &&
3451 MaxHeapSize < LargePageHeapSizeThreshold) {
3452 // No need for large granularity pages w/small heaps.
3453 // Note that large pages are enabled/disabled for both the
3454 // Java heap and the code cache.
3455 FLAG_SET_DEFAULT(UseLargePages, false);
3456 }
3457
3458 #else
3459 if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
3460 FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
3461 }
3462 #endif
3463
3464 #ifndef TIERED
3465 // Tiered compilation is undefined.
3466 UNSUPPORTED_OPTION(TieredCompilation, "TieredCompilation");
3467 #endif
3468
3469 // If we are running in a headless jre, force java.awt.headless property
3470 // to be true unless the property has already been set.
3471 // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.
3472 if (os::is_headless_jre()) {
3473 const char* headless = Arguments::get_property("java.awt.headless");
3474 if (headless == NULL) {
3475 const char *headless_env = ::getenv("JAVA_AWT_HEADLESS");
3476 if (headless_env == NULL) {
3477 if (!add_property("java.awt.headless=true")) {
3478 return JNI_ENOMEM;
3479 }
3480 } else {
3481 char buffer[256];
3482 jio_snprintf(buffer, sizeof(buffer), "java.awt.headless=%s", headless_env);
3483 if (!add_property(buffer)) {
3484 return JNI_ENOMEM;
3485 }
3486 }
3487 }
3488 }
3489
3490 if (UseConcMarkSweepGC && FLAG_IS_DEFAULT(UseParNewGC) && !UseParNewGC) {
3491 // CMS can only be used with ParNew
3492 FLAG_SET_ERGO(bool, UseParNewGC, true);
3493 }
3494
3495 if (!check_vm_args_consistency()) {
3496 return JNI_ERR;
3497 }
3498
3499 return JNI_OK;
3500 }
3501
3502 jint Arguments::parse_java_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
3503 return parse_options_environment_variable("_JAVA_OPTIONS", scp_p,
3504 scp_assembly_required_p);
3505 }
3506
3507 jint Arguments::parse_java_tool_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
3508 return parse_options_environment_variable("JAVA_TOOL_OPTIONS", scp_p,
3509 scp_assembly_required_p);
3510 }
3511
3512 jint Arguments::parse_options_environment_variable(const char* name, SysClassPath* scp_p, bool* scp_assembly_required_p) {
3513 char *buffer = ::getenv(name);
3514
3515 // Don't check this variable if user has special privileges
3516 // (e.g. unix su command).
3517 if (buffer == NULL || os::have_special_privileges()) {
3518 return JNI_OK;
3519 }
3520
3521 if ((buffer = os::strdup(buffer)) == NULL) {
3522 return JNI_ENOMEM;
3523 }
3524
3525 GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JavaVMOption>(2, true); // Construct option array
3526 jio_fprintf(defaultStream::error_stream(),
3527 "Picked up %s: %s\n", name, buffer);
3528 char* rd = buffer; // pointer to the input string (rd)
3529 while (true) { // repeat for all options in the input string
3530 while (isspace(*rd)) rd++; // skip whitespace
3531 if (*rd == 0) break; // we re done when the input string is read completely
3532
3533 // The output, option string, overwrites the input string.
3534 // Because of quoting, the pointer to the option string (wrt) may lag the pointer to
3535 // input string (rd).
3536 char* wrt = rd;
3537
3538 JavaVMOption option;
3539 option.optionString = wrt;
3540 options->append(option); // Fill in option
3541 while (*rd != 0 && !isspace(*rd)) { // unquoted strings terminate with a space or NULL
3542 if (*rd == '\'' || *rd == '"') { // handle a quoted string
3543 int quote = *rd; // matching quote to look for
3544 rd++; // don't copy open quote
3545 while (*rd != quote) { // include everything (even spaces) up until quote
3546 if (*rd == 0) { // string termination means unmatched string
3547 jio_fprintf(defaultStream::error_stream(),
3548 "Unmatched quote in %s\n", name);
3549 delete options;
3550 os::free(buffer);
3551 return JNI_ERR;
3552 }
3553 *wrt++ = *rd++; // copy to option string
3554 }
3555 rd++; // don't copy close quote
3556 } else {
3557 *wrt++ = *rd++; // copy to option string
3558 }
3559 }
3560 // Need to check if we're done before writing a NULL,
3561 // because the write could be to the byte that rd is pointing to.
3562 if (*rd++ == 0) {
3563 *wrt = 0;
3564 break;
3565 }
3566 *wrt = 0; // Zero terminate option
3567 }
3568 JavaVMOption* options_arr =
3569 NEW_C_HEAP_ARRAY_RETURN_NULL(JavaVMOption, options->length(), mtInternal);
3570 if (options_arr == NULL) {
3571 delete options;
3572 os::free(buffer);
3573 return JNI_ENOMEM;
3574 }
3575 for (int i = 0; i < options->length(); i++) {
3576 options_arr[i] = options->at(i);
3577 }
3578
3579 // Construct JavaVMInitArgs structure and parse as if it was part of the command line
3580 JavaVMInitArgs vm_args;
3581 vm_args.version = JNI_VERSION_1_2;
3582 vm_args.options = options_arr;
3583 vm_args.nOptions = options->length();
3584 vm_args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3585
3586 if (PrintVMOptions) {
3587 const char* tail;
3588 for (int i = 0; i < vm_args.nOptions; i++) {
3589 const JavaVMOption *option = vm_args.options + i;
3590 if (match_option(option, "-XX:", &tail)) {
3591 logOption(tail);
3592 }
3593 }
3594 }
3595
3596 jint result = parse_each_vm_init_arg(&vm_args, scp_p, scp_assembly_required_p,
3597 Flag::ENVIRON_VAR);
3598 FREE_C_HEAP_ARRAY(JavaVMOption, options_arr);
3599 delete options;
3600 os::free(buffer);
3601 return result;
3602 }
3603
3604 void Arguments::set_shared_spaces_flags() {
3605 if (DumpSharedSpaces) {
3606 if (RequireSharedSpaces) {
3607 warning("cannot dump shared archive while using shared archive");
3608 }
3609 UseSharedSpaces = false;
3610 #ifdef _LP64
3611 if (!UseCompressedOops || !UseCompressedClassPointers) {
3612 vm_exit_during_initialization(
3613 "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
3614 }
3615 } else {
3616 if (!UseCompressedOops || !UseCompressedClassPointers) {
3617 no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
3618 }
3619 #endif
3620 }
3621 }
3622
3623 #if !INCLUDE_ALL_GCS
3624 static void force_serial_gc() {
3625 FLAG_SET_DEFAULT(UseSerialGC, true);
3626 UNSUPPORTED_GC_OPTION(UseG1GC);
3627 UNSUPPORTED_GC_OPTION(UseParallelGC);
3628 UNSUPPORTED_GC_OPTION(UseParallelOldGC);
3629 UNSUPPORTED_GC_OPTION(UseConcMarkSweepGC);
3630 UNSUPPORTED_GC_OPTION(UseParNewGC);
3631 }
3632 #endif // INCLUDE_ALL_GCS
3633
3634 // Sharing support
3635 // Construct the path to the archive
3636 static char* get_shared_archive_path() {
3637 char *shared_archive_path;
3638 if (SharedArchiveFile == NULL) {
3639 char jvm_path[JVM_MAXPATHLEN];
3640 os::jvm_path(jvm_path, sizeof(jvm_path));
3641 char *end = strrchr(jvm_path, *os::file_separator());
3642 if (end != NULL) *end = '\0';
3643 size_t jvm_path_len = strlen(jvm_path);
3644 size_t file_sep_len = strlen(os::file_separator());
3645 const size_t len = jvm_path_len + file_sep_len + 20;
3646 shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtInternal);
3647 if (shared_archive_path != NULL) {
3648 jio_snprintf(shared_archive_path, len, "%s%sclasses.jsa",
3649 jvm_path, os::file_separator());
3650 }
3651 } else {
3652 shared_archive_path = os::strdup_check_oom(SharedArchiveFile, mtInternal);
3653 }
3654 return shared_archive_path;
3655 }
3656
3657 #ifndef PRODUCT
3658 // Determine whether LogVMOutput should be implicitly turned on.
3659 static bool use_vm_log() {
3660 if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3661 PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3662 PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3663 PrintAssembly || TraceDeoptimization || TraceDependencies ||
3664 (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3665 return true;
3666 }
3667
3668 #ifdef COMPILER1
3669 if (PrintC1Statistics) {
3670 return true;
3671 }
3672 #endif // COMPILER1
3673
3674 #ifdef COMPILER2
3675 if (PrintOptoAssembly || PrintOptoStatistics) {
3676 return true;
3677 }
3678 #endif // COMPILER2
3679
3680 return false;
3681 }
3682 #endif // PRODUCT
3683
3684 // Parse entry point called from JNI_CreateJavaVM
3685
3686 jint Arguments::parse(const JavaVMInitArgs* args) {
3687
3688 // Remaining part of option string
3689 const char* tail;
3690
3691 // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
3692 const char* hotspotrc = ".hotspotrc";
3693 bool settings_file_specified = false;
3694 bool needs_hotspotrc_warning = false;
3695
3696 const char* flags_file;
3697 int index;
3698 for (index = 0; index < args->nOptions; index++) {
3699 const JavaVMOption *option = args->options + index;
3700 if (ArgumentsExt::process_options(option)) {
3701 continue;
3702 }
3703 if (match_option(option, "-XX:Flags=", &tail)) {
3704 flags_file = tail;
3705 settings_file_specified = true;
3706 continue;
3707 }
3708 if (match_option(option, "-XX:+PrintVMOptions")) {
3709 PrintVMOptions = true;
3710 continue;
3711 }
3712 if (match_option(option, "-XX:-PrintVMOptions")) {
3713 PrintVMOptions = false;
3714 continue;
3715 }
3716 if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
3717 IgnoreUnrecognizedVMOptions = true;
3718 continue;
3719 }
3720 if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
3721 IgnoreUnrecognizedVMOptions = false;
3722 continue;
3723 }
3724 if (match_option(option, "-XX:+PrintFlagsInitial")) {
3725 CommandLineFlags::printFlags(tty, false);
3726 vm_exit(0);
3727 }
3728 if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
3729 #if INCLUDE_NMT
3730 // The launcher did not setup nmt environment variable properly.
3731 if (!MemTracker::check_launcher_nmt_support(tail)) {
3732 warning("Native Memory Tracking did not setup properly, using wrong launcher?");
3733 }
3734
3735 // Verify if nmt option is valid.
3736 if (MemTracker::verify_nmt_option()) {
3737 // Late initialization, still in single-threaded mode.
3738 if (MemTracker::tracking_level() >= NMT_summary) {
3739 MemTracker::init();
3740 }
3741 } else {
3742 vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
3743 }
3744 continue;
3745 #else
3746 jio_fprintf(defaultStream::error_stream(),
3747 "Native Memory Tracking is not supported in this VM\n");
3748 return JNI_ERR;
3749 #endif
3750 }
3751
3752 #ifndef PRODUCT
3753 if (match_option(option, "-XX:+PrintFlagsWithComments")) {
3754 CommandLineFlags::printFlags(tty, true);
3755 vm_exit(0);
3756 }
3757 #endif
3758 }
3759
3760 if (IgnoreUnrecognizedVMOptions) {
3761 // uncast const to modify the flag args->ignoreUnrecognized
3762 *(jboolean*)(&args->ignoreUnrecognized) = true;
3763 }
3764
3765 // Parse specified settings file
3766 if (settings_file_specified) {
3767 if (!process_settings_file(flags_file, true, args->ignoreUnrecognized)) {
3768 return JNI_EINVAL;
3769 }
3770 } else {
3771 #ifdef ASSERT
3772 // Parse default .hotspotrc settings file
3773 if (!process_settings_file(".hotspotrc", false, args->ignoreUnrecognized)) {
3774 return JNI_EINVAL;
3775 }
3776 #else
3777 struct stat buf;
3778 if (os::stat(hotspotrc, &buf) == 0) {
3779 needs_hotspotrc_warning = true;
3780 }
3781 #endif
3782 }
3783
3784 if (PrintVMOptions) {
3785 for (index = 0; index < args->nOptions; index++) {
3786 const JavaVMOption *option = args->options + index;
3787 if (match_option(option, "-XX:", &tail)) {
3788 logOption(tail);
3789 }
3790 }
3791 }
3792
3793 // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
3794 jint result = parse_vm_init_args(args);
3795 if (result != JNI_OK) {
3796 return result;
3797 }
3798
3799 // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
3800 SharedArchivePath = get_shared_archive_path();
3801 if (SharedArchivePath == NULL) {
3802 return JNI_ENOMEM;
3803 }
3804
3805 // Set up VerifySharedSpaces
3806 if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
3807 VerifySharedSpaces = true;
3808 }
3809
3810 // Delay warning until here so that we've had a chance to process
3811 // the -XX:-PrintWarnings flag
3812 if (needs_hotspotrc_warning) {
3813 warning("%s file is present but has been ignored. "
3814 "Run with -XX:Flags=%s to load the file.",
3815 hotspotrc, hotspotrc);
3816 }
3817
3818 #if defined(_ALLBSD_SOURCE) || defined(AIX) // UseLargePages is not yet supported on BSD and AIX.
3819 UNSUPPORTED_OPTION(UseLargePages, "-XX:+UseLargePages");
3820 #endif
3821
3822 ArgumentsExt::report_unsupported_options();
3823
3824 #ifndef PRODUCT
3825 if (TraceBytecodesAt != 0) {
3826 TraceBytecodes = true;
3827 }
3828 if (CountCompiledCalls) {
3829 if (UseCounterDecay) {
3830 warning("UseCounterDecay disabled because CountCalls is set");
3831 UseCounterDecay = false;
3832 }
3833 }
3834 #endif // PRODUCT
3835
3836 if (ScavengeRootsInCode == 0) {
3837 if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
3838 warning("forcing ScavengeRootsInCode non-zero");
3839 }
3840 ScavengeRootsInCode = 1;
3841 }
3842
3843 if (PrintGCDetails) {
3844 // Turn on -verbose:gc options as well
3845 PrintGC = true;
3846 }
3847
3848 // Set object alignment values.
3849 set_object_alignment();
3850
3851 #if !INCLUDE_ALL_GCS
3852 force_serial_gc();
3853 #endif // INCLUDE_ALL_GCS
3854 #if !INCLUDE_CDS
3855 if (DumpSharedSpaces || RequireSharedSpaces) {
3856 jio_fprintf(defaultStream::error_stream(),
3857 "Shared spaces are not supported in this VM\n");
3858 return JNI_ERR;
3859 }
3860 if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {
3861 warning("Shared spaces are not supported in this VM");
3862 FLAG_SET_DEFAULT(UseSharedSpaces, false);
3863 FLAG_SET_DEFAULT(PrintSharedSpaces, false);
3864 }
3865 no_shared_spaces("CDS Disabled");
3866 #endif // INCLUDE_CDS
3867
3868 return JNI_OK;
3869 }
3870
3871 jint Arguments::apply_ergo() {
3872
3873 // Set flags based on ergonomics.
3874 set_ergonomics_flags();
3875
3876 set_shared_spaces_flags();
3877
3878 // Check the GC selections again.
3879 if (!check_gc_consistency()) {
3880 return JNI_EINVAL;
3881 }
3882
3883 if (TieredCompilation) {
3884 set_tiered_flags();
3885 } else {
3886 // Check if the policy is valid. Policies 0 and 1 are valid for non-tiered setup.
3887 if (CompilationPolicyChoice >= 2) {
3888 vm_exit_during_initialization(
3889 "Incompatible compilation policy selected", NULL);
3890 }
3891 // Scale CompileThreshold
3892 // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves CompileThreshold unchanged.
3893 if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
3894 FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold));
3895 }
3896 }
3897
3898 #ifdef COMPILER2
3899 #ifndef PRODUCT
3900 if (PrintIdealGraphLevel > 0) {
3901 FLAG_SET_ERGO(bool, PrintIdealGraph, true);
3902 }
3903 #endif
3904 #endif
3905
3906 // Set heap size based on available physical memory
3907 set_heap_size();
3908
3909 ArgumentsExt::set_gc_specific_flags();
3910
3911 // Initialize Metaspace flags and alignments
3912 Metaspace::ergo_initialize();
3913
3914 // Set bytecode rewriting flags
3915 set_bytecode_flags();
3916
3917 // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled
3918 set_aggressive_opts_flags();
3919
3920 // Turn off biased locking for locking debug mode flags,
3921 // which are subtly different from each other but neither works with
3922 // biased locking
3923 if (UseHeavyMonitors
3924 #ifdef COMPILER1
3925 || !UseFastLocking
3926 #endif // COMPILER1
3927 ) {
3928 if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
3929 // flag set to true on command line; warn the user that they
3930 // can't enable biased locking here
3931 warning("Biased Locking is not supported with locking debug flags"
3932 "; ignoring UseBiasedLocking flag." );
3933 }
3934 UseBiasedLocking = false;
3935 }
3936
3937 #ifdef ZERO
3938 // Clear flags not supported on zero.
3939 FLAG_SET_DEFAULT(ProfileInterpreter, false);
3940 FLAG_SET_DEFAULT(UseBiasedLocking, false);
3941 LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
3942 LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
3943 #endif // CC_INTERP
3944
3945 #ifdef COMPILER2
3946 if (!EliminateLocks) {
3947 EliminateNestedLocks = false;
3948 }
3949 if (!Inline) {
3950 IncrementalInline = false;
3951 }
3952 #ifndef PRODUCT
3953 if (!IncrementalInline) {
3954 AlwaysIncrementalInline = false;
3955 }
3956 #endif
3957 if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
3958 // nothing to use the profiling, turn if off
3959 FLAG_SET_DEFAULT(TypeProfileLevel, 0);
3960 }
3961 #endif
3962
3963 if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
3964 warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
3965 DebugNonSafepoints = true;
3966 }
3967
3968 if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
3969 warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
3970 }
3971
3972 #ifndef PRODUCT
3973 if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
3974 if (use_vm_log()) {
3975 LogVMOutput = true;
3976 }
3977 }
3978 #endif // PRODUCT
3979
3980 if (PrintCommandLineFlags) {
3981 CommandLineFlags::printSetFlags(tty);
3982 }
3983
3984 // Apply CPU specific policy for the BiasedLocking
3985 if (UseBiasedLocking) {
3986 if (!VM_Version::use_biased_locking() &&
3987 !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
3988 UseBiasedLocking = false;
3989 }
3990 }
3991 #ifdef COMPILER2
3992 if (!UseBiasedLocking || EmitSync != 0) {
3993 UseOptoBiasInlining = false;
3994 }
3995 #endif
3996
3997 return JNI_OK;
3998 }
3999
4000 jint Arguments::adjust_after_os() {
4001 if (UseNUMA) {
4002 if (UseParallelGC || UseParallelOldGC) {
4003 if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4004 FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4005 }
4006 }
4007 // UseNUMAInterleaving is set to ON for all collectors and
4008 // platforms when UseNUMA is set to ON. NUMA-aware collectors
4009 // such as the parallel collector for Linux and Solaris will
4010 // interleave old gen and survivor spaces on top of NUMA
4011 // allocation policy for the eden space.
4012 // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
4013 // all platforms and ParallelGC on Windows will interleave all
4014 // of the heap spaces across NUMA nodes.
4015 if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
4016 FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
4017 }
4018 }
4019 return JNI_OK;
4020 }
4021
4022 int Arguments::PropertyList_count(SystemProperty* pl) {
4023 int count = 0;
4024 while(pl != NULL) {
4025 count++;
4026 pl = pl->next();
4027 }
4028 return count;
4029 }
4030
4031 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4032 assert(key != NULL, "just checking");
4033 SystemProperty* prop;
4034 for (prop = pl; prop != NULL; prop = prop->next()) {
4035 if (strcmp(key, prop->key()) == 0) return prop->value();
4036 }
4037 return NULL;
4038 }
4039
4040 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
4041 int count = 0;
4042 const char* ret_val = NULL;
4043
4044 while(pl != NULL) {
4045 if(count >= index) {
4046 ret_val = pl->key();
4047 break;
4048 }
4049 count++;
4050 pl = pl->next();
4051 }
4052
4053 return ret_val;
4054 }
4055
4056 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
4057 int count = 0;
4058 char* ret_val = NULL;
4059
4060 while(pl != NULL) {
4061 if(count >= index) {
4062 ret_val = pl->value();
4063 break;
4064 }
4065 count++;
4066 pl = pl->next();
4067 }
4068
4069 return ret_val;
4070 }
4071
4072 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4073 SystemProperty* p = *plist;
4074 if (p == NULL) {
4075 *plist = new_p;
4076 } else {
4077 while (p->next() != NULL) {
4078 p = p->next();
4079 }
4080 p->set_next(new_p);
4081 }
4082 }
4083
4084 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, char* v) {
4085 if (plist == NULL)
4086 return;
4087
4088 SystemProperty* new_p = new SystemProperty(k, v, true);
4089 PropertyList_add(plist, new_p);
4090 }
4091
4092 void Arguments::PropertyList_add(SystemProperty *element) {
4093 PropertyList_add(&_system_properties, element);
4094 }
4095
4096 // This add maintains unique property key in the list.
4097 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, char* v, jboolean append) {
4098 if (plist == NULL)
4099 return;
4100
4101 // If property key exist then update with new value.
4102 SystemProperty* prop;
4103 for (prop = *plist; prop != NULL; prop = prop->next()) {
4104 if (strcmp(k, prop->key()) == 0) {
4105 if (append) {
4106 prop->append_value(v);
4107 } else {
4108 prop->set_value(v);
4109 }
4110 return;
4111 }
4112 }
4113
4114 PropertyList_add(plist, k, v);
4115 }
4116
4117 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4118 // Returns true if all of the source pointed by src has been copied over to
4119 // the destination buffer pointed by buf. Otherwise, returns false.
4120 // Notes:
4121 // 1. If the length (buflen) of the destination buffer excluding the
4122 // NULL terminator character is not long enough for holding the expanded
4123 // pid characters, it also returns false instead of returning the partially
4124 // expanded one.
4125 // 2. The passed in "buflen" should be large enough to hold the null terminator.
4126 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4127 char* buf, size_t buflen) {
4128 const char* p = src;
4129 char* b = buf;
4130 const char* src_end = &src[srclen];
4131 char* buf_end = &buf[buflen - 1];
4132
4133 while (p < src_end && b < buf_end) {
4134 if (*p == '%') {
4135 switch (*(++p)) {
4136 case '%': // "%%" ==> "%"
4137 *b++ = *p++;
4138 break;
4139 case 'p': { // "%p" ==> current process id
4140 // buf_end points to the character before the last character so
4141 // that we could write '\0' to the end of the buffer.
4142 size_t buf_sz = buf_end - b + 1;
4143 int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4144
4145 // if jio_snprintf fails or the buffer is not long enough to hold
4146 // the expanded pid, returns false.
4147 if (ret < 0 || ret >= (int)buf_sz) {
4148 return false;
4149 } else {
4150 b += ret;
4151 assert(*b == '\0', "fail in copy_expand_pid");
4152 if (p == src_end && b == buf_end + 1) {
4153 // reach the end of the buffer.
4154 return true;
4155 }
4156 }
4157 p++;
4158 break;
4159 }
4160 default :
4161 *b++ = '%';
4162 }
4163 } else {
4164 *b++ = *p++;
4165 }
4166 }
4167 *b = '\0';
4168 return (p == src_end); // return false if not all of the source was copied
4169 }