1 // Copyright (c) 1999, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 // Revamped and reorganized by Craig Silverstein
33 // This file contains the implementation of all our command line flags
34 // stuff. Here's how everything fits together
36 // * FlagRegistry owns CommandLineFlags owns FlagValue.
37 // * FlagSaver holds a FlagRegistry (saves it at construct time,
38 // restores it at destroy time).
39 // * CommandLineFlagParser lives outside that hierarchy, but works on
40 // CommandLineFlags (modifying the FlagValues).
41 // * Free functions like SetCommandLineOption() work via one of the
42 // above (such as CommandLineFlagParser).
46 // -- The main classes that hold flag data:
48 // FlagValue holds the current value of a flag. It's
49 // pseudo-templatized: every operation on a FlagValue is typed. It
50 // also deals with storage-lifetime issues (so flag values don't go
51 // away in a destructor), which is why we need a whole class to hold a
54 // CommandLineFlag is all the information about a single command-line
55 // flag. It has a FlagValue for the flag's current value, but also
56 // the flag's name, type, etc.
58 // FlagRegistry is a collection of CommandLineFlags. There's the
59 // global registry, which is where flags defined via DEFINE_foo()
60 // live. But it's possible to define your own flag, manually, in a
61 // different registry you create. (In practice, multiple registries
62 // are used only by FlagSaver).
64 // A given FlagValue is owned by exactly one CommandLineFlag. A given
65 // CommandLineFlag is owned by exactly one FlagRegistry. FlagRegistry
66 // has a lock; any operation that writes to a FlagValue or
67 // CommandLineFlag owned by that registry must acquire the
68 // FlagRegistry lock before doing so.
70 // --- Some other classes and free functions:
72 // CommandLineFlagInfo is a client-exposed version of CommandLineFlag.
73 // Once it's instantiated, it has no dependencies or relationships
74 // with any other part of this file.
76 // FlagRegisterer is the helper class used by the DEFINE_* macros to
77 // allow work to be done at global initialization time.
79 // CommandLineFlagParser is the class that reads from the commandline
80 // and instantiates flag values based on that. It needs to poke into
81 // the innards of the FlagValue->CommandLineFlag->FlagRegistry class
82 // hierarchy to do that. It's careful to acquire the FlagRegistry
83 // lock before doing any writing or other non-const actions.
85 // GetCommandLineOption is just a hook into registry routines to
86 // retrieve a flag based on its name. SetCommandLineOption, on the
87 // other hand, hooks into CommandLineFlagParser. Other API functions
88 // are, similarly, mostly hooks into the functionality described above.
96 #if defined(HAVE_FNMATCH_H)
98 #elif defined(HAVE_SHLWAPI_H)
99 # define NO_SHLWAPI_ISOS
100 # include <shlwapi.h>
102 #include <stdarg.h> // For va_list and related operations
109 #include <utility> // for pair<>
115 using namespace MUTEX_NAMESPACE;
118 // Special flags, type 1: the 'recursive' flags. They set another flag's val.
119 DEFINE_string(flagfile, "", "load flags from file");
120 DEFINE_string(fromenv, "", "set flags from the environment"
121 " [use 'export FLAGS_flag1=value']");
122 DEFINE_string(tryfromenv, "", "set flags from the environment if present");
124 // Special flags, type 2: the 'parsing' flags. They modify how we parse.
125 DEFINE_string(undefok, "", "comma-separated list of flag names that it is okay to specify "
126 "on the command line even if the program does not define a flag "
127 "with that name. IMPORTANT: flags in this list that have "
128 "arguments MUST use the flag=value format");
130 namespace GFLAGS_NAMESPACE {
138 // This is used by the unittest to test error-exit code
139 void GFLAGS_DLL_DECL (*gflags_exitfunc)(int) = &exit; // from stdlib.h
142 // The help message indicating that the commandline flag has been
143 // 'stripped'. It will not show up when doing "-help" and its
144 // variants. The flag is stripped if STRIP_FLAG_HELP is set to 1
145 // before including base/gflags.h
147 // This is used by this file, and also in gflags_reporting.cc
148 const char kStrippedFlagHelp[] = "\001\002\003\004 (unknown) \004\003\002\001";
152 // There are also 'reporting' flags, in gflags_reporting.cc.
154 static const char kError[] = "ERROR: ";
156 // Indicates that undefined options are to be ignored.
157 // Enables deferred processing of flags in dynamically loaded libraries.
158 static bool allow_command_line_reparsing = false;
160 static bool logging_is_probably_set_up = false;
162 // This is a 'prototype' validate-function. 'Real' validate
163 // functions, take a flag-value as an argument: ValidateFn(bool) or
164 // ValidateFn(uint64). However, for easier storage, we strip off this
165 // argument and then restore it when actually calling the function on
167 typedef bool (*ValidateFnProto)();
169 // Whether we should die when reporting an error.
170 enum DieWhenReporting { DIE, DO_NOT_DIE };
172 // Report Error and exit if requested.
173 static void ReportError(DieWhenReporting should_die, const char* format, ...) {
175 va_start(ap, format);
176 vfprintf(stderr, format, ap);
178 fflush(stderr); // should be unnecessary, but cygwin's rxvt buffers stderr
179 if (should_die == DIE) gflags_exitfunc(1);
183 // --------------------------------------------------------------------
185 // This represent the value a single flag might have. The major
186 // functionality is to convert from a string to an object of a
187 // given type, and back. Thread-compatible.
188 // --------------------------------------------------------------------
190 class CommandLineFlag;
204 template <typename FlagType>
205 FlagValue(FlagType* valbuf, bool transfer_ownership_of_value);
208 bool ParseFrom(const char* spec);
209 string ToString() const;
211 ValueType Type() const { return static_cast<ValueType>(type_); }
214 friend class CommandLineFlag; // for many things, including Validate()
215 friend class GFLAGS_NAMESPACE::FlagSaverImpl; // calls New()
216 friend class FlagRegistry; // checks value_buffer_ for flags_by_ptr_ map
217 template <typename T> friend T GetFromEnv(const char*, T);
218 friend bool TryParseLocked(const CommandLineFlag*, FlagValue*,
219 const char*, string*); // for New(), CopyFrom()
221 template <typename FlagType>
222 struct FlagValueTraits;
224 const char* TypeName() const;
225 bool Equal(const FlagValue& x) const;
226 FlagValue* New() const; // creates a new one with default value
227 void CopyFrom(const FlagValue& x);
228 int ValueSize() const;
230 // Calls the given validate-fn on value_buffer_, and returns
231 // whatever it returns. But first casts validate_fn_proto to a
232 // function that takes our value as an argument (eg void
233 // (*validate_fn)(bool) for a bool flag).
234 bool Validate(const char* flagname, ValidateFnProto validate_fn_proto) const;
236 void* const value_buffer_; // points to the buffer holding our data
237 const int8 type_; // how to interpret value_
238 const bool owns_value_; // whether to free value on destruct
240 FlagValue(const FlagValue&); // no copying!
241 void operator=(const FlagValue&);
244 // Map the given C++ type to a value of the ValueType enum at compile time.
245 #define DEFINE_FLAG_TRAITS(type, value) \
247 struct FlagValue::FlagValueTraits<type> { \
248 static const ValueType kValueType = value; \
251 // Define full template specializations of the FlagValueTraits template
252 // for all supported flag types.
253 DEFINE_FLAG_TRAITS(bool, FV_BOOL);
254 DEFINE_FLAG_TRAITS(int32, FV_INT32);
255 DEFINE_FLAG_TRAITS(uint32, FV_UINT32);
256 DEFINE_FLAG_TRAITS(int64, FV_INT64);
257 DEFINE_FLAG_TRAITS(uint64, FV_UINT64);
258 DEFINE_FLAG_TRAITS(double, FV_DOUBLE);
259 DEFINE_FLAG_TRAITS(std::string, FV_STRING);
261 #undef DEFINE_FLAG_TRAITS
264 // This could be a templated method of FlagValue, but doing so adds to the
265 // size of the .o. Since there's no type-safety here anyway, macro is ok.
266 #define VALUE_AS(type) *reinterpret_cast<type*>(value_buffer_)
267 #define OTHER_VALUE_AS(fv, type) *reinterpret_cast<type*>(fv.value_buffer_)
268 #define SET_VALUE_AS(type, value) VALUE_AS(type) = (value)
270 template <typename FlagType>
271 FlagValue::FlagValue(FlagType* valbuf,
272 bool transfer_ownership_of_value)
273 : value_buffer_(valbuf),
274 type_(FlagValueTraits<FlagType>::kValueType),
275 owns_value_(transfer_ownership_of_value) {
278 FlagValue::~FlagValue() {
283 case FV_BOOL: delete reinterpret_cast<bool*>(value_buffer_); break;
284 case FV_INT32: delete reinterpret_cast<int32*>(value_buffer_); break;
285 case FV_UINT32: delete reinterpret_cast<uint32*>(value_buffer_); break;
286 case FV_INT64: delete reinterpret_cast<int64*>(value_buffer_); break;
287 case FV_UINT64: delete reinterpret_cast<uint64*>(value_buffer_); break;
288 case FV_DOUBLE: delete reinterpret_cast<double*>(value_buffer_); break;
289 case FV_STRING: delete reinterpret_cast<string*>(value_buffer_); break;
293 bool FlagValue::ParseFrom(const char* value) {
294 if (type_ == FV_BOOL) {
295 const char* kTrue[] = { "1", "t", "true", "y", "yes" };
296 const char* kFalse[] = { "0", "f", "false", "n", "no" };
297 COMPILE_ASSERT(sizeof(kTrue) == sizeof(kFalse), true_false_equal);
298 for (size_t i = 0; i < sizeof(kTrue)/sizeof(*kTrue); ++i) {
299 if (strcasecmp(value, kTrue[i]) == 0) {
300 SET_VALUE_AS(bool, true);
302 } else if (strcasecmp(value, kFalse[i]) == 0) {
303 SET_VALUE_AS(bool, false);
307 return false; // didn't match a legal input
309 } else if (type_ == FV_STRING) {
310 SET_VALUE_AS(string, value);
314 // OK, it's likely to be numeric, and we'll be using a strtoXXX method.
315 if (value[0] == '\0') // empty-string is only allowed for string type.
318 // Leading 0x puts us in base 16. But leading 0 does not put us in base 8!
319 // It caused too many bugs when we had that behavior.
320 int base = 10; // by default
321 if (value[0] == '0' && (value[1] == 'x' || value[1] == 'X'))
327 const int64 r = strto64(value, &end, base);
328 if (errno || end != value + strlen(value)) return false; // bad parse
329 if (static_cast<int32>(r) != r) // worked, but number out of range
331 SET_VALUE_AS(int32, static_cast<int32>(r));
335 while (*value == ' ') value++;
336 if (*value == '-') return false; // negative number
337 const uint64 r = strtou64(value, &end, base);
338 if (errno || end != value + strlen(value)) return false; // bad parse
339 if (static_cast<uint32>(r) != r) // worked, but number out of range
341 SET_VALUE_AS(uint32, static_cast<uint32>(r));
345 const int64 r = strto64(value, &end, base);
346 if (errno || end != value + strlen(value)) return false; // bad parse
347 SET_VALUE_AS(int64, r);
351 while (*value == ' ') value++;
352 if (*value == '-') return false; // negative number
353 const uint64 r = strtou64(value, &end, base);
354 if (errno || end != value + strlen(value)) return false; // bad parse
355 SET_VALUE_AS(uint64, r);
359 const double r = strtod(value, &end);
360 if (errno || end != value + strlen(value)) return false; // bad parse
361 SET_VALUE_AS(double, r);
365 assert(false); // unknown type
371 string FlagValue::ToString() const {
372 char intbuf[64]; // enough to hold even the biggest number
375 return VALUE_AS(bool) ? "true" : "false";
377 snprintf(intbuf, sizeof(intbuf), "%" PRId32, VALUE_AS(int32));
380 snprintf(intbuf, sizeof(intbuf), "%" PRIu32, VALUE_AS(uint32));
383 snprintf(intbuf, sizeof(intbuf), "%" PRId64, VALUE_AS(int64));
386 snprintf(intbuf, sizeof(intbuf), "%" PRIu64, VALUE_AS(uint64));
389 snprintf(intbuf, sizeof(intbuf), "%.17g", VALUE_AS(double));
392 return VALUE_AS(string);
395 return ""; // unknown type
399 bool FlagValue::Validate(const char* flagname,
400 ValidateFnProto validate_fn_proto) const {
403 return reinterpret_cast<bool (*)(const char*, bool)>(
404 validate_fn_proto)(flagname, VALUE_AS(bool));
406 return reinterpret_cast<bool (*)(const char*, int32)>(
407 validate_fn_proto)(flagname, VALUE_AS(int32));
409 return reinterpret_cast<bool (*)(const char*, uint32)>(
410 validate_fn_proto)(flagname, VALUE_AS(uint32));
412 return reinterpret_cast<bool (*)(const char*, int64)>(
413 validate_fn_proto)(flagname, VALUE_AS(int64));
415 return reinterpret_cast<bool (*)(const char*, uint64)>(
416 validate_fn_proto)(flagname, VALUE_AS(uint64));
418 return reinterpret_cast<bool (*)(const char*, double)>(
419 validate_fn_proto)(flagname, VALUE_AS(double));
421 return reinterpret_cast<bool (*)(const char*, const string&)>(
422 validate_fn_proto)(flagname, VALUE_AS(string));
424 assert(false); // unknown type
429 const char* FlagValue::TypeName() const {
430 static const char types[] =
438 if (type_ > FV_MAX_INDEX) {
442 // Directly indexing the strings in the 'types' string, each of them is 7 bytes long.
443 return &types[type_ * 7];
446 bool FlagValue::Equal(const FlagValue& x) const {
447 if (type_ != x.type_)
450 case FV_BOOL: return VALUE_AS(bool) == OTHER_VALUE_AS(x, bool);
451 case FV_INT32: return VALUE_AS(int32) == OTHER_VALUE_AS(x, int32);
452 case FV_UINT32: return VALUE_AS(uint32) == OTHER_VALUE_AS(x, uint32);
453 case FV_INT64: return VALUE_AS(int64) == OTHER_VALUE_AS(x, int64);
454 case FV_UINT64: return VALUE_AS(uint64) == OTHER_VALUE_AS(x, uint64);
455 case FV_DOUBLE: return VALUE_AS(double) == OTHER_VALUE_AS(x, double);
456 case FV_STRING: return VALUE_AS(string) == OTHER_VALUE_AS(x, string);
457 default: assert(false); return false; // unknown type
461 FlagValue* FlagValue::New() const {
463 case FV_BOOL: return new FlagValue(new bool(false), true);
464 case FV_INT32: return new FlagValue(new int32(0), true);
465 case FV_UINT32: return new FlagValue(new uint32(0), true);
466 case FV_INT64: return new FlagValue(new int64(0), true);
467 case FV_UINT64: return new FlagValue(new uint64(0), true);
468 case FV_DOUBLE: return new FlagValue(new double(0.0), true);
469 case FV_STRING: return new FlagValue(new string, true);
470 default: assert(false); return NULL; // unknown type
474 void FlagValue::CopyFrom(const FlagValue& x) {
475 assert(type_ == x.type_);
477 case FV_BOOL: SET_VALUE_AS(bool, OTHER_VALUE_AS(x, bool)); break;
478 case FV_INT32: SET_VALUE_AS(int32, OTHER_VALUE_AS(x, int32)); break;
479 case FV_UINT32: SET_VALUE_AS(uint32, OTHER_VALUE_AS(x, uint32)); break;
480 case FV_INT64: SET_VALUE_AS(int64, OTHER_VALUE_AS(x, int64)); break;
481 case FV_UINT64: SET_VALUE_AS(uint64, OTHER_VALUE_AS(x, uint64)); break;
482 case FV_DOUBLE: SET_VALUE_AS(double, OTHER_VALUE_AS(x, double)); break;
483 case FV_STRING: SET_VALUE_AS(string, OTHER_VALUE_AS(x, string)); break;
484 default: assert(false); // unknown type
488 int FlagValue::ValueSize() const {
489 if (type_ > FV_MAX_INDEX) {
490 assert(false); // unknown type
493 static const uint8 valuesize[] = {
502 return valuesize[type_];
505 // --------------------------------------------------------------------
507 // This represents a single flag, including its name, description,
508 // default value, and current value. Mostly this serves as a
509 // struct, though it also knows how to register itself.
510 // All CommandLineFlags are owned by a (exactly one)
511 // FlagRegistry. If you wish to modify fields in this class, you
512 // should acquire the FlagRegistry lock for the registry that owns
514 // --------------------------------------------------------------------
516 class CommandLineFlag {
518 // Note: we take over memory-ownership of current_val and default_val.
519 CommandLineFlag(const char* name, const char* help, const char* filename,
520 FlagValue* current_val, FlagValue* default_val);
523 const char* name() const { return name_; }
524 const char* help() const { return help_; }
525 const char* filename() const { return file_; }
526 const char* CleanFileName() const; // nixes irrelevant prefix such as homedir
527 string current_value() const { return current_->ToString(); }
528 string default_value() const { return defvalue_->ToString(); }
529 const char* type_name() const { return defvalue_->TypeName(); }
530 ValidateFnProto validate_function() const { return validate_fn_proto_; }
531 const void* flag_ptr() const { return current_->value_buffer_; }
533 FlagValue::ValueType Type() const { return defvalue_->Type(); }
535 void FillCommandLineFlagInfo(struct CommandLineFlagInfo* result);
537 // If validate_fn_proto_ is non-NULL, calls it on value, returns result.
538 bool Validate(const FlagValue& value) const;
539 bool ValidateCurrent() const { return Validate(*current_); }
540 bool Modified() const { return modified_; }
543 // for SetFlagLocked() and setting flags_by_ptr_
544 friend class FlagRegistry;
545 friend class GFLAGS_NAMESPACE::FlagSaverImpl; // for cloning the values
547 friend bool AddFlagValidator(const void*, ValidateFnProto);
549 // This copies all the non-const members: modified, processed, defvalue, etc.
550 void CopyFrom(const CommandLineFlag& src);
552 void UpdateModifiedBit();
554 const char* const name_; // Flag name
555 const char* const help_; // Help message
556 const char* const file_; // Which file did this come from?
557 bool modified_; // Set after default assignment?
558 FlagValue* defvalue_; // Default value for flag
559 FlagValue* current_; // Current value for flag
560 // This is a casted, 'generic' version of validate_fn, which actually
561 // takes a flag-value as an arg (void (*validate_fn)(bool), say).
562 // When we pass this to current_->Validate(), it will cast it back to
563 // the proper type. This may be NULL to mean we have no validate_fn.
564 ValidateFnProto validate_fn_proto_;
566 CommandLineFlag(const CommandLineFlag&); // no copying!
567 void operator=(const CommandLineFlag&);
570 CommandLineFlag::CommandLineFlag(const char* name, const char* help,
571 const char* filename,
572 FlagValue* current_val, FlagValue* default_val)
573 : name_(name), help_(help), file_(filename), modified_(false),
574 defvalue_(default_val), current_(current_val), validate_fn_proto_(NULL) {
577 CommandLineFlag::~CommandLineFlag() {
582 const char* CommandLineFlag::CleanFileName() const {
583 // Compute top-level directory & file that this appears in
584 // search full path backwards.
585 // Stop going backwards at kRootDir; and skip by the first slash.
586 static const char kRootDir[] = ""; // can set this to root directory,
588 if (sizeof(kRootDir)-1 == 0) // no prefix to strip
591 const char* clean_name = filename() + strlen(filename()) - 1;
592 while ( clean_name > filename() ) {
593 if (*clean_name == PATH_SEPARATOR) {
594 if (strncmp(clean_name, kRootDir, sizeof(kRootDir)-1) == 0) {
595 clean_name += sizeof(kRootDir)-1; // past root-dir
601 while ( *clean_name == PATH_SEPARATOR ) ++clean_name; // Skip any slashes
605 void CommandLineFlag::FillCommandLineFlagInfo(
606 CommandLineFlagInfo* result) {
607 result->name = name();
608 result->type = type_name();
609 result->description = help();
610 result->current_value = current_value();
611 result->default_value = default_value();
612 result->filename = CleanFileName();
614 result->is_default = !modified_;
615 result->has_validator_fn = validate_function() != NULL;
616 result->flag_ptr = flag_ptr();
619 void CommandLineFlag::UpdateModifiedBit() {
620 // Update the "modified" bit in case somebody bypassed the
621 // Flags API and wrote directly through the FLAGS_name variable.
622 if (!modified_ && !current_->Equal(*defvalue_)) {
627 void CommandLineFlag::CopyFrom(const CommandLineFlag& src) {
628 // Note we only copy the non-const members; others are fixed at construct time
629 if (modified_ != src.modified_) modified_ = src.modified_;
630 if (!current_->Equal(*src.current_)) current_->CopyFrom(*src.current_);
631 if (!defvalue_->Equal(*src.defvalue_)) defvalue_->CopyFrom(*src.defvalue_);
632 if (validate_fn_proto_ != src.validate_fn_proto_)
633 validate_fn_proto_ = src.validate_fn_proto_;
636 bool CommandLineFlag::Validate(const FlagValue& value) const {
638 if (validate_function() == NULL)
641 return value.Validate(name(), validate_function());
645 // --------------------------------------------------------------------
647 // A FlagRegistry singleton object holds all flag objects indexed
648 // by their names so that if you know a flag's name (as a C
649 // string), you can access or set it. If the function is named
650 // FooLocked(), you must own the registry lock before calling
651 // the function; otherwise, you should *not* hold the lock, and
652 // the function will acquire it itself if needed.
653 // --------------------------------------------------------------------
655 struct StringCmp { // Used by the FlagRegistry map class to compare char*'s
656 bool operator() (const char* s1, const char* s2) const {
657 return (strcmp(s1, s2) < 0);
667 // Not using STLDeleteElements as that resides in util and this
669 for (FlagMap::iterator p = flags_.begin(), e = flags_.end(); p != e; ++p) {
670 CommandLineFlag* flag = p->second;
675 static void DeleteGlobalRegistry() {
676 delete global_registry_;
677 global_registry_ = NULL;
680 // Store a flag in this registry. Takes ownership of the given pointer.
681 void RegisterFlag(CommandLineFlag* flag);
683 void Lock() { lock_.Lock(); }
684 void Unlock() { lock_.Unlock(); }
686 // Returns the flag object for the specified name, or NULL if not found.
687 CommandLineFlag* FindFlagLocked(const char* name);
689 // Returns the flag object whose current-value is stored at flag_ptr.
690 // That is, for whom current_->value_buffer_ == flag_ptr
691 CommandLineFlag* FindFlagViaPtrLocked(const void* flag_ptr);
693 // A fancier form of FindFlag that works correctly if name is of the
694 // form flag=value. In that case, we set key to point to flag, and
695 // modify v to point to the value (if present), and return the flag
696 // with the given name. If the flag does not exist, returns NULL
697 // and sets error_message.
698 CommandLineFlag* SplitArgumentLocked(const char* argument,
699 string* key, const char** v,
700 string* error_message);
702 // Set the value of a flag. If the flag was successfully set to
703 // value, set msg to indicate the new flag-value, and return true.
704 // Otherwise, set msg to indicate the error, leave flag unchanged,
705 // and return false. msg can be NULL.
706 bool SetFlagLocked(CommandLineFlag* flag, const char* value,
707 FlagSettingMode set_mode, string* msg);
709 static FlagRegistry* GlobalRegistry(); // returns a singleton registry
712 friend class GFLAGS_NAMESPACE::FlagSaverImpl; // reads all the flags in order to copy them
713 friend class CommandLineFlagParser; // for ValidateUnmodifiedFlags
714 friend void GFLAGS_NAMESPACE::GetAllFlags(vector<CommandLineFlagInfo>*);
716 // The map from name to flag, for FindFlagLocked().
717 typedef map<const char*, CommandLineFlag*, StringCmp> FlagMap;
718 typedef FlagMap::iterator FlagIterator;
719 typedef FlagMap::const_iterator FlagConstIterator;
722 // The map from current-value pointer to flag, fo FindFlagViaPtrLocked().
723 typedef map<const void*, CommandLineFlag*> FlagPtrMap;
724 FlagPtrMap flags_by_ptr_;
726 static FlagRegistry* global_registry_; // a singleton registry
729 static Mutex global_registry_lock_;
731 static void InitGlobalRegistry();
734 FlagRegistry(const FlagRegistry&);
735 FlagRegistry& operator=(const FlagRegistry&);
738 class FlagRegistryLock {
740 explicit FlagRegistryLock(FlagRegistry* fr) : fr_(fr) { fr_->Lock(); }
741 ~FlagRegistryLock() { fr_->Unlock(); }
743 FlagRegistry *const fr_;
747 void FlagRegistry::RegisterFlag(CommandLineFlag* flag) {
749 pair<FlagIterator, bool> ins =
750 flags_.insert(pair<const char*, CommandLineFlag*>(flag->name(), flag));
751 if (ins.second == false) { // means the name was already in the map
752 if (strcmp(ins.first->second->filename(), flag->filename()) != 0) {
753 ReportError(DIE, "ERROR: flag '%s' was defined more than once "
754 "(in files '%s' and '%s').\n",
756 ins.first->second->filename(),
759 ReportError(DIE, "ERROR: something wrong with flag '%s' in file '%s'. "
760 "One possibility: file '%s' is being linked both statically "
761 "and dynamically into this executable.\n",
763 flag->filename(), flag->filename());
766 // Also add to the flags_by_ptr_ map.
767 flags_by_ptr_[flag->current_->value_buffer_] = flag;
771 CommandLineFlag* FlagRegistry::FindFlagLocked(const char* name) {
772 FlagConstIterator i = flags_.find(name);
773 if (i == flags_.end()) {
774 // If the name has dashes in it, try again after replacing with
776 if (strchr(name, '-') == NULL) return NULL;
777 string name_rep = name;
778 std::replace(name_rep.begin(), name_rep.end(), '-', '_');
779 return FindFlagLocked(name_rep.c_str());
785 CommandLineFlag* FlagRegistry::FindFlagViaPtrLocked(const void* flag_ptr) {
786 FlagPtrMap::const_iterator i = flags_by_ptr_.find(flag_ptr);
787 if (i == flags_by_ptr_.end()) {
794 CommandLineFlag* FlagRegistry::SplitArgumentLocked(const char* arg,
797 string* error_message) {
798 // Find the flag object for this option
799 const char* flag_name;
800 const char* value = strchr(arg, '=');
805 // Strip out the "=value" portion from arg
806 key->assign(arg, value-arg);
807 *v = ++value; // advance past the '='
809 flag_name = key->c_str();
811 CommandLineFlag* flag = FindFlagLocked(flag_name);
814 // If we can't find the flag-name, then we should return an error.
815 // The one exception is if 1) the flag-name is 'nox', 2) there
816 // exists a flag named 'x', and 3) 'x' is a boolean flag.
817 // In that case, we want to return flag 'x'.
818 if (!(flag_name[0] == 'n' && flag_name[1] == 'o')) {
819 // flag-name is not 'nox', so we're not in the exception case.
820 *error_message = StringPrintf("%sunknown command line flag '%s'\n",
821 kError, key->c_str());
824 flag = FindFlagLocked(flag_name+2);
826 // No flag named 'x' exists, so we're not in the exception case.
827 *error_message = StringPrintf("%sunknown command line flag '%s'\n",
828 kError, key->c_str());
831 if (flag->Type() != FlagValue::FV_BOOL) {
832 // 'x' exists but is not boolean, so we're not in the exception case.
833 *error_message = StringPrintf(
834 "%sboolean value (%s) specified for %s command line flag\n",
835 kError, key->c_str(), flag->type_name());
838 // We're in the exception case!
839 // Make up a fake value to replace the "no" we stripped out
840 key->assign(flag_name+2); // the name without the "no"
844 // Assign a value if this is a boolean flag
845 if (*v == NULL && flag->Type() == FlagValue::FV_BOOL) {
846 *v = "1"; // the --nox case was already handled, so this is the --x case
852 bool TryParseLocked(const CommandLineFlag* flag, FlagValue* flag_value,
853 const char* value, string* msg) {
854 // Use tenative_value, not flag_value, until we know value is valid.
855 FlagValue* tentative_value = flag_value->New();
856 if (!tentative_value->ParseFrom(value)) {
859 "%sillegal value '%s' specified for %s flag '%s'\n",
861 flag->type_name(), flag->name());
863 delete tentative_value;
865 } else if (!flag->Validate(*tentative_value)) {
868 "%sfailed validation of new value '%s' for flag '%s'\n",
869 kError, tentative_value->ToString().c_str(),
872 delete tentative_value;
875 flag_value->CopyFrom(*tentative_value);
877 StringAppendF(msg, "%s set to %s\n",
878 flag->name(), flag_value->ToString().c_str());
880 delete tentative_value;
885 bool FlagRegistry::SetFlagLocked(CommandLineFlag* flag,
887 FlagSettingMode set_mode,
889 flag->UpdateModifiedBit();
891 case SET_FLAGS_VALUE: {
892 // set or modify the flag's value
893 if (!TryParseLocked(flag, flag->current_, value, msg))
895 flag->modified_ = true;
898 case SET_FLAG_IF_DEFAULT: {
899 // set the flag's value, but only if it hasn't been set by someone else
900 if (!flag->modified_) {
901 if (!TryParseLocked(flag, flag->current_, value, msg))
903 flag->modified_ = true;
905 *msg = StringPrintf("%s set to %s",
906 flag->name(), flag->current_value().c_str());
910 case SET_FLAGS_DEFAULT: {
911 // modify the flag's default-value
912 if (!TryParseLocked(flag, flag->defvalue_, value, msg))
914 if (!flag->modified_) {
915 // Need to set both defvalue *and* current, in this case
916 TryParseLocked(flag, flag->current_, value, NULL);
930 // Get the singleton FlagRegistry object
931 FlagRegistry* FlagRegistry::global_registry_ = NULL;
932 Mutex FlagRegistry::global_registry_lock_(Mutex::LINKER_INITIALIZED);
934 FlagRegistry* FlagRegistry::GlobalRegistry() {
935 MutexLock acquire_lock(&global_registry_lock_);
936 if (!global_registry_) {
937 global_registry_ = new FlagRegistry;
939 return global_registry_;
942 // --------------------------------------------------------------------
943 // CommandLineFlagParser
944 // Parsing is done in two stages. In the first, we go through
945 // argv. For every flag-like arg we can make sense of, we parse
946 // it and set the appropriate FLAGS_* variable. For every flag-
947 // like arg we can't make sense of, we store it in a vector,
948 // along with an explanation of the trouble. In stage 2, we
949 // handle the 'reporting' flags like --help and --mpm_version.
950 // (This is via a call to HandleCommandLineHelpFlags(), in
951 // gflags_reporting.cc.)
952 // An optional stage 3 prints out the error messages.
953 // This is a bit of a simplification. For instance, --flagfile
954 // is handled as soon as it's seen in stage 1, not in stage 2.
955 // --------------------------------------------------------------------
957 class CommandLineFlagParser {
959 // The argument is the flag-registry to register the parsed flags in
960 explicit CommandLineFlagParser(FlagRegistry* reg) : registry_(reg) {}
961 ~CommandLineFlagParser() {}
963 // Stage 1: Every time this is called, it reads all flags in argv.
964 // However, it ignores all flags that have been successfully set
965 // before. Typically this is only called once, so this 'reparsing'
966 // behavior isn't important. It can be useful when trying to
967 // reparse after loading a dll, though.
968 uint32 ParseNewCommandLineFlags(int* argc, char*** argv, bool remove_flags);
970 // Stage 2: print reporting info and exit, if requested.
971 // In gflags_reporting.cc:HandleCommandLineHelpFlags().
973 // Stage 3: validate all the commandline flags that have validators
974 // registered and were not set/modified by ParseNewCommandLineFlags.
975 void ValidateFlags(bool all);
976 void ValidateAllFlags();
977 void ValidateUnmodifiedFlags();
979 // Stage 4: report any errors and return true if any were found.
982 // Set a particular command line option. "newval" is a string
983 // describing the new value that the option has been set to. If
984 // option_name does not specify a valid option name, or value is not
985 // a valid value for option_name, newval is empty. Does recursive
986 // processing for --flagfile and --fromenv. Returns the new value
987 // if everything went ok, or empty-string if not. (Actually, the
988 // return-string could hold many flag/value pairs due to --flagfile.)
989 // NB: Must have called registry_->Lock() before calling this function.
990 string ProcessSingleOptionLocked(CommandLineFlag* flag,
992 FlagSettingMode set_mode);
994 // Set a whole batch of command line options as specified by contentdata,
995 // which is in flagfile format (and probably has been read from a flagfile).
996 // Returns the new value if everything went ok, or empty-string if
997 // not. (Actually, the return-string could hold many flag/value
998 // pairs due to --flagfile.)
999 // NB: Must have called registry_->Lock() before calling this function.
1000 string ProcessOptionsFromStringLocked(const string& contentdata,
1001 FlagSettingMode set_mode);
1003 // These are the 'recursive' flags, defined at the top of this file.
1004 // Whenever we see these flags on the commandline, we must take action.
1005 // These are called by ProcessSingleOptionLocked and, similarly, return
1006 // new values if everything went ok, or the empty-string if not.
1007 string ProcessFlagfileLocked(const string& flagval, FlagSettingMode set_mode);
1008 // diff fromenv/tryfromenv
1009 string ProcessFromenvLocked(const string& flagval, FlagSettingMode set_mode,
1010 bool errors_are_fatal);
1013 FlagRegistry* const registry_;
1014 map<string, string> error_flags_; // map from name to error message
1015 // This could be a set<string>, but we reuse the map to minimize the .o size
1016 map<string, string> undefined_names_; // --[flag] name was not registered
1020 // Parse a list of (comma-separated) flags.
1021 static void ParseFlagList(const char* value, vector<string>* flags) {
1022 for (const char *p = value; p && *p; value = p) {
1023 p = strchr(value, ',');
1029 len = strlen(value);
1033 ReportError(DIE, "ERROR: empty flaglist entry\n");
1034 if (value[0] == '-')
1035 ReportError(DIE, "ERROR: flag \"%*s\" begins with '-'\n", len, value);
1037 flags->push_back(string(value, len));
1041 // Snarf an entire file into a C++ string. This is just so that we
1042 // can do all the I/O in one place and not worry about it everywhere.
1043 // Plus, it's convenient to have the whole file contents at hand.
1044 // Adds a newline at the end of the file.
1045 #define PFATAL(s) do { perror(s); gflags_exitfunc(1); } while (0)
1047 static string ReadFileIntoString(const char* filename) {
1048 const int kBufSize = 8092;
1049 char buffer[kBufSize];
1052 if ((errno = SafeFOpen(&fp, filename, "r")) != 0) PFATAL(filename);
1054 while ( (n=fread(buffer, 1, kBufSize, fp)) > 0 ) {
1055 if (ferror(fp)) PFATAL(filename);
1056 s.append(buffer, n);
1062 uint32 CommandLineFlagParser::ParseNewCommandLineFlags(int* argc, char*** argv,
1063 bool remove_flags) {
1064 const char *program_name = strrchr((*argv)[0], PATH_SEPARATOR); // nix path
1065 program_name = (program_name == NULL ? (*argv)[0] : program_name+1);
1067 int first_nonopt = *argc; // for non-options moved to the end
1070 for (int i = 1; i < first_nonopt; i++) {
1071 char* arg = (*argv)[i];
1073 // Like getopt(), we permute non-option flags to be at the end.
1074 if (arg[0] != '-' || // must be a program argument
1075 (arg[0] == '-' && arg[1] == '\0')) { // "-" is an argument, not a flag
1076 memmove((*argv) + i, (*argv) + i+1, (*argc - (i+1)) * sizeof((*argv)[i]));
1077 (*argv)[*argc-1] = arg; // we go last
1078 first_nonopt--; // we've been pushed onto the stack
1079 i--; // to undo the i++ in the loop
1083 if (arg[0] == '-') arg++; // allow leading '-'
1084 if (arg[0] == '-') arg++; // or leading '--'
1086 // -- alone means what it does for GNU: stop options parsing
1092 // Find the flag object for this option
1095 string error_message;
1096 CommandLineFlag* flag = registry_->SplitArgumentLocked(arg, &key, &value,
1099 undefined_names_[key] = ""; // value isn't actually used
1100 error_flags_[key] = error_message;
1104 if (value == NULL) {
1105 // Boolean options are always assigned a value by SplitArgumentLocked()
1106 assert(flag->Type() != FlagValue::FV_BOOL);
1107 if (i+1 >= first_nonopt) {
1108 // This flag needs a value, but there is nothing available
1109 error_flags_[key] = (string(kError) + "flag '" + (*argv)[i] + "'"
1110 + " is missing its argument");
1111 if (flag->help() && flag->help()[0] > '\001') {
1112 // Be useful in case we have a non-stripped description.
1113 error_flags_[key] += string("; flag description: ") + flag->help();
1115 error_flags_[key] += "\n";
1116 break; // we treat this as an unrecoverable error
1118 value = (*argv)[++i]; // read next arg for value
1120 // Heuristic to detect the case where someone treats a string arg
1122 // --my_string_var --foo=bar
1123 // We look for a flag of string type, whose value begins with a
1124 // dash, and where the flag-name and value are separated by a
1125 // space rather than an '='.
1126 // To avoid false positives, we also require the word "true"
1127 // or "false" in the help string. Without this, a valid usage
1128 // "-lat -30.5" would trigger the warning. The common cases we
1129 // want to solve talk about true and false as values.
1131 && flag->Type() == FlagValue::FV_STRING
1132 && (strstr(flag->help(), "true")
1133 || strstr(flag->help(), "false"))) {
1134 LOG(WARNING) << "Did you really mean to set flag '"
1135 << flag->name() << "' to the value '"
1141 // TODO(csilvers): only set a flag if we hadn't set it before here
1142 ProcessSingleOptionLocked(flag, value, SET_FLAGS_VALUE);
1144 registry_->Unlock();
1146 if (remove_flags) { // Fix up argc and argv by removing command line flags
1147 (*argv)[first_nonopt-1] = (*argv)[0];
1148 (*argv) += (first_nonopt-1);
1149 (*argc) -= (first_nonopt-1);
1150 first_nonopt = 1; // because we still don't count argv[0]
1153 logging_is_probably_set_up = true; // because we've parsed --logdir, etc.
1155 return first_nonopt;
1158 string CommandLineFlagParser::ProcessFlagfileLocked(const string& flagval,
1159 FlagSettingMode set_mode) {
1160 if (flagval.empty())
1164 vector<string> filename_list;
1165 ParseFlagList(flagval.c_str(), &filename_list); // take a list of filenames
1166 for (size_t i = 0; i < filename_list.size(); ++i) {
1167 const char* file = filename_list[i].c_str();
1168 msg += ProcessOptionsFromStringLocked(ReadFileIntoString(file), set_mode);
1173 string CommandLineFlagParser::ProcessFromenvLocked(const string& flagval,
1174 FlagSettingMode set_mode,
1175 bool errors_are_fatal) {
1176 if (flagval.empty())
1180 vector<string> flaglist;
1181 ParseFlagList(flagval.c_str(), &flaglist);
1183 for (size_t i = 0; i < flaglist.size(); ++i) {
1184 const char* flagname = flaglist[i].c_str();
1185 CommandLineFlag* flag = registry_->FindFlagLocked(flagname);
1187 error_flags_[flagname] =
1188 StringPrintf("%sunknown command line flag '%s' "
1189 "(via --fromenv or --tryfromenv)\n",
1191 undefined_names_[flagname] = "";
1195 const string envname = string("FLAGS_") + string(flagname);
1197 if (!SafeGetEnv(envname.c_str(), envval)) {
1198 if (errors_are_fatal) {
1199 error_flags_[flagname] = (string(kError) + envname +
1200 " not found in environment\n");
1205 // Avoid infinite recursion.
1206 if (envval == "fromenv" || envval == "tryfromenv") {
1207 error_flags_[flagname] =
1208 StringPrintf("%sinfinite recursion on environment flag '%s'\n",
1209 kError, envval.c_str());
1213 msg += ProcessSingleOptionLocked(flag, envval.c_str(), set_mode);
1218 string CommandLineFlagParser::ProcessSingleOptionLocked(
1219 CommandLineFlag* flag, const char* value, FlagSettingMode set_mode) {
1221 if (value && !registry_->SetFlagLocked(flag, value, set_mode, &msg)) {
1222 error_flags_[flag->name()] = msg;
1226 // The recursive flags, --flagfile and --fromenv and --tryfromenv,
1227 // must be dealt with as soon as they're seen. They will emit
1228 // messages of their own.
1229 if (strcmp(flag->name(), "flagfile") == 0) {
1230 msg += ProcessFlagfileLocked(FLAGS_flagfile, set_mode);
1232 } else if (strcmp(flag->name(), "fromenv") == 0) {
1233 // last arg indicates envval-not-found is fatal (unlike in --tryfromenv)
1234 msg += ProcessFromenvLocked(FLAGS_fromenv, set_mode, true);
1236 } else if (strcmp(flag->name(), "tryfromenv") == 0) {
1237 msg += ProcessFromenvLocked(FLAGS_tryfromenv, set_mode, false);
1243 void CommandLineFlagParser::ValidateFlags(bool all) {
1244 FlagRegistryLock frl(registry_);
1245 for (FlagRegistry::FlagConstIterator i = registry_->flags_.begin();
1246 i != registry_->flags_.end(); ++i) {
1247 if ((all || !i->second->Modified()) && !i->second->ValidateCurrent()) {
1248 // only set a message if one isn't already there. (If there's
1249 // an error message, our job is done, even if it's not exactly
1251 if (error_flags_[i->second->name()].empty()) {
1252 error_flags_[i->second->name()] =
1253 string(kError) + "--" + i->second->name() +
1254 " must be set on the commandline";
1255 if (!i->second->Modified()) {
1256 error_flags_[i->second->name()] += " (default value fails validation)";
1258 error_flags_[i->second->name()] += "\n";
1264 void CommandLineFlagParser::ValidateAllFlags() {
1265 ValidateFlags(true);
1268 void CommandLineFlagParser::ValidateUnmodifiedFlags() {
1269 ValidateFlags(false);
1272 bool CommandLineFlagParser::ReportErrors() {
1273 // error_flags_ indicates errors we saw while parsing.
1274 // But we ignore undefined-names if ok'ed by --undef_ok
1275 if (!FLAGS_undefok.empty()) {
1276 vector<string> flaglist;
1277 ParseFlagList(FLAGS_undefok.c_str(), &flaglist);
1278 for (size_t i = 0; i < flaglist.size(); ++i) {
1279 // We also deal with --no<flag>, in case the flagname was boolean
1280 const string no_version = string("no") + flaglist[i];
1281 if (undefined_names_.find(flaglist[i]) != undefined_names_.end()) {
1282 error_flags_[flaglist[i]] = ""; // clear the error message
1283 } else if (undefined_names_.find(no_version) != undefined_names_.end()) {
1284 error_flags_[no_version] = "";
1288 // Likewise, if they decided to allow reparsing, all undefined-names
1289 // are ok; we just silently ignore them now, and hope that a future
1290 // parse will pick them up somehow.
1291 if (allow_command_line_reparsing) {
1292 for (map<string, string>::const_iterator it = undefined_names_.begin();
1293 it != undefined_names_.end(); ++it)
1294 error_flags_[it->first] = ""; // clear the error message
1297 bool found_error = false;
1298 string error_message;
1299 for (map<string, string>::const_iterator it = error_flags_.begin();
1300 it != error_flags_.end(); ++it) {
1301 if (!it->second.empty()) {
1302 error_message.append(it->second.data(), it->second.size());
1307 ReportError(DO_NOT_DIE, "%s", error_message.c_str());
1311 string CommandLineFlagParser::ProcessOptionsFromStringLocked(
1312 const string& contentdata, FlagSettingMode set_mode) {
1314 const char* flagfile_contents = contentdata.c_str();
1315 bool flags_are_relevant = true; // set to false when filenames don't match
1316 bool in_filename_section = false;
1318 const char* line_end = flagfile_contents;
1319 // We read this file a line at a time.
1320 for (; line_end; flagfile_contents = line_end + 1) {
1321 while (*flagfile_contents && isspace(*flagfile_contents))
1322 ++flagfile_contents;
1323 // Windows uses "\r\n"
1324 line_end = strchr(flagfile_contents, '\r');
1325 if (line_end == NULL)
1326 line_end = strchr(flagfile_contents, '\n');
1328 size_t len = line_end ? line_end - flagfile_contents
1329 : strlen(flagfile_contents);
1330 string line(flagfile_contents, len);
1332 // Each line can be one of four things:
1333 // 1) A comment line -- we skip it
1334 // 2) An empty line -- we skip it
1335 // 3) A list of filenames -- starts a new filenames+flags section
1336 // 4) A --flag=value line -- apply if previous filenames match
1337 if (line.empty() || line[0] == '#') {
1338 // comment or empty line; just ignore
1340 } else if (line[0] == '-') { // flag
1341 in_filename_section = false; // instead, it was a flag-line
1342 if (!flags_are_relevant) // skip this flag; applies to someone else
1345 const char* name_and_val = line.c_str() + 1; // skip the leading -
1346 if (*name_and_val == '-')
1347 name_and_val++; // skip second - too
1350 string error_message;
1351 CommandLineFlag* flag = registry_->SplitArgumentLocked(name_and_val,
1354 // By API, errors parsing flagfile lines are silently ignored.
1356 // "WARNING: flagname '" + key + "' not found\n"
1357 } else if (value == NULL) {
1358 // "WARNING: flagname '" + key + "' missing a value\n"
1360 retval += ProcessSingleOptionLocked(flag, value, set_mode);
1363 } else { // a filename!
1364 if (!in_filename_section) { // start over: assume filenames don't match
1365 in_filename_section = true;
1366 flags_are_relevant = false;
1369 // Split the line up at spaces into glob-patterns
1370 const char* space = line.c_str(); // just has to be non-NULL
1371 for (const char* word = line.c_str(); *space; word = space+1) {
1372 if (flags_are_relevant) // we can stop as soon as we match
1374 space = strchr(word, ' ');
1376 space = word + strlen(word);
1377 const string glob(word, space - word);
1378 // We try matching both against the full argv0 and basename(argv0)
1379 if (glob == ProgramInvocationName() // small optimization
1380 || glob == ProgramInvocationShortName()
1381 #if defined(HAVE_FNMATCH_H)
1382 || fnmatch(glob.c_str(), ProgramInvocationName(), FNM_PATHNAME) == 0
1383 || fnmatch(glob.c_str(), ProgramInvocationShortName(), FNM_PATHNAME) == 0
1384 #elif defined(HAVE_SHLWAPI_H)
1385 || PathMatchSpec(glob.c_str(), ProgramInvocationName())
1386 || PathMatchSpec(glob.c_str(), ProgramInvocationShortName())
1389 flags_are_relevant = true;
1397 // --------------------------------------------------------------------
1399 // AddFlagValidator()
1400 // These are helper functions for routines like BoolFromEnv() and
1401 // RegisterFlagValidator, defined below. They're defined here so
1402 // they can live in the unnamed namespace (which makes friendship
1403 // declarations for these classes possible).
1404 // --------------------------------------------------------------------
1406 template<typename T>
1407 T GetFromEnv(const char *varname, T dflt) {
1409 if (SafeGetEnv(varname, valstr)) {
1410 FlagValue ifv(new T, true);
1411 if (!ifv.ParseFrom(valstr.c_str())) {
1412 ReportError(DIE, "ERROR: error parsing env variable '%s' with value '%s'\n",
1413 varname, valstr.c_str());
1415 return OTHER_VALUE_AS(ifv, T);
1419 bool AddFlagValidator(const void* flag_ptr, ValidateFnProto validate_fn_proto) {
1420 // We want a lock around this routine, in case two threads try to
1421 // add a validator (hopefully the same one!) at once. We could use
1422 // our own thread, but we need to loook at the registry anyway, so
1423 // we just steal that one.
1424 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1425 FlagRegistryLock frl(registry);
1426 // First, find the flag whose current-flag storage is 'flag'.
1427 // This is the CommandLineFlag whose current_->value_buffer_ == flag
1428 CommandLineFlag* flag = registry->FindFlagViaPtrLocked(flag_ptr);
1430 LOG(WARNING) << "Ignoring RegisterValidateFunction() for flag pointer "
1431 << flag_ptr << ": no flag found at that address";
1433 } else if (validate_fn_proto == flag->validate_function()) {
1434 return true; // ok to register the same function over and over again
1435 } else if (validate_fn_proto != NULL && flag->validate_function() != NULL) {
1436 LOG(WARNING) << "Ignoring RegisterValidateFunction() for flag '"
1437 << flag->name() << "': validate-fn already registered";
1440 flag->validate_fn_proto_ = validate_fn_proto;
1445 } // end unnamed namespaces
1448 // Now define the functions that are exported via the .h file
1450 // --------------------------------------------------------------------
1452 // This class exists merely to have a global constructor (the
1453 // kind that runs before main(), that goes an initializes each
1454 // flag that's been declared. Note that it's very important we
1455 // don't have a destructor that deletes flag_, because that would
1456 // cause us to delete current_storage/defvalue_storage as well,
1457 // which can cause a crash if anything tries to access the flag
1458 // values in a global destructor.
1459 // --------------------------------------------------------------------
1462 void RegisterCommandLineFlag(const char* name,
1464 const char* filename,
1466 FlagValue* defvalue) {
1469 // Importantly, flag_ will never be deleted, so storage is always good.
1470 CommandLineFlag* flag =
1471 new CommandLineFlag(name, help, filename, current, defvalue);
1472 FlagRegistry::GlobalRegistry()->RegisterFlag(flag); // default registry
1476 template <typename FlagType>
1477 FlagRegisterer::FlagRegisterer(const char* name,
1479 const char* filename,
1480 FlagType* current_storage,
1481 FlagType* defvalue_storage) {
1482 FlagValue* const current = new FlagValue(current_storage, false);
1483 FlagValue* const defvalue = new FlagValue(defvalue_storage, false);
1484 RegisterCommandLineFlag(name, help, filename, current, defvalue);
1487 // Force compiler to generate code for the given template specialization.
1488 #define INSTANTIATE_FLAG_REGISTERER_CTOR(type) \
1489 template GFLAGS_DLL_DECL FlagRegisterer::FlagRegisterer( \
1490 const char* name, const char* help, const char* filename, \
1491 type* current_storage, type* defvalue_storage)
1493 // Do this for all supported flag types.
1494 INSTANTIATE_FLAG_REGISTERER_CTOR(bool);
1495 INSTANTIATE_FLAG_REGISTERER_CTOR(int32);
1496 INSTANTIATE_FLAG_REGISTERER_CTOR(uint32);
1497 INSTANTIATE_FLAG_REGISTERER_CTOR(int64);
1498 INSTANTIATE_FLAG_REGISTERER_CTOR(uint64);
1499 INSTANTIATE_FLAG_REGISTERER_CTOR(double);
1500 INSTANTIATE_FLAG_REGISTERER_CTOR(std::string);
1502 #undef INSTANTIATE_FLAG_REGISTERER_CTOR
1504 // --------------------------------------------------------------------
1506 // The main way the FlagRegistry class exposes its data. This
1507 // returns, as strings, all the info about all the flags in
1508 // the main registry, sorted first by filename they are defined
1509 // in, and then by flagname.
1510 // --------------------------------------------------------------------
1512 struct FilenameFlagnameCmp {
1513 bool operator()(const CommandLineFlagInfo& a,
1514 const CommandLineFlagInfo& b) const {
1515 int cmp = strcmp(a.filename.c_str(), b.filename.c_str());
1517 cmp = strcmp(a.name.c_str(), b.name.c_str()); // secondary sort key
1522 void GetAllFlags(vector<CommandLineFlagInfo>* OUTPUT) {
1523 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1525 for (FlagRegistry::FlagConstIterator i = registry->flags_.begin();
1526 i != registry->flags_.end(); ++i) {
1527 CommandLineFlagInfo fi;
1528 i->second->FillCommandLineFlagInfo(&fi);
1529 OUTPUT->push_back(fi);
1532 // Now sort the flags, first by filename they occur in, then alphabetically
1533 sort(OUTPUT->begin(), OUTPUT->end(), FilenameFlagnameCmp());
1536 // --------------------------------------------------------------------
1541 // ProgramInvocationName()
1542 // ProgramInvocationShortName()
1543 // SetUsageMessage()
1545 // Functions to set and get argv. Typically the setter is called
1546 // by ParseCommandLineFlags. Also can get the ProgramUsage string,
1547 // set by SetUsageMessage.
1548 // --------------------------------------------------------------------
1550 // These values are not protected by a Mutex because they are normally
1551 // set only once during program startup.
1552 static string argv0("UNKNOWN"); // just the program name
1553 static string cmdline; // the entire command-line
1554 static string program_usage;
1555 static vector<string> argvs;
1556 static uint32 argv_sum = 0;
1558 void SetArgv(int argc, const char** argv) {
1559 static bool called_set_argv = false;
1560 if (called_set_argv) return;
1561 called_set_argv = true;
1563 assert(argc > 0); // every program has at least a name
1567 for (int i = 0; i < argc; i++) {
1568 if (i != 0) cmdline += " ";
1570 argvs.push_back(argv[i]);
1573 // Compute a simple sum of all the chars in argv
1575 for (string::const_iterator c = cmdline.begin(); c != cmdline.end(); ++c) {
1580 const vector<string>& GetArgvs() { return argvs; }
1581 const char* GetArgv() { return cmdline.c_str(); }
1582 const char* GetArgv0() { return argv0.c_str(); }
1583 uint32 GetArgvSum() { return argv_sum; }
1584 const char* ProgramInvocationName() { // like the GNU libc fn
1587 const char* ProgramInvocationShortName() { // like the GNU libc fn
1588 size_t pos = argv0.rfind('/');
1590 if (pos == string::npos) pos = argv0.rfind('\\');
1592 return (pos == string::npos ? argv0.c_str() : (argv0.c_str() + pos + 1));
1595 void SetUsageMessage(const string& usage) {
1596 program_usage = usage;
1599 const char* ProgramUsage() {
1600 if (program_usage.empty()) {
1601 return "Warning: SetUsageMessage() never called";
1603 return program_usage.c_str();
1606 // --------------------------------------------------------------------
1607 // SetVersionString()
1609 // --------------------------------------------------------------------
1611 static string version_string;
1613 void SetVersionString(const string& version) {
1614 version_string = version;
1617 const char* VersionString() {
1618 return version_string.c_str();
1622 // --------------------------------------------------------------------
1623 // GetCommandLineOption()
1624 // GetCommandLineFlagInfo()
1625 // GetCommandLineFlagInfoOrDie()
1626 // SetCommandLineOption()
1627 // SetCommandLineOptionWithMode()
1628 // The programmatic way to set a flag's value, using a string
1629 // for its name rather than the variable itself (that is,
1630 // SetCommandLineOption("foo", x) rather than FLAGS_foo = x).
1631 // There's also a bit more flexibility here due to the various
1632 // set-modes, but typically these are used when you only have
1633 // that flag's name as a string, perhaps at runtime.
1634 // All of these work on the default, global registry.
1635 // For GetCommandLineOption, return false if no such flag
1636 // is known, true otherwise. We clear "value" if a suitable
1638 // --------------------------------------------------------------------
1641 bool GetCommandLineOption(const char* name, string* value) {
1646 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1647 FlagRegistryLock frl(registry);
1648 CommandLineFlag* flag = registry->FindFlagLocked(name);
1652 *value = flag->current_value();
1657 bool GetCommandLineFlagInfo(const char* name, CommandLineFlagInfo* OUTPUT) {
1658 if (NULL == name) return false;
1659 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1660 FlagRegistryLock frl(registry);
1661 CommandLineFlag* flag = registry->FindFlagLocked(name);
1666 flag->FillCommandLineFlagInfo(OUTPUT);
1671 CommandLineFlagInfo GetCommandLineFlagInfoOrDie(const char* name) {
1672 CommandLineFlagInfo info;
1673 if (!GetCommandLineFlagInfo(name, &info)) {
1674 fprintf(stderr, "FATAL ERROR: flag name '%s' doesn't exist\n", name);
1675 gflags_exitfunc(1); // almost certainly gflags_exitfunc()
1680 string SetCommandLineOptionWithMode(const char* name, const char* value,
1681 FlagSettingMode set_mode) {
1683 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1684 FlagRegistryLock frl(registry);
1685 CommandLineFlag* flag = registry->FindFlagLocked(name);
1687 CommandLineFlagParser parser(registry);
1688 result = parser.ProcessSingleOptionLocked(flag, value, set_mode);
1689 if (!result.empty()) { // in the error case, we've already logged
1690 // Could consider logging this change
1693 // The API of this function is that we return empty string on error
1697 string SetCommandLineOption(const char* name, const char* value) {
1698 return SetCommandLineOptionWithMode(name, value, SET_FLAGS_VALUE);
1701 // --------------------------------------------------------------------
1704 // This class stores the states of all flags at construct time,
1705 // and restores all flags to that state at destruct time.
1706 // Its major implementation challenge is that it never modifies
1707 // pointers in the 'main' registry, so global FLAG_* vars always
1708 // point to the right place.
1709 // --------------------------------------------------------------------
1711 class FlagSaverImpl {
1713 // Constructs an empty FlagSaverImpl object.
1714 explicit FlagSaverImpl(FlagRegistry* main_registry)
1715 : main_registry_(main_registry) { }
1717 // reclaim memory from each of our CommandLineFlags
1718 vector<CommandLineFlag*>::const_iterator it;
1719 for (it = backup_registry_.begin(); it != backup_registry_.end(); ++it)
1723 // Saves the flag states from the flag registry into this object.
1724 // It's an error to call this more than once.
1725 // Must be called when the registry mutex is not held.
1726 void SaveFromRegistry() {
1727 FlagRegistryLock frl(main_registry_);
1728 assert(backup_registry_.empty()); // call only once!
1729 for (FlagRegistry::FlagConstIterator it = main_registry_->flags_.begin();
1730 it != main_registry_->flags_.end();
1732 const CommandLineFlag* main = it->second;
1733 // Sets up all the const variables in backup correctly
1734 CommandLineFlag* backup = new CommandLineFlag(
1735 main->name(), main->help(), main->filename(),
1736 main->current_->New(), main->defvalue_->New());
1737 // Sets up all the non-const variables in backup correctly
1738 backup->CopyFrom(*main);
1739 backup_registry_.push_back(backup); // add it to a convenient list
1743 // Restores the saved flag states into the flag registry. We
1744 // assume no flags were added or deleted from the registry since
1745 // the SaveFromRegistry; if they were, that's trouble! Must be
1746 // called when the registry mutex is not held.
1747 void RestoreToRegistry() {
1748 FlagRegistryLock frl(main_registry_);
1749 vector<CommandLineFlag*>::const_iterator it;
1750 for (it = backup_registry_.begin(); it != backup_registry_.end(); ++it) {
1751 CommandLineFlag* main = main_registry_->FindFlagLocked((*it)->name());
1752 if (main != NULL) { // if NULL, flag got deleted from registry(!)
1753 main->CopyFrom(**it);
1759 FlagRegistry* const main_registry_;
1760 vector<CommandLineFlag*> backup_registry_;
1762 FlagSaverImpl(const FlagSaverImpl&); // no copying!
1763 void operator=(const FlagSaverImpl&);
1766 FlagSaver::FlagSaver()
1767 : impl_(new FlagSaverImpl(FlagRegistry::GlobalRegistry())) {
1768 impl_->SaveFromRegistry();
1771 FlagSaver::~FlagSaver() {
1772 impl_->RestoreToRegistry();
1777 // --------------------------------------------------------------------
1778 // CommandlineFlagsIntoString()
1779 // ReadFlagsFromString()
1780 // AppendFlagsIntoFile()
1781 // ReadFromFlagsFile()
1782 // These are mostly-deprecated routines that stick the
1783 // commandline flags into a file/string and read them back
1784 // out again. I can see a use for CommandlineFlagsIntoString,
1785 // for creating a flagfile, but the rest don't seem that useful
1786 // -- some, I think, are a poor-man's attempt at FlagSaver --
1787 // and are included only until we can delete them from callers.
1788 // Note they don't save --flagfile flags (though they do save
1789 // the result of having called the flagfile, of course).
1790 // --------------------------------------------------------------------
1792 static string TheseCommandlineFlagsIntoString(
1793 const vector<CommandLineFlagInfo>& flags) {
1794 vector<CommandLineFlagInfo>::const_iterator i;
1796 size_t retval_space = 0;
1797 for (i = flags.begin(); i != flags.end(); ++i) {
1798 // An (over)estimate of how much space it will take to print this flag
1799 retval_space += i->name.length() + i->current_value.length() + 5;
1803 retval.reserve(retval_space);
1804 for (i = flags.begin(); i != flags.end(); ++i) {
1808 retval += i->current_value;
1814 string CommandlineFlagsIntoString() {
1815 vector<CommandLineFlagInfo> sorted_flags;
1816 GetAllFlags(&sorted_flags);
1817 return TheseCommandlineFlagsIntoString(sorted_flags);
1820 bool ReadFlagsFromString(const string& flagfilecontents,
1821 const char* /*prog_name*/, // TODO(csilvers): nix this
1822 bool errors_are_fatal) {
1823 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1824 FlagSaverImpl saved_states(registry);
1825 saved_states.SaveFromRegistry();
1827 CommandLineFlagParser parser(registry);
1829 parser.ProcessOptionsFromStringLocked(flagfilecontents, SET_FLAGS_VALUE);
1831 // Should we handle --help and such when reading flags from a string? Sure.
1832 HandleCommandLineHelpFlags();
1833 if (parser.ReportErrors()) {
1834 // Error. Restore all global flags to their previous values.
1835 if (errors_are_fatal)
1837 saved_states.RestoreToRegistry();
1843 // TODO(csilvers): nix prog_name in favor of ProgramInvocationShortName()
1844 bool AppendFlagsIntoFile(const string& filename, const char *prog_name) {
1846 if (SafeFOpen(&fp, filename.c_str(), "a") != 0) {
1851 fprintf(fp, "%s\n", prog_name);
1853 vector<CommandLineFlagInfo> flags;
1854 GetAllFlags(&flags);
1855 // But we don't want --flagfile, which leads to weird recursion issues
1856 vector<CommandLineFlagInfo>::iterator i;
1857 for (i = flags.begin(); i != flags.end(); ++i) {
1858 if (strcmp(i->name.c_str(), "flagfile") == 0) {
1863 fprintf(fp, "%s", TheseCommandlineFlagsIntoString(flags).c_str());
1869 bool ReadFromFlagsFile(const string& filename, const char* prog_name,
1870 bool errors_are_fatal) {
1871 return ReadFlagsFromString(ReadFileIntoString(filename.c_str()),
1872 prog_name, errors_are_fatal);
1876 // --------------------------------------------------------------------
1884 // Reads the value from the environment and returns it.
1885 // We use an FlagValue to make the parsing easy.
1887 // DEFINE_bool(myflag, BoolFromEnv("MYFLAG_DEFAULT", false), "whatever");
1888 // --------------------------------------------------------------------
1890 bool BoolFromEnv(const char *v, bool dflt) {
1891 return GetFromEnv(v, dflt);
1893 int32 Int32FromEnv(const char *v, int32 dflt) {
1894 return GetFromEnv(v, dflt);
1896 uint32 Uint32FromEnv(const char *v, uint32 dflt) {
1897 return GetFromEnv(v, dflt);
1899 int64 Int64FromEnv(const char *v, int64 dflt) {
1900 return GetFromEnv(v, dflt);
1902 uint64 Uint64FromEnv(const char *v, uint64 dflt) {
1903 return GetFromEnv(v, dflt);
1905 double DoubleFromEnv(const char *v, double dflt) {
1906 return GetFromEnv(v, dflt);
1910 # pragma warning(push)
1911 # pragma warning(disable: 4996) // ignore getenv security warning
1913 const char *StringFromEnv(const char *varname, const char *dflt) {
1914 const char* const val = getenv(varname);
1915 return val ? val : dflt;
1918 # pragma warning(pop)
1922 // --------------------------------------------------------------------
1923 // RegisterFlagValidator()
1924 // RegisterFlagValidator() is the function that clients use to
1925 // 'decorate' a flag with a validation function. Once this is
1926 // done, every time the flag is set (including when the flag
1927 // is parsed from argv), the validator-function is called.
1928 // These functions return true if the validator was added
1929 // successfully, or false if not: the flag already has a validator,
1930 // (only one allowed per flag), the 1st arg isn't a flag, etc.
1931 // This function is not thread-safe.
1932 // --------------------------------------------------------------------
1934 bool RegisterFlagValidator(const bool* flag,
1935 bool (*validate_fn)(const char*, bool)) {
1936 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1938 bool RegisterFlagValidator(const int32* flag,
1939 bool (*validate_fn)(const char*, int32)) {
1940 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1942 bool RegisterFlagValidator(const uint32* flag,
1943 bool (*validate_fn)(const char*, uint32)) {
1944 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1946 bool RegisterFlagValidator(const int64* flag,
1947 bool (*validate_fn)(const char*, int64)) {
1948 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1950 bool RegisterFlagValidator(const uint64* flag,
1951 bool (*validate_fn)(const char*, uint64)) {
1952 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1954 bool RegisterFlagValidator(const double* flag,
1955 bool (*validate_fn)(const char*, double)) {
1956 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1958 bool RegisterFlagValidator(const string* flag,
1959 bool (*validate_fn)(const char*, const string&)) {
1960 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1964 // --------------------------------------------------------------------
1965 // ParseCommandLineFlags()
1966 // ParseCommandLineNonHelpFlags()
1967 // HandleCommandLineHelpFlags()
1968 // This is the main function called from main(), to actually
1969 // parse the commandline. It modifies argc and argv as described
1970 // at the top of gflags.h. You can also divide this
1971 // function into two parts, if you want to do work between
1972 // the parsing of the flags and the printing of any help output.
1973 // --------------------------------------------------------------------
1975 static uint32 ParseCommandLineFlagsInternal(int* argc, char*** argv,
1976 bool remove_flags, bool do_report) {
1977 SetArgv(*argc, const_cast<const char**>(*argv)); // save it for later
1979 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1980 CommandLineFlagParser parser(registry);
1982 // When we parse the commandline flags, we'll handle --flagfile,
1983 // --tryfromenv, etc. as we see them (since flag-evaluation order
1984 // may be important). But sometimes apps set FLAGS_tryfromenv/etc.
1985 // manually before calling ParseCommandLineFlags. We want to evaluate
1986 // those too, as if they were the first flags on the commandline.
1988 parser.ProcessFlagfileLocked(FLAGS_flagfile, SET_FLAGS_VALUE);
1989 // Last arg here indicates whether flag-not-found is a fatal error or not
1990 parser.ProcessFromenvLocked(FLAGS_fromenv, SET_FLAGS_VALUE, true);
1991 parser.ProcessFromenvLocked(FLAGS_tryfromenv, SET_FLAGS_VALUE, false);
1994 // Now get the flags specified on the commandline
1995 const int r = parser.ParseNewCommandLineFlags(argc, argv, remove_flags);
1998 HandleCommandLineHelpFlags(); // may cause us to exit on --help, etc.
2000 // See if any of the unset flags fail their validation checks
2001 parser.ValidateUnmodifiedFlags();
2003 if (parser.ReportErrors()) // may cause us to exit on illegal flags
2008 uint32 ParseCommandLineFlags(int* argc, char*** argv, bool remove_flags) {
2009 return ParseCommandLineFlagsInternal(argc, argv, remove_flags, true);
2012 uint32 ParseCommandLineNonHelpFlags(int* argc, char*** argv,
2013 bool remove_flags) {
2014 return ParseCommandLineFlagsInternal(argc, argv, remove_flags, false);
2017 // --------------------------------------------------------------------
2018 // AllowCommandLineReparsing()
2019 // ReparseCommandLineNonHelpFlags()
2020 // This is most useful for shared libraries. The idea is if
2021 // a flag is defined in a shared library that is dlopen'ed
2022 // sometime after main(), you can ParseCommandLineFlags before
2023 // the dlopen, then ReparseCommandLineNonHelpFlags() after the
2024 // dlopen, to get the new flags. But you have to explicitly
2025 // Allow() it; otherwise, you get the normal default behavior
2026 // of unrecognized flags calling a fatal error.
2027 // TODO(csilvers): this isn't used. Just delete it?
2028 // --------------------------------------------------------------------
2030 void AllowCommandLineReparsing() {
2031 allow_command_line_reparsing = true;
2034 void ReparseCommandLineNonHelpFlags() {
2035 // We make a copy of argc and argv to pass in
2036 const vector<string>& argvs = GetArgvs();
2037 int tmp_argc = static_cast<int>(argvs.size());
2038 char** tmp_argv = new char* [tmp_argc + 1];
2039 for (int i = 0; i < tmp_argc; ++i)
2040 tmp_argv[i] = strdup(argvs[i].c_str()); // TODO(csilvers): don't dup
2042 ParseCommandLineNonHelpFlags(&tmp_argc, &tmp_argv, false);
2044 for (int i = 0; i < tmp_argc; ++i)
2049 void ShutDownCommandLineFlags() {
2050 FlagRegistry::DeleteGlobalRegistry();
2054 } // namespace GFLAGS_NAMESPACE