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