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)
101 #include <stdarg.h> // For va_list and related operations
108 #include <utility> // for pair<>
114 using namespace MUTEX_NAMESPACE;
117 // Special flags, type 1: the 'recursive' flags. They set another flag's val.
118 DEFINE_string(flagfile, "", "load flags from file");
119 DEFINE_string(fromenv, "", "set flags from the environment"
120 " [use 'export FLAGS_flag1=value']");
121 DEFINE_string(tryfromenv, "", "set flags from the environment if present");
123 // Special flags, type 2: the 'parsing' flags. They modify how we parse.
124 DEFINE_string(undefok, "", "comma-separated list of flag names that it is okay to specify "
125 "on the command line even if the program does not define a flag "
126 "with that name. IMPORTANT: flags in this list that have "
127 "arguments MUST use the flag=value format");
129 namespace GFLAGS_NAMESPACE {
137 // This is used by the unittest to test error-exit code
138 void GFLAGS_DLL_DECL (*gflags_exitfunc)(int) = &exit; // from stdlib.h
141 // The help message indicating that the commandline flag has been
142 // 'stripped'. It will not show up when doing "-help" and its
143 // variants. The flag is stripped if STRIP_FLAG_HELP is set to 1
144 // before including base/gflags.h
146 // This is used by this file, and also in gflags_reporting.cc
147 const char kStrippedFlagHelp[] = "\001\002\003\004 (unknown) \004\003\002\001";
151 // There are also 'reporting' flags, in gflags_reporting.cc.
153 static const char kError[] = "ERROR: ";
155 // Indicates that undefined options are to be ignored.
156 // Enables deferred processing of flags in dynamically loaded libraries.
157 static bool allow_command_line_reparsing = false;
159 static bool logging_is_probably_set_up = false;
161 // This is a 'prototype' validate-function. 'Real' validate
162 // functions, take a flag-value as an argument: ValidateFn(bool) or
163 // ValidateFn(uint64). However, for easier storage, we strip off this
164 // argument and then restore it when actually calling the function on
166 typedef bool (*ValidateFnProto)();
168 // Whether we should die when reporting an error.
169 enum DieWhenReporting { DIE, DO_NOT_DIE };
171 // Report Error and exit if requested.
172 static void ReportError(DieWhenReporting should_die, const char* format, ...) {
173 char error_message[255];
175 va_start(ap, format);
176 vsnprintf(error_message, sizeof(error_message), format, ap);
178 fprintf(stderr, "%s", error_message);
179 fflush(stderr); // should be unnecessary, but cygwin's rxvt buffers stderr
180 if (should_die == DIE) gflags_exitfunc(1);
184 // --------------------------------------------------------------------
186 // This represent the value a single flag might have. The major
187 // functionality is to convert from a string to an object of a
188 // given type, and back. Thread-compatible.
189 // --------------------------------------------------------------------
191 class CommandLineFlag;
194 FlagValue(void* valbuf, const char* type, bool transfer_ownership_of_value);
197 bool ParseFrom(const char* spec);
198 string ToString() const;
201 friend class CommandLineFlag; // for many things, including Validate()
202 friend class GFLAGS_NAMESPACE::FlagSaverImpl; // calls New()
203 friend class FlagRegistry; // checks value_buffer_ for flags_by_ptr_ map
204 template <typename T> friend T GetFromEnv(const char*, const char*, T);
205 friend bool TryParseLocked(const CommandLineFlag*, FlagValue*,
206 const char*, string*); // for New(), CopyFrom()
217 const char* TypeName() const;
218 bool Equal(const FlagValue& x) const;
219 FlagValue* New() const; // creates a new one with default value
220 void CopyFrom(const FlagValue& x);
221 int ValueSize() const;
223 // Calls the given validate-fn on value_buffer_, and returns
224 // whatever it returns. But first casts validate_fn_proto to a
225 // function that takes our value as an argument (eg void
226 // (*validate_fn)(bool) for a bool flag).
227 bool Validate(const char* flagname, ValidateFnProto validate_fn_proto) const;
229 void* value_buffer_; // points to the buffer holding our data
230 int8 type_; // how to interpret value_
231 bool owns_value_; // whether to free value on destruct
233 FlagValue(const FlagValue&); // no copying!
234 void operator=(const FlagValue&);
238 // This could be a templated method of FlagValue, but doing so adds to the
239 // size of the .o. Since there's no type-safety here anyway, macro is ok.
240 #define VALUE_AS(type) *reinterpret_cast<type*>(value_buffer_)
241 #define OTHER_VALUE_AS(fv, type) *reinterpret_cast<type*>(fv.value_buffer_)
242 #define SET_VALUE_AS(type, value) VALUE_AS(type) = (value)
244 FlagValue::FlagValue(void* valbuf, const char* type,
245 bool transfer_ownership_of_value)
246 : value_buffer_(valbuf),
247 owns_value_(transfer_ownership_of_value) {
248 for (type_ = 0; type_ <= FV_MAX_INDEX; ++type_) {
249 if (!strcmp(type, TypeName())) {
253 assert(type_ <= FV_MAX_INDEX); // Unknown typename
256 FlagValue::~FlagValue() {
261 case FV_BOOL: delete reinterpret_cast<bool*>(value_buffer_); break;
262 case FV_INT32: delete reinterpret_cast<int32*>(value_buffer_); break;
263 case FV_INT64: delete reinterpret_cast<int64*>(value_buffer_); break;
264 case FV_UINT64: delete reinterpret_cast<uint64*>(value_buffer_); break;
265 case FV_DOUBLE: delete reinterpret_cast<double*>(value_buffer_); break;
266 case FV_STRING: delete reinterpret_cast<string*>(value_buffer_); break;
270 bool FlagValue::ParseFrom(const char* value) {
271 if (type_ == FV_BOOL) {
272 const char* kTrue[] = { "1", "t", "true", "y", "yes" };
273 const char* kFalse[] = { "0", "f", "false", "n", "no" };
274 COMPILE_ASSERT(sizeof(kTrue) == sizeof(kFalse), true_false_equal);
275 for (size_t i = 0; i < sizeof(kTrue)/sizeof(*kTrue); ++i) {
276 if (strcasecmp(value, kTrue[i]) == 0) {
277 SET_VALUE_AS(bool, true);
279 } else if (strcasecmp(value, kFalse[i]) == 0) {
280 SET_VALUE_AS(bool, false);
284 return false; // didn't match a legal input
286 } else if (type_ == FV_STRING) {
287 SET_VALUE_AS(string, value);
291 // OK, it's likely to be numeric, and we'll be using a strtoXXX method.
292 if (value[0] == '\0') // empty-string is only allowed for string type.
295 // Leading 0x puts us in base 16. But leading 0 does not put us in base 8!
296 // It caused too many bugs when we had that behavior.
297 int base = 10; // by default
298 if (value[0] == '0' && (value[1] == 'x' || value[1] == 'X'))
304 const int64 r = strto64(value, &end, base);
305 if (errno || end != value + strlen(value)) return false; // bad parse
306 if (static_cast<int32>(r) != r) // worked, but number out of range
308 SET_VALUE_AS(int32, static_cast<int32>(r));
312 const int64 r = strto64(value, &end, base);
313 if (errno || end != value + strlen(value)) return false; // bad parse
314 SET_VALUE_AS(int64, r);
318 while (*value == ' ') value++;
319 if (*value == '-') return false; // negative number
320 const uint64 r = strtou64(value, &end, base);
321 if (errno || end != value + strlen(value)) return false; // bad parse
322 SET_VALUE_AS(uint64, r);
326 const double r = strtod(value, &end);
327 if (errno || end != value + strlen(value)) return false; // bad parse
328 SET_VALUE_AS(double, r);
332 assert(false); // unknown type
338 string FlagValue::ToString() const {
339 char intbuf[64]; // enough to hold even the biggest number
342 return VALUE_AS(bool) ? "true" : "false";
344 snprintf(intbuf, sizeof(intbuf), "%" PRId32, VALUE_AS(int32));
347 snprintf(intbuf, sizeof(intbuf), "%" PRId64, VALUE_AS(int64));
350 snprintf(intbuf, sizeof(intbuf), "%" PRIu64, VALUE_AS(uint64));
353 snprintf(intbuf, sizeof(intbuf), "%.17g", VALUE_AS(double));
356 return VALUE_AS(string);
359 return ""; // unknown type
363 bool FlagValue::Validate(const char* flagname,
364 ValidateFnProto validate_fn_proto) const {
367 return reinterpret_cast<bool (*)(const char*, bool)>(
368 validate_fn_proto)(flagname, VALUE_AS(bool));
370 return reinterpret_cast<bool (*)(const char*, int32)>(
371 validate_fn_proto)(flagname, VALUE_AS(int32));
373 return reinterpret_cast<bool (*)(const char*, int64)>(
374 validate_fn_proto)(flagname, VALUE_AS(int64));
376 return reinterpret_cast<bool (*)(const char*, uint64)>(
377 validate_fn_proto)(flagname, VALUE_AS(uint64));
379 return reinterpret_cast<bool (*)(const char*, double)>(
380 validate_fn_proto)(flagname, VALUE_AS(double));
382 return reinterpret_cast<bool (*)(const char*, const string&)>(
383 validate_fn_proto)(flagname, VALUE_AS(string));
385 assert(false); // unknown type
390 const char* FlagValue::TypeName() const {
391 static const char types[] =
398 if (type_ > FV_MAX_INDEX) {
402 // Directly indexing the strings in the 'types' string, each of them is 7 bytes long.
403 return &types[type_ * 7];
406 bool FlagValue::Equal(const FlagValue& x) const {
407 if (type_ != x.type_)
410 case FV_BOOL: return VALUE_AS(bool) == OTHER_VALUE_AS(x, bool);
411 case FV_INT32: return VALUE_AS(int32) == OTHER_VALUE_AS(x, int32);
412 case FV_INT64: return VALUE_AS(int64) == OTHER_VALUE_AS(x, int64);
413 case FV_UINT64: return VALUE_AS(uint64) == OTHER_VALUE_AS(x, uint64);
414 case FV_DOUBLE: return VALUE_AS(double) == OTHER_VALUE_AS(x, double);
415 case FV_STRING: return VALUE_AS(string) == OTHER_VALUE_AS(x, string);
416 default: assert(false); return false; // unknown type
420 FlagValue* FlagValue::New() const {
421 const char *type = TypeName();
423 case FV_BOOL: return new FlagValue(new bool(false), type, true);
424 case FV_INT32: return new FlagValue(new int32(0), type, true);
425 case FV_INT64: return new FlagValue(new int64(0), type, true);
426 case FV_UINT64: return new FlagValue(new uint64(0), type, true);
427 case FV_DOUBLE: return new FlagValue(new double(0.0), type, true);
428 case FV_STRING: return new FlagValue(new string, type, true);
429 default: assert(false); return NULL; // unknown type
433 void FlagValue::CopyFrom(const FlagValue& x) {
434 assert(type_ == x.type_);
436 case FV_BOOL: SET_VALUE_AS(bool, OTHER_VALUE_AS(x, bool)); break;
437 case FV_INT32: SET_VALUE_AS(int32, OTHER_VALUE_AS(x, int32)); break;
438 case FV_INT64: SET_VALUE_AS(int64, OTHER_VALUE_AS(x, int64)); break;
439 case FV_UINT64: SET_VALUE_AS(uint64, OTHER_VALUE_AS(x, uint64)); break;
440 case FV_DOUBLE: SET_VALUE_AS(double, OTHER_VALUE_AS(x, double)); break;
441 case FV_STRING: SET_VALUE_AS(string, OTHER_VALUE_AS(x, string)); break;
442 default: assert(false); // unknown type
446 int FlagValue::ValueSize() const {
447 if (type_ > FV_MAX_INDEX) {
448 assert(false); // unknown type
451 static const uint8 valuesize[] = {
459 return valuesize[type_];
462 // --------------------------------------------------------------------
464 // This represents a single flag, including its name, description,
465 // default value, and current value. Mostly this serves as a
466 // struct, though it also knows how to register itself.
467 // All CommandLineFlags are owned by a (exactly one)
468 // FlagRegistry. If you wish to modify fields in this class, you
469 // should acquire the FlagRegistry lock for the registry that owns
471 // --------------------------------------------------------------------
473 class CommandLineFlag {
475 // Note: we take over memory-ownership of current_val and default_val.
476 CommandLineFlag(const char* name, const char* help, const char* filename,
477 FlagValue* current_val, FlagValue* default_val);
480 const char* name() const { return name_; }
481 const char* help() const { return help_; }
482 const char* filename() const { return file_; }
483 const char* CleanFileName() const; // nixes irrelevant prefix such as homedir
484 string current_value() const { return current_->ToString(); }
485 string default_value() const { return defvalue_->ToString(); }
486 const char* type_name() const { return defvalue_->TypeName(); }
487 ValidateFnProto validate_function() const { return validate_fn_proto_; }
488 const void* flag_ptr() const { return current_->value_buffer_; }
490 void FillCommandLineFlagInfo(struct CommandLineFlagInfo* result);
492 // If validate_fn_proto_ is non-NULL, calls it on value, returns result.
493 bool Validate(const FlagValue& value) const;
494 bool ValidateCurrent() const { return Validate(*current_); }
497 // for SetFlagLocked() and setting flags_by_ptr_
498 friend class FlagRegistry;
499 friend class GFLAGS_NAMESPACE::FlagSaverImpl; // for cloning the values
501 friend bool AddFlagValidator(const void*, ValidateFnProto);
503 // This copies all the non-const members: modified, processed, defvalue, etc.
504 void CopyFrom(const CommandLineFlag& src);
506 void UpdateModifiedBit();
508 const char* const name_; // Flag name
509 const char* const help_; // Help message
510 const char* const file_; // Which file did this come from?
511 bool modified_; // Set after default assignment?
512 FlagValue* defvalue_; // Default value for flag
513 FlagValue* current_; // Current value for flag
514 // This is a casted, 'generic' version of validate_fn, which actually
515 // takes a flag-value as an arg (void (*validate_fn)(bool), say).
516 // When we pass this to current_->Validate(), it will cast it back to
517 // the proper type. This may be NULL to mean we have no validate_fn.
518 ValidateFnProto validate_fn_proto_;
520 CommandLineFlag(const CommandLineFlag&); // no copying!
521 void operator=(const CommandLineFlag&);
524 CommandLineFlag::CommandLineFlag(const char* name, const char* help,
525 const char* filename,
526 FlagValue* current_val, FlagValue* default_val)
527 : name_(name), help_(help), file_(filename), modified_(false),
528 defvalue_(default_val), current_(current_val), validate_fn_proto_(NULL) {
531 CommandLineFlag::~CommandLineFlag() {
536 const char* CommandLineFlag::CleanFileName() const {
537 // Compute top-level directory & file that this appears in
538 // search full path backwards.
539 // Stop going backwards at kRootDir; and skip by the first slash.
540 static const char kRootDir[] = ""; // can set this to root directory,
542 if (sizeof(kRootDir)-1 == 0) // no prefix to strip
545 const char* clean_name = filename() + strlen(filename()) - 1;
546 while ( clean_name > filename() ) {
547 if (*clean_name == PATH_SEPARATOR) {
548 if (strncmp(clean_name, kRootDir, sizeof(kRootDir)-1) == 0) {
549 clean_name += sizeof(kRootDir)-1; // past root-dir
555 while ( *clean_name == PATH_SEPARATOR ) ++clean_name; // Skip any slashes
559 void CommandLineFlag::FillCommandLineFlagInfo(
560 CommandLineFlagInfo* result) {
561 result->name = name();
562 result->type = type_name();
563 result->description = help();
564 result->current_value = current_value();
565 result->default_value = default_value();
566 result->filename = CleanFileName();
568 result->is_default = !modified_;
569 result->has_validator_fn = validate_function() != NULL;
570 result->flag_ptr = flag_ptr();
573 void CommandLineFlag::UpdateModifiedBit() {
574 // Update the "modified" bit in case somebody bypassed the
575 // Flags API and wrote directly through the FLAGS_name variable.
576 if (!modified_ && !current_->Equal(*defvalue_)) {
581 void CommandLineFlag::CopyFrom(const CommandLineFlag& src) {
582 // Note we only copy the non-const members; others are fixed at construct time
583 if (modified_ != src.modified_) modified_ = src.modified_;
584 if (!current_->Equal(*src.current_)) current_->CopyFrom(*src.current_);
585 if (!defvalue_->Equal(*src.defvalue_)) defvalue_->CopyFrom(*src.defvalue_);
586 if (validate_fn_proto_ != src.validate_fn_proto_)
587 validate_fn_proto_ = src.validate_fn_proto_;
590 bool CommandLineFlag::Validate(const FlagValue& value) const {
592 if (validate_function() == NULL)
595 return value.Validate(name(), validate_function());
599 // --------------------------------------------------------------------
601 // A FlagRegistry singleton object holds all flag objects indexed
602 // by their names so that if you know a flag's name (as a C
603 // string), you can access or set it. If the function is named
604 // FooLocked(), you must own the registry lock before calling
605 // the function; otherwise, you should *not* hold the lock, and
606 // the function will acquire it itself if needed.
607 // --------------------------------------------------------------------
609 struct StringCmp { // Used by the FlagRegistry map class to compare char*'s
610 bool operator() (const char* s1, const char* s2) const {
611 return (strcmp(s1, s2) < 0);
621 // Not using STLDeleteElements as that resides in util and this
623 for (FlagMap::iterator p = flags_.begin(), e = flags_.end(); p != e; ++p) {
624 CommandLineFlag* flag = p->second;
629 static void DeleteGlobalRegistry() {
630 delete global_registry_;
631 global_registry_ = NULL;
634 // Store a flag in this registry. Takes ownership of the given pointer.
635 void RegisterFlag(CommandLineFlag* flag);
637 void Lock() { lock_.Lock(); }
638 void Unlock() { lock_.Unlock(); }
640 // Returns the flag object for the specified name, or NULL if not found.
641 CommandLineFlag* FindFlagLocked(const char* name);
643 // Returns the flag object whose current-value is stored at flag_ptr.
644 // That is, for whom current_->value_buffer_ == flag_ptr
645 CommandLineFlag* FindFlagViaPtrLocked(const void* flag_ptr);
647 // A fancier form of FindFlag that works correctly if name is of the
648 // form flag=value. In that case, we set key to point to flag, and
649 // modify v to point to the value (if present), and return the flag
650 // with the given name. If the flag does not exist, returns NULL
651 // and sets error_message.
652 CommandLineFlag* SplitArgumentLocked(const char* argument,
653 string* key, const char** v,
654 string* error_message);
656 // Set the value of a flag. If the flag was successfully set to
657 // value, set msg to indicate the new flag-value, and return true.
658 // Otherwise, set msg to indicate the error, leave flag unchanged,
659 // and return false. msg can be NULL.
660 bool SetFlagLocked(CommandLineFlag* flag, const char* value,
661 FlagSettingMode set_mode, string* msg);
663 static FlagRegistry* GlobalRegistry(); // returns a singleton registry
666 friend class GFLAGS_NAMESPACE::FlagSaverImpl; // reads all the flags in order to copy them
667 friend class CommandLineFlagParser; // for ValidateAllFlags
668 friend void GFLAGS_NAMESPACE::GetAllFlags(vector<CommandLineFlagInfo>*);
670 // The map from name to flag, for FindFlagLocked().
671 typedef map<const char*, CommandLineFlag*, StringCmp> FlagMap;
672 typedef FlagMap::iterator FlagIterator;
673 typedef FlagMap::const_iterator FlagConstIterator;
676 // The map from current-value pointer to flag, fo FindFlagViaPtrLocked().
677 typedef map<const void*, CommandLineFlag*> FlagPtrMap;
678 FlagPtrMap flags_by_ptr_;
680 static FlagRegistry* global_registry_; // a singleton registry
683 static Mutex global_registry_lock_;
685 static void InitGlobalRegistry();
688 FlagRegistry(const FlagRegistry&);
689 FlagRegistry& operator=(const FlagRegistry&);
692 class FlagRegistryLock {
694 explicit FlagRegistryLock(FlagRegistry* fr) : fr_(fr) { fr_->Lock(); }
695 ~FlagRegistryLock() { fr_->Unlock(); }
697 FlagRegistry *const fr_;
701 void FlagRegistry::RegisterFlag(CommandLineFlag* flag) {
703 pair<FlagIterator, bool> ins =
704 flags_.insert(pair<const char*, CommandLineFlag*>(flag->name(), flag));
705 if (ins.second == false) { // means the name was already in the map
706 if (strcmp(ins.first->second->filename(), flag->filename()) != 0) {
707 ReportError(DIE, "ERROR: flag '%s' was defined more than once "
708 "(in files '%s' and '%s').\n",
710 ins.first->second->filename(),
713 ReportError(DIE, "ERROR: something wrong with flag '%s' in file '%s'. "
714 "One possibility: file '%s' is being linked both statically "
715 "and dynamically into this executable.\n",
717 flag->filename(), flag->filename());
720 // Also add to the flags_by_ptr_ map.
721 flags_by_ptr_[flag->current_->value_buffer_] = flag;
725 CommandLineFlag* FlagRegistry::FindFlagLocked(const char* name) {
726 FlagConstIterator i = flags_.find(name);
727 if (i == flags_.end()) {
734 CommandLineFlag* FlagRegistry::FindFlagViaPtrLocked(const void* flag_ptr) {
735 FlagPtrMap::const_iterator i = flags_by_ptr_.find(flag_ptr);
736 if (i == flags_by_ptr_.end()) {
743 CommandLineFlag* FlagRegistry::SplitArgumentLocked(const char* arg,
746 string* error_message) {
747 // Find the flag object for this option
748 const char* flag_name;
749 const char* value = strchr(arg, '=');
754 // Strip out the "=value" portion from arg
755 key->assign(arg, value-arg);
756 *v = ++value; // advance past the '='
758 flag_name = key->c_str();
760 CommandLineFlag* flag = FindFlagLocked(flag_name);
763 // If we can't find the flag-name, then we should return an error.
764 // The one exception is if 1) the flag-name is 'nox', 2) there
765 // exists a flag named 'x', and 3) 'x' is a boolean flag.
766 // In that case, we want to return flag 'x'.
767 if (!(flag_name[0] == 'n' && flag_name[1] == 'o')) {
768 // flag-name is not 'nox', so we're not in the exception case.
769 *error_message = StringPrintf("%sunknown command line flag '%s'\n",
770 kError, key->c_str());
773 flag = FindFlagLocked(flag_name+2);
775 // No flag named 'x' exists, so we're not in the exception case.
776 *error_message = StringPrintf("%sunknown command line flag '%s'\n",
777 kError, key->c_str());
780 if (strcmp(flag->type_name(), "bool") != 0) {
781 // 'x' exists but is not boolean, so we're not in the exception case.
782 *error_message = StringPrintf(
783 "%sboolean value (%s) specified for %s command line flag\n",
784 kError, key->c_str(), flag->type_name());
787 // We're in the exception case!
788 // Make up a fake value to replace the "no" we stripped out
789 key->assign(flag_name+2); // the name without the "no"
793 // Assign a value if this is a boolean flag
794 if (*v == NULL && strcmp(flag->type_name(), "bool") == 0) {
795 *v = "1"; // the --nox case was already handled, so this is the --x case
801 bool TryParseLocked(const CommandLineFlag* flag, FlagValue* flag_value,
802 const char* value, string* msg) {
803 // Use tenative_value, not flag_value, until we know value is valid.
804 FlagValue* tentative_value = flag_value->New();
805 if (!tentative_value->ParseFrom(value)) {
808 "%sillegal value '%s' specified for %s flag '%s'\n",
810 flag->type_name(), flag->name());
812 delete tentative_value;
814 } else if (!flag->Validate(*tentative_value)) {
817 "%sfailed validation of new value '%s' for flag '%s'\n",
818 kError, tentative_value->ToString().c_str(),
821 delete tentative_value;
824 flag_value->CopyFrom(*tentative_value);
826 StringAppendF(msg, "%s set to %s\n",
827 flag->name(), flag_value->ToString().c_str());
829 delete tentative_value;
834 bool FlagRegistry::SetFlagLocked(CommandLineFlag* flag,
836 FlagSettingMode set_mode,
838 flag->UpdateModifiedBit();
840 case SET_FLAGS_VALUE: {
841 // set or modify the flag's value
842 if (!TryParseLocked(flag, flag->current_, value, msg))
844 flag->modified_ = true;
847 case SET_FLAG_IF_DEFAULT: {
848 // set the flag's value, but only if it hasn't been set by someone else
849 if (!flag->modified_) {
850 if (!TryParseLocked(flag, flag->current_, value, msg))
852 flag->modified_ = true;
854 *msg = StringPrintf("%s set to %s",
855 flag->name(), flag->current_value().c_str());
859 case SET_FLAGS_DEFAULT: {
860 // modify the flag's default-value
861 if (!TryParseLocked(flag, flag->defvalue_, value, msg))
863 if (!flag->modified_) {
864 // Need to set both defvalue *and* current, in this case
865 TryParseLocked(flag, flag->current_, value, NULL);
879 // Get the singleton FlagRegistry object
880 FlagRegistry* FlagRegistry::global_registry_ = NULL;
881 Mutex FlagRegistry::global_registry_lock_(Mutex::LINKER_INITIALIZED);
883 FlagRegistry* FlagRegistry::GlobalRegistry() {
884 MutexLock acquire_lock(&global_registry_lock_);
885 if (!global_registry_) {
886 global_registry_ = new FlagRegistry;
888 return global_registry_;
891 // --------------------------------------------------------------------
892 // CommandLineFlagParser
893 // Parsing is done in two stages. In the first, we go through
894 // argv. For every flag-like arg we can make sense of, we parse
895 // it and set the appropriate FLAGS_* variable. For every flag-
896 // like arg we can't make sense of, we store it in a vector,
897 // along with an explanation of the trouble. In stage 2, we
898 // handle the 'reporting' flags like --help and --mpm_version.
899 // (This is via a call to HandleCommandLineHelpFlags(), in
900 // gflags_reporting.cc.)
901 // An optional stage 3 prints out the error messages.
902 // This is a bit of a simplification. For instance, --flagfile
903 // is handled as soon as it's seen in stage 1, not in stage 2.
904 // --------------------------------------------------------------------
906 class CommandLineFlagParser {
908 // The argument is the flag-registry to register the parsed flags in
909 explicit CommandLineFlagParser(FlagRegistry* reg) : registry_(reg) {}
910 ~CommandLineFlagParser() {}
912 // Stage 1: Every time this is called, it reads all flags in argv.
913 // However, it ignores all flags that have been successfully set
914 // before. Typically this is only called once, so this 'reparsing'
915 // behavior isn't important. It can be useful when trying to
916 // reparse after loading a dll, though.
917 uint32 ParseNewCommandLineFlags(int* argc, char*** argv, bool remove_flags);
919 // Stage 2: print reporting info and exit, if requested.
920 // In gflags_reporting.cc:HandleCommandLineHelpFlags().
922 // Stage 3: validate all the commandline flags that have validators
924 void ValidateAllFlags();
926 // Stage 4: report any errors and return true if any were found.
929 // Set a particular command line option. "newval" is a string
930 // describing the new value that the option has been set to. If
931 // option_name does not specify a valid option name, or value is not
932 // a valid value for option_name, newval is empty. Does recursive
933 // processing for --flagfile and --fromenv. Returns the new value
934 // if everything went ok, or empty-string if not. (Actually, the
935 // return-string could hold many flag/value pairs due to --flagfile.)
936 // NB: Must have called registry_->Lock() before calling this function.
937 string ProcessSingleOptionLocked(CommandLineFlag* flag,
939 FlagSettingMode set_mode);
941 // Set a whole batch of command line options as specified by contentdata,
942 // which is in flagfile format (and probably has been read from a flagfile).
943 // Returns the new value if everything went ok, or empty-string if
944 // not. (Actually, the return-string could hold many flag/value
945 // pairs due to --flagfile.)
946 // NB: Must have called registry_->Lock() before calling this function.
947 string ProcessOptionsFromStringLocked(const string& contentdata,
948 FlagSettingMode set_mode);
950 // These are the 'recursive' flags, defined at the top of this file.
951 // Whenever we see these flags on the commandline, we must take action.
952 // These are called by ProcessSingleOptionLocked and, similarly, return
953 // new values if everything went ok, or the empty-string if not.
954 string ProcessFlagfileLocked(const string& flagval, FlagSettingMode set_mode);
955 // diff fromenv/tryfromenv
956 string ProcessFromenvLocked(const string& flagval, FlagSettingMode set_mode,
957 bool errors_are_fatal);
960 FlagRegistry* const registry_;
961 map<string, string> error_flags_; // map from name to error message
962 // This could be a set<string>, but we reuse the map to minimize the .o size
963 map<string, string> undefined_names_; // --[flag] name was not registered
967 // Parse a list of (comma-separated) flags.
968 static void ParseFlagList(const char* value, vector<string>* flags) {
969 for (const char *p = value; p && *p; value = p) {
970 p = strchr(value, ',');
980 ReportError(DIE, "ERROR: empty flaglist entry\n");
982 ReportError(DIE, "ERROR: flag \"%*s\" begins with '-'\n", len, value);
984 flags->push_back(string(value, len));
988 // Snarf an entire file into a C++ string. This is just so that we
989 // can do all the I/O in one place and not worry about it everywhere.
990 // Plus, it's convenient to have the whole file contents at hand.
991 // Adds a newline at the end of the file.
992 #define PFATAL(s) do { perror(s); gflags_exitfunc(1); } while (0)
994 static string ReadFileIntoString(const char* filename) {
995 const int kBufSize = 8092;
996 char buffer[kBufSize];
999 if ((errno = SafeFOpen(&fp, filename, "r")) != 0) PFATAL(filename);
1001 while ( (n=fread(buffer, 1, kBufSize, fp)) > 0 ) {
1002 if (ferror(fp)) PFATAL(filename);
1003 s.append(buffer, n);
1009 uint32 CommandLineFlagParser::ParseNewCommandLineFlags(int* argc, char*** argv,
1010 bool remove_flags) {
1011 const char *program_name = strrchr((*argv)[0], PATH_SEPARATOR); // nix path
1012 program_name = (program_name == NULL ? (*argv)[0] : program_name+1);
1014 int first_nonopt = *argc; // for non-options moved to the end
1017 for (int i = 1; i < first_nonopt; i++) {
1018 char* arg = (*argv)[i];
1020 // Like getopt(), we permute non-option flags to be at the end.
1021 if (arg[0] != '-' || // must be a program argument
1022 (arg[0] == '-' && arg[1] == '\0')) { // "-" is an argument, not a flag
1023 memmove((*argv) + i, (*argv) + i+1, (*argc - (i+1)) * sizeof((*argv)[i]));
1024 (*argv)[*argc-1] = arg; // we go last
1025 first_nonopt--; // we've been pushed onto the stack
1026 i--; // to undo the i++ in the loop
1030 if (arg[0] == '-') arg++; // allow leading '-'
1031 if (arg[0] == '-') arg++; // or leading '--'
1033 // -- alone means what it does for GNU: stop options parsing
1039 // Find the flag object for this option
1042 string error_message;
1043 CommandLineFlag* flag = registry_->SplitArgumentLocked(arg, &key, &value,
1046 undefined_names_[key] = ""; // value isn't actually used
1047 error_flags_[key] = error_message;
1051 if (value == NULL) {
1052 // Boolean options are always assigned a value by SplitArgumentLocked()
1053 assert(strcmp(flag->type_name(), "bool") != 0);
1054 if (i+1 >= first_nonopt) {
1055 // This flag needs a value, but there is nothing available
1056 error_flags_[key] = (string(kError) + "flag '" + (*argv)[i] + "'"
1057 + " is missing its argument");
1058 if (flag->help() && flag->help()[0] > '\001') {
1059 // Be useful in case we have a non-stripped description.
1060 error_flags_[key] += string("; flag description: ") + flag->help();
1062 error_flags_[key] += "\n";
1063 break; // we treat this as an unrecoverable error
1065 value = (*argv)[++i]; // read next arg for value
1067 // Heuristic to detect the case where someone treats a string arg
1069 // --my_string_var --foo=bar
1070 // We look for a flag of string type, whose value begins with a
1071 // dash, and where the flag-name and value are separated by a
1072 // space rather than an '='.
1073 // To avoid false positives, we also require the word "true"
1074 // or "false" in the help string. Without this, a valid usage
1075 // "-lat -30.5" would trigger the warning. The common cases we
1076 // want to solve talk about true and false as values.
1078 && strcmp(flag->type_name(), "string") == 0
1079 && (strstr(flag->help(), "true")
1080 || strstr(flag->help(), "false"))) {
1081 LOG(WARNING) << "Did you really mean to set flag '"
1082 << flag->name() << "' to the value '"
1088 // TODO(csilvers): only set a flag if we hadn't set it before here
1089 ProcessSingleOptionLocked(flag, value, SET_FLAGS_VALUE);
1091 registry_->Unlock();
1093 if (remove_flags) { // Fix up argc and argv by removing command line flags
1094 (*argv)[first_nonopt-1] = (*argv)[0];
1095 (*argv) += (first_nonopt-1);
1096 (*argc) -= (first_nonopt-1);
1097 first_nonopt = 1; // because we still don't count argv[0]
1100 logging_is_probably_set_up = true; // because we've parsed --logdir, etc.
1102 return first_nonopt;
1105 string CommandLineFlagParser::ProcessFlagfileLocked(const string& flagval,
1106 FlagSettingMode set_mode) {
1107 if (flagval.empty())
1111 vector<string> filename_list;
1112 ParseFlagList(flagval.c_str(), &filename_list); // take a list of filenames
1113 for (size_t i = 0; i < filename_list.size(); ++i) {
1114 const char* file = filename_list[i].c_str();
1115 msg += ProcessOptionsFromStringLocked(ReadFileIntoString(file), set_mode);
1120 string CommandLineFlagParser::ProcessFromenvLocked(const string& flagval,
1121 FlagSettingMode set_mode,
1122 bool errors_are_fatal) {
1123 if (flagval.empty())
1127 vector<string> flaglist;
1128 ParseFlagList(flagval.c_str(), &flaglist);
1130 for (size_t i = 0; i < flaglist.size(); ++i) {
1131 const char* flagname = flaglist[i].c_str();
1132 CommandLineFlag* flag = registry_->FindFlagLocked(flagname);
1134 error_flags_[flagname] =
1135 StringPrintf("%sunknown command line flag '%s' "
1136 "(via --fromenv or --tryfromenv)\n",
1138 undefined_names_[flagname] = "";
1142 const string envname = string("FLAGS_") + string(flagname);
1144 if (!SafeGetEnv(envname.c_str(), envval)) {
1145 if (errors_are_fatal) {
1146 error_flags_[flagname] = (string(kError) + envname +
1147 " not found in environment\n");
1152 // Avoid infinite recursion.
1153 if (envval == "fromenv" || envval == "tryfromenv") {
1154 error_flags_[flagname] =
1155 StringPrintf("%sinfinite recursion on environment flag '%s'\n",
1156 kError, envval.c_str());
1160 msg += ProcessSingleOptionLocked(flag, envval.c_str(), set_mode);
1165 string CommandLineFlagParser::ProcessSingleOptionLocked(
1166 CommandLineFlag* flag, const char* value, FlagSettingMode set_mode) {
1168 if (value && !registry_->SetFlagLocked(flag, value, set_mode, &msg)) {
1169 error_flags_[flag->name()] = msg;
1173 // The recursive flags, --flagfile and --fromenv and --tryfromenv,
1174 // must be dealt with as soon as they're seen. They will emit
1175 // messages of their own.
1176 if (strcmp(flag->name(), "flagfile") == 0) {
1177 msg += ProcessFlagfileLocked(FLAGS_flagfile, set_mode);
1179 } else if (strcmp(flag->name(), "fromenv") == 0) {
1180 // last arg indicates envval-not-found is fatal (unlike in --tryfromenv)
1181 msg += ProcessFromenvLocked(FLAGS_fromenv, set_mode, true);
1183 } else if (strcmp(flag->name(), "tryfromenv") == 0) {
1184 msg += ProcessFromenvLocked(FLAGS_tryfromenv, set_mode, false);
1190 void CommandLineFlagParser::ValidateAllFlags() {
1191 FlagRegistryLock frl(registry_);
1192 for (FlagRegistry::FlagConstIterator i = registry_->flags_.begin();
1193 i != registry_->flags_.end(); ++i) {
1194 if (!i->second->ValidateCurrent()) {
1195 // only set a message if one isn't already there. (If there's
1196 // an error message, our job is done, even if it's not exactly
1198 if (error_flags_[i->second->name()].empty())
1199 error_flags_[i->second->name()] =
1200 string(kError) + "--" + i->second->name() +
1201 " must be set on the commandline"
1202 " (default value fails validation)\n";
1207 bool CommandLineFlagParser::ReportErrors() {
1208 // error_flags_ indicates errors we saw while parsing.
1209 // But we ignore undefined-names if ok'ed by --undef_ok
1210 if (!FLAGS_undefok.empty()) {
1211 vector<string> flaglist;
1212 ParseFlagList(FLAGS_undefok.c_str(), &flaglist);
1213 for (size_t i = 0; i < flaglist.size(); ++i) {
1214 // We also deal with --no<flag>, in case the flagname was boolean
1215 const string no_version = string("no") + flaglist[i];
1216 if (undefined_names_.find(flaglist[i]) != undefined_names_.end()) {
1217 error_flags_[flaglist[i]] = ""; // clear the error message
1218 } else if (undefined_names_.find(no_version) != undefined_names_.end()) {
1219 error_flags_[no_version] = "";
1223 // Likewise, if they decided to allow reparsing, all undefined-names
1224 // are ok; we just silently ignore them now, and hope that a future
1225 // parse will pick them up somehow.
1226 if (allow_command_line_reparsing) {
1227 for (map<string, string>::const_iterator it = undefined_names_.begin();
1228 it != undefined_names_.end(); ++it)
1229 error_flags_[it->first] = ""; // clear the error message
1232 bool found_error = false;
1233 string error_message;
1234 for (map<string, string>::const_iterator it = error_flags_.begin();
1235 it != error_flags_.end(); ++it) {
1236 if (!it->second.empty()) {
1237 error_message.append(it->second.data(), it->second.size());
1242 ReportError(DO_NOT_DIE, "%s", error_message.c_str());
1246 string CommandLineFlagParser::ProcessOptionsFromStringLocked(
1247 const string& contentdata, FlagSettingMode set_mode) {
1249 const char* flagfile_contents = contentdata.c_str();
1250 bool flags_are_relevant = true; // set to false when filenames don't match
1251 bool in_filename_section = false;
1253 const char* line_end = flagfile_contents;
1254 // We read this file a line at a time.
1255 for (; line_end; flagfile_contents = line_end + 1) {
1256 while (*flagfile_contents && isspace(*flagfile_contents))
1257 ++flagfile_contents;
1258 line_end = strchr(flagfile_contents, '\n');
1259 size_t len = line_end ? line_end - flagfile_contents
1260 : strlen(flagfile_contents);
1261 string line(flagfile_contents, len);
1263 // Each line can be one of four things:
1264 // 1) A comment line -- we skip it
1265 // 2) An empty line -- we skip it
1266 // 3) A list of filenames -- starts a new filenames+flags section
1267 // 4) A --flag=value line -- apply if previous filenames match
1268 if (line.empty() || line[0] == '#') {
1269 // comment or empty line; just ignore
1271 } else if (line[0] == '-') { // flag
1272 in_filename_section = false; // instead, it was a flag-line
1273 if (!flags_are_relevant) // skip this flag; applies to someone else
1276 const char* name_and_val = line.c_str() + 1; // skip the leading -
1277 if (*name_and_val == '-')
1278 name_and_val++; // skip second - too
1281 string error_message;
1282 CommandLineFlag* flag = registry_->SplitArgumentLocked(name_and_val,
1285 // By API, errors parsing flagfile lines are silently ignored.
1287 // "WARNING: flagname '" + key + "' not found\n"
1288 } else if (value == NULL) {
1289 // "WARNING: flagname '" + key + "' missing a value\n"
1291 retval += ProcessSingleOptionLocked(flag, value, set_mode);
1294 } else { // a filename!
1295 if (!in_filename_section) { // start over: assume filenames don't match
1296 in_filename_section = true;
1297 flags_are_relevant = false;
1300 // Split the line up at spaces into glob-patterns
1301 const char* space = line.c_str(); // just has to be non-NULL
1302 for (const char* word = line.c_str(); *space; word = space+1) {
1303 if (flags_are_relevant) // we can stop as soon as we match
1305 space = strchr(word, ' ');
1307 space = word + strlen(word);
1308 const string glob(word, space - word);
1309 // We try matching both against the full argv0 and basename(argv0)
1310 if (glob == ProgramInvocationName() // small optimization
1311 || glob == ProgramInvocationShortName()
1312 #if defined(HAVE_FNMATCH_H)
1313 || fnmatch(glob.c_str(), ProgramInvocationName(), FNM_PATHNAME) == 0
1314 || fnmatch(glob.c_str(), ProgramInvocationShortName(), FNM_PATHNAME) == 0
1315 #elif defined(HAVE_SHLWAPI_H)
1316 || PathMatchSpec(glob.c_str(), ProgramInvocationName())
1317 || PathMatchSpec(glob.c_str(), ProgramInvocationShortName())
1320 flags_are_relevant = true;
1328 // --------------------------------------------------------------------
1330 // AddFlagValidator()
1331 // These are helper functions for routines like BoolFromEnv() and
1332 // RegisterFlagValidator, defined below. They're defined here so
1333 // they can live in the unnamed namespace (which makes friendship
1334 // declarations for these classes possible).
1335 // --------------------------------------------------------------------
1337 template<typename T>
1338 T GetFromEnv(const char *varname, const char* type, T dflt) {
1340 if (SafeGetEnv(varname, valstr)) {
1341 FlagValue ifv(new T, type, true);
1342 if (!ifv.ParseFrom(valstr.c_str())) {
1343 ReportError(DIE, "ERROR: error parsing env variable '%s' with value '%s'\n",
1344 varname, valstr.c_str());
1346 return OTHER_VALUE_AS(ifv, T);
1350 bool AddFlagValidator(const void* flag_ptr, ValidateFnProto validate_fn_proto) {
1351 // We want a lock around this routine, in case two threads try to
1352 // add a validator (hopefully the same one!) at once. We could use
1353 // our own thread, but we need to loook at the registry anyway, so
1354 // we just steal that one.
1355 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1356 FlagRegistryLock frl(registry);
1357 // First, find the flag whose current-flag storage is 'flag'.
1358 // This is the CommandLineFlag whose current_->value_buffer_ == flag
1359 CommandLineFlag* flag = registry->FindFlagViaPtrLocked(flag_ptr);
1361 LOG(WARNING) << "Ignoring RegisterValidateFunction() for flag pointer "
1362 << flag_ptr << ": no flag found at that address";
1364 } else if (validate_fn_proto == flag->validate_function()) {
1365 return true; // ok to register the same function over and over again
1366 } else if (validate_fn_proto != NULL && flag->validate_function() != NULL) {
1367 LOG(WARNING) << "Ignoring RegisterValidateFunction() for flag '"
1368 << flag->name() << "': validate-fn already registered";
1371 flag->validate_fn_proto_ = validate_fn_proto;
1376 } // end unnamed namespaces
1379 // Now define the functions that are exported via the .h file
1381 // --------------------------------------------------------------------
1383 // This class exists merely to have a global constructor (the
1384 // kind that runs before main(), that goes an initializes each
1385 // flag that's been declared. Note that it's very important we
1386 // don't have a destructor that deletes flag_, because that would
1387 // cause us to delete current_storage/defvalue_storage as well,
1388 // which can cause a crash if anything tries to access the flag
1389 // values in a global destructor.
1390 // --------------------------------------------------------------------
1392 FlagRegisterer::FlagRegisterer(const char* name, const char* type,
1393 const char* help, const char* filename,
1394 void* current_storage, void* defvalue_storage) {
1397 // FlagValue expects the type-name to not include any namespace
1398 // components, so we get rid of those, if any.
1399 if (strchr(type, ':'))
1400 type = strrchr(type, ':') + 1;
1401 FlagValue* current = new FlagValue(current_storage, type, false);
1402 FlagValue* defvalue = new FlagValue(defvalue_storage, type, false);
1403 // Importantly, flag_ will never be deleted, so storage is always good.
1404 CommandLineFlag* flag = new CommandLineFlag(name, help, filename,
1406 FlagRegistry::GlobalRegistry()->RegisterFlag(flag); // default registry
1409 // --------------------------------------------------------------------
1411 // The main way the FlagRegistry class exposes its data. This
1412 // returns, as strings, all the info about all the flags in
1413 // the main registry, sorted first by filename they are defined
1414 // in, and then by flagname.
1415 // --------------------------------------------------------------------
1417 struct FilenameFlagnameCmp {
1418 bool operator()(const CommandLineFlagInfo& a,
1419 const CommandLineFlagInfo& b) const {
1420 int cmp = strcmp(a.filename.c_str(), b.filename.c_str());
1422 cmp = strcmp(a.name.c_str(), b.name.c_str()); // secondary sort key
1427 void GetAllFlags(vector<CommandLineFlagInfo>* OUTPUT) {
1428 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1430 for (FlagRegistry::FlagConstIterator i = registry->flags_.begin();
1431 i != registry->flags_.end(); ++i) {
1432 CommandLineFlagInfo fi;
1433 i->second->FillCommandLineFlagInfo(&fi);
1434 OUTPUT->push_back(fi);
1437 // Now sort the flags, first by filename they occur in, then alphabetically
1438 sort(OUTPUT->begin(), OUTPUT->end(), FilenameFlagnameCmp());
1441 // --------------------------------------------------------------------
1446 // ProgramInvocationName()
1447 // ProgramInvocationShortName()
1448 // SetUsageMessage()
1450 // Functions to set and get argv. Typically the setter is called
1451 // by ParseCommandLineFlags. Also can get the ProgramUsage string,
1452 // set by SetUsageMessage.
1453 // --------------------------------------------------------------------
1455 // These values are not protected by a Mutex because they are normally
1456 // set only once during program startup.
1457 static string argv0("UNKNOWN"); // just the program name
1458 static string cmdline; // the entire command-line
1459 static string program_usage;
1460 static vector<string> argvs;
1461 static uint32 argv_sum = 0;
1463 void SetArgv(int argc, const char** argv) {
1464 static bool called_set_argv = false;
1465 if (called_set_argv) return;
1466 called_set_argv = true;
1468 assert(argc > 0); // every program has at least a name
1472 for (int i = 0; i < argc; i++) {
1473 if (i != 0) cmdline += " ";
1475 argvs.push_back(argv[i]);
1478 // Compute a simple sum of all the chars in argv
1480 for (string::const_iterator c = cmdline.begin(); c != cmdline.end(); ++c) {
1485 const vector<string>& GetArgvs() { return argvs; }
1486 const char* GetArgv() { return cmdline.c_str(); }
1487 const char* GetArgv0() { return argv0.c_str(); }
1488 uint32 GetArgvSum() { return argv_sum; }
1489 const char* ProgramInvocationName() { // like the GNU libc fn
1492 const char* ProgramInvocationShortName() { // like the GNU libc fn
1493 size_t pos = argv0.rfind('/');
1495 if (pos == string::npos) pos = argv0.rfind('\\');
1497 return (pos == string::npos ? argv0.c_str() : (argv0.c_str() + pos + 1));
1500 void SetUsageMessage(const string& usage) {
1501 program_usage = usage;
1504 const char* ProgramUsage() {
1505 if (program_usage.empty()) {
1506 return "Warning: SetUsageMessage() never called";
1508 return program_usage.c_str();
1511 // --------------------------------------------------------------------
1512 // SetVersionString()
1514 // --------------------------------------------------------------------
1516 static string version_string;
1518 void SetVersionString(const string& version) {
1519 version_string = version;
1522 const char* VersionString() {
1523 return version_string.c_str();
1527 // --------------------------------------------------------------------
1528 // GetCommandLineOption()
1529 // GetCommandLineFlagInfo()
1530 // GetCommandLineFlagInfoOrDie()
1531 // SetCommandLineOption()
1532 // SetCommandLineOptionWithMode()
1533 // The programmatic way to set a flag's value, using a string
1534 // for its name rather than the variable itself (that is,
1535 // SetCommandLineOption("foo", x) rather than FLAGS_foo = x).
1536 // There's also a bit more flexibility here due to the various
1537 // set-modes, but typically these are used when you only have
1538 // that flag's name as a string, perhaps at runtime.
1539 // All of these work on the default, global registry.
1540 // For GetCommandLineOption, return false if no such flag
1541 // is known, true otherwise. We clear "value" if a suitable
1543 // --------------------------------------------------------------------
1546 bool GetCommandLineOption(const char* name, string* value) {
1551 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1552 FlagRegistryLock frl(registry);
1553 CommandLineFlag* flag = registry->FindFlagLocked(name);
1557 *value = flag->current_value();
1562 bool GetCommandLineFlagInfo(const char* name, CommandLineFlagInfo* OUTPUT) {
1563 if (NULL == name) return false;
1564 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1565 FlagRegistryLock frl(registry);
1566 CommandLineFlag* flag = registry->FindFlagLocked(name);
1571 flag->FillCommandLineFlagInfo(OUTPUT);
1576 CommandLineFlagInfo GetCommandLineFlagInfoOrDie(const char* name) {
1577 CommandLineFlagInfo info;
1578 if (!GetCommandLineFlagInfo(name, &info)) {
1579 fprintf(stderr, "FATAL ERROR: flag name '%s' doesn't exist\n", name);
1580 gflags_exitfunc(1); // almost certainly gflags_exitfunc()
1585 string SetCommandLineOptionWithMode(const char* name, const char* value,
1586 FlagSettingMode set_mode) {
1588 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1589 FlagRegistryLock frl(registry);
1590 CommandLineFlag* flag = registry->FindFlagLocked(name);
1592 CommandLineFlagParser parser(registry);
1593 result = parser.ProcessSingleOptionLocked(flag, value, set_mode);
1594 if (!result.empty()) { // in the error case, we've already logged
1595 // Could consider logging this change
1598 // The API of this function is that we return empty string on error
1602 string SetCommandLineOption(const char* name, const char* value) {
1603 return SetCommandLineOptionWithMode(name, value, SET_FLAGS_VALUE);
1606 // --------------------------------------------------------------------
1609 // This class stores the states of all flags at construct time,
1610 // and restores all flags to that state at destruct time.
1611 // Its major implementation challenge is that it never modifies
1612 // pointers in the 'main' registry, so global FLAG_* vars always
1613 // point to the right place.
1614 // --------------------------------------------------------------------
1616 class FlagSaverImpl {
1618 // Constructs an empty FlagSaverImpl object.
1619 explicit FlagSaverImpl(FlagRegistry* main_registry)
1620 : main_registry_(main_registry) { }
1622 // reclaim memory from each of our CommandLineFlags
1623 vector<CommandLineFlag*>::const_iterator it;
1624 for (it = backup_registry_.begin(); it != backup_registry_.end(); ++it)
1628 // Saves the flag states from the flag registry into this object.
1629 // It's an error to call this more than once.
1630 // Must be called when the registry mutex is not held.
1631 void SaveFromRegistry() {
1632 FlagRegistryLock frl(main_registry_);
1633 assert(backup_registry_.empty()); // call only once!
1634 for (FlagRegistry::FlagConstIterator it = main_registry_->flags_.begin();
1635 it != main_registry_->flags_.end();
1637 const CommandLineFlag* main = it->second;
1638 // Sets up all the const variables in backup correctly
1639 CommandLineFlag* backup = new CommandLineFlag(
1640 main->name(), main->help(), main->filename(),
1641 main->current_->New(), main->defvalue_->New());
1642 // Sets up all the non-const variables in backup correctly
1643 backup->CopyFrom(*main);
1644 backup_registry_.push_back(backup); // add it to a convenient list
1648 // Restores the saved flag states into the flag registry. We
1649 // assume no flags were added or deleted from the registry since
1650 // the SaveFromRegistry; if they were, that's trouble! Must be
1651 // called when the registry mutex is not held.
1652 void RestoreToRegistry() {
1653 FlagRegistryLock frl(main_registry_);
1654 vector<CommandLineFlag*>::const_iterator it;
1655 for (it = backup_registry_.begin(); it != backup_registry_.end(); ++it) {
1656 CommandLineFlag* main = main_registry_->FindFlagLocked((*it)->name());
1657 if (main != NULL) { // if NULL, flag got deleted from registry(!)
1658 main->CopyFrom(**it);
1664 FlagRegistry* const main_registry_;
1665 vector<CommandLineFlag*> backup_registry_;
1667 FlagSaverImpl(const FlagSaverImpl&); // no copying!
1668 void operator=(const FlagSaverImpl&);
1671 FlagSaver::FlagSaver()
1672 : impl_(new FlagSaverImpl(FlagRegistry::GlobalRegistry())) {
1673 impl_->SaveFromRegistry();
1676 FlagSaver::~FlagSaver() {
1677 impl_->RestoreToRegistry();
1682 // --------------------------------------------------------------------
1683 // CommandlineFlagsIntoString()
1684 // ReadFlagsFromString()
1685 // AppendFlagsIntoFile()
1686 // ReadFromFlagsFile()
1687 // These are mostly-deprecated routines that stick the
1688 // commandline flags into a file/string and read them back
1689 // out again. I can see a use for CommandlineFlagsIntoString,
1690 // for creating a flagfile, but the rest don't seem that useful
1691 // -- some, I think, are a poor-man's attempt at FlagSaver --
1692 // and are included only until we can delete them from callers.
1693 // Note they don't save --flagfile flags (though they do save
1694 // the result of having called the flagfile, of course).
1695 // --------------------------------------------------------------------
1697 static string TheseCommandlineFlagsIntoString(
1698 const vector<CommandLineFlagInfo>& flags) {
1699 vector<CommandLineFlagInfo>::const_iterator i;
1701 size_t retval_space = 0;
1702 for (i = flags.begin(); i != flags.end(); ++i) {
1703 // An (over)estimate of how much space it will take to print this flag
1704 retval_space += i->name.length() + i->current_value.length() + 5;
1708 retval.reserve(retval_space);
1709 for (i = flags.begin(); i != flags.end(); ++i) {
1713 retval += i->current_value;
1719 string CommandlineFlagsIntoString() {
1720 vector<CommandLineFlagInfo> sorted_flags;
1721 GetAllFlags(&sorted_flags);
1722 return TheseCommandlineFlagsIntoString(sorted_flags);
1725 bool ReadFlagsFromString(const string& flagfilecontents,
1726 const char* /*prog_name*/, // TODO(csilvers): nix this
1727 bool errors_are_fatal) {
1728 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1729 FlagSaverImpl saved_states(registry);
1730 saved_states.SaveFromRegistry();
1732 CommandLineFlagParser parser(registry);
1734 parser.ProcessOptionsFromStringLocked(flagfilecontents, SET_FLAGS_VALUE);
1736 // Should we handle --help and such when reading flags from a string? Sure.
1737 HandleCommandLineHelpFlags();
1738 if (parser.ReportErrors()) {
1739 // Error. Restore all global flags to their previous values.
1740 if (errors_are_fatal)
1742 saved_states.RestoreToRegistry();
1748 // TODO(csilvers): nix prog_name in favor of ProgramInvocationShortName()
1749 bool AppendFlagsIntoFile(const string& filename, const char *prog_name) {
1751 if (SafeFOpen(&fp, filename.c_str(), "a") != 0) {
1756 fprintf(fp, "%s\n", prog_name);
1758 vector<CommandLineFlagInfo> flags;
1759 GetAllFlags(&flags);
1760 // But we don't want --flagfile, which leads to weird recursion issues
1761 vector<CommandLineFlagInfo>::iterator i;
1762 for (i = flags.begin(); i != flags.end(); ++i) {
1763 if (strcmp(i->name.c_str(), "flagfile") == 0) {
1768 fprintf(fp, "%s", TheseCommandlineFlagsIntoString(flags).c_str());
1774 bool ReadFromFlagsFile(const string& filename, const char* prog_name,
1775 bool errors_are_fatal) {
1776 return ReadFlagsFromString(ReadFileIntoString(filename.c_str()),
1777 prog_name, errors_are_fatal);
1781 // --------------------------------------------------------------------
1788 // Reads the value from the environment and returns it.
1789 // We use an FlagValue to make the parsing easy.
1791 // DEFINE_bool(myflag, BoolFromEnv("MYFLAG_DEFAULT", false), "whatever");
1792 // --------------------------------------------------------------------
1794 bool BoolFromEnv(const char *v, bool dflt) {
1795 return GetFromEnv(v, "bool", dflt);
1797 int32 Int32FromEnv(const char *v, int32 dflt) {
1798 return GetFromEnv(v, "int32", dflt);
1800 int64 Int64FromEnv(const char *v, int64 dflt) {
1801 return GetFromEnv(v, "int64", dflt);
1803 uint64 Uint64FromEnv(const char *v, uint64 dflt) {
1804 return GetFromEnv(v, "uint64", dflt);
1806 double DoubleFromEnv(const char *v, double dflt) {
1807 return GetFromEnv(v, "double", dflt);
1811 # pragma warning(push)
1812 # pragma warning(disable: 4996) // ignore getenv security warning
1814 const char *StringFromEnv(const char *varname, const char *dflt) {
1815 const char* const val = getenv(varname);
1816 return val ? val : dflt;
1819 # pragma warning(pop)
1823 // --------------------------------------------------------------------
1824 // RegisterFlagValidator()
1825 // RegisterFlagValidator() is the function that clients use to
1826 // 'decorate' a flag with a validation function. Once this is
1827 // done, every time the flag is set (including when the flag
1828 // is parsed from argv), the validator-function is called.
1829 // These functions return true if the validator was added
1830 // successfully, or false if not: the flag already has a validator,
1831 // (only one allowed per flag), the 1st arg isn't a flag, etc.
1832 // This function is not thread-safe.
1833 // --------------------------------------------------------------------
1835 bool RegisterFlagValidator(const bool* flag,
1836 bool (*validate_fn)(const char*, bool)) {
1837 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1839 bool RegisterFlagValidator(const int32* flag,
1840 bool (*validate_fn)(const char*, int32)) {
1841 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1843 bool RegisterFlagValidator(const int64* flag,
1844 bool (*validate_fn)(const char*, int64)) {
1845 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1847 bool RegisterFlagValidator(const uint64* flag,
1848 bool (*validate_fn)(const char*, uint64)) {
1849 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1851 bool RegisterFlagValidator(const double* flag,
1852 bool (*validate_fn)(const char*, double)) {
1853 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1855 bool RegisterFlagValidator(const string* flag,
1856 bool (*validate_fn)(const char*, const string&)) {
1857 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1861 // --------------------------------------------------------------------
1862 // ParseCommandLineFlags()
1863 // ParseCommandLineNonHelpFlags()
1864 // HandleCommandLineHelpFlags()
1865 // This is the main function called from main(), to actually
1866 // parse the commandline. It modifies argc and argv as described
1867 // at the top of gflags.h. You can also divide this
1868 // function into two parts, if you want to do work between
1869 // the parsing of the flags and the printing of any help output.
1870 // --------------------------------------------------------------------
1872 static uint32 ParseCommandLineFlagsInternal(int* argc, char*** argv,
1873 bool remove_flags, bool do_report) {
1874 SetArgv(*argc, const_cast<const char**>(*argv)); // save it for later
1876 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1877 CommandLineFlagParser parser(registry);
1879 // When we parse the commandline flags, we'll handle --flagfile,
1880 // --tryfromenv, etc. as we see them (since flag-evaluation order
1881 // may be important). But sometimes apps set FLAGS_tryfromenv/etc.
1882 // manually before calling ParseCommandLineFlags. We want to evaluate
1883 // those too, as if they were the first flags on the commandline.
1885 parser.ProcessFlagfileLocked(FLAGS_flagfile, SET_FLAGS_VALUE);
1886 // Last arg here indicates whether flag-not-found is a fatal error or not
1887 parser.ProcessFromenvLocked(FLAGS_fromenv, SET_FLAGS_VALUE, true);
1888 parser.ProcessFromenvLocked(FLAGS_tryfromenv, SET_FLAGS_VALUE, false);
1891 // Now get the flags specified on the commandline
1892 const int r = parser.ParseNewCommandLineFlags(argc, argv, remove_flags);
1895 HandleCommandLineHelpFlags(); // may cause us to exit on --help, etc.
1897 // See if any of the unset flags fail their validation checks
1898 parser.ValidateAllFlags();
1900 if (parser.ReportErrors()) // may cause us to exit on illegal flags
1905 uint32 ParseCommandLineFlags(int* argc, char*** argv, bool remove_flags) {
1906 return ParseCommandLineFlagsInternal(argc, argv, remove_flags, true);
1909 uint32 ParseCommandLineNonHelpFlags(int* argc, char*** argv,
1910 bool remove_flags) {
1911 return ParseCommandLineFlagsInternal(argc, argv, remove_flags, false);
1914 // --------------------------------------------------------------------
1915 // AllowCommandLineReparsing()
1916 // ReparseCommandLineNonHelpFlags()
1917 // This is most useful for shared libraries. The idea is if
1918 // a flag is defined in a shared library that is dlopen'ed
1919 // sometime after main(), you can ParseCommandLineFlags before
1920 // the dlopen, then ReparseCommandLineNonHelpFlags() after the
1921 // dlopen, to get the new flags. But you have to explicitly
1922 // Allow() it; otherwise, you get the normal default behavior
1923 // of unrecognized flags calling a fatal error.
1924 // TODO(csilvers): this isn't used. Just delete it?
1925 // --------------------------------------------------------------------
1927 void AllowCommandLineReparsing() {
1928 allow_command_line_reparsing = true;
1931 void ReparseCommandLineNonHelpFlags() {
1932 // We make a copy of argc and argv to pass in
1933 const vector<string>& argvs = GetArgvs();
1934 int tmp_argc = static_cast<int>(argvs.size());
1935 char** tmp_argv = new char* [tmp_argc + 1];
1936 for (int i = 0; i < tmp_argc; ++i)
1937 tmp_argv[i] = strdup(argvs[i].c_str()); // TODO(csilvers): don't dup
1939 ParseCommandLineNonHelpFlags(&tmp_argc, &tmp_argv, false);
1941 for (int i = 0; i < tmp_argc; ++i)
1946 void ShutDownCommandLineFlags() {
1947 FlagRegistry::DeleteGlobalRegistry();
1951 } // namespace GFLAGS_NAMESPACE