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