1 /*
  2  * Copyright (c) 1997, 2025, 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 #ifndef SHARE_RUNTIME_ARGUMENTS_HPP
 26 #define SHARE_RUNTIME_ARGUMENTS_HPP
 27 
 28 #include "jni.h"
 29 #include "memory/allocation.hpp"
 30 #include "memory/allStatic.hpp"
 31 #include "runtime/flags/jvmFlag.hpp"
 32 #include "runtime/java.hpp"
 33 #include "utilities/globalDefinitions.hpp"
 34 
 35 // Arguments parses the command line and recognizes options
 36 
 37 template <typename E>
 38 class GrowableArray;
 39 class JVMFlag;
 40 
 41 // Invocation API hook typedefs (these should really be defined in jni.h)
 42 extern "C" {
 43   typedef void (JNICALL *abort_hook_t)(void);
 44   typedef void (JNICALL *exit_hook_t)(jint code);
 45   typedef jint (JNICALL *vfprintf_hook_t)(FILE *fp, const char *format, va_list args)  ATTRIBUTE_PRINTF(2, 0);
 46 }
 47 
 48 // Obsolete or deprecated -XX flag.
 49 struct SpecialFlag {
 50   const char* name;
 51   JDK_Version deprecated_in; // When the deprecation warning started (or "undefined").
 52   JDK_Version obsolete_in;   // When the obsolete warning started (or "undefined").
 53   JDK_Version expired_in;    // When the option expires (or "undefined").
 54 };
 55 
 56 struct LegacyGCLogging {
 57     const char* file;        // null -> stdout
 58     int lastFlag;            // 0 not set; 1 -> -verbose:gc; 2 -> -Xloggc
 59 };
 60 
 61 // PathString is used as:
 62 //  - the underlying value for a SystemProperty
 63 //  - the path portion of an --patch-module module/path pair
 64 //  - the string that represents the boot class path, Arguments::_boot_class_path.
 65 class PathString : public CHeapObj<mtArguments> {
 66  protected:
 67   char* _value;
 68  public:
 69   char* value() const { return _value; }
 70 
 71   // return false iff OOM && alloc_failmode == AllocFailStrategy::RETURN_NULL
 72   bool set_value(const char *value, AllocFailType alloc_failmode = AllocFailStrategy::EXIT_OOM);
 73   void append_value(const char *value);
 74 
 75   PathString(const char* value);
 76   ~PathString();
 77 
 78   // for JVM_ReadSystemPropertiesInfo
 79   static int value_offset_in_bytes()  { return (int)offset_of(PathString, _value);  }
 80 };
 81 
 82 // ModulePatchPath records the module/path pair as specified to --patch-module.
 83 class ModulePatchPath : public CHeapObj<mtInternal> {
 84 private:
 85   char* _module_name;
 86   PathString* _path;
 87 public:
 88   ModulePatchPath(const char* module_name, const char* path);
 89   ~ModulePatchPath();
 90 
 91   inline const char* module_name() const { return _module_name; }
 92   inline char* path_string() const { return _path->value(); }
 93 };
 94 
 95 // Element describing System and User (-Dkey=value flags) defined property.
 96 //
 97 // An internal SystemProperty is one that has been removed in
 98 // jdk.internal.VM.saveAndRemoveProperties, like jdk.boot.class.path.append.
 99 //
100 class SystemProperty : public PathString {
101  private:
102   char*           _key;
103   SystemProperty* _next;
104   bool            _internal;
105   bool            _writeable;
106 
107  public:
108   // Accessors
109   char* value() const                 { return PathString::value(); }
110   const char* key() const             { return _key; }
111   bool internal() const               { return _internal; }
112   SystemProperty* next() const        { return _next; }
113   void set_next(SystemProperty* next) { _next = next; }
114   bool writeable() const              { return _writeable; }
115 
116   bool readable() const {
117     return !_internal || (strcmp(_key, "jdk.boot.class.path.append") == 0 &&
118                           value() != nullptr);
119   }
120 
121   // A system property should only have its value set
122   // via an external interface if it is a writeable property.
123   // The internal, non-writeable property jdk.boot.class.path.append
124   // is the only exception to this rule.  It can be set externally
125   // via -Xbootclasspath/a or JVMTI OnLoad phase call to AddToBootstrapClassLoaderSearch.
126   // In those cases for jdk.boot.class.path.append, the base class
127   // set_value and append_value methods are called directly.
128   void set_writeable_value(const char *value) {
129     if (writeable()) {
130       set_value(value);
131     }
132   }
133   void append_writeable_value(const char *value) {
134     if (writeable()) {
135       append_value(value);
136     }
137   }
138 
139   // Constructor
140   SystemProperty(const char* key, const char* value, bool writeable, bool internal = false);
141 
142   // for JVM_ReadSystemPropertiesInfo
143   static int key_offset_in_bytes()  { return (int)offset_of(SystemProperty, _key);  }
144   static int next_offset_in_bytes() { return (int)offset_of(SystemProperty, _next); }
145 };
146 
147 // Helper class for controlling the lifetime of JavaVMInitArgs objects.
148 class ScopedVMInitArgs;
149 
150 struct VMInitArgsGroup;
151 template <typename E, MemTag MT> class GrowableArrayCHeap;
152 
153 class Arguments : AllStatic {
154   friend class VMStructs;
155   friend class JvmtiExport;
156   friend class ArgumentsTest;
157   friend class LargeOptionsTest;
158  public:
159   // Operation modi
160   enum Mode {
161     _int,       // corresponds to -Xint
162     _mixed,     // corresponds to -Xmixed
163     _comp       // corresponds to -Xcomp
164   };
165 
166   enum ArgsRange {
167     arg_unreadable = -3,
168     arg_too_small  = -2,
169     arg_too_big    = -1,
170     arg_in_range   = 0
171   };
172 
173   enum PropertyAppendable {
174     AppendProperty,
175     AddProperty
176   };
177 
178   enum PropertyWriteable {
179     WriteableProperty,
180     UnwriteableProperty
181   };
182 
183   enum PropertyInternal {
184     InternalProperty,
185     ExternalProperty
186   };
187 
188  private:
189 
190   // a pointer to the flags file name if it is specified
191   static char*  _jvm_flags_file;
192   // an array containing all flags specified in the .hotspotrc file
193   static char** _jvm_flags_array;
194   static int    _num_jvm_flags;
195   // an array containing all jvm arguments specified in the command line
196   static char** _jvm_args_array;
197   static int    _num_jvm_args;
198   // string containing all java command (class/jarfile name and app args)
199   static char* _java_command;
200   // number of unique modules specified in the --add-modules option
201   static unsigned int _addmods_count;
202 #if INCLUDE_JVMCI
203   // was jdk.internal.vm.ci module specified in the --add-modules option?
204   static bool _jvmci_module_added;
205 #endif
206 
207   // Property list
208   static SystemProperty* _system_properties;
209 
210   // Quick accessor to System properties in the list:
211   static SystemProperty *_sun_boot_library_path;
212   static SystemProperty *_java_library_path;
213   static SystemProperty *_java_home;
214   static SystemProperty *_java_class_path;
215   static SystemProperty *_jdk_boot_class_path_append;
216   static SystemProperty *_vm_info;
217 
218   // --patch-module=module=<file>(<pathsep><file>)*
219   // Each element contains the associated module name, path
220   // string pair as specified to --patch-module.
221   static GrowableArray<ModulePatchPath*>* _patch_mod_prefix;
222 
223   // The constructed value of the system class path after
224   // argument processing and JVMTI OnLoad additions via
225   // calls to AddToBootstrapClassLoaderSearch.  This is the
226   // final form before ClassLoader::setup_bootstrap_search().
227   // Note: since --patch-module is a module name/path pair, the
228   // boot class path string no longer contains the "prefix"
229   // to the boot class path base piece as it did when
230   // -Xbootclasspath/p was supported.
231   static PathString* _boot_class_path;
232 
233   // Set if a modular java runtime image is present vs. a build with exploded modules
234   static bool _has_jimage;
235 
236   // temporary: to emit warning if the default ext dirs are not empty.
237   // remove this variable when the warning is no longer needed.
238   static char* _ext_dirs;
239 
240   // java.vendor.url.bug, bug reporting URL for fatal errors.
241   static const char* _java_vendor_url_bug;
242 
243   // sun.java.launcher, private property to provide information about
244   // java launcher
245   static const char* _sun_java_launcher;
246 
247   // was this VM created with the -XX:+ExecutingUnitTests option
248   static bool _executing_unit_tests;
249 
250   // for legacy gc options (-verbose:gc and -Xloggc:)
251   static LegacyGCLogging _legacyGCLogging;
252 
253   // Value of the conservative maximum heap alignment needed
254   static size_t  _conservative_max_heap_alignment;
255 
256   // Operation modi
257   static Mode _mode;
258 
259   // preview features
260   static bool _enable_preview;
261 
262   // jdwp
263   static bool _has_jdwp_agent;
264 
265   // Used to save default settings
266   static bool _AlwaysCompileLoopMethods;
267   static bool _UseOnStackReplacement;
268   static bool _BackgroundCompilation;
269   static bool _ClipInlining;
270 
271   // GC ergonomics
272   static void set_conservative_max_heap_alignment();
273   static void set_use_compressed_oops();
274   static jint set_ergonomics_flags();
275   static void set_compact_headers_flags();
276   // Limits the given heap size by the maximum amount of virtual
277   // memory this process is currently allowed to use. It also takes
278   // the virtual-to-physical ratio of the current GC into account.
279   static size_t limit_heap_by_allocatable_memory(size_t size);
280   // Setup heap size
281   static void set_heap_size();
282 
283   // Bytecode rewriting
284   static void set_bytecode_flags();
285 
286   // Invocation API hooks
287   static abort_hook_t     _abort_hook;
288   static exit_hook_t      _exit_hook;
289   static vfprintf_hook_t  _vfprintf_hook;
290 
291   // System properties
292   static bool add_property(const char* prop, PropertyWriteable writeable=WriteableProperty,
293                            PropertyInternal internal=ExternalProperty);
294 
295   // Used for module system related properties: converted from command-line flags.
296   // Basic properties are writeable as they operate as "last one wins" and will get overwritten.
297   // Numbered properties are never writeable, and always internal.
298   static bool create_module_property(const char* prop_name, const char* prop_value, PropertyInternal internal);
299   static bool create_numbered_module_property(const char* prop_base_name, const char* prop_value, unsigned int count);
300 
301   static int process_patch_mod_option(const char* patch_mod_tail);
302 
303   // Aggressive optimization flags.
304   static jint set_aggressive_opts_flags();
305 
306   static jint set_aggressive_heap_flags();
307 
308   // Argument parsing
309   static bool parse_argument(const char* arg, JVMFlagOrigin origin);
310   static bool process_argument(const char* arg, jboolean ignore_unrecognized, JVMFlagOrigin origin);
311   static void process_java_launcher_argument(const char*, void*);
312   static jint parse_options_environment_variable(const char* name, ScopedVMInitArgs* vm_args);
313   static jint parse_java_tool_options_environment_variable(ScopedVMInitArgs* vm_args);
314   static jint parse_java_options_environment_variable(ScopedVMInitArgs* vm_args);
315   static jint parse_jdk_aot_vm_options_environment_variable(GrowableArrayCHeap<VMInitArgsGroup, mtArguments>* all_args,
316                                                             ScopedVMInitArgs* jdk_aot_vm_options_args);
317   static jint parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args);
318   static jint parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args);
319   static jint parse_xss(const JavaVMOption* option, const char* tail, intx* out_ThreadStackSize);
320   static jint insert_vm_options_file(const JavaVMInitArgs* args,
321                                      const char* vm_options_file,
322                                      const int vm_options_file_pos,
323                                      ScopedVMInitArgs* vm_options_file_args,
324                                      ScopedVMInitArgs* args_out);
325   static bool args_contains_vm_options_file_arg(const JavaVMInitArgs* args);
326   static jint expand_vm_options_as_needed(const JavaVMInitArgs* args_in,
327                                           ScopedVMInitArgs* mod_args,
328                                           JavaVMInitArgs** args_out);
329   static jint match_special_option_and_act(const JavaVMInitArgs* args,
330                                            ScopedVMInitArgs* args_out);
331 
332   static bool handle_deprecated_print_gc_flags();
333 
334   static jint parse_vm_init_args(GrowableArrayCHeap<VMInitArgsGroup, mtArguments>* all_args);
335   static jint parse_each_vm_init_arg(const JavaVMInitArgs* args, JVMFlagOrigin origin);
336   static jint finalize_vm_init_args();
337   static bool is_bad_option(const JavaVMOption* option, jboolean ignore, const char* option_type);
338 
339   static bool is_bad_option(const JavaVMOption* option, jboolean ignore) {
340     return is_bad_option(option, ignore, nullptr);
341   }
342 
343   static void describe_range_error(ArgsRange errcode);
344   static ArgsRange check_memory_size(julong size, julong min_size, julong max_size);
345   static ArgsRange parse_memory_size(const char* s, julong* long_arg,
346                                      julong min_size, julong max_size = max_uintx);
347 
348   // methods to build strings from individual args
349   static void build_jvm_args(const char* arg);
350   static void build_jvm_flags(const char* arg);
351   static void add_string(char*** bldarray, int* count, const char* arg);
352   static const char* build_resource_string(char** args, int count);
353 
354   // Returns true if the flag is obsolete (and not yet expired).
355   // In this case the 'version' buffer is filled in with
356   // the version number when the flag became obsolete.
357   static bool is_obsolete_flag(const char* flag_name, JDK_Version* version);
358 
359   // Returns 1 if the flag is deprecated (and not yet obsolete or expired).
360   //     In this case the 'version' buffer is filled in with the version number when
361   //     the flag became deprecated.
362   // Returns -1 if the flag is expired or obsolete.
363   // Returns 0 otherwise.
364   static int is_deprecated_flag(const char* flag_name, JDK_Version* version);
365 
366   // Return the real name for the flag passed on the command line (either an alias name or "flag_name").
367   static const char* real_flag_name(const char *flag_name);
368   static JVMFlag* find_jvm_flag(const char* name, size_t name_length);
369 
370   // Return the "real" name for option arg if arg is an alias, and print a warning if arg is deprecated.
371   // Return nullptr if the arg has expired.
372   static const char* handle_aliases_and_deprecation(const char* arg);
373   static size_t _default_SharedBaseAddress; // The default value specified in globals.hpp
374 
375   static bool internal_module_property_helper(const char* property, bool check_for_cds);
376 
377  public:
378   // Parses the arguments, first phase
379   static jint parse(const JavaVMInitArgs* args);
380   // Parse a string for a unsigned integer.  Returns true if value
381   // is an unsigned integer greater than or equal to the minimum
382   // parameter passed and returns the value in uint_arg.  Returns
383   // false otherwise, with uint_arg undefined.
384   static bool parse_uint(const char* value, uint* uintx_arg,
385                          uint min_size);
386   // Apply ergonomics
387   static jint apply_ergo();
388   // Adjusts the arguments after the OS have adjusted the arguments
389   static jint adjust_after_os();
390 
391   // Check consistency or otherwise of VM argument settings
392   static bool check_vm_args_consistency();
393   // Used by os_solaris
394   static bool process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized);
395 
396   static size_t conservative_max_heap_alignment() { return _conservative_max_heap_alignment; }
397   // Return the maximum size a heap with compressed oops can take
398   static size_t max_heap_for_compressed_oops();
399 
400   // return a char* array containing all options
401   static char** jvm_flags_array()          { return _jvm_flags_array; }
402   static char** jvm_args_array()           { return _jvm_args_array; }
403   static int num_jvm_flags()               { return _num_jvm_flags; }
404   static int num_jvm_args()                { return _num_jvm_args; }
405   // return the arguments passed to the Java application
406   static const char* java_command()        { return _java_command; }
407 
408   // print jvm_flags, jvm_args and java_command
409   static void print_on(outputStream* st);
410   static void print_summary_on(outputStream* st);
411 
412   // convenient methods to get and set jvm_flags_file
413   static const char* get_jvm_flags_file()  { return _jvm_flags_file; }
414   static void set_jvm_flags_file(const char *value);
415 
416   // convenient methods to obtain / print jvm_flags and jvm_args
417   static const char* jvm_flags()           { return build_resource_string(_jvm_flags_array, _num_jvm_flags); }
418   static const char* jvm_args()            { return build_resource_string(_jvm_args_array, _num_jvm_args); }
419   static void print_jvm_flags_on(outputStream* st);
420   static void print_jvm_args_on(outputStream* st);
421 
422   // -Dkey=value flags
423   static SystemProperty*  system_properties()   { return _system_properties; }
424   static const char*    get_property(const char* key);
425 
426   // -Djava.vendor.url.bug
427   static const char* java_vendor_url_bug()  { return _java_vendor_url_bug; }
428 
429   // -Dsun.java.launcher
430   static const char* sun_java_launcher()    { return _sun_java_launcher; }
431   // Was VM created by a Java launcher?
432   static bool created_by_java_launcher();
433   // -XX:+ExecutingUnitTests
434   static bool executing_unit_tests();
435 
436   // abort, exit, vfprintf hooks
437   static abort_hook_t    abort_hook()       { return _abort_hook; }
438   static exit_hook_t     exit_hook()        { return _exit_hook; }
439   static vfprintf_hook_t vfprintf_hook()    { return _vfprintf_hook; }
440 
441   static void no_shared_spaces(const char* message);
442   static size_t default_SharedBaseAddress() { return _default_SharedBaseAddress; }
443   // Java launcher properties
444   static void process_sun_java_launcher_properties(JavaVMInitArgs* args);
445 
446   // System properties
447   static void init_system_properties();
448 
449   // Update/Initialize System properties after JDK version number is known
450   static void init_version_specific_system_properties();
451 
452   // Update VM info property - called after argument parsing
453   static void update_vm_info_property(const char* vm_info) {
454     _vm_info->set_value(vm_info);
455   }
456 
457   // Property List manipulation
458   static void PropertyList_add(SystemProperty *element);
459   static void PropertyList_add(SystemProperty** plist, SystemProperty *element);
460   static void PropertyList_add(SystemProperty** plist, const char* k, const char* v, bool writeable, bool internal);
461 
462   static void PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v,
463                                       PropertyAppendable append, PropertyWriteable writeable,
464                                       PropertyInternal internal);
465   static const char* PropertyList_get_value(SystemProperty* plist, const char* key);
466   static const char* PropertyList_get_readable_value(SystemProperty* plist, const char* key);
467   static int  PropertyList_count(SystemProperty* pl);
468   static int  PropertyList_readable_count(SystemProperty* pl);
469 
470   static bool is_internal_module_property(const char* option);
471   static bool is_incompatible_cds_internal_module_property(const char* property);
472 
473   // Miscellaneous System property value getter and setters.
474   static void set_dll_dir(const char *value) { _sun_boot_library_path->set_value(value); }
475   static void set_java_home(const char *value) { _java_home->set_value(value); }
476   static void set_library_path(const char *value) { _java_library_path->set_value(value); }
477   static void set_ext_dirs(char *value);
478 
479   // Set up the underlying pieces of the boot class path
480   static void add_patch_mod_prefix(const char *module_name, const char *path);
481   static void set_boot_class_path(const char *value, bool has_jimage) {
482     // During start up, set by os::set_boot_path()
483     assert(get_boot_class_path() == nullptr, "Boot class path previously set");
484     _boot_class_path->set_value(value);
485     _has_jimage = has_jimage;
486   }
487   static void append_sysclasspath(const char *value) {
488     _boot_class_path->append_value(value);
489     _jdk_boot_class_path_append->append_value(value);
490   }
491 
492   static GrowableArray<ModulePatchPath*>* get_patch_mod_prefix() { return _patch_mod_prefix; }
493   static char* get_boot_class_path() { return _boot_class_path->value(); }
494   static bool has_jimage() { return _has_jimage; }
495 
496   static char* get_java_home()    { return _java_home->value(); }
497   static char* get_dll_dir()      { return _sun_boot_library_path->value(); }
498   static char* get_appclasspath() { return _java_class_path->value(); }
499   static void  fix_appclasspath();
500 
501   // Operation modi
502   static Mode mode()                { return _mode;           }
503   static void set_mode_flags(Mode mode);
504   static bool is_interpreter_only() { return mode() == _int;  }
505   static bool is_compiler_only()    { return mode() == _comp; }
506 
507 
508   // preview features
509   static void set_enable_preview() { _enable_preview = true; }
510   static bool enable_preview() { return _enable_preview; }
511 
512   // jdwp
513   static bool has_jdwp_agent() { return _has_jdwp_agent; }
514 
515   // Utility: copies src into buf, replacing "%%" with "%" and "%p" with pid.
516   static bool copy_expand_pid(const char* src, size_t srclen, char* buf, size_t buflen);
517 
518   static bool atojulong(const char *s, julong* result);
519 
520   static bool has_jfr_option() NOT_JFR_RETURN_(false);
521 
522   DEBUG_ONLY(static bool verify_special_jvm_flags(bool check_globals);)
523 };
524 
525 // Disable options not supported in this release, with a warning if they
526 // were explicitly requested on the command-line
527 #define UNSUPPORTED_OPTION(opt)                          \
528 do {                                                     \
529   if (opt) {                                             \
530     if (FLAG_IS_CMDLINE(opt)) {                          \
531       warning("-XX:+" #opt " not supported in this VM"); \
532     }                                                    \
533     FLAG_SET_DEFAULT(opt, false);                        \
534   }                                                      \
535 } while(0)
536 
537 // similar to UNSUPPORTED_OPTION but sets flag to nullptr
538 #define UNSUPPORTED_OPTION_NULL(opt)                         \
539 do {                                                         \
540   if (opt) {                                                 \
541     if (FLAG_IS_CMDLINE(opt)) {                              \
542       warning("-XX flag " #opt " not supported in this VM"); \
543     }                                                        \
544     FLAG_SET_DEFAULT(opt, nullptr);                          \
545   }                                                          \
546 } while(0)
547 
548 // Initialize options not supported in this release, with a warning
549 // if they were explicitly requested on the command-line
550 #define UNSUPPORTED_OPTION_INIT(opt, value)              \
551 do {                                                     \
552   if (FLAG_IS_CMDLINE(opt)) {                            \
553     warning("-XX flag " #opt " not supported in this VM"); \
554   }                                                      \
555   FLAG_SET_DEFAULT(opt, value);                          \
556 } while(0)
557 
558 #endif // SHARE_RUNTIME_ARGUMENTS_HPP