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 #include "precompiled.hpp"
 26 #include "jfr/jfrEvents.hpp"
 27 #include "jvm_io.h"
 28 #include "memory/allocation.inline.hpp"
 29 #include "memory/universe.hpp"
 30 #include "runtime/arguments.hpp"
 31 #include "runtime/flags/jvmFlag.hpp"
 32 #include "runtime/flags/jvmFlagAccess.hpp"
 33 #include "runtime/flags/jvmFlagLookup.hpp"
 34 #include "runtime/globals_extension.hpp"
 35 #include "utilities/defaultStream.hpp"
 36 #include "utilities/stringUtils.hpp"
 37 
 38 static bool is_product_build() {
 39 #ifdef PRODUCT
 40   return true;
 41 #else
 42   return false;
 43 #endif
 44 }
 45 
 46 void JVMFlag::set_origin(JVMFlagOrigin new_origin) {
 47   int old_flags = _flags;
 48   int origin = static_cast<int>(new_origin);
 49   assert((origin & VALUE_ORIGIN_MASK) == origin, "sanity");
 50   int was_in_cmdline = (new_origin == JVMFlagOrigin::COMMAND_LINE) ? WAS_SET_ON_COMMAND_LINE : 0;
 51   _flags = Flags((_flags & ~VALUE_ORIGIN_MASK) | origin | was_in_cmdline);
 52   if ((old_flags & WAS_SET_ON_COMMAND_LINE) != 0) {
 53     assert((_flags & WAS_SET_ON_COMMAND_LINE) != 0, "once initialized, should never change");
 54   }
 55 }
 56 
 57 /**
 58  * Returns if this flag is a constant in the binary.  Right now this is
 59  * true for develop flags in product builds.
 60  */
 61 bool JVMFlag::is_constant_in_binary() const {
 62 #ifdef PRODUCT
 63   return is_develop();
 64 #else
 65   return false;
 66 #endif
 67 }
 68 
 69 bool JVMFlag::is_unlocker() const {
 70   return strcmp(_name, "UnlockDiagnosticVMOptions") == 0 ||
 71          strcmp(_name, "UnlockExperimentalVMOptions") == 0;
 72 }
 73 
 74 bool JVMFlag::is_unlocked() const {
 75   if (is_diagnostic()) {
 76     return UnlockDiagnosticVMOptions;
 77   }
 78   if (is_experimental()) {
 79     return UnlockExperimentalVMOptions;
 80   }
 81   return true;
 82 }
 83 
 84 void JVMFlag::clear_diagnostic() {
 85   assert(is_diagnostic(), "sanity");
 86   _flags = Flags(_flags & ~KIND_DIAGNOSTIC);
 87   assert(!is_diagnostic(), "sanity");
 88 }
 89 
 90 void JVMFlag::clear_experimental() {
 91   assert(is_experimental(), "sanity");
 92   _flags = Flags(_flags & ~KIND_EXPERIMENTAL);
 93   assert(!is_experimental(), "sanity");
 94 }
 95 
 96 void JVMFlag::set_product() {
 97   assert(!is_product(), "sanity");
 98   _flags = Flags(_flags | KIND_PRODUCT);
 99   assert(is_product(), "sanity");
100 }
101 
102 // Get custom message for this locked flag, or null if
103 // none is available. Returns message type produced.
104 JVMFlag::MsgType JVMFlag::get_locked_message(char* buf, int buflen) const {
105   buf[0] = '\0';
106   if (is_diagnostic() && !is_unlocked()) {
107     jio_snprintf(buf, buflen,
108                  "Error: VM option '%s' is diagnostic and must be enabled via -XX:+UnlockDiagnosticVMOptions.\n"
109                  "Error: The unlock option must precede '%s'.\n",
110                  _name, _name);
111     return JVMFlag::DIAGNOSTIC_FLAG_BUT_LOCKED;
112   }
113   if (is_experimental() && !is_unlocked()) {
114     jio_snprintf(buf, buflen,
115                  "Error: VM option '%s' is experimental and must be enabled via -XX:+UnlockExperimentalVMOptions.\n"
116                  "Error: The unlock option must precede '%s'.\n",
117                  _name, _name);
118     return JVMFlag::EXPERIMENTAL_FLAG_BUT_LOCKED;
119   }
120   if (is_develop() && is_product_build()) {
121     jio_snprintf(buf, buflen, "Error: VM option '%s' is develop and is available only in debug version of VM.\n",
122                  _name);
123     return JVMFlag::DEVELOPER_FLAG_BUT_PRODUCT_BUILD;
124   }
125   return JVMFlag::NONE;
126 }
127 
128 // Helper function for JVMFlag::print_on().
129 // Fills current line up to requested position.
130 // Should the current position already be past the requested position,
131 // one separator blank is enforced.
132 static void fill_to_pos(outputStream* st, unsigned int req_pos) {
133   if ((unsigned int)st->position() < req_pos) {
134     st->fill_to(req_pos);  // need to fill with blanks to reach req_pos
135   } else {
136     st->print(" ");        // enforce blank separation. Previous field too long.
137   }
138 }
139 
140 void JVMFlag::print_on(outputStream* st, bool withComments, bool printRanges) const {
141   // Don't print develop flags in a product build.
142   if (is_constant_in_binary()) {
143     return;
144   }
145 
146   if (!printRanges) {
147     // The command line options -XX:+PrintFlags* cause this function to be called
148     // for each existing flag to print information pertinent to this flag. The data
149     // is displayed in columnar form, with the following layout:
150     //  col1 - data type, right-justified
151     //  col2 - name,      left-justified
152     //  col3 - ' ='       double-char, leading space to align with possible '+='
153     //  col4 - value      left-justified
154     //  col5 - kind       right-justified
155     //  col6 - origin     left-justified
156     //  col7 - comments   left-justified
157     //
158     //  The column widths are fixed. They are defined such that, for most cases,
159     //  an eye-pleasing tabular output is created.
160     //
161     //  Sample output:
162     //       bool ThreadPriorityVerbose                    = false                                     {product} {default}
163     //      uintx ThresholdTolerance                       = 10                                        {product} {default}
164     //     size_t TLABSize                                 = 0                                         {product} {default}
165     //      uintx SurvivorRatio                            = 8                                         {product} {default}
166     //     double InitialRAMPercentage                     = 1.562500                                  {product} {default}
167     //      ccstr CompileCommandFile                       = MyFile.cmd                                {product} {command line}
168     //  ccstrlist CompileOnly                              = Method1
169     //            CompileOnly                             += Method2                                   {product} {command line}
170     //  |         |                                       |  |                              |                    |               |
171     //  |         |                                       |  |                              |                    |               +-- col7
172     //  |         |                                       |  |                              |                    +-- col6
173     //  |         |                                       |  |                              +-- col5
174     //  |         |                                       |  +-- col4
175     //  |         |                                       +-- col3
176     //  |         +-- col2
177     //  +-- col1
178 
179     const unsigned int col_spacing = 1;
180     const unsigned int col1_pos    = 0;
181     const unsigned int col1_width  = 9;
182     const unsigned int col2_pos    = col1_pos + col1_width + col_spacing;
183     const unsigned int col2_width  = 39;
184     const unsigned int col3_pos    = col2_pos + col2_width + col_spacing;
185     const unsigned int col3_width  = 2;
186     const unsigned int col4_pos    = col3_pos + col3_width + col_spacing;
187     const unsigned int col4_width  = 30;
188     const unsigned int col5_pos    = col4_pos + col4_width + col_spacing;
189     const unsigned int col5_width  = 20;
190     const unsigned int col6_pos    = col5_pos + col5_width + col_spacing;
191     const unsigned int col6_width  = 15;
192     const unsigned int col7_pos    = col6_pos + col6_width + col_spacing;
193     const unsigned int col7_width  = 1;
194 
195     st->fill_to(col1_pos);
196     st->print("%*s", col1_width, type_string());  // right-justified, therefore width is required.
197 
198     fill_to_pos(st, col2_pos);
199     st->print("%s", _name);
200 
201     fill_to_pos(st, col3_pos);
202     st->print(" =");  // use " =" for proper alignment with multiline ccstr output.
203 
204     fill_to_pos(st, col4_pos);
205     if (is_bool()) {
206       st->print("%s", get_bool() ? "true" : "false");
207     } else if (is_int()) {
208       st->print("%d", get_int());
209     } else if (is_uint()) {
210       st->print("%u", get_uint());
211     } else if (is_intx()) {
212       st->print(INTX_FORMAT, get_intx());
213     } else if (is_uintx()) {
214       st->print(UINTX_FORMAT, get_uintx());
215     } else if (is_uint64_t()) {
216       st->print(UINT64_FORMAT, get_uint64_t());
217     } else if (is_size_t()) {
218       st->print(SIZE_FORMAT, get_size_t());
219     } else if (is_double()) {
220       st->print("%f", get_double());
221     } else if (is_ccstr()) {
222       // Honor <newline> characters in ccstr: print multiple lines.
223       const char* cp = get_ccstr();
224       if (cp != nullptr) {
225         const char* eol;
226         while ((eol = strchr(cp, '\n')) != nullptr) {
227           size_t llen = pointer_delta(eol, cp, sizeof(char));
228           st->print("%.*s", (int)llen, cp);
229           st->cr();
230           cp = eol+1;
231           fill_to_pos(st, col2_pos);
232           st->print("%s", _name);
233           fill_to_pos(st, col3_pos);
234           st->print("+=");
235           fill_to_pos(st, col4_pos);
236         }
237         st->print("%s", cp);
238       }
239     } else {
240       st->print("unhandled  type %s", type_string());
241       st->cr();
242       return;
243     }
244 
245     fill_to_pos(st, col5_pos);
246     print_kind(st, col5_width);
247 
248     fill_to_pos(st, col6_pos);
249     print_origin(st, col6_width);
250 
251 #ifndef PRODUCT
252     if (withComments) {
253       fill_to_pos(st, col7_pos);
254       st->print("%s", _doc);
255     }
256 #endif
257     st->cr();
258   } else if (!is_bool() && !is_ccstr()) {
259     // The command line options -XX:+PrintFlags* cause this function to be called
260     // for each existing flag to print information pertinent to this flag. The data
261     // is displayed in columnar form, with the following layout:
262     //  col1 - data type, right-justified
263     //  col2 - name,      left-justified
264     //  col4 - range      [ min ... max]
265     //  col5 - kind       right-justified
266     //  col6 - origin     left-justified
267     //  col7 - comments   left-justified
268     //
269     //  The column widths are fixed. They are defined such that, for most cases,
270     //  an eye-pleasing tabular output is created.
271     //
272     //  Sample output:
273     //       intx MinPassesBeforeFlush                               [ 0                         ...       9223372036854775807 ]                         {diagnostic} {default}
274     //     double MinRAMPercentage                                   [ 0.000                     ...                   100.000 ]                            {product} {default}
275     //      uintx MinSurvivorRatio                                   [ 3                         ...      18446744073709551615 ]                            {product} {default}
276     //     size_t MinTLABSize                                        [ 1                         ...       9223372036854775807 ]                            {product} {default}
277     //       intx MaxInlineSize                                      [ 0                         ...                2147483647 ]                            {product} {default}
278     //  |         |                                                  |                                                           |                                    |               |
279     //  |         |                                                  |                                                           |                                    |               +-- col7
280     //  |         |                                                  |                                                           |                                    +-- col6
281     //  |         |                                                  |                                                           +-- col5
282     //  |         |                                                  +-- col4
283     //  |         +-- col2
284     //  +-- col1
285 
286     const unsigned int col_spacing = 1;
287     const unsigned int col1_pos    = 0;
288     const unsigned int col1_width  = 9;
289     const unsigned int col2_pos    = col1_pos + col1_width + col_spacing;
290     const unsigned int col2_width  = 49;
291     const unsigned int col3_pos    = col2_pos + col2_width + col_spacing;
292     const unsigned int col3_width  = 0;
293     const unsigned int col4_pos    = col3_pos + col3_width + col_spacing;
294     const unsigned int col4_width  = 60;
295     const unsigned int col5_pos    = col4_pos + col4_width + col_spacing;
296     const unsigned int col5_width  = 35;
297     const unsigned int col6_pos    = col5_pos + col5_width + col_spacing;
298     const unsigned int col6_width  = 15;
299     const unsigned int col7_pos    = col6_pos + col6_width + col_spacing;
300     const unsigned int col7_width  = 1;
301 
302     st->fill_to(col1_pos);
303     st->print("%*s", col1_width, type_string());  // right-justified, therefore width is required.
304 
305     fill_to_pos(st, col2_pos);
306     st->print("%s", _name);
307 
308     fill_to_pos(st, col4_pos);
309     JVMFlagAccess::print_range(st, this);
310 
311     fill_to_pos(st, col5_pos);
312     print_kind(st, col5_width);
313 
314     fill_to_pos(st, col6_pos);
315     print_origin(st, col6_width);
316 
317 #ifndef PRODUCT
318     if (withComments) {
319       fill_to_pos(st, col7_pos);
320       st->print("%s", _doc);
321     }
322 #endif
323     st->cr();
324   }
325 }
326 
327 void JVMFlag::print_kind(outputStream* st, unsigned int width) const {
328   struct Data {
329     int flag;
330     const char* name;
331   };
332 
333   Data data[] = {
334     { KIND_JVMCI, "JVMCI" },
335     { KIND_C1, "C1" },
336     { KIND_C2, "C2" },
337     { KIND_ARCH, "ARCH" },
338     { KIND_PLATFORM_DEPENDENT, "pd" },
339     { KIND_PRODUCT, "product" },
340     { KIND_MANAGEABLE, "manageable" },
341     { KIND_DIAGNOSTIC, "diagnostic" },
342     { KIND_EXPERIMENTAL, "experimental" },
343     { KIND_DEVELOP, "develop" },
344     { KIND_LP64_PRODUCT, "lp64_product" },
345     { -1, "" }
346   };
347 
348   if ((_flags & KIND_MASK) != 0) {
349     bool is_first = true;
350     const size_t buffer_size = 64;
351     size_t buffer_used = 0;
352     char kind[buffer_size];
353 
354     jio_snprintf(kind, buffer_size, "{");
355     buffer_used++;
356     for (int i = 0; data[i].flag != -1; i++) {
357       Data d = data[i];
358       if ((_flags & d.flag) != 0) {
359         if (is_first) {
360           is_first = false;
361         } else {
362           assert(buffer_used + 1 < buffer_size, "Too small buffer");
363           jio_snprintf(kind + buffer_used, buffer_size - buffer_used, " ");
364           buffer_used++;
365         }
366         size_t length = strlen(d.name);
367         assert(buffer_used + length < buffer_size, "Too small buffer");
368         jio_snprintf(kind + buffer_used, buffer_size - buffer_used, "%s", d.name);
369         buffer_used += length;
370       }
371     }
372     assert(buffer_used + 2 <= buffer_size, "Too small buffer");
373     jio_snprintf(kind + buffer_used, buffer_size - buffer_used, "}");
374     st->print("%*s", width, kind);
375   }
376 }
377 
378 void JVMFlag::print_origin(outputStream* st, unsigned int width) const {
379   st->print("{");
380   switch(get_origin()) {
381     case JVMFlagOrigin::DEFAULT:
382       st->print("default"); break;
383     case JVMFlagOrigin::COMMAND_LINE:
384       st->print("command line"); break;
385     case JVMFlagOrigin::ENVIRON_VAR:
386       st->print("environment"); break;
387     case JVMFlagOrigin::CONFIG_FILE:
388       st->print("config file"); break;
389     case JVMFlagOrigin::MANAGEMENT:
390       st->print("management"); break;
391     case JVMFlagOrigin::ERGONOMIC:
392       if (_flags & WAS_SET_ON_COMMAND_LINE) {
393         st->print("command line, ");
394       }
395       st->print("ergonomic"); break;
396     case JVMFlagOrigin::ATTACH_ON_DEMAND:
397       st->print("attach"); break;
398     case JVMFlagOrigin::INTERNAL:
399       st->print("internal"); break;
400     case JVMFlagOrigin::JIMAGE_RESOURCE:
401       st->print("jimage"); break;
402   }
403   st->print("}");
404 }
405 
406 void JVMFlag::print_as_flag(outputStream* st) const {
407   if (is_bool()) {
408     st->print("-XX:%s%s", get_bool() ? "+" : "-", _name);
409   } else if (is_int()) {
410     st->print("-XX:%s=%d", _name, get_int());
411   } else if (is_uint()) {
412     st->print("-XX:%s=%u", _name, get_uint());
413   } else if (is_intx()) {
414     st->print("-XX:%s=" INTX_FORMAT, _name, get_intx());
415   } else if (is_uintx()) {
416     st->print("-XX:%s=" UINTX_FORMAT, _name, get_uintx());
417   } else if (is_uint64_t()) {
418     st->print("-XX:%s=" UINT64_FORMAT, _name, get_uint64_t());
419   } else if (is_size_t()) {
420     st->print("-XX:%s=" SIZE_FORMAT, _name, get_size_t());
421   } else if (is_double()) {
422     st->print("-XX:%s=%f", _name, get_double());
423   } else if (is_ccstr()) {
424     st->print("-XX:%s=", _name);
425     const char* cp = get_ccstr();
426     if (cp != nullptr) {
427       // Need to turn embedded '\n's back into separate arguments
428       // Not so efficient to print one character at a time,
429       // but the choice is to do the transformation to a buffer
430       // and print that.  And this need not be efficient.
431       for (; *cp != '\0'; cp += 1) {
432         switch (*cp) {
433           default:
434             st->print("%c", *cp);
435             break;
436           case '\n':
437             st->print(" -XX:%s=", _name);
438             break;
439         }
440       }
441     }
442   } else {
443     ShouldNotReachHere();
444   }
445 }
446 
447 //----------------------------------------------------------------------
448 // Build flagTable[]
449 
450 // Find out the number of LP64/ARCH/JVMCI/COMPILER1/COMPILER2 flags,
451 // for JVMFlag::flag_group()
452 
453 #define ENUM_F(type, name, ...)  enum_##name,
454 #define IGNORE_F(...)
455 
456 //                                                  dev     dev-pd  pro     pro-pd  range     constraint
457 enum FlagCounter_LP64  { LP64_RUNTIME_FLAGS(        ENUM_F, ENUM_F, ENUM_F, ENUM_F, IGNORE_F, IGNORE_F)  num_flags_LP64   };
458 enum FlagCounter_ARCH  { ARCH_FLAGS(                ENUM_F,         ENUM_F,         IGNORE_F, IGNORE_F)  num_flags_ARCH   };
459 enum FlagCounter_JVMCI { JVMCI_ONLY(JVMCI_FLAGS(    ENUM_F, ENUM_F, ENUM_F, ENUM_F, IGNORE_F, IGNORE_F)) num_flags_JVMCI  };
460 enum FlagCounter_C1    { COMPILER1_PRESENT(C1_FLAGS(ENUM_F, ENUM_F, ENUM_F, ENUM_F, IGNORE_F, IGNORE_F)) num_flags_C1     };
461 enum FlagCounter_C2    { COMPILER2_PRESENT(C2_FLAGS(ENUM_F, ENUM_F, ENUM_F, ENUM_F, IGNORE_F, IGNORE_F)) num_flags_C2     };
462 
463 const int first_flag_enum_LP64   = 0;
464 const int first_flag_enum_ARCH   = first_flag_enum_LP64  + num_flags_LP64;
465 const int first_flag_enum_JVMCI  = first_flag_enum_ARCH  + num_flags_ARCH;
466 const int first_flag_enum_C1     = first_flag_enum_JVMCI + num_flags_JVMCI;
467 const int first_flag_enum_C2     = first_flag_enum_C1    + num_flags_C1;
468 const int first_flag_enum_other  = first_flag_enum_C2    + num_flags_C2;
469 
470 static constexpr int flag_group(int flag_enum) {
471   if (flag_enum < first_flag_enum_ARCH)  return JVMFlag::KIND_LP64_PRODUCT;
472   if (flag_enum < first_flag_enum_JVMCI) return JVMFlag::KIND_ARCH;
473   if (flag_enum < first_flag_enum_C1)    return JVMFlag::KIND_JVMCI;
474   if (flag_enum < first_flag_enum_C2)    return JVMFlag::KIND_C1;
475   if (flag_enum < first_flag_enum_other) return JVMFlag::KIND_C2;
476 
477   return 0;
478 }
479 
480 constexpr JVMFlag::JVMFlag(int flag_enum, FlagType type, const char* name,
481                            void* addr, int flags, int extra_flags, const char* doc) :
482   _addr(addr), _name(name), _flags(), _type(type) NOT_PRODUCT(COMMA _doc(doc)) {
483   flags = flags | extra_flags | static_cast<int>(JVMFlagOrigin::DEFAULT) | flag_group(flag_enum);
484   if ((flags & JVMFlag::KIND_PRODUCT) != 0) {
485     if (flags & (JVMFlag::KIND_DIAGNOSTIC | JVMFlag::KIND_MANAGEABLE | JVMFlag::KIND_EXPERIMENTAL)) {
486       // Backwards compatibility. This will be relaxed in JDK-7123237.
487       flags &= ~(JVMFlag::KIND_PRODUCT);
488     }
489   }
490   _flags = static_cast<Flags>(flags);
491 }
492 
493 constexpr JVMFlag::JVMFlag(int flag_enum,  FlagType type, const char* name,
494                            void* addr, int flags, const char* doc) :
495   JVMFlag(flag_enum, type, name, addr, flags, /*extra_flags*/0, doc) {}
496 
497 const int PRODUCT_KIND     = JVMFlag::KIND_PRODUCT;
498 const int PRODUCT_KIND_PD  = JVMFlag::KIND_PRODUCT | JVMFlag::KIND_PLATFORM_DEPENDENT;
499 const int DEVELOP_KIND     = JVMFlag::KIND_DEVELOP;
500 const int DEVELOP_KIND_PD  = JVMFlag::KIND_DEVELOP | JVMFlag::KIND_PLATFORM_DEPENDENT;
501 
502 #define FLAG_TYPE(type) (JVMFlag::TYPE_ ## type)
503 #define INITIALIZE_DEVELOP_FLAG(   type, name, value, ...) JVMFlag(FLAG_MEMBER_ENUM(name), FLAG_TYPE(type), XSTR(name), (void*)&name, DEVELOP_KIND,    __VA_ARGS__),
504 #define INITIALIZE_DEVELOP_FLAG_PD(type, name,        ...) JVMFlag(FLAG_MEMBER_ENUM(name), FLAG_TYPE(type), XSTR(name), (void*)&name, DEVELOP_KIND_PD, __VA_ARGS__),
505 #define INITIALIZE_PRODUCT_FLAG(   type, name, value, ...) JVMFlag(FLAG_MEMBER_ENUM(name), FLAG_TYPE(type), XSTR(name), (void*)&name, PRODUCT_KIND,    __VA_ARGS__),
506 #define INITIALIZE_PRODUCT_FLAG_PD(type, name,        ...) JVMFlag(FLAG_MEMBER_ENUM(name), FLAG_TYPE(type), XSTR(name), (void*)&name, PRODUCT_KIND_PD, __VA_ARGS__),
507 
508 // Handy aliases to match the symbols used in the flag specification macros.
509 const int DIAGNOSTIC   = JVMFlag::KIND_DIAGNOSTIC;
510 const int MANAGEABLE   = JVMFlag::KIND_MANAGEABLE;
511 const int EXPERIMENTAL = JVMFlag::KIND_EXPERIMENTAL;
512 
513 #define MATERIALIZE_ALL_FLAGS      \
514   ALL_FLAGS(INITIALIZE_DEVELOP_FLAG,     \
515             INITIALIZE_DEVELOP_FLAG_PD,  \
516             INITIALIZE_PRODUCT_FLAG,     \
517             INITIALIZE_PRODUCT_FLAG_PD,  \
518             IGNORE_RANGE,          \
519             IGNORE_CONSTRAINT)
520 
521 static JVMFlag flagTable[NUM_JVMFlagsEnum + 1] = {
522   MATERIALIZE_ALL_FLAGS
523   JVMFlag() // The iteration code wants a flag with a null name at the end of the table.
524 };
525 
526 // We want flagTable[] to be completely initialized at C++ compilation time, which requires
527 // that all arguments passed to JVMFlag() constructors be constexpr. The following line
528 // checks for this -- if any non-constexpr arguments are passed, the C++ compiler will
529 // generate an error.
530 //
531 // constexpr implies internal linkage. This means the flagTable_verify_constexpr[] variable
532 // will not be included in jvmFlag.o, so there's no footprint cost for having this variable.
533 //
534 // Note that we cannot declare flagTable[] as constexpr because JVMFlag::_flags is modified
535 // at runtime.
536 constexpr JVMFlag flagTable_verify_constexpr[] = { MATERIALIZE_ALL_FLAGS };
537 
538 JVMFlag* JVMFlag::flags = flagTable;
539 size_t JVMFlag::numFlags = (sizeof(flagTable) / sizeof(JVMFlag));
540 
541 #define JVM_FLAG_TYPE_SIGNATURE(t) JVMFlag::type_signature<t>(),
542 
543 const int JVMFlag::type_signatures[] = {
544   JVM_FLAG_NON_STRING_TYPES_DO(JVM_FLAG_TYPE_SIGNATURE)
545   JVMFlag::type_signature<ccstr>(),
546   JVMFlag::type_signature<ccstr>()
547 };
548 
549 // Search the flag table for a named flag
550 JVMFlag* JVMFlag::find_flag(const char* name, size_t length, bool allow_locked, bool return_flag) {
551   JVMFlag* flag = JVMFlagLookup::find(name, length);
552   if (flag != nullptr) {
553     // Found a matching entry.
554     // Don't report develop flags in product builds.
555     if (flag->is_constant_in_binary()) {
556       return (return_flag ? flag : nullptr);
557     }
558     // Report locked flags only if allowed.
559     if (!(flag->is_unlocked() || flag->is_unlocker())) {
560       if (!allow_locked) {
561         // disable use of locked flags, e.g. diagnostic, experimental,
562         // etc. until they are explicitly unlocked
563         return nullptr;
564       }
565     }
566     return flag;
567   }
568   // JVMFlag name is not in the flag table
569   return nullptr;
570 }
571 
572 JVMFlag* JVMFlag::fuzzy_match(const char* name, size_t length, bool allow_locked) {
573   double VMOptionsFuzzyMatchSimilarity = 0.7;
574   JVMFlag* match = nullptr;
575   double score;
576   double max_score = -1;
577 
578   for (JVMFlag* current = &flagTable[0]; current->_name != nullptr; current++) {
579     score = StringUtils::similarity(current->_name, strlen(current->_name), name, length);
580     if (score > max_score) {
581       max_score = score;
582       match = current;
583     }
584   }
585 
586   if (match == nullptr) {
587     return nullptr;
588   }
589 
590   if (!(match->is_unlocked() || match->is_unlocker())) {
591     if (!allow_locked) {
592       return nullptr;
593     }
594   }
595 
596   if (max_score < VMOptionsFuzzyMatchSimilarity) {
597     return nullptr;
598   }
599 
600   return match;
601 }
602 
603 bool JVMFlag::is_default(JVMFlagsEnum flag) {
604   return flag_from_enum(flag)->is_default();
605 }
606 
607 bool JVMFlag::is_ergo(JVMFlagsEnum flag) {
608   return flag_from_enum(flag)->is_ergonomic();
609 }
610 
611 bool JVMFlag::is_cmdline(JVMFlagsEnum flag) {
612   return flag_from_enum(flag)->is_command_line();
613 }
614 
615 bool JVMFlag::is_jimage_resource(JVMFlagsEnum flag) {
616   return flag_from_enum(flag)->is_jimage_resource();
617 }
618 
619 void JVMFlag::setOnCmdLine(JVMFlagsEnum flag) {
620   flag_from_enum(flag)->set_command_line();
621 }
622 
623 extern "C" {
624   static int compare_flags(const void* void_a, const void* void_b) {
625     return strcmp((*((JVMFlag**) void_a))->name(), (*((JVMFlag**) void_b))->name());
626   }
627 }
628 
629 void JVMFlag::printSetFlags(outputStream* out) {
630   // Print which flags were set on the command line
631   // note: this method is called before the thread structure is in place
632   //       which means resource allocation cannot be used.
633 
634   // The last entry is the null entry.
635   const size_t length = JVMFlag::numFlags - 1;
636 
637   // Sort
638   JVMFlag** array = NEW_C_HEAP_ARRAY(JVMFlag*, length, mtArguments);
639   for (size_t i = 0; i < length; i++) {
640     array[i] = &flagTable[i];
641   }
642   qsort(array, length, sizeof(JVMFlag*), compare_flags);
643 
644   // Print
645   for (size_t i = 0; i < length; i++) {
646     if (array[i]->get_origin() != JVMFlagOrigin::DEFAULT) {
647       array[i]->print_as_flag(out);
648       out->print(" ");
649     }
650   }
651   out->cr();
652   FREE_C_HEAP_ARRAY(JVMFlag*, array);
653 }
654 
655 #ifndef PRODUCT
656 
657 void JVMFlag::verify() {
658   assert(Arguments::check_vm_args_consistency(), "Some flag settings conflict");
659 }
660 
661 #endif // PRODUCT
662 
663 #ifdef ASSERT
664 
665 void JVMFlag::assert_valid_flag_enum(JVMFlagsEnum i) {
666   assert(0 <= int(i) && int(i) < NUM_JVMFlagsEnum, "must be");
667 }
668 
669 void JVMFlag::check_all_flag_declarations() {
670   for (JVMFlag* current = &flagTable[0]; current->_name != nullptr; current++) {
671     int flags = static_cast<int>(current->_flags);
672     // Backwards compatibility. This will be relaxed/removed in JDK-7123237.
673     int mask = JVMFlag::KIND_DIAGNOSTIC | JVMFlag::KIND_MANAGEABLE | JVMFlag::KIND_EXPERIMENTAL;
674     if ((flags & mask) != 0) {
675       assert((flags & mask) == JVMFlag::KIND_DIAGNOSTIC ||
676              (flags & mask) == JVMFlag::KIND_MANAGEABLE ||
677              (flags & mask) == JVMFlag::KIND_EXPERIMENTAL,
678              "%s can be declared with at most one of "
679              "DIAGNOSTIC, MANAGEABLE or EXPERIMENTAL", current->_name);
680       assert((flags & KIND_DEVELOP) == 0,
681              "%s has an optional DIAGNOSTIC, MANAGEABLE or EXPERIMENTAL "
682              "attribute; it must be declared as a product flag", current->_name);
683     }
684   }
685 }
686 
687 #endif // ASSERT
688 
689 void JVMFlag::printFlags(outputStream* out, bool withComments, bool printRanges, bool skipDefaults) {
690   // Print the flags sorted by name
691   // Note: This method may be called before the thread structure is in place
692   //       which means resource allocation cannot be used. Also, it may be
693   //       called as part of error reporting, so handle native OOMs gracefully.
694 
695   // The last entry is the null entry.
696   const size_t length = JVMFlag::numFlags - 1;
697 
698   const char* tag = 0;
699   if (xtty_owns(out))
700     xtty->head("%s", tag = !Universe::is_fully_initialized()
701                ? "vm_flags_initial" : "vm_flags_final");
702 
703   // Print
704   if (!printRanges) {
705     out->print_cr("[Global flags]");
706   } else {
707     out->print_cr("[Global flags ranges]");
708   }
709 
710   // Sort
711   JVMFlag** array = NEW_C_HEAP_ARRAY_RETURN_NULL(JVMFlag*, length, mtArguments);
712   if (array != nullptr) {
713     for (size_t i = 0; i < length; i++) {
714       array[i] = &flagTable[i];
715     }
716     qsort(array, length, sizeof(JVMFlag*), compare_flags);
717 
718     for (size_t i = 0; i < length; i++) {
719       if (array[i]->is_unlocked() && !(skipDefaults && array[i]->is_default())) {
720         array[i]->print_on(out, withComments, printRanges);
721       }
722     }
723     FREE_C_HEAP_ARRAY(JVMFlag*, array);
724   } else {
725     // OOM? Print unsorted.
726     for (size_t i = 0; i < length; i++) {
727       if (flagTable[i].is_unlocked() && !(skipDefaults && flagTable[i].is_default())) {
728         flagTable[i].print_on(out, withComments, printRanges);
729       }
730     }
731   }
732   if (xtty_owns(out))
733     xtty->tail(tag);
734 }
735 
736 void JVMFlag::printError(bool verbose, const char* msg, ...) {
737   if (verbose) {
738     va_list listPointer;
739     va_start(listPointer, msg);
740     jio_vfprintf(defaultStream::error_stream(), msg, listPointer);
741     va_end(listPointer);
742   }
743 }