Use += for appends
[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
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>
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
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
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
370 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
398 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
428 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
445 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
460 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
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
505   const char* name() const { return name_; }
506   const char* help() const { return help_; }
507   const char* filename() const { return file_; }
508   const char* CleanFileName() const;  // nixes irrelevant prefix such as homedir
509   string current_value() const { return current_->ToString(); }
510   string default_value() const { return defvalue_->ToString(); }
511   const char* type_name() const { return defvalue_->TypeName(); }
512   ValidateFnProto validate_function() const { return validate_fn_proto_; }
513   const void* flag_ptr() const { return current_->value_buffer_; }
514
515   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;
521   bool ValidateCurrent() const { return Validate(*current_); }
522   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
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
559 CommandLineFlag::~CommandLineFlag() {
560   delete current_;
561   delete defvalue_;
562 }
563
564 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
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
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
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
606 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
626   bool operator() (const char* s1, const char* s2) const {
627     return (strcmp(s1, s2) < 0);
628   }
629 };
630
631
632 class FlagRegistry {
633  public:
634   FlagRegistry() {
635   }
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
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
653   void Lock() { lock_.Lock(); }
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:
709   explicit FlagRegistryLock(FlagRegistry* fr) : fr_(fr) { fr_->Lock(); }
710   ~FlagRegistryLock() { fr_->Unlock(); }
711  private:
712   FlagRegistry *const fr_;
713 };
714
715
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
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
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
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
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
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
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
929   explicit CommandLineFlagParser(FlagRegistry* reg) : registry_(reg) {}
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.
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
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
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] != '-' ||           // must be a program argument
1040         (arg[0] == '-' && arg[1] == '\0')) {  // "-" is an argument, not a flag
1041       memmove((*argv) + i, (*argv) + i+1, (*argc - (i+1)) * sizeof((*argv)[i]));
1042       (*argv)[*argc-1] = arg;      // we go last
1043       first_nonopt--;              // we've been pushed onto the stack
1044       i--;                         // to undo the i++ in the loop
1045       continue;
1046     }
1047
1048     if (arg[0] == '-') arg++;      // allow leading '-'
1049     if (arg[0] == '-') arg++;      // or leading '--'
1050
1051     // -- alone means what it does for GNU: stop options parsing
1052     if (*arg == '\0') {
1053       first_nonopt = i+1;
1054       break;
1055     }
1056
1057     // Find the flag object for this option
1058     string key;
1059     const char* value;
1060     string error_message;
1061     CommandLineFlag* flag = registry_->SplitArgumentLocked(arg, &key, &value,
1062                                                            &error_message);
1063     if (flag == NULL) {
1064       undefined_names_[key] = "";    // value isn't actually used
1065       error_flags_[key] = error_message;
1066       continue;
1067     }
1068
1069     if (value == NULL) {
1070       // Boolean options are always assigned a value by SplitArgumentLocked()
1071       assert(flag->Type() != FlagValue::FV_BOOL);
1072       if (i+1 >= first_nonopt) {
1073         // This flag needs a value, but there is nothing available
1074         error_flags_[key] = (string(kError) + "flag '" + (*argv)[i] + "'"
1075                              + " is missing its argument");
1076         if (flag->help() && flag->help()[0] > '\001') {
1077           // Be useful in case we have a non-stripped description.
1078           error_flags_[key] += string("; flag description: ") + flag->help();
1079         }
1080         error_flags_[key] += "\n";
1081         break;    // we treat this as an unrecoverable error
1082       } else {
1083         value = (*argv)[++i];                   // read next arg for value
1084
1085         // Heuristic to detect the case where someone treats a string arg
1086         // like a bool:
1087         // --my_string_var --foo=bar
1088         // We look for a flag of string type, whose value begins with a
1089         // dash, and where the flag-name and value are separated by a
1090         // space rather than an '='.
1091         // To avoid false positives, we also require the word "true"
1092         // or "false" in the help string.  Without this, a valid usage
1093         // "-lat -30.5" would trigger the warning.  The common cases we
1094         // want to solve talk about true and false as values.
1095         if (value[0] == '-'
1096             && flag->Type() == FlagValue::FV_STRING
1097             && (strstr(flag->help(), "true")
1098                 || strstr(flag->help(), "false"))) {
1099           LOG(WARNING) << "Did you really mean to set flag '"
1100                        << flag->name() << "' to the value '"
1101                        << value << "'?";
1102         }
1103       }
1104     }
1105
1106     // TODO(csilvers): only set a flag if we hadn't set it before here
1107     ProcessSingleOptionLocked(flag, value, SET_FLAGS_VALUE);
1108   }
1109   registry_->Unlock();
1110
1111   if (remove_flags) {   // Fix up argc and argv by removing command line flags
1112     (*argv)[first_nonopt-1] = (*argv)[0];
1113     (*argv) += (first_nonopt-1);
1114     (*argc) -= (first_nonopt-1);
1115     first_nonopt = 1;   // because we still don't count argv[0]
1116   }
1117
1118   logging_is_probably_set_up = true;   // because we've parsed --logdir, etc.
1119
1120   return first_nonopt;
1121 }
1122
1123 string CommandLineFlagParser::ProcessFlagfileLocked(const string& flagval,
1124                                                     FlagSettingMode set_mode) {
1125   if (flagval.empty())
1126     return "";
1127
1128   string msg;
1129   vector<string> filename_list;
1130   ParseFlagList(flagval.c_str(), &filename_list);  // take a list of filenames
1131   for (size_t i = 0; i < filename_list.size(); ++i) {
1132     const char* file = filename_list[i].c_str();
1133     msg += ProcessOptionsFromStringLocked(ReadFileIntoString(file), set_mode);
1134   }
1135   return msg;
1136 }
1137
1138 string CommandLineFlagParser::ProcessFromenvLocked(const string& flagval,
1139                                                    FlagSettingMode set_mode,
1140                                                    bool errors_are_fatal) {
1141   if (flagval.empty())
1142     return "";
1143
1144   string msg;
1145   vector<string> flaglist;
1146   ParseFlagList(flagval.c_str(), &flaglist);
1147
1148   for (size_t i = 0; i < flaglist.size(); ++i) {
1149     const char* flagname = flaglist[i].c_str();
1150     CommandLineFlag* flag = registry_->FindFlagLocked(flagname);
1151     if (flag == NULL) {
1152       error_flags_[flagname] =
1153           StringPrintf("%sunknown command line flag '%s' "
1154                        "(via --fromenv or --tryfromenv)\n",
1155                        kError, flagname);
1156       undefined_names_[flagname] = "";
1157       continue;
1158     }
1159
1160     const string envname = string("FLAGS_") + string(flagname);
1161     string envval;
1162     if (!SafeGetEnv(envname.c_str(), envval)) {
1163       if (errors_are_fatal) {
1164         error_flags_[flagname] = (string(kError) + envname +
1165                                   " not found in environment\n");
1166       }
1167       continue;
1168     }
1169
1170     // Avoid infinite recursion.
1171     if (envval == "fromenv" || envval == "tryfromenv") {
1172       error_flags_[flagname] =
1173           StringPrintf("%sinfinite recursion on environment flag '%s'\n",
1174                        kError, envval.c_str());
1175       continue;
1176     }
1177
1178     msg += ProcessSingleOptionLocked(flag, envval.c_str(), set_mode);
1179   }
1180   return msg;
1181 }
1182
1183 string CommandLineFlagParser::ProcessSingleOptionLocked(
1184     CommandLineFlag* flag, const char* value, FlagSettingMode set_mode) {
1185   string msg;
1186   if (value && !registry_->SetFlagLocked(flag, value, set_mode, &msg)) {
1187     error_flags_[flag->name()] = msg;
1188     return "";
1189   }
1190
1191   // The recursive flags, --flagfile and --fromenv and --tryfromenv,
1192   // must be dealt with as soon as they're seen.  They will emit
1193   // messages of their own.
1194   if (strcmp(flag->name(), "flagfile") == 0) {
1195     msg += ProcessFlagfileLocked(FLAGS_flagfile, set_mode);
1196
1197   } else if (strcmp(flag->name(), "fromenv") == 0) {
1198     // last arg indicates envval-not-found is fatal (unlike in --tryfromenv)
1199     msg += ProcessFromenvLocked(FLAGS_fromenv, set_mode, true);
1200
1201   } else if (strcmp(flag->name(), "tryfromenv") == 0) {
1202     msg += ProcessFromenvLocked(FLAGS_tryfromenv, set_mode, false);
1203   }
1204
1205   return msg;
1206 }
1207
1208 void CommandLineFlagParser::ValidateFlags(bool all) {
1209   FlagRegistryLock frl(registry_);
1210   for (FlagRegistry::FlagConstIterator i = registry_->flags_.begin();
1211        i != registry_->flags_.end(); ++i) {
1212     if ((all || !i->second->Modified()) && !i->second->ValidateCurrent()) {
1213       // only set a message if one isn't already there.  (If there's
1214       // an error message, our job is done, even if it's not exactly
1215       // the same error.)
1216       if (error_flags_[i->second->name()].empty()) {
1217         error_flags_[i->second->name()] =
1218             string(kError) + "--" + i->second->name() +
1219             " must be set on the commandline";
1220         if (!i->second->Modified()) {
1221           error_flags_[i->second->name()] += " (default value fails validation)";
1222         }
1223         error_flags_[i->second->name()] += "\n";
1224       }
1225     }
1226   }
1227 }
1228
1229 void CommandLineFlagParser::ValidateUnmodifiedFlags() {
1230   ValidateFlags(false);
1231 }
1232
1233 bool CommandLineFlagParser::ReportErrors() {
1234   // error_flags_ indicates errors we saw while parsing.
1235   // But we ignore undefined-names if ok'ed by --undef_ok
1236   if (!FLAGS_undefok.empty()) {
1237     vector<string> flaglist;
1238     ParseFlagList(FLAGS_undefok.c_str(), &flaglist);
1239     for (size_t i = 0; i < flaglist.size(); ++i) {
1240       // We also deal with --no<flag>, in case the flagname was boolean
1241       const string no_version = string("no") + flaglist[i];
1242       if (undefined_names_.find(flaglist[i]) != undefined_names_.end()) {
1243         error_flags_[flaglist[i]] = "";    // clear the error message
1244       } else if (undefined_names_.find(no_version) != undefined_names_.end()) {
1245         error_flags_[no_version] = "";
1246       }
1247     }
1248   }
1249   // Likewise, if they decided to allow reparsing, all undefined-names
1250   // are ok; we just silently ignore them now, and hope that a future
1251   // parse will pick them up somehow.
1252   if (allow_command_line_reparsing) {
1253     for (map<string, string>::const_iterator it = undefined_names_.begin();
1254          it != undefined_names_.end();  ++it)
1255       error_flags_[it->first] = "";      // clear the error message
1256   }
1257
1258   bool found_error = false;
1259   string error_message;
1260   for (map<string, string>::const_iterator it = error_flags_.begin();
1261        it != error_flags_.end(); ++it) {
1262     if (!it->second.empty()) {
1263       error_message.append(it->second.data(), it->second.size());
1264       found_error = true;
1265     }
1266   }
1267   if (found_error)
1268     ReportError(DO_NOT_DIE, "%s", error_message.c_str());
1269   return found_error;
1270 }
1271
1272 string CommandLineFlagParser::ProcessOptionsFromStringLocked(
1273     const string& contentdata, FlagSettingMode set_mode) {
1274   string retval;
1275   const char* flagfile_contents = contentdata.c_str();
1276   bool flags_are_relevant = true;   // set to false when filenames don't match
1277   bool in_filename_section = false;
1278
1279   const char* line_end = flagfile_contents;
1280   // We read this file a line at a time.
1281   for (; line_end; flagfile_contents = line_end + 1) {
1282     while (*flagfile_contents && isspace(*flagfile_contents))
1283       ++flagfile_contents;
1284     // Windows uses "\r\n"
1285     line_end = strchr(flagfile_contents, '\r');
1286     if (line_end == NULL)
1287         line_end = strchr(flagfile_contents, '\n');
1288
1289     size_t len = line_end ? line_end - flagfile_contents
1290                           : strlen(flagfile_contents);
1291     string line(flagfile_contents, len);
1292
1293     // Each line can be one of four things:
1294     // 1) A comment line -- we skip it
1295     // 2) An empty line -- we skip it
1296     // 3) A list of filenames -- starts a new filenames+flags section
1297     // 4) A --flag=value line -- apply if previous filenames match
1298     if (line.empty() || line[0] == '#') {
1299       // comment or empty line; just ignore
1300
1301     } else if (line[0] == '-') {    // flag
1302       in_filename_section = false;  // instead, it was a flag-line
1303       if (!flags_are_relevant)      // skip this flag; applies to someone else
1304         continue;
1305
1306       const char* name_and_val = line.c_str() + 1;    // skip the leading -
1307       if (*name_and_val == '-')
1308         name_and_val++;                               // skip second - too
1309       string key;
1310       const char* value;
1311       string error_message;
1312       CommandLineFlag* flag = registry_->SplitArgumentLocked(name_and_val,
1313                                                              &key, &value,
1314                                                              &error_message);
1315       // By API, errors parsing flagfile lines are silently ignored.
1316       if (flag == NULL) {
1317         // "WARNING: flagname '" + key + "' not found\n"
1318       } else if (value == NULL) {
1319         // "WARNING: flagname '" + key + "' missing a value\n"
1320       } else {
1321         retval += ProcessSingleOptionLocked(flag, value, set_mode);
1322       }
1323
1324     } else {                        // a filename!
1325       if (!in_filename_section) {   // start over: assume filenames don't match
1326         in_filename_section = true;
1327         flags_are_relevant = false;
1328       }
1329
1330       // Split the line up at spaces into glob-patterns
1331       const char* space = line.c_str();   // just has to be non-NULL
1332       for (const char* word = line.c_str(); *space; word = space+1) {
1333         if (flags_are_relevant)     // we can stop as soon as we match
1334           break;
1335         space = strchr(word, ' ');
1336         if (space == NULL)
1337           space = word + strlen(word);
1338         const string glob(word, space - word);
1339         // We try matching both against the full argv0 and basename(argv0)
1340         if (glob == ProgramInvocationName()       // small optimization
1341             || glob == ProgramInvocationShortName()
1342 #if defined(HAVE_FNMATCH_H)
1343             || fnmatch(glob.c_str(), ProgramInvocationName(),      FNM_PATHNAME) == 0
1344             || fnmatch(glob.c_str(), ProgramInvocationShortName(), FNM_PATHNAME) == 0
1345 #elif defined(HAVE_SHLWAPI_H)
1346             || PathMatchSpec(glob.c_str(), ProgramInvocationName())
1347             || PathMatchSpec(glob.c_str(), ProgramInvocationShortName())
1348 #endif
1349             ) {
1350           flags_are_relevant = true;
1351         }
1352       }
1353     }
1354   }
1355   return retval;
1356 }
1357
1358 // --------------------------------------------------------------------
1359 // GetFromEnv()
1360 // AddFlagValidator()
1361 //    These are helper functions for routines like BoolFromEnv() and
1362 //    RegisterFlagValidator, defined below.  They're defined here so
1363 //    they can live in the unnamed namespace (which makes friendship
1364 //    declarations for these classes possible).
1365 // --------------------------------------------------------------------
1366
1367 template<typename T>
1368 T GetFromEnv(const char *varname, T dflt) {
1369   std::string valstr;
1370   if (SafeGetEnv(varname, valstr)) {
1371     FlagValue ifv(new T, true);
1372     if (!ifv.ParseFrom(valstr.c_str())) {
1373       ReportError(DIE, "ERROR: error parsing env variable '%s' with value '%s'\n",
1374                   varname, valstr.c_str());
1375     }
1376     return OTHER_VALUE_AS(ifv, T);
1377   } else return dflt;
1378 }
1379
1380 bool AddFlagValidator(const void* flag_ptr, ValidateFnProto validate_fn_proto) {
1381   // We want a lock around this routine, in case two threads try to
1382   // add a validator (hopefully the same one!) at once.  We could use
1383   // our own thread, but we need to loook at the registry anyway, so
1384   // we just steal that one.
1385   FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1386   FlagRegistryLock frl(registry);
1387   // First, find the flag whose current-flag storage is 'flag'.
1388   // This is the CommandLineFlag whose current_->value_buffer_ == flag
1389   CommandLineFlag* flag = registry->FindFlagViaPtrLocked(flag_ptr);
1390   if (!flag) {
1391     LOG(WARNING) << "Ignoring RegisterValidateFunction() for flag pointer "
1392                  << flag_ptr << ": no flag found at that address";
1393     return false;
1394   } else if (validate_fn_proto == flag->validate_function()) {
1395     return true;    // ok to register the same function over and over again
1396   } else if (validate_fn_proto != NULL && flag->validate_function() != NULL) {
1397     LOG(WARNING) << "Ignoring RegisterValidateFunction() for flag '"
1398                  << flag->name() << "': validate-fn already registered";
1399     return false;
1400   } else {
1401     flag->validate_fn_proto_ = validate_fn_proto;
1402     return true;
1403   }
1404 }
1405
1406 }  // end unnamed namespaces
1407
1408
1409 // Now define the functions that are exported via the .h file
1410
1411 // --------------------------------------------------------------------
1412 // FlagRegisterer
1413 //    This class exists merely to have a global constructor (the
1414 //    kind that runs before main(), that goes an initializes each
1415 //    flag that's been declared.  Note that it's very important we
1416 //    don't have a destructor that deletes flag_, because that would
1417 //    cause us to delete current_storage/defvalue_storage as well,
1418 //    which can cause a crash if anything tries to access the flag
1419 //    values in a global destructor.
1420 // --------------------------------------------------------------------
1421
1422 namespace {
1423 void RegisterCommandLineFlag(const char* name,
1424                              const char* help,
1425                              const char* filename,
1426                              FlagValue* current,
1427                              FlagValue* defvalue) {
1428   if (help == NULL)
1429     help = "";
1430   // Importantly, flag_ will never be deleted, so storage is always good.
1431   CommandLineFlag* flag =
1432       new CommandLineFlag(name, help, filename, current, defvalue);
1433   FlagRegistry::GlobalRegistry()->RegisterFlag(flag);  // default registry
1434 }
1435 }
1436
1437 template <typename FlagType>
1438 FlagRegisterer::FlagRegisterer(const char* name,
1439                                const char* help,
1440                                const char* filename,
1441                                FlagType* current_storage,
1442                                FlagType* defvalue_storage) {
1443   FlagValue* const current = new FlagValue(current_storage, false);
1444   FlagValue* const defvalue = new FlagValue(defvalue_storage, false);
1445   RegisterCommandLineFlag(name, help, filename, current, defvalue);
1446 }
1447
1448 // Force compiler to generate code for the given template specialization.
1449 #define INSTANTIATE_FLAG_REGISTERER_CTOR(type)                  \
1450   template GFLAGS_DLL_DECL FlagRegisterer::FlagRegisterer(      \
1451       const char* name, const char* help, const char* filename, \
1452       type* current_storage, type* defvalue_storage)
1453
1454 // Do this for all supported flag types.
1455 INSTANTIATE_FLAG_REGISTERER_CTOR(bool);
1456 INSTANTIATE_FLAG_REGISTERER_CTOR(int32);
1457 INSTANTIATE_FLAG_REGISTERER_CTOR(uint32);
1458 INSTANTIATE_FLAG_REGISTERER_CTOR(int64);
1459 INSTANTIATE_FLAG_REGISTERER_CTOR(uint64);
1460 INSTANTIATE_FLAG_REGISTERER_CTOR(double);
1461 INSTANTIATE_FLAG_REGISTERER_CTOR(std::string);
1462
1463 #undef INSTANTIATE_FLAG_REGISTERER_CTOR
1464
1465 // --------------------------------------------------------------------
1466 // GetAllFlags()
1467 //    The main way the FlagRegistry class exposes its data.  This
1468 //    returns, as strings, all the info about all the flags in
1469 //    the main registry, sorted first by filename they are defined
1470 //    in, and then by flagname.
1471 // --------------------------------------------------------------------
1472
1473 struct FilenameFlagnameCmp {
1474   bool operator()(const CommandLineFlagInfo& a,
1475                   const CommandLineFlagInfo& b) const {
1476     int cmp = strcmp(a.filename.c_str(), b.filename.c_str());
1477     if (cmp == 0)
1478       cmp = strcmp(a.name.c_str(), b.name.c_str());  // secondary sort key
1479     return cmp < 0;
1480   }
1481 };
1482
1483 void GetAllFlags(vector<CommandLineFlagInfo>* OUTPUT) {
1484   FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1485   registry->Lock();
1486   for (FlagRegistry::FlagConstIterator i = registry->flags_.begin();
1487        i != registry->flags_.end(); ++i) {
1488     CommandLineFlagInfo fi;
1489     i->second->FillCommandLineFlagInfo(&fi);
1490     OUTPUT->push_back(fi);
1491   }
1492   registry->Unlock();
1493   // Now sort the flags, first by filename they occur in, then alphabetically
1494   sort(OUTPUT->begin(), OUTPUT->end(), FilenameFlagnameCmp());
1495 }
1496
1497 // --------------------------------------------------------------------
1498 // SetArgv()
1499 // GetArgvs()
1500 // GetArgv()
1501 // GetArgv0()
1502 // ProgramInvocationName()
1503 // ProgramInvocationShortName()
1504 // SetUsageMessage()
1505 // ProgramUsage()
1506 //    Functions to set and get argv.  Typically the setter is called
1507 //    by ParseCommandLineFlags.  Also can get the ProgramUsage string,
1508 //    set by SetUsageMessage.
1509 // --------------------------------------------------------------------
1510
1511 // These values are not protected by a Mutex because they are normally
1512 // set only once during program startup.
1513 static string argv0("UNKNOWN");  // just the program name
1514 static string cmdline;           // the entire command-line
1515 static string program_usage;
1516 static vector<string> argvs;
1517 static uint32 argv_sum = 0;
1518
1519 void SetArgv(int argc, const char** argv) {
1520   static bool called_set_argv = false;
1521   if (called_set_argv) return;
1522   called_set_argv = true;
1523
1524   assert(argc > 0); // every program has at least a name
1525   argv0 = argv[0];
1526
1527   cmdline.clear();
1528   for (int i = 0; i < argc; i++) {
1529     if (i != 0) cmdline += " ";
1530     cmdline += argv[i];
1531     argvs.push_back(argv[i]);
1532   }
1533
1534   // Compute a simple sum of all the chars in argv
1535   argv_sum = 0;
1536   for (string::const_iterator c = cmdline.begin(); c != cmdline.end(); ++c) {
1537     argv_sum += *c;
1538   }
1539 }
1540
1541 const vector<string>& GetArgvs() { return argvs; }
1542 const char* GetArgv()            { return cmdline.c_str(); }
1543 const char* GetArgv0()           { return argv0.c_str(); }
1544 uint32 GetArgvSum()              { return argv_sum; }
1545 const char* ProgramInvocationName() {             // like the GNU libc fn
1546   return GetArgv0();
1547 }
1548 const char* ProgramInvocationShortName() {        // like the GNU libc fn
1549   size_t pos = argv0.rfind('/');
1550 #ifdef OS_WINDOWS
1551   if (pos == string::npos) pos = argv0.rfind('\\');
1552 #endif
1553   return (pos == string::npos ? argv0.c_str() : (argv0.c_str() + pos + 1));
1554 }
1555
1556 void SetUsageMessage(const string& usage) {
1557   program_usage = usage;
1558 }
1559
1560 const char* ProgramUsage() {
1561   if (program_usage.empty()) {
1562     return "Warning: SetUsageMessage() never called";
1563   }
1564   return program_usage.c_str();
1565 }
1566
1567 // --------------------------------------------------------------------
1568 // SetVersionString()
1569 // VersionString()
1570 // --------------------------------------------------------------------
1571
1572 static string version_string;
1573
1574 void SetVersionString(const string& version) {
1575   version_string = version;
1576 }
1577
1578 const char* VersionString() {
1579   return version_string.c_str();
1580 }
1581
1582
1583 // --------------------------------------------------------------------
1584 // GetCommandLineOption()
1585 // GetCommandLineFlagInfo()
1586 // GetCommandLineFlagInfoOrDie()
1587 // SetCommandLineOption()
1588 // SetCommandLineOptionWithMode()
1589 //    The programmatic way to set a flag's value, using a string
1590 //    for its name rather than the variable itself (that is,
1591 //    SetCommandLineOption("foo", x) rather than FLAGS_foo = x).
1592 //    There's also a bit more flexibility here due to the various
1593 //    set-modes, but typically these are used when you only have
1594 //    that flag's name as a string, perhaps at runtime.
1595 //    All of these work on the default, global registry.
1596 //       For GetCommandLineOption, return false if no such flag
1597 //    is known, true otherwise.  We clear "value" if a suitable
1598 //    flag is found.
1599 // --------------------------------------------------------------------
1600
1601
1602 bool GetCommandLineOption(const char* name, string* value) {
1603   if (NULL == name)
1604     return false;
1605   assert(value);
1606
1607   FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1608   FlagRegistryLock frl(registry);
1609   CommandLineFlag* flag = registry->FindFlagLocked(name);
1610   if (flag == NULL) {
1611     return false;
1612   } else {
1613     *value = flag->current_value();
1614     return true;
1615   }
1616 }
1617
1618 bool GetCommandLineFlagInfo(const char* name, CommandLineFlagInfo* OUTPUT) {
1619   if (NULL == name) return false;
1620   FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1621   FlagRegistryLock frl(registry);
1622   CommandLineFlag* flag = registry->FindFlagLocked(name);
1623   if (flag == NULL) {
1624     return false;
1625   } else {
1626     assert(OUTPUT);
1627     flag->FillCommandLineFlagInfo(OUTPUT);
1628     return true;
1629   }
1630 }
1631
1632 CommandLineFlagInfo GetCommandLineFlagInfoOrDie(const char* name) {
1633   CommandLineFlagInfo info;
1634   if (!GetCommandLineFlagInfo(name, &info)) {
1635     fprintf(stderr, "FATAL ERROR: flag name '%s' doesn't exist\n", name);
1636     gflags_exitfunc(1);    // almost certainly gflags_exitfunc()
1637   }
1638   return info;
1639 }
1640
1641 string SetCommandLineOptionWithMode(const char* name, const char* value,
1642                                     FlagSettingMode set_mode) {
1643   string result;
1644   FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1645   FlagRegistryLock frl(registry);
1646   CommandLineFlag* flag = registry->FindFlagLocked(name);
1647   if (flag) {
1648     CommandLineFlagParser parser(registry);
1649     result = parser.ProcessSingleOptionLocked(flag, value, set_mode);
1650     if (!result.empty()) {   // in the error case, we've already logged
1651       // Could consider logging this change
1652     }
1653   }
1654   // The API of this function is that we return empty string on error
1655   return result;
1656 }
1657
1658 string SetCommandLineOption(const char* name, const char* value) {
1659   return SetCommandLineOptionWithMode(name, value, SET_FLAGS_VALUE);
1660 }
1661
1662 // --------------------------------------------------------------------
1663 // FlagSaver
1664 // FlagSaverImpl
1665 //    This class stores the states of all flags at construct time,
1666 //    and restores all flags to that state at destruct time.
1667 //    Its major implementation challenge is that it never modifies
1668 //    pointers in the 'main' registry, so global FLAG_* vars always
1669 //    point to the right place.
1670 // --------------------------------------------------------------------
1671
1672 class FlagSaverImpl {
1673  public:
1674   // Constructs an empty FlagSaverImpl object.
1675   explicit FlagSaverImpl(FlagRegistry* main_registry)
1676       : main_registry_(main_registry) { }
1677   ~FlagSaverImpl() {
1678     // reclaim memory from each of our CommandLineFlags
1679     vector<CommandLineFlag*>::const_iterator it;
1680     for (it = backup_registry_.begin(); it != backup_registry_.end(); ++it)
1681       delete *it;
1682   }
1683
1684   // Saves the flag states from the flag registry into this object.
1685   // It's an error to call this more than once.
1686   // Must be called when the registry mutex is not held.
1687   void SaveFromRegistry() {
1688     FlagRegistryLock frl(main_registry_);
1689     assert(backup_registry_.empty());   // call only once!
1690     for (FlagRegistry::FlagConstIterator it = main_registry_->flags_.begin();
1691          it != main_registry_->flags_.end();
1692          ++it) {
1693       const CommandLineFlag* main = it->second;
1694       // Sets up all the const variables in backup correctly
1695       CommandLineFlag* backup = new CommandLineFlag(
1696           main->name(), main->help(), main->filename(),
1697           main->current_->New(), main->defvalue_->New());
1698       // Sets up all the non-const variables in backup correctly
1699       backup->CopyFrom(*main);
1700       backup_registry_.push_back(backup);   // add it to a convenient list
1701     }
1702   }
1703
1704   // Restores the saved flag states into the flag registry.  We
1705   // assume no flags were added or deleted from the registry since
1706   // the SaveFromRegistry; if they were, that's trouble!  Must be
1707   // called when the registry mutex is not held.
1708   void RestoreToRegistry() {
1709     FlagRegistryLock frl(main_registry_);
1710     vector<CommandLineFlag*>::const_iterator it;
1711     for (it = backup_registry_.begin(); it != backup_registry_.end(); ++it) {
1712       CommandLineFlag* main = main_registry_->FindFlagLocked((*it)->name());
1713       if (main != NULL) {       // if NULL, flag got deleted from registry(!)
1714         main->CopyFrom(**it);
1715       }
1716     }
1717   }
1718
1719  private:
1720   FlagRegistry* const main_registry_;
1721   vector<CommandLineFlag*> backup_registry_;
1722
1723   FlagSaverImpl(const FlagSaverImpl&);  // no copying!
1724   void operator=(const FlagSaverImpl&);
1725 };
1726
1727 FlagSaver::FlagSaver()
1728     : impl_(new FlagSaverImpl(FlagRegistry::GlobalRegistry())) {
1729   impl_->SaveFromRegistry();
1730 }
1731
1732 FlagSaver::~FlagSaver() {
1733   impl_->RestoreToRegistry();
1734   delete impl_;
1735 }
1736
1737
1738 // --------------------------------------------------------------------
1739 // CommandlineFlagsIntoString()
1740 // ReadFlagsFromString()
1741 // AppendFlagsIntoFile()
1742 // ReadFromFlagsFile()
1743 //    These are mostly-deprecated routines that stick the
1744 //    commandline flags into a file/string and read them back
1745 //    out again.  I can see a use for CommandlineFlagsIntoString,
1746 //    for creating a flagfile, but the rest don't seem that useful
1747 //    -- some, I think, are a poor-man's attempt at FlagSaver --
1748 //    and are included only until we can delete them from callers.
1749 //    Note they don't save --flagfile flags (though they do save
1750 //    the result of having called the flagfile, of course).
1751 // --------------------------------------------------------------------
1752
1753 static string TheseCommandlineFlagsIntoString(
1754     const vector<CommandLineFlagInfo>& flags) {
1755   vector<CommandLineFlagInfo>::const_iterator i;
1756
1757   size_t retval_space = 0;
1758   for (i = flags.begin(); i != flags.end(); ++i) {
1759     // An (over)estimate of how much space it will take to print this flag
1760     retval_space += i->name.length() + i->current_value.length() + 5;
1761   }
1762
1763   string retval;
1764   retval.reserve(retval_space);
1765   for (i = flags.begin(); i != flags.end(); ++i) {
1766     retval += "--";
1767     retval += i->name;
1768     retval += "=";
1769     retval += i->current_value;
1770     retval += "\n";
1771   }
1772   return retval;
1773 }
1774
1775 string CommandlineFlagsIntoString() {
1776   vector<CommandLineFlagInfo> sorted_flags;
1777   GetAllFlags(&sorted_flags);
1778   return TheseCommandlineFlagsIntoString(sorted_flags);
1779 }
1780
1781 bool ReadFlagsFromString(const string& flagfilecontents,
1782                          const char* /*prog_name*/,  // TODO(csilvers): nix this
1783                          bool errors_are_fatal) {
1784   FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1785   FlagSaverImpl saved_states(registry);
1786   saved_states.SaveFromRegistry();
1787
1788   CommandLineFlagParser parser(registry);
1789   registry->Lock();
1790   parser.ProcessOptionsFromStringLocked(flagfilecontents, SET_FLAGS_VALUE);
1791   registry->Unlock();
1792   // Should we handle --help and such when reading flags from a string?  Sure.
1793   HandleCommandLineHelpFlags();
1794   if (parser.ReportErrors()) {
1795     // Error.  Restore all global flags to their previous values.
1796     if (errors_are_fatal)
1797       gflags_exitfunc(1);
1798     saved_states.RestoreToRegistry();
1799     return false;
1800   }
1801   return true;
1802 }
1803
1804 // TODO(csilvers): nix prog_name in favor of ProgramInvocationShortName()
1805 bool AppendFlagsIntoFile(const string& filename, const char *prog_name) {
1806   FILE *fp;
1807   if (SafeFOpen(&fp, filename.c_str(), "a") != 0) {
1808     return false;
1809   }
1810
1811   if (prog_name)
1812     fprintf(fp, "%s\n", prog_name);
1813
1814   vector<CommandLineFlagInfo> flags;
1815   GetAllFlags(&flags);
1816   // But we don't want --flagfile, which leads to weird recursion issues
1817   vector<CommandLineFlagInfo>::iterator i;
1818   for (i = flags.begin(); i != flags.end(); ++i) {
1819     if (strcmp(i->name.c_str(), "flagfile") == 0) {
1820       flags.erase(i);
1821       break;
1822     }
1823   }
1824   fprintf(fp, "%s", TheseCommandlineFlagsIntoString(flags).c_str());
1825
1826   fclose(fp);
1827   return true;
1828 }
1829
1830 bool ReadFromFlagsFile(const string& filename, const char* prog_name,
1831                        bool errors_are_fatal) {
1832   return ReadFlagsFromString(ReadFileIntoString(filename.c_str()),
1833                              prog_name, errors_are_fatal);
1834 }
1835
1836
1837 // --------------------------------------------------------------------
1838 // BoolFromEnv()
1839 // Int32FromEnv()
1840 // Uint32FromEnv()
1841 // Int64FromEnv()
1842 // Uint64FromEnv()
1843 // DoubleFromEnv()
1844 // StringFromEnv()
1845 //    Reads the value from the environment and returns it.
1846 //    We use an FlagValue to make the parsing easy.
1847 //    Example usage:
1848 //       DEFINE_bool(myflag, BoolFromEnv("MYFLAG_DEFAULT", false), "whatever");
1849 // --------------------------------------------------------------------
1850
1851 bool BoolFromEnv(const char *v, bool dflt) {
1852   return GetFromEnv(v, dflt);
1853 }
1854 int32 Int32FromEnv(const char *v, int32 dflt) {
1855   return GetFromEnv(v, dflt);
1856 }
1857 uint32 Uint32FromEnv(const char *v, uint32 dflt) {
1858   return GetFromEnv(v, dflt);
1859 }
1860 int64 Int64FromEnv(const char *v, int64 dflt)    {
1861   return GetFromEnv(v, dflt);
1862 }
1863 uint64 Uint64FromEnv(const char *v, uint64 dflt) {
1864   return GetFromEnv(v, dflt);
1865 }
1866 double DoubleFromEnv(const char *v, double dflt) {
1867   return GetFromEnv(v, dflt);
1868 }
1869
1870 #ifdef _MSC_VER
1871 #  pragma warning(push)
1872 #  pragma warning(disable: 4996) // ignore getenv security warning
1873 #endif
1874 const char *StringFromEnv(const char *varname, const char *dflt) {
1875   const char* const val = getenv(varname);
1876   return val ? val : dflt;
1877 }
1878 #ifdef _MSC_VER
1879 #  pragma warning(pop)
1880 #endif
1881
1882
1883 // --------------------------------------------------------------------
1884 // RegisterFlagValidator()
1885 //    RegisterFlagValidator() is the function that clients use to
1886 //    'decorate' a flag with a validation function.  Once this is
1887 //    done, every time the flag is set (including when the flag
1888 //    is parsed from argv), the validator-function is called.
1889 //       These functions return true if the validator was added
1890 //    successfully, or false if not: the flag already has a validator,
1891 //    (only one allowed per flag), the 1st arg isn't a flag, etc.
1892 //       This function is not thread-safe.
1893 // --------------------------------------------------------------------
1894
1895 bool RegisterFlagValidator(const bool* flag,
1896                            bool (*validate_fn)(const char*, bool)) {
1897   return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1898 }
1899 bool RegisterFlagValidator(const int32* flag,
1900                            bool (*validate_fn)(const char*, int32)) {
1901   return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1902 }
1903 bool RegisterFlagValidator(const uint32* flag,
1904                            bool (*validate_fn)(const char*, uint32)) {
1905   return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1906 }
1907 bool RegisterFlagValidator(const int64* flag,
1908                            bool (*validate_fn)(const char*, int64)) {
1909   return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1910 }
1911 bool RegisterFlagValidator(const uint64* flag,
1912                            bool (*validate_fn)(const char*, uint64)) {
1913   return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1914 }
1915 bool RegisterFlagValidator(const double* flag,
1916                            bool (*validate_fn)(const char*, double)) {
1917   return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1918 }
1919 bool RegisterFlagValidator(const string* flag,
1920                            bool (*validate_fn)(const char*, const string&)) {
1921   return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1922 }
1923
1924
1925 // --------------------------------------------------------------------
1926 // ParseCommandLineFlags()
1927 // ParseCommandLineNonHelpFlags()
1928 // HandleCommandLineHelpFlags()
1929 //    This is the main function called from main(), to actually
1930 //    parse the commandline.  It modifies argc and argv as described
1931 //    at the top of gflags.h.  You can also divide this
1932 //    function into two parts, if you want to do work between
1933 //    the parsing of the flags and the printing of any help output.
1934 // --------------------------------------------------------------------
1935
1936 static uint32 ParseCommandLineFlagsInternal(int* argc, char*** argv,
1937                                             bool remove_flags, bool do_report) {
1938   SetArgv(*argc, const_cast<const char**>(*argv));    // save it for later
1939
1940   FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1941   CommandLineFlagParser parser(registry);
1942
1943   // When we parse the commandline flags, we'll handle --flagfile,
1944   // --tryfromenv, etc. as we see them (since flag-evaluation order
1945   // may be important).  But sometimes apps set FLAGS_tryfromenv/etc.
1946   // manually before calling ParseCommandLineFlags.  We want to evaluate
1947   // those too, as if they were the first flags on the commandline.
1948   registry->Lock();
1949   parser.ProcessFlagfileLocked(FLAGS_flagfile, SET_FLAGS_VALUE);
1950   // Last arg here indicates whether flag-not-found is a fatal error or not
1951   parser.ProcessFromenvLocked(FLAGS_fromenv, SET_FLAGS_VALUE, true);
1952   parser.ProcessFromenvLocked(FLAGS_tryfromenv, SET_FLAGS_VALUE, false);
1953   registry->Unlock();
1954
1955   // Now get the flags specified on the commandline
1956   const int r = parser.ParseNewCommandLineFlags(argc, argv, remove_flags);
1957
1958   if (do_report)
1959     HandleCommandLineHelpFlags();   // may cause us to exit on --help, etc.
1960
1961   // See if any of the unset flags fail their validation checks
1962   parser.ValidateUnmodifiedFlags();
1963
1964   if (parser.ReportErrors())        // may cause us to exit on illegal flags
1965     gflags_exitfunc(1);
1966   return r;
1967 }
1968
1969 uint32 ParseCommandLineFlags(int* argc, char*** argv, bool remove_flags) {
1970   return ParseCommandLineFlagsInternal(argc, argv, remove_flags, true);
1971 }
1972
1973 uint32 ParseCommandLineNonHelpFlags(int* argc, char*** argv,
1974                                     bool remove_flags) {
1975   return ParseCommandLineFlagsInternal(argc, argv, remove_flags, false);
1976 }
1977
1978 // --------------------------------------------------------------------
1979 // AllowCommandLineReparsing()
1980 // ReparseCommandLineNonHelpFlags()
1981 //    This is most useful for shared libraries.  The idea is if
1982 //    a flag is defined in a shared library that is dlopen'ed
1983 //    sometime after main(), you can ParseCommandLineFlags before
1984 //    the dlopen, then ReparseCommandLineNonHelpFlags() after the
1985 //    dlopen, to get the new flags.  But you have to explicitly
1986 //    Allow() it; otherwise, you get the normal default behavior
1987 //    of unrecognized flags calling a fatal error.
1988 // TODO(csilvers): this isn't used.  Just delete it?
1989 // --------------------------------------------------------------------
1990
1991 void AllowCommandLineReparsing() {
1992   allow_command_line_reparsing = true;
1993 }
1994
1995 void ReparseCommandLineNonHelpFlags() {
1996   // We make a copy of argc and argv to pass in
1997   const vector<string>& argvs = GetArgvs();
1998   int tmp_argc = static_cast<int>(argvs.size());
1999   char** tmp_argv = new char* [tmp_argc + 1];
2000   for (int i = 0; i < tmp_argc; ++i)
2001     tmp_argv[i] = strdup(argvs[i].c_str());   // TODO(csilvers): don't dup
2002
2003   ParseCommandLineNonHelpFlags(&tmp_argc, &tmp_argv, false);
2004
2005   for (int i = 0; i < tmp_argc; ++i)
2006     free(tmp_argv[i]);
2007   delete[] tmp_argv;
2008 }
2009
2010 void ShutDownCommandLineFlags() {
2011   FlagRegistry::DeleteGlobalRegistry();
2012 }
2013
2014
2015 } // namespace GFLAGS_NAMESPACE