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