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