• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 1999, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
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
13 // distribution.
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.
17 //
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.
29 
30 // ---
31 // Revamped and reorganized by Craig Silverstein
32 //
33 // This file contains the implementation of all our command line flags
34 // stuff.  Here's how everything fits together
35 //
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).
43 //
44 // In more detail:
45 //
46 // -- The main classes that hold flag data:
47 //
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
52 // variable's value.
53 //
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.
57 //
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).
63 //
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.
69 //
70 // --- Some other classes and free functions:
71 //
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.
75 //
76 // FlagRegisterer is the helper class used by the DEFINE_* macros to
77 // allow work to be done at global initialization time.
78 //
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.
84 //
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.
89 
90 #include "config.h"
91 #include "gflags/gflags.h"
92 
93 #include <assert.h>
94 #include <ctype.h>
95 #include <errno.h>
96 #if defined(HAVE_FNMATCH_H)
97 #  include <fnmatch.h>
98 #elif defined(HAVE_SHLWAPI_H)
99 #  define NO_SHLWAPI_ISOS
100 #  include <shlwapi.h>
101 #endif
102 #include <stdarg.h> // For va_list and related operations
103 #include <stdio.h>
104 #include <string.h>
105 
106 #include <algorithm>
107 #include <map>
108 #include <string>
109 #include <utility>     // for pair<>
110 #include <vector>
111 
112 #include "mutex.h"
113 #include "util.h"
114 
115 using namespace MUTEX_NAMESPACE;
116 
117 
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");
123 
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");
129 
130 namespace GFLAGS_NAMESPACE {
131 
132 using std::map;
133 using std::pair;
134 using std::sort;
135 using std::string;
136 using std::vector;
137 
138 // This is used by the unittest to test error-exit code
139 void GFLAGS_DLL_DECL (*gflags_exitfunc)(int) = &exit;  // from stdlib.h
140 
141 
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
146 
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";
149 
150 namespace {
151 
152 // There are also 'reporting' flags, in gflags_reporting.cc.
153 
154 static const char kError[] = "ERROR: ";
155 
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;
159 
160 static bool logging_is_probably_set_up = false;
161 
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
166 // a flag value.
167 typedef bool (*ValidateFnProto)();
168 
169 // Whether we should die when reporting an error.
170 enum DieWhenReporting { DIE, DO_NOT_DIE };
171 
172 // Report Error and exit if requested.
ReportError(DieWhenReporting should_die,const char * format,...)173 static void ReportError(DieWhenReporting should_die, const char* format, ...) {
174   va_list ap;
175   va_start(ap, format);
176   vfprintf(stderr, format, ap);
177   va_end(ap);
178   fflush(stderr);   // should be unnecessary, but cygwin's rxvt buffers stderr
179   if (should_die == DIE) gflags_exitfunc(1);
180 }
181 
182 
183 // --------------------------------------------------------------------
184 // FlagValue
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 // --------------------------------------------------------------------
189 
190 class CommandLineFlag;
191 class FlagValue {
192  public:
193   enum ValueType {
194     FV_BOOL = 0,
195     FV_INT32 = 1,
196     FV_UINT32 = 2,
197     FV_INT64 = 3,
198     FV_UINT64 = 4,
199     FV_DOUBLE = 5,
200     FV_STRING = 6,
201     FV_MAX_INDEX = 6,
202   };
203 
204   template <typename FlagType>
205   FlagValue(FlagType* valbuf, bool transfer_ownership_of_value);
206   ~FlagValue();
207 
208   bool ParseFrom(const char* spec);
209   string ToString() const;
210 
Type() const211   ValueType Type() const { return static_cast<ValueType>(type_); }
212 
213  private:
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()
220 
221   template <typename FlagType>
222   struct FlagValueTraits;
223 
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 
229   // Calls the given validate-fn on value_buffer_, and returns
230   // whatever it returns.  But first casts validate_fn_proto to a
231   // function that takes our value as an argument (eg void
232   // (*validate_fn)(bool) for a bool flag).
233   bool Validate(const char* flagname, ValidateFnProto validate_fn_proto) const;
234 
235   void* const value_buffer_;          // points to the buffer holding our data
236   const int8 type_;                   // how to interpret value_
237   const bool owns_value_;             // whether to free value on destruct
238 
239   FlagValue(const FlagValue&);   // no copying!
240   void operator=(const FlagValue&);
241 };
242 
243 // Map the given C++ type to a value of the ValueType enum at compile time.
244 #define DEFINE_FLAG_TRAITS(type, value)        \
245   template <>                                  \
246   struct FlagValue::FlagValueTraits<type> {    \
247     static const ValueType kValueType = value; \
248   }
249 
250 // Define full template specializations of the FlagValueTraits template
251 // for all supported flag types.
252 DEFINE_FLAG_TRAITS(bool, FV_BOOL);
253 DEFINE_FLAG_TRAITS(int32, FV_INT32);
254 DEFINE_FLAG_TRAITS(uint32, FV_UINT32);
255 DEFINE_FLAG_TRAITS(int64, FV_INT64);
256 DEFINE_FLAG_TRAITS(uint64, FV_UINT64);
257 DEFINE_FLAG_TRAITS(double, FV_DOUBLE);
258 DEFINE_FLAG_TRAITS(std::string, FV_STRING);
259 
260 #undef DEFINE_FLAG_TRAITS
261 
262 
263 // This could be a templated method of FlagValue, but doing so adds to the
264 // size of the .o.  Since there's no type-safety here anyway, macro is ok.
265 #define VALUE_AS(type)  *reinterpret_cast<type*>(value_buffer_)
266 #define OTHER_VALUE_AS(fv, type)  *reinterpret_cast<type*>(fv.value_buffer_)
267 #define SET_VALUE_AS(type, value)  VALUE_AS(type) = (value)
268 
269 template <typename FlagType>
FlagValue(FlagType * valbuf,bool transfer_ownership_of_value)270 FlagValue::FlagValue(FlagType* valbuf,
271                      bool transfer_ownership_of_value)
272     : value_buffer_(valbuf),
273       type_(FlagValueTraits<FlagType>::kValueType),
274       owns_value_(transfer_ownership_of_value) {
275 }
276 
~FlagValue()277 FlagValue::~FlagValue() {
278   if (!owns_value_) {
279     return;
280   }
281   switch (type_) {
282     case FV_BOOL: delete reinterpret_cast<bool*>(value_buffer_); break;
283     case FV_INT32: delete reinterpret_cast<int32*>(value_buffer_); break;
284     case FV_UINT32: delete reinterpret_cast<uint32*>(value_buffer_); break;
285     case FV_INT64: delete reinterpret_cast<int64*>(value_buffer_); break;
286     case FV_UINT64: delete reinterpret_cast<uint64*>(value_buffer_); break;
287     case FV_DOUBLE: delete reinterpret_cast<double*>(value_buffer_); break;
288     case FV_STRING: delete reinterpret_cast<string*>(value_buffer_); break;
289   }
290 }
291 
ParseFrom(const char * value)292 bool FlagValue::ParseFrom(const char* value) {
293   if (type_ == FV_BOOL) {
294     const char* kTrue[] = { "1", "t", "true", "y", "yes" };
295     const char* kFalse[] = { "0", "f", "false", "n", "no" };
296     COMPILE_ASSERT(sizeof(kTrue) == sizeof(kFalse), true_false_equal);
297     for (size_t i = 0; i < sizeof(kTrue)/sizeof(*kTrue); ++i) {
298       if (strcasecmp(value, kTrue[i]) == 0) {
299         SET_VALUE_AS(bool, true);
300         return true;
301       } else if (strcasecmp(value, kFalse[i]) == 0) {
302         SET_VALUE_AS(bool, false);
303         return true;
304       }
305     }
306     return false;   // didn't match a legal input
307 
308   } else if (type_ == FV_STRING) {
309     SET_VALUE_AS(string, value);
310     return true;
311   }
312 
313   // OK, it's likely to be numeric, and we'll be using a strtoXXX method.
314   if (value[0] == '\0')   // empty-string is only allowed for string type.
315     return false;
316   char* end;
317   // Leading 0x puts us in base 16.  But leading 0 does not put us in base 8!
318   // It caused too many bugs when we had that behavior.
319   int base = 10;    // by default
320   if (value[0] == '0' && (value[1] == 'x' || value[1] == 'X'))
321     base = 16;
322   errno = 0;
323 
324   switch (type_) {
325     case FV_INT32: {
326       const int64 r = strto64(value, &end, base);
327       if (errno || end != value + strlen(value))  return false;  // bad parse
328       if (static_cast<int32>(r) != r)  // worked, but number out of range
329         return false;
330       SET_VALUE_AS(int32, static_cast<int32>(r));
331       return true;
332     }
333     case FV_UINT32: {
334       while (*value == ' ') value++;
335       if (*value == '-') return false;  // negative number
336       const uint64 r = strtou64(value, &end, base);
337       if (errno || end != value + strlen(value))  return false;  // bad parse
338         if (static_cast<uint32>(r) != r)  // worked, but number out of range
339         return false;
340       SET_VALUE_AS(uint32, static_cast<uint32>(r));
341       return true;
342     }
343     case FV_INT64: {
344       const int64 r = strto64(value, &end, base);
345       if (errno || end != value + strlen(value))  return false;  // bad parse
346       SET_VALUE_AS(int64, r);
347       return true;
348     }
349     case FV_UINT64: {
350       while (*value == ' ') value++;
351       if (*value == '-') return false;  // negative number
352       const uint64 r = strtou64(value, &end, base);
353       if (errno || end != value + strlen(value))  return false;  // bad parse
354       SET_VALUE_AS(uint64, r);
355       return true;
356     }
357     case FV_DOUBLE: {
358       const double r = strtod(value, &end);
359       if (errno || end != value + strlen(value))  return false;  // bad parse
360       SET_VALUE_AS(double, r);
361       return true;
362     }
363     default: {
364       assert(false);  // unknown type
365       return false;
366     }
367   }
368 }
369 
ToString() const370 string FlagValue::ToString() const {
371   char intbuf[64];    // enough to hold even the biggest number
372   switch (type_) {
373     case FV_BOOL:
374       return VALUE_AS(bool) ? "true" : "false";
375     case FV_INT32:
376       snprintf(intbuf, sizeof(intbuf), "%" PRId32, VALUE_AS(int32));
377       return intbuf;
378     case FV_UINT32:
379       snprintf(intbuf, sizeof(intbuf), "%" PRIu32, VALUE_AS(uint32));
380       return intbuf;
381     case FV_INT64:
382       snprintf(intbuf, sizeof(intbuf), "%" PRId64, VALUE_AS(int64));
383       return intbuf;
384     case FV_UINT64:
385       snprintf(intbuf, sizeof(intbuf), "%" PRIu64, VALUE_AS(uint64));
386       return intbuf;
387     case FV_DOUBLE:
388       snprintf(intbuf, sizeof(intbuf), "%.17g", VALUE_AS(double));
389       return intbuf;
390     case FV_STRING:
391       return VALUE_AS(string);
392     default:
393       assert(false);
394       return "";  // unknown type
395   }
396 }
397 
Validate(const char * flagname,ValidateFnProto validate_fn_proto) const398 bool FlagValue::Validate(const char* flagname,
399                          ValidateFnProto validate_fn_proto) const {
400   switch (type_) {
401     case FV_BOOL:
402       return reinterpret_cast<bool (*)(const char*, bool)>(
403           validate_fn_proto)(flagname, VALUE_AS(bool));
404     case FV_INT32:
405       return reinterpret_cast<bool (*)(const char*, int32)>(
406           validate_fn_proto)(flagname, VALUE_AS(int32));
407     case FV_UINT32:
408       return reinterpret_cast<bool (*)(const char*, uint32)>(
409           validate_fn_proto)(flagname, VALUE_AS(uint32));
410     case FV_INT64:
411       return reinterpret_cast<bool (*)(const char*, int64)>(
412           validate_fn_proto)(flagname, VALUE_AS(int64));
413     case FV_UINT64:
414       return reinterpret_cast<bool (*)(const char*, uint64)>(
415           validate_fn_proto)(flagname, VALUE_AS(uint64));
416     case FV_DOUBLE:
417       return reinterpret_cast<bool (*)(const char*, double)>(
418           validate_fn_proto)(flagname, VALUE_AS(double));
419     case FV_STRING:
420       return reinterpret_cast<bool (*)(const char*, const string&)>(
421           validate_fn_proto)(flagname, VALUE_AS(string));
422     default:
423       assert(false);  // unknown type
424       return false;
425   }
426 }
427 
TypeName() const428 const char* FlagValue::TypeName() const {
429   static const char types[] =
430       "bool\0xx"
431       "int32\0x"
432       "uint32\0"
433       "int64\0x"
434       "uint64\0"
435       "double\0"
436       "string";
437   if (type_ > FV_MAX_INDEX) {
438     assert(false);
439     return "";
440   }
441   // Directly indexing the strings in the 'types' string, each of them is 7 bytes long.
442   return &types[type_ * 7];
443 }
444 
Equal(const FlagValue & x) const445 bool FlagValue::Equal(const FlagValue& x) const {
446   if (type_ != x.type_)
447     return false;
448   switch (type_) {
449     case FV_BOOL:   return VALUE_AS(bool) == OTHER_VALUE_AS(x, bool);
450     case FV_INT32:  return VALUE_AS(int32) == OTHER_VALUE_AS(x, int32);
451     case FV_UINT32: return VALUE_AS(uint32) == OTHER_VALUE_AS(x, uint32);
452     case FV_INT64:  return VALUE_AS(int64) == OTHER_VALUE_AS(x, int64);
453     case FV_UINT64: return VALUE_AS(uint64) == OTHER_VALUE_AS(x, uint64);
454     case FV_DOUBLE: return VALUE_AS(double) == OTHER_VALUE_AS(x, double);
455     case FV_STRING: return VALUE_AS(string) == OTHER_VALUE_AS(x, string);
456     default: assert(false); return false;  // unknown type
457   }
458 }
459 
New() const460 FlagValue* FlagValue::New() const {
461   switch (type_) {
462     case FV_BOOL:   return new FlagValue(new bool(false), true);
463     case FV_INT32:  return new FlagValue(new int32(0), true);
464     case FV_UINT32: return new FlagValue(new uint32(0), true);
465     case FV_INT64:  return new FlagValue(new int64(0), true);
466     case FV_UINT64: return new FlagValue(new uint64(0), true);
467     case FV_DOUBLE: return new FlagValue(new double(0.0), true);
468     case FV_STRING: return new FlagValue(new string, true);
469     default: assert(false); return NULL;  // unknown type
470   }
471 }
472 
CopyFrom(const FlagValue & x)473 void FlagValue::CopyFrom(const FlagValue& x) {
474   assert(type_ == x.type_);
475   switch (type_) {
476     case FV_BOOL:   SET_VALUE_AS(bool, OTHER_VALUE_AS(x, bool));      break;
477     case FV_INT32:  SET_VALUE_AS(int32, OTHER_VALUE_AS(x, int32));    break;
478     case FV_UINT32: SET_VALUE_AS(uint32, OTHER_VALUE_AS(x, uint32));  break;
479     case FV_INT64:  SET_VALUE_AS(int64, OTHER_VALUE_AS(x, int64));    break;
480     case FV_UINT64: SET_VALUE_AS(uint64, OTHER_VALUE_AS(x, uint64));  break;
481     case FV_DOUBLE: SET_VALUE_AS(double, OTHER_VALUE_AS(x, double));  break;
482     case FV_STRING: SET_VALUE_AS(string, OTHER_VALUE_AS(x, string));  break;
483     default: assert(false);  // unknown type
484   }
485 }
486 
487 // --------------------------------------------------------------------
488 // CommandLineFlag
489 //    This represents a single flag, including its name, description,
490 //    default value, and current value.  Mostly this serves as a
491 //    struct, though it also knows how to register itself.
492 //       All CommandLineFlags are owned by a (exactly one)
493 //    FlagRegistry.  If you wish to modify fields in this class, you
494 //    should acquire the FlagRegistry lock for the registry that owns
495 //    this flag.
496 // --------------------------------------------------------------------
497 
498 class CommandLineFlag {
499  public:
500   // Note: we take over memory-ownership of current_val and default_val.
501   CommandLineFlag(const char* name, const char* help, const char* filename,
502                   FlagValue* current_val, FlagValue* default_val);
503   ~CommandLineFlag();
504 
name() const505   const char* name() const { return name_; }
help() const506   const char* help() const { return help_; }
filename() const507   const char* filename() const { return file_; }
508   const char* CleanFileName() const;  // nixes irrelevant prefix such as homedir
current_value() const509   string current_value() const { return current_->ToString(); }
default_value() const510   string default_value() const { return defvalue_->ToString(); }
type_name() const511   const char* type_name() const { return defvalue_->TypeName(); }
validate_function() const512   ValidateFnProto validate_function() const { return validate_fn_proto_; }
flag_ptr() const513   const void* flag_ptr() const { return current_->value_buffer_; }
514 
Type() const515   FlagValue::ValueType Type() const { return defvalue_->Type(); }
516 
517   void FillCommandLineFlagInfo(struct CommandLineFlagInfo* result);
518 
519   // If validate_fn_proto_ is non-NULL, calls it on value, returns result.
520   bool Validate(const FlagValue& value) const;
ValidateCurrent() const521   bool ValidateCurrent() const { return Validate(*current_); }
Modified() const522   bool Modified() const { return modified_; }
523 
524  private:
525   // for SetFlagLocked() and setting flags_by_ptr_
526   friend class FlagRegistry;
527   friend class GFLAGS_NAMESPACE::FlagSaverImpl;  // for cloning the values
528   // set validate_fn
529   friend bool AddFlagValidator(const void*, ValidateFnProto);
530 
531   // This copies all the non-const members: modified, processed, defvalue, etc.
532   void CopyFrom(const CommandLineFlag& src);
533 
534   void UpdateModifiedBit();
535 
536   const char* const name_;     // Flag name
537   const char* const help_;     // Help message
538   const char* const file_;     // Which file did this come from?
539   bool modified_;              // Set after default assignment?
540   FlagValue* defvalue_;        // Default value for flag
541   FlagValue* current_;         // Current value for flag
542   // This is a casted, 'generic' version of validate_fn, which actually
543   // takes a flag-value as an arg (void (*validate_fn)(bool), say).
544   // When we pass this to current_->Validate(), it will cast it back to
545   // the proper type.  This may be NULL to mean we have no validate_fn.
546   ValidateFnProto validate_fn_proto_;
547 
548   CommandLineFlag(const CommandLineFlag&);   // no copying!
549   void operator=(const CommandLineFlag&);
550 };
551 
CommandLineFlag(const char * name,const char * help,const char * filename,FlagValue * current_val,FlagValue * default_val)552 CommandLineFlag::CommandLineFlag(const char* name, const char* help,
553                                  const char* filename,
554                                  FlagValue* current_val, FlagValue* default_val)
555     : name_(name), help_(help), file_(filename), modified_(false),
556       defvalue_(default_val), current_(current_val), validate_fn_proto_(NULL) {
557 }
558 
~CommandLineFlag()559 CommandLineFlag::~CommandLineFlag() {
560   delete current_;
561   delete defvalue_;
562 }
563 
CleanFileName() const564 const char* CommandLineFlag::CleanFileName() const {
565   // This function has been used to strip off a common prefix from
566   // flag source file names. Because flags can be defined in different
567   // shared libraries, there may not be a single common prefix.
568   // Further, this functionality hasn't been active for many years.
569   // Need a better way to produce more user friendly help output or
570   // "anonymize" file paths in help output, respectively.
571   // Follow issue at: https://github.com/gflags/gflags/issues/86
572   return filename();
573 }
574 
FillCommandLineFlagInfo(CommandLineFlagInfo * result)575 void CommandLineFlag::FillCommandLineFlagInfo(
576     CommandLineFlagInfo* result) {
577   result->name = name();
578   result->type = type_name();
579   result->description = help();
580   result->current_value = current_value();
581   result->default_value = default_value();
582   result->filename = CleanFileName();
583   UpdateModifiedBit();
584   result->is_default = !modified_;
585   result->has_validator_fn = validate_function() != NULL;
586   result->flag_ptr = flag_ptr();
587 }
588 
UpdateModifiedBit()589 void CommandLineFlag::UpdateModifiedBit() {
590   // Update the "modified" bit in case somebody bypassed the
591   // Flags API and wrote directly through the FLAGS_name variable.
592   if (!modified_ && !current_->Equal(*defvalue_)) {
593     modified_ = true;
594   }
595 }
596 
CopyFrom(const CommandLineFlag & src)597 void CommandLineFlag::CopyFrom(const CommandLineFlag& src) {
598   // Note we only copy the non-const members; others are fixed at construct time
599   if (modified_ != src.modified_) modified_ = src.modified_;
600   if (!current_->Equal(*src.current_)) current_->CopyFrom(*src.current_);
601   if (!defvalue_->Equal(*src.defvalue_)) defvalue_->CopyFrom(*src.defvalue_);
602   if (validate_fn_proto_ != src.validate_fn_proto_)
603     validate_fn_proto_ = src.validate_fn_proto_;
604 }
605 
Validate(const FlagValue & value) const606 bool CommandLineFlag::Validate(const FlagValue& value) const {
607 
608   if (validate_function() == NULL)
609     return true;
610   else
611     return value.Validate(name(), validate_function());
612 }
613 
614 
615 // --------------------------------------------------------------------
616 // FlagRegistry
617 //    A FlagRegistry singleton object holds all flag objects indexed
618 //    by their names so that if you know a flag's name (as a C
619 //    string), you can access or set it.  If the function is named
620 //    FooLocked(), you must own the registry lock before calling
621 //    the function; otherwise, you should *not* hold the lock, and
622 //    the function will acquire it itself if needed.
623 // --------------------------------------------------------------------
624 
625 struct StringCmp {  // Used by the FlagRegistry map class to compare char*'s
operator ()GFLAGS_NAMESPACE::__anon73d8155c0111::StringCmp626   bool operator() (const char* s1, const char* s2) const {
627     return (strcmp(s1, s2) < 0);
628   }
629 };
630 
631 
632 class FlagRegistry {
633  public:
FlagRegistry()634   FlagRegistry() {
635   }
~FlagRegistry()636   ~FlagRegistry() {
637     // Not using STLDeleteElements as that resides in util and this
638     // class is base.
639     for (FlagMap::iterator p = flags_.begin(), e = flags_.end(); p != e; ++p) {
640       CommandLineFlag* flag = p->second;
641       delete flag;
642     }
643   }
644 
DeleteGlobalRegistry()645   static void DeleteGlobalRegistry() {
646     delete global_registry_;
647     global_registry_ = NULL;
648   }
649 
650   // Store a flag in this registry.  Takes ownership of the given pointer.
651   void RegisterFlag(CommandLineFlag* flag);
652 
Lock()653   void Lock() { lock_.Lock(); }
Unlock()654   void Unlock() { lock_.Unlock(); }
655 
656   // Returns the flag object for the specified name, or NULL if not found.
657   CommandLineFlag* FindFlagLocked(const char* name);
658 
659   // Returns the flag object whose current-value is stored at flag_ptr.
660   // That is, for whom current_->value_buffer_ == flag_ptr
661   CommandLineFlag* FindFlagViaPtrLocked(const void* flag_ptr);
662 
663   // A fancier form of FindFlag that works correctly if name is of the
664   // form flag=value.  In that case, we set key to point to flag, and
665   // modify v to point to the value (if present), and return the flag
666   // with the given name.  If the flag does not exist, returns NULL
667   // and sets error_message.
668   CommandLineFlag* SplitArgumentLocked(const char* argument,
669                                        string* key, const char** v,
670                                        string* error_message);
671 
672   // Set the value of a flag.  If the flag was successfully set to
673   // value, set msg to indicate the new flag-value, and return true.
674   // Otherwise, set msg to indicate the error, leave flag unchanged,
675   // and return false.  msg can be NULL.
676   bool SetFlagLocked(CommandLineFlag* flag, const char* value,
677                      FlagSettingMode set_mode, string* msg);
678 
679   static FlagRegistry* GlobalRegistry();   // returns a singleton registry
680 
681  private:
682   friend class GFLAGS_NAMESPACE::FlagSaverImpl;  // reads all the flags in order to copy them
683   friend class CommandLineFlagParser;    // for ValidateUnmodifiedFlags
684   friend void GFLAGS_NAMESPACE::GetAllFlags(vector<CommandLineFlagInfo>*);
685 
686   // The map from name to flag, for FindFlagLocked().
687   typedef map<const char*, CommandLineFlag*, StringCmp> FlagMap;
688   typedef FlagMap::iterator FlagIterator;
689   typedef FlagMap::const_iterator FlagConstIterator;
690   FlagMap flags_;
691 
692   // The map from current-value pointer to flag, fo FindFlagViaPtrLocked().
693   typedef map<const void*, CommandLineFlag*> FlagPtrMap;
694   FlagPtrMap flags_by_ptr_;
695 
696   static FlagRegistry* global_registry_;   // a singleton registry
697 
698   Mutex lock_;
699 
700   static void InitGlobalRegistry();
701 
702   // Disallow
703   FlagRegistry(const FlagRegistry&);
704   FlagRegistry& operator=(const FlagRegistry&);
705 };
706 
707 class FlagRegistryLock {
708  public:
FlagRegistryLock(FlagRegistry * fr)709   explicit FlagRegistryLock(FlagRegistry* fr) : fr_(fr) { fr_->Lock(); }
~FlagRegistryLock()710   ~FlagRegistryLock() { fr_->Unlock(); }
711  private:
712   FlagRegistry *const fr_;
713 };
714 
715 
RegisterFlag(CommandLineFlag * flag)716 void FlagRegistry::RegisterFlag(CommandLineFlag* flag) {
717   Lock();
718   pair<FlagIterator, bool> ins =
719     flags_.insert(pair<const char*, CommandLineFlag*>(flag->name(), flag));
720   if (ins.second == false) {   // means the name was already in the map
721     if (strcmp(ins.first->second->filename(), flag->filename()) != 0) {
722       ReportError(DIE, "ERROR: flag '%s' was defined more than once "
723                   "(in files '%s' and '%s').\n",
724                   flag->name(),
725                   ins.first->second->filename(),
726                   flag->filename());
727     } else {
728       ReportError(DIE, "ERROR: something wrong with flag '%s' in file '%s'.  "
729                   "One possibility: file '%s' is being linked both statically "
730                   "and dynamically into this executable.\n",
731                   flag->name(),
732                   flag->filename(), flag->filename());
733     }
734   }
735   // Also add to the flags_by_ptr_ map.
736   flags_by_ptr_[flag->current_->value_buffer_] = flag;
737   Unlock();
738 }
739 
FindFlagLocked(const char * name)740 CommandLineFlag* FlagRegistry::FindFlagLocked(const char* name) {
741   FlagConstIterator i = flags_.find(name);
742   if (i == flags_.end()) {
743     // If the name has dashes in it, try again after replacing with
744     // underscores.
745     if (strchr(name, '-') == NULL) return NULL;
746     string name_rep = name;
747     std::replace(name_rep.begin(), name_rep.end(), '-', '_');
748     return FindFlagLocked(name_rep.c_str());
749   } else {
750     return i->second;
751   }
752 }
753 
FindFlagViaPtrLocked(const void * flag_ptr)754 CommandLineFlag* FlagRegistry::FindFlagViaPtrLocked(const void* flag_ptr) {
755   FlagPtrMap::const_iterator i = flags_by_ptr_.find(flag_ptr);
756   if (i == flags_by_ptr_.end()) {
757     return NULL;
758   } else {
759     return i->second;
760   }
761 }
762 
SplitArgumentLocked(const char * arg,string * key,const char ** v,string * error_message)763 CommandLineFlag* FlagRegistry::SplitArgumentLocked(const char* arg,
764                                                    string* key,
765                                                    const char** v,
766                                                    string* error_message) {
767   // Find the flag object for this option
768   const char* flag_name;
769   const char* value = strchr(arg, '=');
770   if (value == NULL) {
771     key->assign(arg);
772     *v = NULL;
773   } else {
774     // Strip out the "=value" portion from arg
775     key->assign(arg, value-arg);
776     *v = ++value;    // advance past the '='
777   }
778   flag_name = key->c_str();
779 
780   CommandLineFlag* flag = FindFlagLocked(flag_name);
781 
782   if (flag == NULL) {
783     // If we can't find the flag-name, then we should return an error.
784     // The one exception is if 1) the flag-name is 'nox', 2) there
785     // exists a flag named 'x', and 3) 'x' is a boolean flag.
786     // In that case, we want to return flag 'x'.
787     if (!(flag_name[0] == 'n' && flag_name[1] == 'o')) {
788       // flag-name is not 'nox', so we're not in the exception case.
789       *error_message = StringPrintf("%sunknown command line flag '%s'\n",
790                                     kError, key->c_str());
791       return NULL;
792     }
793     flag = FindFlagLocked(flag_name+2);
794     if (flag == NULL) {
795       // No flag named 'x' exists, so we're not in the exception case.
796       *error_message = StringPrintf("%sunknown command line flag '%s'\n",
797                                     kError, key->c_str());
798       return NULL;
799     }
800     if (flag->Type() != FlagValue::FV_BOOL) {
801       // 'x' exists but is not boolean, so we're not in the exception case.
802       *error_message = StringPrintf(
803           "%sboolean value (%s) specified for %s command line flag\n",
804           kError, key->c_str(), flag->type_name());
805       return NULL;
806     }
807     // We're in the exception case!
808     // Make up a fake value to replace the "no" we stripped out
809     key->assign(flag_name+2);   // the name without the "no"
810     *v = "0";
811   }
812 
813   // Assign a value if this is a boolean flag
814   if (*v == NULL && flag->Type() == FlagValue::FV_BOOL) {
815     *v = "1";    // the --nox case was already handled, so this is the --x case
816   }
817 
818   return flag;
819 }
820 
TryParseLocked(const CommandLineFlag * flag,FlagValue * flag_value,const char * value,string * msg)821 bool TryParseLocked(const CommandLineFlag* flag, FlagValue* flag_value,
822                     const char* value, string* msg) {
823   // Use tenative_value, not flag_value, until we know value is valid.
824   FlagValue* tentative_value = flag_value->New();
825   if (!tentative_value->ParseFrom(value)) {
826     if (msg) {
827       StringAppendF(msg,
828                     "%sillegal value '%s' specified for %s flag '%s'\n",
829                     kError, value,
830                     flag->type_name(), flag->name());
831     }
832     delete tentative_value;
833     return false;
834   } else if (!flag->Validate(*tentative_value)) {
835     if (msg) {
836       StringAppendF(msg,
837           "%sfailed validation of new value '%s' for flag '%s'\n",
838           kError, tentative_value->ToString().c_str(),
839           flag->name());
840     }
841     delete tentative_value;
842     return false;
843   } else {
844     flag_value->CopyFrom(*tentative_value);
845     if (msg) {
846       StringAppendF(msg, "%s set to %s\n",
847                     flag->name(), flag_value->ToString().c_str());
848     }
849     delete tentative_value;
850     return true;
851   }
852 }
853 
SetFlagLocked(CommandLineFlag * flag,const char * value,FlagSettingMode set_mode,string * msg)854 bool FlagRegistry::SetFlagLocked(CommandLineFlag* flag,
855                                  const char* value,
856                                  FlagSettingMode set_mode,
857                                  string* msg) {
858   flag->UpdateModifiedBit();
859   switch (set_mode) {
860     case SET_FLAGS_VALUE: {
861       // set or modify the flag's value
862       if (!TryParseLocked(flag, flag->current_, value, msg))
863         return false;
864       flag->modified_ = true;
865       break;
866     }
867     case SET_FLAG_IF_DEFAULT: {
868       // set the flag's value, but only if it hasn't been set by someone else
869       if (!flag->modified_) {
870         if (!TryParseLocked(flag, flag->current_, value, msg))
871           return false;
872         flag->modified_ = true;
873       } else {
874         *msg = StringPrintf("%s set to %s",
875                             flag->name(), flag->current_value().c_str());
876       }
877       break;
878     }
879     case SET_FLAGS_DEFAULT: {
880       // modify the flag's default-value
881       if (!TryParseLocked(flag, flag->defvalue_, value, msg))
882         return false;
883       if (!flag->modified_) {
884         // Need to set both defvalue *and* current, in this case
885         TryParseLocked(flag, flag->current_, value, NULL);
886       }
887       break;
888     }
889     default: {
890       // unknown set_mode
891       assert(false);
892       return false;
893     }
894   }
895 
896   return true;
897 }
898 
899 // Get the singleton FlagRegistry object
900 FlagRegistry* FlagRegistry::global_registry_ = NULL;
901 
GlobalRegistry()902 FlagRegistry* FlagRegistry::GlobalRegistry() {
903   static Mutex lock(Mutex::LINKER_INITIALIZED);
904   MutexLock acquire_lock(&lock);
905   if (!global_registry_) {
906     global_registry_ = new FlagRegistry;
907   }
908   return global_registry_;
909 }
910 
911 // --------------------------------------------------------------------
912 // CommandLineFlagParser
913 //    Parsing is done in two stages.  In the first, we go through
914 //    argv.  For every flag-like arg we can make sense of, we parse
915 //    it and set the appropriate FLAGS_* variable.  For every flag-
916 //    like arg we can't make sense of, we store it in a vector,
917 //    along with an explanation of the trouble.  In stage 2, we
918 //    handle the 'reporting' flags like --help and --mpm_version.
919 //    (This is via a call to HandleCommandLineHelpFlags(), in
920 //    gflags_reporting.cc.)
921 //    An optional stage 3 prints out the error messages.
922 //       This is a bit of a simplification.  For instance, --flagfile
923 //    is handled as soon as it's seen in stage 1, not in stage 2.
924 // --------------------------------------------------------------------
925 
926 class CommandLineFlagParser {
927  public:
928   // The argument is the flag-registry to register the parsed flags in
CommandLineFlagParser(FlagRegistry * reg)929   explicit CommandLineFlagParser(FlagRegistry* reg) : registry_(reg) {}
~CommandLineFlagParser()930   ~CommandLineFlagParser() {}
931 
932   // Stage 1: Every time this is called, it reads all flags in argv.
933   // However, it ignores all flags that have been successfully set
934   // before.  Typically this is only called once, so this 'reparsing'
935   // behavior isn't important.  It can be useful when trying to
936   // reparse after loading a dll, though.
937   uint32 ParseNewCommandLineFlags(int* argc, char*** argv, bool remove_flags);
938 
939   // Stage 2: print reporting info and exit, if requested.
940   // In gflags_reporting.cc:HandleCommandLineHelpFlags().
941 
942   // Stage 3: validate all the commandline flags that have validators
943   // registered and were not set/modified by ParseNewCommandLineFlags.
944   void ValidateFlags(bool all);
945   void ValidateUnmodifiedFlags();
946 
947   // Stage 4: report any errors and return true if any were found.
948   bool ReportErrors();
949 
950   // Set a particular command line option.  "newval" is a string
951   // describing the new value that the option has been set to.  If
952   // option_name does not specify a valid option name, or value is not
953   // a valid value for option_name, newval is empty.  Does recursive
954   // processing for --flagfile and --fromenv.  Returns the new value
955   // if everything went ok, or empty-string if not.  (Actually, the
956   // return-string could hold many flag/value pairs due to --flagfile.)
957   // NB: Must have called registry_->Lock() before calling this function.
958   string ProcessSingleOptionLocked(CommandLineFlag* flag,
959                                    const char* value,
960                                    FlagSettingMode set_mode);
961 
962   // Set a whole batch of command line options as specified by contentdata,
963   // which is in flagfile format (and probably has been read from a flagfile).
964   // Returns the new value if everything went ok, or empty-string if
965   // not.  (Actually, the return-string could hold many flag/value
966   // pairs due to --flagfile.)
967   // NB: Must have called registry_->Lock() before calling this function.
968   string ProcessOptionsFromStringLocked(const string& contentdata,
969                                         FlagSettingMode set_mode);
970 
971   // These are the 'recursive' flags, defined at the top of this file.
972   // Whenever we see these flags on the commandline, we must take action.
973   // These are called by ProcessSingleOptionLocked and, similarly, return
974   // new values if everything went ok, or the empty-string if not.
975   string ProcessFlagfileLocked(const string& flagval, FlagSettingMode set_mode);
976   // diff fromenv/tryfromenv
977   string ProcessFromenvLocked(const string& flagval, FlagSettingMode set_mode,
978                               bool errors_are_fatal);
979 
980  private:
981   FlagRegistry* const registry_;
982   map<string, string> error_flags_;      // map from name to error message
983   // This could be a set<string>, but we reuse the map to minimize the .o size
984   map<string, string> undefined_names_;  // --[flag] name was not registered
985 };
986 
987 
988 // Parse a list of (comma-separated) flags.
ParseFlagList(const char * value,vector<string> * flags)989 static void ParseFlagList(const char* value, vector<string>* flags) {
990   for (const char *p = value; p && *p; value = p) {
991     p = strchr(value, ',');
992     size_t len;
993     if (p) {
994       len = p - value;
995       p++;
996     } else {
997       len = strlen(value);
998     }
999 
1000     if (len == 0)
1001       ReportError(DIE, "ERROR: empty flaglist entry\n");
1002     if (value[0] == '-')
1003       ReportError(DIE, "ERROR: flag \"%*s\" begins with '-'\n", len, value);
1004 
1005     flags->push_back(string(value, len));
1006   }
1007 }
1008 
1009 // Snarf an entire file into a C++ string.  This is just so that we
1010 // can do all the I/O in one place and not worry about it everywhere.
1011 // Plus, it's convenient to have the whole file contents at hand.
1012 // Adds a newline at the end of the file.
1013 #define PFATAL(s)  do { perror(s); gflags_exitfunc(1); } while (0)
1014 
ReadFileIntoString(const char * filename)1015 static string ReadFileIntoString(const char* filename) {
1016   const int kBufSize = 8092;
1017   char buffer[kBufSize];
1018   string s;
1019   FILE* fp;
1020   if ((errno = SafeFOpen(&fp, filename, "r")) != 0) PFATAL(filename);
1021   size_t n;
1022   while ( (n=fread(buffer, 1, kBufSize, fp)) > 0 ) {
1023     if (ferror(fp))  PFATAL(filename);
1024     s.append(buffer, n);
1025   }
1026   fclose(fp);
1027   return s;
1028 }
1029 
ParseNewCommandLineFlags(int * argc,char *** argv,bool remove_flags)1030 uint32 CommandLineFlagParser::ParseNewCommandLineFlags(int* argc, char*** argv,
1031                                                        bool remove_flags) {
1032   int first_nonopt = *argc;        // for non-options moved to the end
1033 
1034   registry_->Lock();
1035   for (int i = 1; i < first_nonopt; i++) {
1036     char* arg = (*argv)[i];
1037 
1038     // Like getopt(), we permute non-option flags to be at the end.
1039     if (arg[0] != '-' || arg[1] == '\0') {	// must be a program argument: "-" is an argument, not a flag
1040       memmove((*argv) + i, (*argv) + i+1, (*argc - (i+1)) * sizeof((*argv)[i]));
1041       (*argv)[*argc-1] = arg;      // we go last
1042       first_nonopt--;              // we've been pushed onto the stack
1043       i--;                         // to undo the i++ in the loop
1044       continue;
1045     }
1046     arg++;                     // skip leading '-'
1047     if (arg[0] == '-') arg++;  // or leading '--'
1048 
1049     // -- alone means what it does for GNU: stop options parsing
1050     if (*arg == '\0') {
1051       first_nonopt = i+1;
1052       break;
1053     }
1054 
1055     // Find the flag object for this option
1056     string key;
1057     const char* value;
1058     string error_message;
1059     CommandLineFlag* flag = registry_->SplitArgumentLocked(arg, &key, &value,
1060                                                            &error_message);
1061     if (flag == NULL) {
1062       undefined_names_[key] = "";    // value isn't actually used
1063       error_flags_[key] = error_message;
1064       continue;
1065     }
1066 
1067     if (value == NULL) {
1068       // Boolean options are always assigned a value by SplitArgumentLocked()
1069       assert(flag->Type() != FlagValue::FV_BOOL);
1070       if (i+1 >= first_nonopt) {
1071         // This flag needs a value, but there is nothing available
1072         error_flags_[key] = (string(kError) + "flag '" + (*argv)[i] + "'"
1073                              + " is missing its argument");
1074         if (flag->help() && flag->help()[0] > '\001') {
1075           // Be useful in case we have a non-stripped description.
1076           error_flags_[key] += string("; flag description: ") + flag->help();
1077         }
1078         error_flags_[key] += "\n";
1079         break;    // we treat this as an unrecoverable error
1080       } else {
1081         value = (*argv)[++i];                   // read next arg for value
1082 
1083         // Heuristic to detect the case where someone treats a string arg
1084         // like a bool:
1085         // --my_string_var --foo=bar
1086         // We look for a flag of string type, whose value begins with a
1087         // dash, and where the flag-name and value are separated by a
1088         // space rather than an '='.
1089         // To avoid false positives, we also require the word "true"
1090         // or "false" in the help string.  Without this, a valid usage
1091         // "-lat -30.5" would trigger the warning.  The common cases we
1092         // want to solve talk about true and false as values.
1093         if (value[0] == '-'
1094             && flag->Type() == FlagValue::FV_STRING
1095             && (strstr(flag->help(), "true")
1096                 || strstr(flag->help(), "false"))) {
1097           LOG(WARNING) << "Did you really mean to set flag '"
1098                        << flag->name() << "' to the value '"
1099                        << value << "'?";
1100         }
1101       }
1102     }
1103 
1104     // TODO(csilvers): only set a flag if we hadn't set it before here
1105     ProcessSingleOptionLocked(flag, value, SET_FLAGS_VALUE);
1106   }
1107   registry_->Unlock();
1108 
1109   if (remove_flags) {   // Fix up argc and argv by removing command line flags
1110     (*argv)[first_nonopt-1] = (*argv)[0];
1111     (*argv) += (first_nonopt-1);
1112     (*argc) -= (first_nonopt-1);
1113     first_nonopt = 1;   // because we still don't count argv[0]
1114   }
1115 
1116   logging_is_probably_set_up = true;   // because we've parsed --logdir, etc.
1117 
1118   return first_nonopt;
1119 }
1120 
ProcessFlagfileLocked(const string & flagval,FlagSettingMode set_mode)1121 string CommandLineFlagParser::ProcessFlagfileLocked(const string& flagval,
1122                                                     FlagSettingMode set_mode) {
1123   if (flagval.empty())
1124     return "";
1125 
1126   string msg;
1127   vector<string> filename_list;
1128   ParseFlagList(flagval.c_str(), &filename_list);  // take a list of filenames
1129   for (size_t i = 0; i < filename_list.size(); ++i) {
1130     const char* file = filename_list[i].c_str();
1131     msg += ProcessOptionsFromStringLocked(ReadFileIntoString(file), set_mode);
1132   }
1133   return msg;
1134 }
1135 
ProcessFromenvLocked(const string & flagval,FlagSettingMode set_mode,bool errors_are_fatal)1136 string CommandLineFlagParser::ProcessFromenvLocked(const string& flagval,
1137                                                    FlagSettingMode set_mode,
1138                                                    bool errors_are_fatal) {
1139   if (flagval.empty())
1140     return "";
1141 
1142   string msg;
1143   vector<string> flaglist;
1144   ParseFlagList(flagval.c_str(), &flaglist);
1145 
1146   for (size_t i = 0; i < flaglist.size(); ++i) {
1147     const char* flagname = flaglist[i].c_str();
1148     CommandLineFlag* flag = registry_->FindFlagLocked(flagname);
1149     if (flag == NULL) {
1150       error_flags_[flagname] =
1151           StringPrintf("%sunknown command line flag '%s' "
1152                        "(via --fromenv or --tryfromenv)\n",
1153                        kError, flagname);
1154       undefined_names_[flagname] = "";
1155       continue;
1156     }
1157 
1158     const string envname = string("FLAGS_") + string(flagname);
1159     string envval;
1160     if (!SafeGetEnv(envname.c_str(), envval)) {
1161       if (errors_are_fatal) {
1162         error_flags_[flagname] = (string(kError) + envname +
1163                                   " not found in environment\n");
1164       }
1165       continue;
1166     }
1167 
1168     // Avoid infinite recursion.
1169     if (envval == "fromenv" || envval == "tryfromenv") {
1170       error_flags_[flagname] =
1171           StringPrintf("%sinfinite recursion on environment flag '%s'\n",
1172                        kError, envval.c_str());
1173       continue;
1174     }
1175 
1176     msg += ProcessSingleOptionLocked(flag, envval.c_str(), set_mode);
1177   }
1178   return msg;
1179 }
1180 
ProcessSingleOptionLocked(CommandLineFlag * flag,const char * value,FlagSettingMode set_mode)1181 string CommandLineFlagParser::ProcessSingleOptionLocked(
1182     CommandLineFlag* flag, const char* value, FlagSettingMode set_mode) {
1183   string msg;
1184   if (value && !registry_->SetFlagLocked(flag, value, set_mode, &msg)) {
1185     error_flags_[flag->name()] = msg;
1186     return "";
1187   }
1188 
1189   // The recursive flags, --flagfile and --fromenv and --tryfromenv,
1190   // must be dealt with as soon as they're seen.  They will emit
1191   // messages of their own.
1192   if (strcmp(flag->name(), "flagfile") == 0) {
1193     msg += ProcessFlagfileLocked(FLAGS_flagfile, set_mode);
1194 
1195   } else if (strcmp(flag->name(), "fromenv") == 0) {
1196     // last arg indicates envval-not-found is fatal (unlike in --tryfromenv)
1197     msg += ProcessFromenvLocked(FLAGS_fromenv, set_mode, true);
1198 
1199   } else if (strcmp(flag->name(), "tryfromenv") == 0) {
1200     msg += ProcessFromenvLocked(FLAGS_tryfromenv, set_mode, false);
1201   }
1202 
1203   return msg;
1204 }
1205 
ValidateFlags(bool all)1206 void CommandLineFlagParser::ValidateFlags(bool all) {
1207   FlagRegistryLock frl(registry_);
1208   for (FlagRegistry::FlagConstIterator i = registry_->flags_.begin();
1209        i != registry_->flags_.end(); ++i) {
1210     if ((all || !i->second->Modified()) && !i->second->ValidateCurrent()) {
1211       // only set a message if one isn't already there.  (If there's
1212       // an error message, our job is done, even if it's not exactly
1213       // the same error.)
1214       if (error_flags_[i->second->name()].empty()) {
1215         error_flags_[i->second->name()] =
1216             string(kError) + "--" + i->second->name() +
1217             " must be set on the commandline";
1218         if (!i->second->Modified()) {
1219           error_flags_[i->second->name()] += " (default value fails validation)";
1220         }
1221         error_flags_[i->second->name()] += "\n";
1222       }
1223     }
1224   }
1225 }
1226 
ValidateUnmodifiedFlags()1227 void CommandLineFlagParser::ValidateUnmodifiedFlags() {
1228   ValidateFlags(false);
1229 }
1230 
ReportErrors()1231 bool CommandLineFlagParser::ReportErrors() {
1232   // error_flags_ indicates errors we saw while parsing.
1233   // But we ignore undefined-names if ok'ed by --undef_ok
1234   if (!FLAGS_undefok.empty()) {
1235     vector<string> flaglist;
1236     ParseFlagList(FLAGS_undefok.c_str(), &flaglist);
1237     for (size_t i = 0; i < flaglist.size(); ++i) {
1238       // We also deal with --no<flag>, in case the flagname was boolean
1239       const string no_version = string("no") + flaglist[i];
1240       if (undefined_names_.find(flaglist[i]) != undefined_names_.end()) {
1241         error_flags_[flaglist[i]] = "";    // clear the error message
1242       } else if (undefined_names_.find(no_version) != undefined_names_.end()) {
1243         error_flags_[no_version] = "";
1244       }
1245     }
1246   }
1247   // Likewise, if they decided to allow reparsing, all undefined-names
1248   // are ok; we just silently ignore them now, and hope that a future
1249   // parse will pick them up somehow.
1250   if (allow_command_line_reparsing) {
1251     for (map<string, string>::const_iterator it = undefined_names_.begin();
1252          it != undefined_names_.end();  ++it)
1253       error_flags_[it->first] = "";      // clear the error message
1254   }
1255 
1256   bool found_error = false;
1257   string error_message;
1258   for (map<string, string>::const_iterator it = error_flags_.begin();
1259        it != error_flags_.end(); ++it) {
1260     if (!it->second.empty()) {
1261       error_message.append(it->second.data(), it->second.size());
1262       found_error = true;
1263     }
1264   }
1265   if (found_error)
1266     ReportError(DO_NOT_DIE, "%s", error_message.c_str());
1267   return found_error;
1268 }
1269 
ProcessOptionsFromStringLocked(const string & contentdata,FlagSettingMode set_mode)1270 string CommandLineFlagParser::ProcessOptionsFromStringLocked(
1271     const string& contentdata, FlagSettingMode set_mode) {
1272   string retval;
1273   const char* flagfile_contents = contentdata.c_str();
1274   bool flags_are_relevant = true;   // set to false when filenames don't match
1275   bool in_filename_section = false;
1276 
1277   const char* line_end = flagfile_contents;
1278   // We read this file a line at a time.
1279   for (; line_end; flagfile_contents = line_end + 1) {
1280     while (*flagfile_contents && isspace(*flagfile_contents))
1281       ++flagfile_contents;
1282     // Windows uses "\r\n"
1283     line_end = strchr(flagfile_contents, '\r');
1284     if (line_end == NULL)
1285         line_end = strchr(flagfile_contents, '\n');
1286 
1287     size_t len = line_end ? line_end - flagfile_contents
1288                           : strlen(flagfile_contents);
1289     string line(flagfile_contents, len);
1290 
1291     // Each line can be one of four things:
1292     // 1) A comment line -- we skip it
1293     // 2) An empty line -- we skip it
1294     // 3) A list of filenames -- starts a new filenames+flags section
1295     // 4) A --flag=value line -- apply if previous filenames match
1296     if (line.empty() || line[0] == '#') {
1297       // comment or empty line; just ignore
1298 
1299     } else if (line[0] == '-') {    // flag
1300       in_filename_section = false;  // instead, it was a flag-line
1301       if (!flags_are_relevant)      // skip this flag; applies to someone else
1302         continue;
1303 
1304       const char* name_and_val = line.c_str() + 1;    // skip the leading -
1305       if (*name_and_val == '-')
1306         name_and_val++;                               // skip second - too
1307       string key;
1308       const char* value;
1309       string error_message;
1310       CommandLineFlag* flag = registry_->SplitArgumentLocked(name_and_val,
1311                                                              &key, &value,
1312                                                              &error_message);
1313       // By API, errors parsing flagfile lines are silently ignored.
1314       if (flag == NULL) {
1315         // "WARNING: flagname '" + key + "' not found\n"
1316       } else if (value == NULL) {
1317         // "WARNING: flagname '" + key + "' missing a value\n"
1318       } else {
1319         retval += ProcessSingleOptionLocked(flag, value, set_mode);
1320       }
1321 
1322     } else {                        // a filename!
1323       if (!in_filename_section) {   // start over: assume filenames don't match
1324         in_filename_section = true;
1325         flags_are_relevant = false;
1326       }
1327 
1328       // Split the line up at spaces into glob-patterns
1329       const char* space = line.c_str();   // just has to be non-NULL
1330       for (const char* word = line.c_str(); *space; word = space+1) {
1331         if (flags_are_relevant)     // we can stop as soon as we match
1332           break;
1333         space = strchr(word, ' ');
1334         if (space == NULL)
1335           space = word + strlen(word);
1336         const string glob(word, space - word);
1337         // We try matching both against the full argv0 and basename(argv0)
1338         if (glob == ProgramInvocationName()       // small optimization
1339             || glob == ProgramInvocationShortName()
1340 #if defined(HAVE_FNMATCH_H)
1341             || fnmatch(glob.c_str(), ProgramInvocationName(),      FNM_PATHNAME) == 0
1342             || fnmatch(glob.c_str(), ProgramInvocationShortName(), FNM_PATHNAME) == 0
1343 #elif defined(HAVE_SHLWAPI_H)
1344             || PathMatchSpecA(glob.c_str(), ProgramInvocationName())
1345             || PathMatchSpecA(glob.c_str(), ProgramInvocationShortName())
1346 #endif
1347             ) {
1348           flags_are_relevant = true;
1349         }
1350       }
1351     }
1352   }
1353   return retval;
1354 }
1355 
1356 // --------------------------------------------------------------------
1357 // GetFromEnv()
1358 // AddFlagValidator()
1359 //    These are helper functions for routines like BoolFromEnv() and
1360 //    RegisterFlagValidator, defined below.  They're defined here so
1361 //    they can live in the unnamed namespace (which makes friendship
1362 //    declarations for these classes possible).
1363 // --------------------------------------------------------------------
1364 
1365 template<typename T>
GetFromEnv(const char * varname,T dflt)1366 T GetFromEnv(const char *varname, T dflt) {
1367   std::string valstr;
1368   if (SafeGetEnv(varname, valstr)) {
1369     FlagValue ifv(new T, true);
1370     if (!ifv.ParseFrom(valstr.c_str())) {
1371       ReportError(DIE, "ERROR: error parsing env variable '%s' with value '%s'\n",
1372                   varname, valstr.c_str());
1373     }
1374     return OTHER_VALUE_AS(ifv, T);
1375   } else return dflt;
1376 }
1377 
AddFlagValidator(const void * flag_ptr,ValidateFnProto validate_fn_proto)1378 bool AddFlagValidator(const void* flag_ptr, ValidateFnProto validate_fn_proto) {
1379   // We want a lock around this routine, in case two threads try to
1380   // add a validator (hopefully the same one!) at once.  We could use
1381   // our own thread, but we need to loook at the registry anyway, so
1382   // we just steal that one.
1383   FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1384   FlagRegistryLock frl(registry);
1385   // First, find the flag whose current-flag storage is 'flag'.
1386   // This is the CommandLineFlag whose current_->value_buffer_ == flag
1387   CommandLineFlag* flag = registry->FindFlagViaPtrLocked(flag_ptr);
1388   if (!flag) {
1389     LOG(WARNING) << "Ignoring RegisterValidateFunction() for flag pointer "
1390                  << flag_ptr << ": no flag found at that address";
1391     return false;
1392   } else if (validate_fn_proto == flag->validate_function()) {
1393     return true;    // ok to register the same function over and over again
1394   } else if (validate_fn_proto != NULL && flag->validate_function() != NULL) {
1395     LOG(WARNING) << "Ignoring RegisterValidateFunction() for flag '"
1396                  << flag->name() << "': validate-fn already registered";
1397     return false;
1398   } else {
1399     flag->validate_fn_proto_ = validate_fn_proto;
1400     return true;
1401   }
1402 }
1403 
1404 }  // end unnamed namespaces
1405 
1406 
1407 // Now define the functions that are exported via the .h file
1408 
1409 // --------------------------------------------------------------------
1410 // FlagRegisterer
1411 //    This class exists merely to have a global constructor (the
1412 //    kind that runs before main(), that goes an initializes each
1413 //    flag that's been declared.  Note that it's very important we
1414 //    don't have a destructor that deletes flag_, because that would
1415 //    cause us to delete current_storage/defvalue_storage as well,
1416 //    which can cause a crash if anything tries to access the flag
1417 //    values in a global destructor.
1418 // --------------------------------------------------------------------
1419 
1420 namespace {
RegisterCommandLineFlag(const char * name,const char * help,const char * filename,FlagValue * current,FlagValue * defvalue)1421 void RegisterCommandLineFlag(const char* name,
1422                              const char* help,
1423                              const char* filename,
1424                              FlagValue* current,
1425                              FlagValue* defvalue) {
1426   if (help == NULL)
1427     help = "";
1428   // Importantly, flag_ will never be deleted, so storage is always good.
1429   CommandLineFlag* flag =
1430       new CommandLineFlag(name, help, filename, current, defvalue);
1431   FlagRegistry::GlobalRegistry()->RegisterFlag(flag);  // default registry
1432 }
1433 }
1434 
1435 template <typename FlagType>
FlagRegisterer(const char * name,const char * help,const char * filename,FlagType * current_storage,FlagType * defvalue_storage)1436 FlagRegisterer::FlagRegisterer(const char* name,
1437                                const char* help,
1438                                const char* filename,
1439                                FlagType* current_storage,
1440                                FlagType* defvalue_storage) {
1441   FlagValue* const current = new FlagValue(current_storage, false);
1442   FlagValue* const defvalue = new FlagValue(defvalue_storage, false);
1443   RegisterCommandLineFlag(name, help, filename, current, defvalue);
1444 }
1445 
1446 // Force compiler to generate code for the given template specialization.
1447 #define INSTANTIATE_FLAG_REGISTERER_CTOR(type)                  \
1448   template GFLAGS_DLL_DECL FlagRegisterer::FlagRegisterer(      \
1449       const char* name, const char* help, const char* filename, \
1450       type* current_storage, type* defvalue_storage)
1451 
1452 // Do this for all supported flag types.
1453 INSTANTIATE_FLAG_REGISTERER_CTOR(bool);
1454 INSTANTIATE_FLAG_REGISTERER_CTOR(int32);
1455 INSTANTIATE_FLAG_REGISTERER_CTOR(uint32);
1456 INSTANTIATE_FLAG_REGISTERER_CTOR(int64);
1457 INSTANTIATE_FLAG_REGISTERER_CTOR(uint64);
1458 INSTANTIATE_FLAG_REGISTERER_CTOR(double);
1459 INSTANTIATE_FLAG_REGISTERER_CTOR(std::string);
1460 
1461 #undef INSTANTIATE_FLAG_REGISTERER_CTOR
1462 
1463 // --------------------------------------------------------------------
1464 // GetAllFlags()
1465 //    The main way the FlagRegistry class exposes its data.  This
1466 //    returns, as strings, all the info about all the flags in
1467 //    the main registry, sorted first by filename they are defined
1468 //    in, and then by flagname.
1469 // --------------------------------------------------------------------
1470 
1471 struct FilenameFlagnameCmp {
operator ()GFLAGS_NAMESPACE::FilenameFlagnameCmp1472   bool operator()(const CommandLineFlagInfo& a,
1473                   const CommandLineFlagInfo& b) const {
1474     int cmp = strcmp(a.filename.c_str(), b.filename.c_str());
1475     if (cmp == 0)
1476       cmp = strcmp(a.name.c_str(), b.name.c_str());  // secondary sort key
1477     return cmp < 0;
1478   }
1479 };
1480 
GetAllFlags(vector<CommandLineFlagInfo> * OUTPUT)1481 void GetAllFlags(vector<CommandLineFlagInfo>* OUTPUT) {
1482   FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1483   registry->Lock();
1484   for (FlagRegistry::FlagConstIterator i = registry->flags_.begin();
1485        i != registry->flags_.end(); ++i) {
1486     CommandLineFlagInfo fi;
1487     i->second->FillCommandLineFlagInfo(&fi);
1488     OUTPUT->push_back(fi);
1489   }
1490   registry->Unlock();
1491   // Now sort the flags, first by filename they occur in, then alphabetically
1492   sort(OUTPUT->begin(), OUTPUT->end(), FilenameFlagnameCmp());
1493 }
1494 
1495 // --------------------------------------------------------------------
1496 // SetArgv()
1497 // GetArgvs()
1498 // GetArgv()
1499 // GetArgv0()
1500 // ProgramInvocationName()
1501 // ProgramInvocationShortName()
1502 // SetUsageMessage()
1503 // ProgramUsage()
1504 //    Functions to set and get argv.  Typically the setter is called
1505 //    by ParseCommandLineFlags.  Also can get the ProgramUsage string,
1506 //    set by SetUsageMessage.
1507 // --------------------------------------------------------------------
1508 
1509 // These values are not protected by a Mutex because they are normally
1510 // set only once during program startup.
1511 static string argv0("UNKNOWN");  // just the program name
1512 static string cmdline;           // the entire command-line
1513 static string program_usage;
1514 static vector<string> argvs;
1515 static uint32 argv_sum = 0;
1516 
SetArgv(int argc,const char ** argv)1517 void SetArgv(int argc, const char** argv) {
1518   static bool called_set_argv = false;
1519   if (called_set_argv) return;
1520   called_set_argv = true;
1521 
1522   assert(argc > 0); // every program has at least a name
1523   argv0 = argv[0];
1524 
1525   cmdline.clear();
1526   for (int i = 0; i < argc; i++) {
1527     if (i != 0) cmdline += " ";
1528     cmdline += argv[i];
1529     argvs.push_back(argv[i]);
1530   }
1531 
1532   // Compute a simple sum of all the chars in argv
1533   argv_sum = 0;
1534   for (string::const_iterator c = cmdline.begin(); c != cmdline.end(); ++c) {
1535     argv_sum += *c;
1536   }
1537 }
1538 
GetArgvs()1539 const vector<string>& GetArgvs() { return argvs; }
GetArgv()1540 const char* GetArgv()            { return cmdline.c_str(); }
GetArgv0()1541 const char* GetArgv0()           { return argv0.c_str(); }
GetArgvSum()1542 uint32 GetArgvSum()              { return argv_sum; }
ProgramInvocationName()1543 const char* ProgramInvocationName() {             // like the GNU libc fn
1544   return GetArgv0();
1545 }
ProgramInvocationShortName()1546 const char* ProgramInvocationShortName() {        // like the GNU libc fn
1547   size_t pos = argv0.rfind('/');
1548 #ifdef OS_WINDOWS
1549   if (pos == string::npos) pos = argv0.rfind('\\');
1550 #endif
1551   return (pos == string::npos ? argv0.c_str() : (argv0.c_str() + pos + 1));
1552 }
1553 
SetUsageMessage(const string & usage)1554 void SetUsageMessage(const string& usage) {
1555   program_usage = usage;
1556 }
1557 
ProgramUsage()1558 const char* ProgramUsage() {
1559   if (program_usage.empty()) {
1560     return "Warning: SetUsageMessage() never called";
1561   }
1562   return program_usage.c_str();
1563 }
1564 
1565 // --------------------------------------------------------------------
1566 // SetVersionString()
1567 // VersionString()
1568 // --------------------------------------------------------------------
1569 
1570 static string version_string;
1571 
SetVersionString(const string & version)1572 void SetVersionString(const string& version) {
1573   version_string = version;
1574 }
1575 
VersionString()1576 const char* VersionString() {
1577   return version_string.c_str();
1578 }
1579 
1580 
1581 // --------------------------------------------------------------------
1582 // GetCommandLineOption()
1583 // GetCommandLineFlagInfo()
1584 // GetCommandLineFlagInfoOrDie()
1585 // SetCommandLineOption()
1586 // SetCommandLineOptionWithMode()
1587 //    The programmatic way to set a flag's value, using a string
1588 //    for its name rather than the variable itself (that is,
1589 //    SetCommandLineOption("foo", x) rather than FLAGS_foo = x).
1590 //    There's also a bit more flexibility here due to the various
1591 //    set-modes, but typically these are used when you only have
1592 //    that flag's name as a string, perhaps at runtime.
1593 //    All of these work on the default, global registry.
1594 //       For GetCommandLineOption, return false if no such flag
1595 //    is known, true otherwise.  We clear "value" if a suitable
1596 //    flag is found.
1597 // --------------------------------------------------------------------
1598 
1599 
GetCommandLineOption(const char * name,string * value)1600 bool GetCommandLineOption(const char* name, string* value) {
1601   if (NULL == name)
1602     return false;
1603   assert(value);
1604 
1605   FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1606   FlagRegistryLock frl(registry);
1607   CommandLineFlag* flag = registry->FindFlagLocked(name);
1608   if (flag == NULL) {
1609     return false;
1610   } else {
1611     *value = flag->current_value();
1612     return true;
1613   }
1614 }
1615 
GetCommandLineFlagInfo(const char * name,CommandLineFlagInfo * OUTPUT)1616 bool GetCommandLineFlagInfo(const char* name, CommandLineFlagInfo* OUTPUT) {
1617   if (NULL == name) return false;
1618   FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1619   FlagRegistryLock frl(registry);
1620   CommandLineFlag* flag = registry->FindFlagLocked(name);
1621   if (flag == NULL) {
1622     return false;
1623   } else {
1624     assert(OUTPUT);
1625     flag->FillCommandLineFlagInfo(OUTPUT);
1626     return true;
1627   }
1628 }
1629 
GetCommandLineFlagInfoOrDie(const char * name)1630 CommandLineFlagInfo GetCommandLineFlagInfoOrDie(const char* name) {
1631   CommandLineFlagInfo info;
1632   if (!GetCommandLineFlagInfo(name, &info)) {
1633     fprintf(stderr, "FATAL ERROR: flag name '%s' doesn't exist\n", name);
1634     gflags_exitfunc(1);    // almost certainly gflags_exitfunc()
1635   }
1636   return info;
1637 }
1638 
SetCommandLineOptionWithMode(const char * name,const char * value,FlagSettingMode set_mode)1639 string SetCommandLineOptionWithMode(const char* name, const char* value,
1640                                     FlagSettingMode set_mode) {
1641   string result;
1642   FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1643   FlagRegistryLock frl(registry);
1644   CommandLineFlag* flag = registry->FindFlagLocked(name);
1645   if (flag) {
1646     CommandLineFlagParser parser(registry);
1647     result = parser.ProcessSingleOptionLocked(flag, value, set_mode);
1648     if (!result.empty()) {   // in the error case, we've already logged
1649       // Could consider logging this change
1650     }
1651   }
1652   // The API of this function is that we return empty string on error
1653   return result;
1654 }
1655 
SetCommandLineOption(const char * name,const char * value)1656 string SetCommandLineOption(const char* name, const char* value) {
1657   return SetCommandLineOptionWithMode(name, value, SET_FLAGS_VALUE);
1658 }
1659 
1660 // --------------------------------------------------------------------
1661 // FlagSaver
1662 // FlagSaverImpl
1663 //    This class stores the states of all flags at construct time,
1664 //    and restores all flags to that state at destruct time.
1665 //    Its major implementation challenge is that it never modifies
1666 //    pointers in the 'main' registry, so global FLAG_* vars always
1667 //    point to the right place.
1668 // --------------------------------------------------------------------
1669 
1670 class FlagSaverImpl {
1671  public:
1672   // Constructs an empty FlagSaverImpl object.
FlagSaverImpl(FlagRegistry * main_registry)1673   explicit FlagSaverImpl(FlagRegistry* main_registry)
1674       : main_registry_(main_registry) { }
~FlagSaverImpl()1675   ~FlagSaverImpl() {
1676     // reclaim memory from each of our CommandLineFlags
1677     vector<CommandLineFlag*>::const_iterator it;
1678     for (it = backup_registry_.begin(); it != backup_registry_.end(); ++it)
1679       delete *it;
1680   }
1681 
1682   // Saves the flag states from the flag registry into this object.
1683   // It's an error to call this more than once.
1684   // Must be called when the registry mutex is not held.
SaveFromRegistry()1685   void SaveFromRegistry() {
1686     FlagRegistryLock frl(main_registry_);
1687     assert(backup_registry_.empty());   // call only once!
1688     for (FlagRegistry::FlagConstIterator it = main_registry_->flags_.begin();
1689          it != main_registry_->flags_.end();
1690          ++it) {
1691       const CommandLineFlag* main = it->second;
1692       // Sets up all the const variables in backup correctly
1693       CommandLineFlag* backup = new CommandLineFlag(
1694           main->name(), main->help(), main->filename(),
1695           main->current_->New(), main->defvalue_->New());
1696       // Sets up all the non-const variables in backup correctly
1697       backup->CopyFrom(*main);
1698       backup_registry_.push_back(backup);   // add it to a convenient list
1699     }
1700   }
1701 
1702   // Restores the saved flag states into the flag registry.  We
1703   // assume no flags were added or deleted from the registry since
1704   // the SaveFromRegistry; if they were, that's trouble!  Must be
1705   // called when the registry mutex is not held.
RestoreToRegistry()1706   void RestoreToRegistry() {
1707     FlagRegistryLock frl(main_registry_);
1708     vector<CommandLineFlag*>::const_iterator it;
1709     for (it = backup_registry_.begin(); it != backup_registry_.end(); ++it) {
1710       CommandLineFlag* main = main_registry_->FindFlagLocked((*it)->name());
1711       if (main != NULL) {       // if NULL, flag got deleted from registry(!)
1712         main->CopyFrom(**it);
1713       }
1714     }
1715   }
1716 
1717  private:
1718   FlagRegistry* const main_registry_;
1719   vector<CommandLineFlag*> backup_registry_;
1720 
1721   FlagSaverImpl(const FlagSaverImpl&);  // no copying!
1722   void operator=(const FlagSaverImpl&);
1723 };
1724 
FlagSaver()1725 FlagSaver::FlagSaver()
1726     : impl_(new FlagSaverImpl(FlagRegistry::GlobalRegistry())) {
1727   impl_->SaveFromRegistry();
1728 }
1729 
~FlagSaver()1730 FlagSaver::~FlagSaver() {
1731   impl_->RestoreToRegistry();
1732   delete impl_;
1733 }
1734 
1735 
1736 // --------------------------------------------------------------------
1737 // CommandlineFlagsIntoString()
1738 // ReadFlagsFromString()
1739 // AppendFlagsIntoFile()
1740 // ReadFromFlagsFile()
1741 //    These are mostly-deprecated routines that stick the
1742 //    commandline flags into a file/string and read them back
1743 //    out again.  I can see a use for CommandlineFlagsIntoString,
1744 //    for creating a flagfile, but the rest don't seem that useful
1745 //    -- some, I think, are a poor-man's attempt at FlagSaver --
1746 //    and are included only until we can delete them from callers.
1747 //    Note they don't save --flagfile flags (though they do save
1748 //    the result of having called the flagfile, of course).
1749 // --------------------------------------------------------------------
1750 
TheseCommandlineFlagsIntoString(const vector<CommandLineFlagInfo> & flags)1751 static string TheseCommandlineFlagsIntoString(
1752     const vector<CommandLineFlagInfo>& flags) {
1753   vector<CommandLineFlagInfo>::const_iterator i;
1754 
1755   size_t retval_space = 0;
1756   for (i = flags.begin(); i != flags.end(); ++i) {
1757     // An (over)estimate of how much space it will take to print this flag
1758     retval_space += i->name.length() + i->current_value.length() + 5;
1759   }
1760 
1761   string retval;
1762   retval.reserve(retval_space);
1763   for (i = flags.begin(); i != flags.end(); ++i) {
1764     retval += "--";
1765     retval += i->name;
1766     retval += "=";
1767     retval += i->current_value;
1768     retval += "\n";
1769   }
1770   return retval;
1771 }
1772 
CommandlineFlagsIntoString()1773 string CommandlineFlagsIntoString() {
1774   vector<CommandLineFlagInfo> sorted_flags;
1775   GetAllFlags(&sorted_flags);
1776   return TheseCommandlineFlagsIntoString(sorted_flags);
1777 }
1778 
ReadFlagsFromString(const string & flagfilecontents,const char *,bool errors_are_fatal)1779 bool ReadFlagsFromString(const string& flagfilecontents,
1780                          const char* /*prog_name*/,  // TODO(csilvers): nix this
1781                          bool errors_are_fatal) {
1782   FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1783   FlagSaverImpl saved_states(registry);
1784   saved_states.SaveFromRegistry();
1785 
1786   CommandLineFlagParser parser(registry);
1787   registry->Lock();
1788   parser.ProcessOptionsFromStringLocked(flagfilecontents, SET_FLAGS_VALUE);
1789   registry->Unlock();
1790   // Should we handle --help and such when reading flags from a string?  Sure.
1791   HandleCommandLineHelpFlags();
1792   if (parser.ReportErrors()) {
1793     // Error.  Restore all global flags to their previous values.
1794     if (errors_are_fatal)
1795       gflags_exitfunc(1);
1796     saved_states.RestoreToRegistry();
1797     return false;
1798   }
1799   return true;
1800 }
1801 
1802 // TODO(csilvers): nix prog_name in favor of ProgramInvocationShortName()
AppendFlagsIntoFile(const string & filename,const char * prog_name)1803 bool AppendFlagsIntoFile(const string& filename, const char *prog_name) {
1804   FILE *fp;
1805   if (SafeFOpen(&fp, filename.c_str(), "a") != 0) {
1806     return false;
1807   }
1808 
1809   if (prog_name)
1810     fprintf(fp, "%s\n", prog_name);
1811 
1812   vector<CommandLineFlagInfo> flags;
1813   GetAllFlags(&flags);
1814   // But we don't want --flagfile, which leads to weird recursion issues
1815   vector<CommandLineFlagInfo>::iterator i;
1816   for (i = flags.begin(); i != flags.end(); ++i) {
1817     if (strcmp(i->name.c_str(), "flagfile") == 0) {
1818       flags.erase(i);
1819       break;
1820     }
1821   }
1822   fprintf(fp, "%s", TheseCommandlineFlagsIntoString(flags).c_str());
1823 
1824   fclose(fp);
1825   return true;
1826 }
1827 
ReadFromFlagsFile(const string & filename,const char * prog_name,bool errors_are_fatal)1828 bool ReadFromFlagsFile(const string& filename, const char* prog_name,
1829                        bool errors_are_fatal) {
1830   return ReadFlagsFromString(ReadFileIntoString(filename.c_str()),
1831                              prog_name, errors_are_fatal);
1832 }
1833 
1834 
1835 // --------------------------------------------------------------------
1836 // BoolFromEnv()
1837 // Int32FromEnv()
1838 // Uint32FromEnv()
1839 // Int64FromEnv()
1840 // Uint64FromEnv()
1841 // DoubleFromEnv()
1842 // StringFromEnv()
1843 //    Reads the value from the environment and returns it.
1844 //    We use an FlagValue to make the parsing easy.
1845 //    Example usage:
1846 //       DEFINE_bool(myflag, BoolFromEnv("MYFLAG_DEFAULT", false), "whatever");
1847 // --------------------------------------------------------------------
1848 
BoolFromEnv(const char * v,bool dflt)1849 bool BoolFromEnv(const char *v, bool dflt) {
1850   return GetFromEnv(v, dflt);
1851 }
Int32FromEnv(const char * v,int32 dflt)1852 int32 Int32FromEnv(const char *v, int32 dflt) {
1853   return GetFromEnv(v, dflt);
1854 }
Uint32FromEnv(const char * v,uint32 dflt)1855 uint32 Uint32FromEnv(const char *v, uint32 dflt) {
1856   return GetFromEnv(v, dflt);
1857 }
Int64FromEnv(const char * v,int64 dflt)1858 int64 Int64FromEnv(const char *v, int64 dflt)    {
1859   return GetFromEnv(v, dflt);
1860 }
Uint64FromEnv(const char * v,uint64 dflt)1861 uint64 Uint64FromEnv(const char *v, uint64 dflt) {
1862   return GetFromEnv(v, dflt);
1863 }
DoubleFromEnv(const char * v,double dflt)1864 double DoubleFromEnv(const char *v, double dflt) {
1865   return GetFromEnv(v, dflt);
1866 }
1867 
1868 #ifdef _MSC_VER
1869 #  pragma warning(push)
1870 #  pragma warning(disable: 4996) // ignore getenv security warning
1871 #endif
StringFromEnv(const char * varname,const char * dflt)1872 const char *StringFromEnv(const char *varname, const char *dflt) {
1873   const char* const val = getenv(varname);
1874   return val ? val : dflt;
1875 }
1876 #ifdef _MSC_VER
1877 #  pragma warning(pop)
1878 #endif
1879 
1880 
1881 // --------------------------------------------------------------------
1882 // RegisterFlagValidator()
1883 //    RegisterFlagValidator() is the function that clients use to
1884 //    'decorate' a flag with a validation function.  Once this is
1885 //    done, every time the flag is set (including when the flag
1886 //    is parsed from argv), the validator-function is called.
1887 //       These functions return true if the validator was added
1888 //    successfully, or false if not: the flag already has a validator,
1889 //    (only one allowed per flag), the 1st arg isn't a flag, etc.
1890 //       This function is not thread-safe.
1891 // --------------------------------------------------------------------
1892 
RegisterFlagValidator(const bool * flag,bool (* validate_fn)(const char *,bool))1893 bool RegisterFlagValidator(const bool* flag,
1894                            bool (*validate_fn)(const char*, bool)) {
1895   return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1896 }
RegisterFlagValidator(const int32 * flag,bool (* validate_fn)(const char *,int32))1897 bool RegisterFlagValidator(const int32* flag,
1898                            bool (*validate_fn)(const char*, int32)) {
1899   return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1900 }
RegisterFlagValidator(const uint32 * flag,bool (* validate_fn)(const char *,uint32))1901 bool RegisterFlagValidator(const uint32* flag,
1902                            bool (*validate_fn)(const char*, uint32)) {
1903   return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1904 }
RegisterFlagValidator(const int64 * flag,bool (* validate_fn)(const char *,int64))1905 bool RegisterFlagValidator(const int64* flag,
1906                            bool (*validate_fn)(const char*, int64)) {
1907   return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1908 }
RegisterFlagValidator(const uint64 * flag,bool (* validate_fn)(const char *,uint64))1909 bool RegisterFlagValidator(const uint64* flag,
1910                            bool (*validate_fn)(const char*, uint64)) {
1911   return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1912 }
RegisterFlagValidator(const double * flag,bool (* validate_fn)(const char *,double))1913 bool RegisterFlagValidator(const double* flag,
1914                            bool (*validate_fn)(const char*, double)) {
1915   return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1916 }
RegisterFlagValidator(const string * flag,bool (* validate_fn)(const char *,const string &))1917 bool RegisterFlagValidator(const string* flag,
1918                            bool (*validate_fn)(const char*, const string&)) {
1919   return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1920 }
1921 
1922 
1923 // --------------------------------------------------------------------
1924 // ParseCommandLineFlags()
1925 // ParseCommandLineNonHelpFlags()
1926 // HandleCommandLineHelpFlags()
1927 //    This is the main function called from main(), to actually
1928 //    parse the commandline.  It modifies argc and argv as described
1929 //    at the top of gflags.h.  You can also divide this
1930 //    function into two parts, if you want to do work between
1931 //    the parsing of the flags and the printing of any help output.
1932 // --------------------------------------------------------------------
1933 
ParseCommandLineFlagsInternal(int * argc,char *** argv,bool remove_flags,bool do_report)1934 static uint32 ParseCommandLineFlagsInternal(int* argc, char*** argv,
1935                                             bool remove_flags, bool do_report) {
1936   SetArgv(*argc, const_cast<const char**>(*argv));    // save it for later
1937 
1938   FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1939   CommandLineFlagParser parser(registry);
1940 
1941   // When we parse the commandline flags, we'll handle --flagfile,
1942   // --tryfromenv, etc. as we see them (since flag-evaluation order
1943   // may be important).  But sometimes apps set FLAGS_tryfromenv/etc.
1944   // manually before calling ParseCommandLineFlags.  We want to evaluate
1945   // those too, as if they were the first flags on the commandline.
1946   registry->Lock();
1947   parser.ProcessFlagfileLocked(FLAGS_flagfile, SET_FLAGS_VALUE);
1948   // Last arg here indicates whether flag-not-found is a fatal error or not
1949   parser.ProcessFromenvLocked(FLAGS_fromenv, SET_FLAGS_VALUE, true);
1950   parser.ProcessFromenvLocked(FLAGS_tryfromenv, SET_FLAGS_VALUE, false);
1951   registry->Unlock();
1952 
1953   // Now get the flags specified on the commandline
1954   const int r = parser.ParseNewCommandLineFlags(argc, argv, remove_flags);
1955 
1956   if (do_report)
1957     HandleCommandLineHelpFlags();   // may cause us to exit on --help, etc.
1958 
1959   // See if any of the unset flags fail their validation checks
1960   parser.ValidateUnmodifiedFlags();
1961 
1962   if (parser.ReportErrors())        // may cause us to exit on illegal flags
1963     gflags_exitfunc(1);
1964   return r;
1965 }
1966 
ParseCommandLineFlags(int * argc,char *** argv,bool remove_flags)1967 uint32 ParseCommandLineFlags(int* argc, char*** argv, bool remove_flags) {
1968   return ParseCommandLineFlagsInternal(argc, argv, remove_flags, true);
1969 }
1970 
ParseCommandLineNonHelpFlags(int * argc,char *** argv,bool remove_flags)1971 uint32 ParseCommandLineNonHelpFlags(int* argc, char*** argv,
1972                                     bool remove_flags) {
1973   return ParseCommandLineFlagsInternal(argc, argv, remove_flags, false);
1974 }
1975 
1976 // --------------------------------------------------------------------
1977 // AllowCommandLineReparsing()
1978 // ReparseCommandLineNonHelpFlags()
1979 //    This is most useful for shared libraries.  The idea is if
1980 //    a flag is defined in a shared library that is dlopen'ed
1981 //    sometime after main(), you can ParseCommandLineFlags before
1982 //    the dlopen, then ReparseCommandLineNonHelpFlags() after the
1983 //    dlopen, to get the new flags.  But you have to explicitly
1984 //    Allow() it; otherwise, you get the normal default behavior
1985 //    of unrecognized flags calling a fatal error.
1986 // TODO(csilvers): this isn't used.  Just delete it?
1987 // --------------------------------------------------------------------
1988 
AllowCommandLineReparsing()1989 void AllowCommandLineReparsing() {
1990   allow_command_line_reparsing = true;
1991 }
1992 
ReparseCommandLineNonHelpFlags()1993 void ReparseCommandLineNonHelpFlags() {
1994   // We make a copy of argc and argv to pass in
1995   const vector<string>& argvs = GetArgvs();
1996   int tmp_argc = static_cast<int>(argvs.size());
1997   char** tmp_argv = new char* [tmp_argc + 1];
1998   for (int i = 0; i < tmp_argc; ++i)
1999     tmp_argv[i] = strdup(argvs[i].c_str());   // TODO(csilvers): don't dup
2000 
2001   ParseCommandLineNonHelpFlags(&tmp_argc, &tmp_argv, false);
2002 
2003   for (int i = 0; i < tmp_argc; ++i)
2004     free(tmp_argv[i]);
2005   delete[] tmp_argv;
2006 }
2007 
ShutDownCommandLineFlags()2008 void ShutDownCommandLineFlags() {
2009   FlagRegistry::DeleteGlobalRegistry();
2010 }
2011 
2012 
2013 } // namespace GFLAGS_NAMESPACE
2014