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