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