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