blob: 6c3c93e35e3d1d272d403e58ecff008c41bc095c [file] [log] [blame]
Craig Silverstein917f4e72011-07-29 04:26:49 +00001// Copyright (c) 1999, Google Inc.
Craig Silversteinb9f23482007-03-22 00:15:41 +00002// 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// ---
Craig Silversteinb9f23482007-03-22 00:15:41 +000031// Revamped and reorganized by Craig Silverstein
32//
33// This file contains the implementation of all our command line flags
Craig Silversteinc79c32d2008-07-22 23:29:39 +000034// 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.
Craig Silversteinb9f23482007-03-22 00:15:41 +000089
Andreas Schuhf7e89ba2013-04-21 03:38:25 +010090#include "config.h"
91#include "gflags.h"
Craig Silverstein917f4e72011-07-29 04:26:49 +000092
Craig Silverstein917f4e72011-07-29 04:26:49 +000093#include <assert.h>
Craig Silversteinb9f23482007-03-22 00:15:41 +000094#include <ctype.h>
95#include <errno.h>
Andreas Schuh392eb672013-04-21 03:05:35 +010096#if HAVE_FNMATCH_H
Andreas Schuhf7e89ba2013-04-21 03:38:25 +010097# include <fnmatch.h>
Craig Silverstein917f4e72011-07-29 04:26:49 +000098#endif
99#include <stdarg.h> // For va_list and related operations
100#include <stdio.h>
101#include <string.h>
102
Craig Silversteinb9f23482007-03-22 00:15:41 +0000103#include <algorithm>
Craig Silverstein917f4e72011-07-29 04:26:49 +0000104#include <map>
105#include <string>
106#include <utility> // for pair<>
107#include <vector>
Andreas Schuhf7e89ba2013-04-21 03:38:25 +0100108
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000109#include "mutex.h"
Craig Silverstein917f4e72011-07-29 04:26:49 +0000110#include "util.h"
Craig Silversteinb9f23482007-03-22 00:15:41 +0000111
Craig Silversteinc44e0552010-09-16 18:53:42 +0000112
Craig Silversteinb9f23482007-03-22 00:15:41 +0000113// Special flags, type 1: the 'recursive' flags. They set another flag's val.
114DEFINE_string(flagfile, "",
115 "load flags from file");
116DEFINE_string(fromenv, "",
Craig Silverstein67914682008-08-21 00:50:59 +0000117 "set flags from the environment"
118 " [use 'export FLAGS_flag1=value']");
Craig Silversteinb9f23482007-03-22 00:15:41 +0000119DEFINE_string(tryfromenv, "",
120 "set flags from the environment if present");
121
122// Special flags, type 2: the 'parsing' flags. They modify how we parse.
123DEFINE_string(undefok, "",
124 "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
Andreas Schuh392eb672013-04-21 03:05:35 +0100129namespace GFLAGS_NAMESPACE {
Craig Silversteinb9f23482007-03-22 00:15:41 +0000130
Craig Silverstein31c8edc2010-01-05 02:25:45 +0000131using std::map;
132using std::pair;
133using std::sort;
134using std::string;
135using std::vector;
136
Craig Silverstein917f4e72011-07-29 04:26:49 +0000137// This is used by the unittest to test error-exit code
138void GFLAGS_DLL_DECL (*gflags_exitfunc)(int) = &exit; // from stdlib.h
139
140
Craig Silverstein585a44a2007-10-18 20:08:26 +0000141// 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
Craig Silverstein917f4e72011-07-29 04:26:49 +0000144// before including base/gflags.h
Craig Silverstein585a44a2007-10-18 20:08:26 +0000145
Craig Silverstein917f4e72011-07-29 04:26:49 +0000146// This is used by this file, and also in gflags_reporting.cc
Craig Silverstein585a44a2007-10-18 20:08:26 +0000147const char kStrippedFlagHelp[] = "\001\002\003\004 (unknown) \004\003\002\001";
Craig Silversteinb9f23482007-03-22 00:15:41 +0000148
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000149namespace {
150
Craig Silverstein917f4e72011-07-29 04:26:49 +0000151// There are also 'reporting' flags, in gflags_reporting.cc.
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000152
153static const char kError[] = "ERROR: ";
154
Craig Silversteinb9f23482007-03-22 00:15:41 +0000155// Indicates that undefined options are to be ignored.
156// Enables deferred processing of flags in dynamically loaded libraries.
157static bool allow_command_line_reparsing = false;
158
Craig Silverstein83911c12008-03-27 20:11:07 +0000159static bool logging_is_probably_set_up = false;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000160
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000161// 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.
166typedef bool (*ValidateFnProto)();
167
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000168// Whether we should die when reporting an error.
169enum DieWhenReporting { DIE, DO_NOT_DIE };
170
171// Report Error and exit if requested.
172static void ReportError(DieWhenReporting should_die, const char* format, ...) {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000173 char error_message[255];
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000174 va_list ap;
175 va_start(ap, format);
Craig Silverstein917f4e72011-07-29 04:26:49 +0000176 vsnprintf(error_message, sizeof(error_message), format, ap);
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000177 va_end(ap);
Craig Silverstein917f4e72011-07-29 04:26:49 +0000178 fprintf(stderr, "%s", error_message);
Craig Silverstein6b70a752011-11-03 23:11:24 +0000179 fflush(stderr); // should be unnecessary, but cygwin's rxvt buffers stderr
Craig Silverstein917f4e72011-07-29 04:26:49 +0000180 if (should_die == DIE) gflags_exitfunc(1);
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000181}
182
Craig Silversteinb9f23482007-03-22 00:15:41 +0000183
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
Craig Silverstein83911c12008-03-27 20:11:07 +0000188// given type, and back. Thread-compatible.
Craig Silversteinb9f23482007-03-22 00:15:41 +0000189// --------------------------------------------------------------------
190
Craig Silversteine0b71e52008-09-19 19:32:05 +0000191class CommandLineFlag;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000192class FlagValue {
193 public:
Craig Silverstein0baf4ab2011-01-14 21:58:28 +0000194 FlagValue(void* valbuf, const char* type, bool transfer_ownership_of_value);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000195 ~FlagValue();
196
197 bool ParseFrom(const char* spec);
198 string ToString() const;
199
200 private:
Craig Silverstein67914682008-08-21 00:50:59 +0000201 friend class CommandLineFlag; // for many things, including Validate()
Andreas Schuh392eb672013-04-21 03:05:35 +0100202 friend class GFLAGS_NAMESPACE::FlagSaverImpl; // calls New()
Craig Silverstein67914682008-08-21 00:50:59 +0000203 friend class FlagRegistry; // checks value_buffer_ for flags_by_ptr_ map
Craig Silversteinb9f23482007-03-22 00:15:41 +0000204 template <typename T> friend T GetFromEnv(const char*, const char*, T);
Craig Silversteine0b71e52008-09-19 19:32:05 +0000205 friend bool TryParseLocked(const CommandLineFlag*, FlagValue*,
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000206 const char*, string*); // for New(), CopyFrom()
Craig Silversteinb9f23482007-03-22 00:15:41 +0000207
Craig Silversteinc44e0552010-09-16 18:53:42 +0000208 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 };
Craig Silversteinb9f23482007-03-22 00:15:41 +0000217 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);
Craig Silverstein20500a92010-05-07 21:33:49 +0000221 int ValueSize() const;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000222
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000223 // 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
Craig Silversteinb9f23482007-03-22 00:15:41 +0000229 void* value_buffer_; // points to the buffer holding our data
Craig Silverstein0baf4ab2011-01-14 21:58:28 +0000230 int8 type_; // how to interpret value_
231 bool owns_value_; // whether to free value on destruct
Craig Silversteinb9f23482007-03-22 00:15:41 +0000232
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
Craig Silverstein0baf4ab2011-01-14 21:58:28 +0000244FlagValue::FlagValue(void* valbuf, const char* type,
245 bool transfer_ownership_of_value)
246 : value_buffer_(valbuf),
247 owns_value_(transfer_ownership_of_value) {
Craig Silversteinc44e0552010-09-16 18:53:42 +0000248 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
Craig Silversteinb9f23482007-03-22 00:15:41 +0000254}
255
256FlagValue::~FlagValue() {
Craig Silverstein0baf4ab2011-01-14 21:58:28 +0000257 if (!owns_value_) {
258 return;
259 }
Craig Silversteinb9f23482007-03-22 00:15:41 +0000260 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
270bool 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" };
Craig Silverstein917f4e72011-07-29 04:26:49 +0000274 COMPILE_ASSERT(sizeof(kTrue) == sizeof(kFalse), true_false_equal);
Craig Silverstein67914682008-08-21 00:50:59 +0000275 for (size_t i = 0; i < sizeof(kTrue)/sizeof(*kTrue); ++i) {
Craig Silversteinb9f23482007-03-22 00:15:41 +0000276 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: {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000304 const int64 r = strto64(value, &end, base);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000305 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;
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000308 SET_VALUE_AS(int32, static_cast<int32>(r));
Craig Silversteinb9f23482007-03-22 00:15:41 +0000309 return true;
310 }
311 case FV_INT64: {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000312 const int64 r = strto64(value, &end, base);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000313 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
Craig Silverstein917f4e72011-07-29 04:26:49 +0000320 const uint64 r = strtou64(value, &end, base);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000321 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: {
Craig Silverstein67914682008-08-21 00:50:59 +0000332 assert(false); // unknown type
Craig Silversteinb9f23482007-03-22 00:15:41 +0000333 return false;
334 }
335 }
336}
337
338string 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:
Andreas Schuhe88280e2012-05-29 15:19:11 +0000344 snprintf(intbuf, sizeof(intbuf), "%" PRId32, VALUE_AS(int32));
Craig Silversteinb9f23482007-03-22 00:15:41 +0000345 return intbuf;
346 case FV_INT64:
Andreas Schuhe88280e2012-05-29 15:19:11 +0000347 snprintf(intbuf, sizeof(intbuf), "%" PRId64, VALUE_AS(int64));
Craig Silversteinb9f23482007-03-22 00:15:41 +0000348 return intbuf;
349 case FV_UINT64:
Andreas Schuhe88280e2012-05-29 15:19:11 +0000350 snprintf(intbuf, sizeof(intbuf), "%" PRIu64, VALUE_AS(uint64));
Craig Silversteinb9f23482007-03-22 00:15:41 +0000351 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:
Craig Silverstein67914682008-08-21 00:50:59 +0000358 assert(false);
359 return ""; // unknown type
Craig Silversteinb9f23482007-03-22 00:15:41 +0000360 }
361}
362
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000363bool 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:
Craig Silverstein67914682008-08-21 00:50:59 +0000385 assert(false); // unknown type
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000386 return false;
387 }
388}
389
Craig Silversteinb9f23482007-03-22 00:15:41 +0000390const char* FlagValue::TypeName() const {
Craig Silversteinc44e0552010-09-16 18:53:42 +0000391 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 "";
Craig Silversteinb9f23482007-03-22 00:15:41 +0000401 }
Craig Silversteinc44e0552010-09-16 18:53:42 +0000402 // Directly indexing the strigns in the 'types' string, each of them
403 // is 7 bytes long.
404 return &types[type_ * 7];
Craig Silversteinb9f23482007-03-22 00:15:41 +0000405}
406
407bool FlagValue::Equal(const FlagValue& x) const {
408 if (type_ != x.type_)
409 return false;
410 switch (type_) {
411 case FV_BOOL: return VALUE_AS(bool) == OTHER_VALUE_AS(x, bool);
412 case FV_INT32: return VALUE_AS(int32) == OTHER_VALUE_AS(x, int32);
413 case FV_INT64: return VALUE_AS(int64) == OTHER_VALUE_AS(x, int64);
414 case FV_UINT64: return VALUE_AS(uint64) == OTHER_VALUE_AS(x, uint64);
415 case FV_DOUBLE: return VALUE_AS(double) == OTHER_VALUE_AS(x, double);
416 case FV_STRING: return VALUE_AS(string) == OTHER_VALUE_AS(x, string);
Craig Silverstein67914682008-08-21 00:50:59 +0000417 default: assert(false); return false; // unknown type
Craig Silversteinb9f23482007-03-22 00:15:41 +0000418 }
419}
420
421FlagValue* FlagValue::New() const {
Craig Silversteinc44e0552010-09-16 18:53:42 +0000422 const char *type = TypeName();
Craig Silversteinb9f23482007-03-22 00:15:41 +0000423 switch (type_) {
Craig Silverstein0baf4ab2011-01-14 21:58:28 +0000424 case FV_BOOL: return new FlagValue(new bool(false), type, true);
425 case FV_INT32: return new FlagValue(new int32(0), type, true);
426 case FV_INT64: return new FlagValue(new int64(0), type, true);
427 case FV_UINT64: return new FlagValue(new uint64(0), type, true);
428 case FV_DOUBLE: return new FlagValue(new double(0.0), type, true);
429 case FV_STRING: return new FlagValue(new string, type, true);
Craig Silverstein67914682008-08-21 00:50:59 +0000430 default: assert(false); return NULL; // unknown type
Craig Silversteinb9f23482007-03-22 00:15:41 +0000431 }
432}
433
434void FlagValue::CopyFrom(const FlagValue& x) {
435 assert(type_ == x.type_);
436 switch (type_) {
437 case FV_BOOL: SET_VALUE_AS(bool, OTHER_VALUE_AS(x, bool)); break;
438 case FV_INT32: SET_VALUE_AS(int32, OTHER_VALUE_AS(x, int32)); break;
439 case FV_INT64: SET_VALUE_AS(int64, OTHER_VALUE_AS(x, int64)); break;
440 case FV_UINT64: SET_VALUE_AS(uint64, OTHER_VALUE_AS(x, uint64)); break;
441 case FV_DOUBLE: SET_VALUE_AS(double, OTHER_VALUE_AS(x, double)); break;
442 case FV_STRING: SET_VALUE_AS(string, OTHER_VALUE_AS(x, string)); break;
Craig Silverstein67914682008-08-21 00:50:59 +0000443 default: assert(false); // unknown type
Craig Silversteinb9f23482007-03-22 00:15:41 +0000444 }
445}
446
Craig Silverstein20500a92010-05-07 21:33:49 +0000447int FlagValue::ValueSize() const {
Craig Silversteinc44e0552010-09-16 18:53:42 +0000448 if (type_ > FV_MAX_INDEX) {
449 assert(false); // unknown type
450 return 0;
Craig Silverstein20500a92010-05-07 21:33:49 +0000451 }
Craig Silversteinc44e0552010-09-16 18:53:42 +0000452 static const uint8 valuesize[] = {
453 sizeof(bool),
454 sizeof(int32),
455 sizeof(int64),
456 sizeof(uint64),
457 sizeof(double),
458 sizeof(string),
459 };
460 return valuesize[type_];
Craig Silverstein20500a92010-05-07 21:33:49 +0000461}
462
Craig Silversteinb9f23482007-03-22 00:15:41 +0000463// --------------------------------------------------------------------
464// CommandLineFlag
465// This represents a single flag, including its name, description,
466// default value, and current value. Mostly this serves as a
467// struct, though it also knows how to register itself.
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000468// All CommandLineFlags are owned by a (exactly one)
469// FlagRegistry. If you wish to modify fields in this class, you
470// should acquire the FlagRegistry lock for the registry that owns
471// this flag.
Craig Silversteinb9f23482007-03-22 00:15:41 +0000472// --------------------------------------------------------------------
473
474class CommandLineFlag {
475 public:
476 // Note: we take over memory-ownership of current_val and default_val.
477 CommandLineFlag(const char* name, const char* help, const char* filename,
478 FlagValue* current_val, FlagValue* default_val);
479 ~CommandLineFlag();
480
481 const char* name() const { return name_; }
482 const char* help() const { return help_; }
483 const char* filename() const { return file_; }
484 const char* CleanFileName() const; // nixes irrelevant prefix such as homedir
485 string current_value() const { return current_->ToString(); }
486 string default_value() const { return defvalue_->ToString(); }
487 const char* type_name() const { return defvalue_->TypeName(); }
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000488 ValidateFnProto validate_function() const { return validate_fn_proto_; }
Craig Silverstein17a627a2011-11-03 23:18:00 +0000489 const void* flag_ptr() const { return current_->value_buffer_; }
Craig Silversteinb9f23482007-03-22 00:15:41 +0000490
Craig Silverstein290da382007-03-28 21:54:07 +0000491 void FillCommandLineFlagInfo(struct CommandLineFlagInfo* result);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000492
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000493 // If validate_fn_proto_ is non-NULL, calls it on value, returns result.
494 bool Validate(const FlagValue& value) const;
495 bool ValidateCurrent() const { return Validate(*current_); }
496
Craig Silversteinb9f23482007-03-22 00:15:41 +0000497 private:
Craig Silverstein67914682008-08-21 00:50:59 +0000498 // for SetFlagLocked() and setting flags_by_ptr_
499 friend class FlagRegistry;
Andreas Schuh392eb672013-04-21 03:05:35 +0100500 friend class GFLAGS_NAMESPACE::FlagSaverImpl; // for cloning the values
Craig Silverstein67914682008-08-21 00:50:59 +0000501 // set validate_fn
502 friend bool AddFlagValidator(const void*, ValidateFnProto);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000503
504 // This copies all the non-const members: modified, processed, defvalue, etc.
505 void CopyFrom(const CommandLineFlag& src);
506
507 void UpdateModifiedBit();
508
509 const char* const name_; // Flag name
510 const char* const help_; // Help message
511 const char* const file_; // Which file did this come from?
512 bool modified_; // Set after default assignment?
513 FlagValue* defvalue_; // Default value for flag
514 FlagValue* current_; // Current value for flag
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000515 // This is a casted, 'generic' version of validate_fn, which actually
516 // takes a flag-value as an arg (void (*validate_fn)(bool), say).
517 // When we pass this to current_->Validate(), it will cast it back to
518 // the proper type. This may be NULL to mean we have no validate_fn.
519 ValidateFnProto validate_fn_proto_;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000520
521 CommandLineFlag(const CommandLineFlag&); // no copying!
522 void operator=(const CommandLineFlag&);
523};
524
525CommandLineFlag::CommandLineFlag(const char* name, const char* help,
Craig Silversteinc23c6c62011-11-03 23:25:32 +0000526 const char* filename,
Craig Silversteinb9f23482007-03-22 00:15:41 +0000527 FlagValue* current_val, FlagValue* default_val)
Craig Silversteinc23c6c62011-11-03 23:25:32 +0000528 : name_(name), help_(help), file_(filename), modified_(false),
529 defvalue_(default_val), current_(current_val), validate_fn_proto_(NULL) {
Craig Silversteinb9f23482007-03-22 00:15:41 +0000530}
531
532CommandLineFlag::~CommandLineFlag() {
533 delete current_;
534 delete defvalue_;
535}
536
537const char* CommandLineFlag::CleanFileName() const {
538 // Compute top-level directory & file that this appears in
Craig Silversteineb208392007-08-15 19:44:54 +0000539 // search full path backwards.
Craig Silverstein83911c12008-03-27 20:11:07 +0000540 // Stop going backwards at kRootDir; and skip by the first slash.
541 static const char kRootDir[] = ""; // can set this to root directory,
Craig Silversteinb9f23482007-03-22 00:15:41 +0000542
Craig Silverstein83911c12008-03-27 20:11:07 +0000543 if (sizeof(kRootDir)-1 == 0) // no prefix to strip
Craig Silversteinb9f23482007-03-22 00:15:41 +0000544 return filename();
545
546 const char* clean_name = filename() + strlen(filename()) - 1;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000547 while ( clean_name > filename() ) {
548 if (*clean_name == PATH_SEPARATOR) {
Craig Silverstein83911c12008-03-27 20:11:07 +0000549 if (strncmp(clean_name, kRootDir, sizeof(kRootDir)-1) == 0) {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000550 clean_name += sizeof(kRootDir)-1; // past root-dir
Craig Silversteinb9f23482007-03-22 00:15:41 +0000551 break;
552 }
553 }
554 --clean_name;
555 }
556 while ( *clean_name == PATH_SEPARATOR ) ++clean_name; // Skip any slashes
557 return clean_name;
558}
559
560void CommandLineFlag::FillCommandLineFlagInfo(
Craig Silverstein290da382007-03-28 21:54:07 +0000561 CommandLineFlagInfo* result) {
Craig Silversteinb9f23482007-03-22 00:15:41 +0000562 result->name = name();
563 result->type = type_name();
564 result->description = help();
565 result->current_value = current_value();
566 result->default_value = default_value();
567 result->filename = CleanFileName();
Craig Silverstein290da382007-03-28 21:54:07 +0000568 UpdateModifiedBit();
569 result->is_default = !modified_;
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000570 result->has_validator_fn = validate_function() != NULL;
Craig Silverstein17a627a2011-11-03 23:18:00 +0000571 result->flag_ptr = flag_ptr();
Craig Silversteinb9f23482007-03-22 00:15:41 +0000572}
573
574void CommandLineFlag::UpdateModifiedBit() {
575 // Update the "modified" bit in case somebody bypassed the
576 // Flags API and wrote directly through the FLAGS_name variable.
577 if (!modified_ && !current_->Equal(*defvalue_)) {
578 modified_ = true;
579 }
580}
581
582void CommandLineFlag::CopyFrom(const CommandLineFlag& src) {
583 // Note we only copy the non-const members; others are fixed at construct time
Craig Silverstein67914682008-08-21 00:50:59 +0000584 if (modified_ != src.modified_) modified_ = src.modified_;
585 if (!current_->Equal(*src.current_)) current_->CopyFrom(*src.current_);
586 if (!defvalue_->Equal(*src.defvalue_)) defvalue_->CopyFrom(*src.defvalue_);
587 if (validate_fn_proto_ != src.validate_fn_proto_)
588 validate_fn_proto_ = src.validate_fn_proto_;
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000589}
590
591bool CommandLineFlag::Validate(const FlagValue& value) const {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000592
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000593 if (validate_function() == NULL)
594 return true;
595 else
596 return value.Validate(name(), validate_function());
Craig Silversteinb9f23482007-03-22 00:15:41 +0000597}
598
599
600// --------------------------------------------------------------------
601// FlagRegistry
602// A FlagRegistry singleton object holds all flag objects indexed
603// by their names so that if you know a flag's name (as a C
604// string), you can access or set it. If the function is named
605// FooLocked(), you must own the registry lock before calling
606// the function; otherwise, you should *not* hold the lock, and
607// the function will acquire it itself if needed.
608// --------------------------------------------------------------------
609
610struct StringCmp { // Used by the FlagRegistry map class to compare char*'s
611 bool operator() (const char* s1, const char* s2) const {
612 return (strcmp(s1, s2) < 0);
613 }
614};
615
Craig Silverstein917f4e72011-07-29 04:26:49 +0000616
Craig Silversteinb9f23482007-03-22 00:15:41 +0000617class FlagRegistry {
618 public:
Craig Silverstein917f4e72011-07-29 04:26:49 +0000619 FlagRegistry() {
620 }
Craig Silverstein0baf4ab2011-01-14 21:58:28 +0000621 ~FlagRegistry() {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000622 // Not using STLDeleteElements as that resides in util and this
623 // class is base.
Craig Silverstein0baf4ab2011-01-14 21:58:28 +0000624 for (FlagMap::iterator p = flags_.begin(), e = flags_.end(); p != e; ++p) {
625 CommandLineFlag* flag = p->second;
626 delete flag;
627 }
628 }
629
630 static void DeleteGlobalRegistry() {
631 delete global_registry_;
632 global_registry_ = NULL;
633 }
Craig Silverstein67914682008-08-21 00:50:59 +0000634
Craig Silversteinb9f23482007-03-22 00:15:41 +0000635 // Store a flag in this registry. Takes ownership of the given pointer.
636 void RegisterFlag(CommandLineFlag* flag);
637
Craig Silverstein917f4e72011-07-29 04:26:49 +0000638 void Lock() { lock_.Lock(); }
639 void Unlock() { lock_.Unlock(); }
640
Craig Silversteinb9f23482007-03-22 00:15:41 +0000641 // Returns the flag object for the specified name, or NULL if not found.
642 CommandLineFlag* FindFlagLocked(const char* name);
643
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000644 // Returns the flag object whose current-value is stored at flag_ptr.
645 // That is, for whom current_->value_buffer_ == flag_ptr
646 CommandLineFlag* FindFlagViaPtrLocked(const void* flag_ptr);
647
Craig Silversteinb9f23482007-03-22 00:15:41 +0000648 // A fancier form of FindFlag that works correctly if name is of the
649 // form flag=value. In that case, we set key to point to flag, and
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000650 // modify v to point to the value (if present), and return the flag
651 // with the given name. If the flag does not exist, returns NULL
652 // and sets error_message.
Craig Silversteinb9f23482007-03-22 00:15:41 +0000653 CommandLineFlag* SplitArgumentLocked(const char* argument,
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000654 string* key, const char** v,
655 string* error_message);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000656
657 // Set the value of a flag. If the flag was successfully set to
658 // value, set msg to indicate the new flag-value, and return true.
659 // Otherwise, set msg to indicate the error, leave flag unchanged,
660 // and return false. msg can be NULL.
661 bool SetFlagLocked(CommandLineFlag* flag, const char* value,
662 FlagSettingMode set_mode, string* msg);
663
664 static FlagRegistry* GlobalRegistry(); // returns a singleton registry
665
666 private:
Andreas Schuh392eb672013-04-21 03:05:35 +0100667 friend class GFLAGS_NAMESPACE::FlagSaverImpl; // reads all the flags in order to copy them
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000668 friend class CommandLineFlagParser; // for ValidateAllFlags
Andreas Schuh392eb672013-04-21 03:05:35 +0100669 friend void GFLAGS_NAMESPACE::GetAllFlags(vector<CommandLineFlagInfo>*);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000670
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000671 // The map from name to flag, for FindFlagLocked().
Craig Silversteinb9f23482007-03-22 00:15:41 +0000672 typedef map<const char*, CommandLineFlag*, StringCmp> FlagMap;
673 typedef FlagMap::iterator FlagIterator;
674 typedef FlagMap::const_iterator FlagConstIterator;
675 FlagMap flags_;
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000676
677 // The map from current-value pointer to flag, fo FindFlagViaPtrLocked().
678 typedef map<const void*, CommandLineFlag*> FlagPtrMap;
679 FlagPtrMap flags_by_ptr_;
680
Craig Silversteinb9f23482007-03-22 00:15:41 +0000681 static FlagRegistry* global_registry_; // a singleton registry
Craig Silverstein917f4e72011-07-29 04:26:49 +0000682
683 Mutex lock_;
684 static Mutex global_registry_lock_;
685
686 static void InitGlobalRegistry();
Craig Silversteinb9f23482007-03-22 00:15:41 +0000687
688 // Disallow
689 FlagRegistry(const FlagRegistry&);
690 FlagRegistry& operator=(const FlagRegistry&);
691};
692
Craig Silverstein917f4e72011-07-29 04:26:49 +0000693class FlagRegistryLock {
694 public:
695 explicit FlagRegistryLock(FlagRegistry* fr) : fr_(fr) { fr_->Lock(); }
696 ~FlagRegistryLock() { fr_->Unlock(); }
697 private:
698 FlagRegistry *const fr_;
699};
Craig Silverstein67914682008-08-21 00:50:59 +0000700
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000701
Craig Silversteinb9f23482007-03-22 00:15:41 +0000702void FlagRegistry::RegisterFlag(CommandLineFlag* flag) {
703 Lock();
704 pair<FlagIterator, bool> ins =
705 flags_.insert(pair<const char*, CommandLineFlag*>(flag->name(), flag));
706 if (ins.second == false) { // means the name was already in the map
707 if (strcmp(ins.first->second->filename(), flag->filename()) != 0) {
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000708 ReportError(DIE, "ERROR: flag '%s' was defined more than once "
709 "(in files '%s' and '%s').\n",
710 flag->name(),
711 ins.first->second->filename(),
712 flag->filename());
Craig Silversteinb9f23482007-03-22 00:15:41 +0000713 } else {
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000714 ReportError(DIE, "ERROR: something wrong with flag '%s' in file '%s'. "
715 "One possibility: file '%s' is being linked both statically "
716 "and dynamically into this executable.\n",
717 flag->name(),
718 flag->filename(), flag->filename());
Craig Silversteinb9f23482007-03-22 00:15:41 +0000719 }
Craig Silversteinb9f23482007-03-22 00:15:41 +0000720 }
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000721 // Also add to the flags_by_ptr_ map.
722 flags_by_ptr_[flag->current_->value_buffer_] = flag;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000723 Unlock();
724}
725
726CommandLineFlag* FlagRegistry::FindFlagLocked(const char* name) {
727 FlagConstIterator i = flags_.find(name);
728 if (i == flags_.end()) {
729 return NULL;
730 } else {
731 return i->second;
732 }
733}
734
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000735CommandLineFlag* FlagRegistry::FindFlagViaPtrLocked(const void* flag_ptr) {
736 FlagPtrMap::const_iterator i = flags_by_ptr_.find(flag_ptr);
737 if (i == flags_by_ptr_.end()) {
738 return NULL;
739 } else {
740 return i->second;
741 }
742}
743
Craig Silversteinb9f23482007-03-22 00:15:41 +0000744CommandLineFlag* FlagRegistry::SplitArgumentLocked(const char* arg,
745 string* key,
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000746 const char** v,
747 string* error_message) {
Craig Silversteinb9f23482007-03-22 00:15:41 +0000748 // Find the flag object for this option
749 const char* flag_name;
750 const char* value = strchr(arg, '=');
751 if (value == NULL) {
752 key->assign(arg);
753 *v = NULL;
754 } else {
755 // Strip out the "=value" portion from arg
756 key->assign(arg, value-arg);
757 *v = ++value; // advance past the '='
758 }
759 flag_name = key->c_str();
760
761 CommandLineFlag* flag = FindFlagLocked(flag_name);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000762
763 if (flag == NULL) {
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000764 // If we can't find the flag-name, then we should return an error.
765 // The one exception is if 1) the flag-name is 'nox', 2) there
766 // exists a flag named 'x', and 3) 'x' is a boolean flag.
767 // In that case, we want to return flag 'x'.
768 if (!(flag_name[0] == 'n' && flag_name[1] == 'o')) {
769 // flag-name is not 'nox', so we're not in the exception case.
Craig Silverstein917f4e72011-07-29 04:26:49 +0000770 *error_message = StringPrintf("%sunknown command line flag '%s'\n",
771 kError, key->c_str());
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000772 return NULL;
773 }
774 flag = FindFlagLocked(flag_name+2);
775 if (flag == NULL) {
776 // No flag named 'x' exists, so we're not in the exception case.
Craig Silverstein917f4e72011-07-29 04:26:49 +0000777 *error_message = StringPrintf("%sunknown command line flag '%s'\n",
778 kError, key->c_str());
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000779 return NULL;
780 }
781 if (strcmp(flag->type_name(), "bool") != 0) {
782 // 'x' exists but is not boolean, so we're not in the exception case.
Craig Silverstein917f4e72011-07-29 04:26:49 +0000783 *error_message = StringPrintf(
784 "%sboolean value (%s) specified for %s command line flag\n",
785 kError, key->c_str(), flag->type_name());
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000786 return NULL;
787 }
788 // We're in the exception case!
789 // Make up a fake value to replace the "no" we stripped out
790 key->assign(flag_name+2); // the name without the "no"
791 *v = "0";
Craig Silversteinb9f23482007-03-22 00:15:41 +0000792 }
793
794 // Assign a value if this is a boolean flag
795 if (*v == NULL && strcmp(flag->type_name(), "bool") == 0) {
796 *v = "1"; // the --nox case was already handled, so this is the --x case
797 }
798
799 return flag;
800}
801
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000802bool TryParseLocked(const CommandLineFlag* flag, FlagValue* flag_value,
803 const char* value, string* msg) {
804 // Use tenative_value, not flag_value, until we know value is valid.
805 FlagValue* tentative_value = flag_value->New();
806 if (!tentative_value->ParseFrom(value)) {
807 if (msg) {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000808 StringAppendF(msg,
809 "%sillegal value '%s' specified for %s flag '%s'\n",
810 kError, value,
811 flag->type_name(), flag->name());
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000812 }
813 delete tentative_value;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000814 return false;
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000815 } else if (!flag->Validate(*tentative_value)) {
Craig Silverstein67914682008-08-21 00:50:59 +0000816 if (msg) {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000817 StringAppendF(msg,
818 "%sfailed validation of new value '%s' for flag '%s'\n",
819 kError, tentative_value->ToString().c_str(),
820 flag->name());
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000821 }
822 delete tentative_value;
823 return false;
824 } else {
825 flag_value->CopyFrom(*tentative_value);
826 if (msg) {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000827 StringAppendF(msg, "%s set to %s\n",
828 flag->name(), flag_value->ToString().c_str());
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000829 }
830 delete tentative_value;
831 return true;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000832 }
833}
834
835bool FlagRegistry::SetFlagLocked(CommandLineFlag* flag,
836 const char* value,
837 FlagSettingMode set_mode,
838 string* msg) {
839 flag->UpdateModifiedBit();
840 switch (set_mode) {
841 case SET_FLAGS_VALUE: {
842 // set or modify the flag's value
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000843 if (!TryParseLocked(flag, flag->current_, value, msg))
Craig Silversteinb9f23482007-03-22 00:15:41 +0000844 return false;
845 flag->modified_ = true;
846 break;
847 }
848 case SET_FLAG_IF_DEFAULT: {
849 // set the flag's value, but only if it hasn't been set by someone else
850 if (!flag->modified_) {
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000851 if (!TryParseLocked(flag, flag->current_, value, msg))
Craig Silversteinb9f23482007-03-22 00:15:41 +0000852 return false;
853 flag->modified_ = true;
854 } else {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000855 *msg = StringPrintf("%s set to %s",
856 flag->name(), flag->current_value().c_str());
Craig Silversteinb9f23482007-03-22 00:15:41 +0000857 }
858 break;
859 }
860 case SET_FLAGS_DEFAULT: {
861 // modify the flag's default-value
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000862 if (!TryParseLocked(flag, flag->defvalue_, value, msg))
Craig Silversteinb9f23482007-03-22 00:15:41 +0000863 return false;
864 if (!flag->modified_) {
865 // Need to set both defvalue *and* current, in this case
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000866 TryParseLocked(flag, flag->current_, value, NULL);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000867 }
868 break;
869 }
870 default: {
Craig Silverstein690172b2007-04-20 21:16:33 +0000871 // unknown set_mode
Craig Silverstein67914682008-08-21 00:50:59 +0000872 assert(false);
873 return false;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000874 }
875 }
876
877 return true;
878}
879
Craig Silverstein917f4e72011-07-29 04:26:49 +0000880// Get the singleton FlagRegistry object
881FlagRegistry* FlagRegistry::global_registry_ = NULL;
882Mutex FlagRegistry::global_registry_lock_(Mutex::LINKER_INITIALIZED);
883
884FlagRegistry* FlagRegistry::GlobalRegistry() {
885 MutexLock acquire_lock(&global_registry_lock_);
886 if (!global_registry_) {
887 global_registry_ = new FlagRegistry;
888 }
889 return global_registry_;
890}
Craig Silversteinb9f23482007-03-22 00:15:41 +0000891
Craig Silversteinb9f23482007-03-22 00:15:41 +0000892// --------------------------------------------------------------------
893// CommandLineFlagParser
894// Parsing is done in two stages. In the first, we go through
895// argv. For every flag-like arg we can make sense of, we parse
896// it and set the appropriate FLAGS_* variable. For every flag-
897// like arg we can't make sense of, we store it in a vector,
898// along with an explanation of the trouble. In stage 2, we
899// handle the 'reporting' flags like --help and --mpm_version.
900// (This is via a call to HandleCommandLineHelpFlags(), in
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000901// gflags_reporting.cc.)
Craig Silversteinb9f23482007-03-22 00:15:41 +0000902// An optional stage 3 prints out the error messages.
903// This is a bit of a simplification. For instance, --flagfile
904// is handled as soon as it's seen in stage 1, not in stage 2.
905// --------------------------------------------------------------------
906
907class CommandLineFlagParser {
908 public:
909 // The argument is the flag-registry to register the parsed flags in
910 explicit CommandLineFlagParser(FlagRegistry* reg) : registry_(reg) {}
911 ~CommandLineFlagParser() {}
912
913 // Stage 1: Every time this is called, it reads all flags in argv.
914 // However, it ignores all flags that have been successfully set
915 // before. Typically this is only called once, so this 'reparsing'
916 // behavior isn't important. It can be useful when trying to
917 // reparse after loading a dll, though.
918 uint32 ParseNewCommandLineFlags(int* argc, char*** argv, bool remove_flags);
919
920 // Stage 2: print reporting info and exit, if requested.
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000921 // In gflags_reporting.cc:HandleCommandLineHelpFlags().
Craig Silversteinb9f23482007-03-22 00:15:41 +0000922
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000923 // Stage 3: validate all the commandline flags that have validators
924 // registered.
925 void ValidateAllFlags();
926
927 // Stage 4: report any errors and return true if any were found.
Craig Silversteinb9f23482007-03-22 00:15:41 +0000928 bool ReportErrors();
929
930 // Set a particular command line option. "newval" is a string
931 // describing the new value that the option has been set to. If
932 // option_name does not specify a valid option name, or value is not
933 // a valid value for option_name, newval is empty. Does recursive
934 // processing for --flagfile and --fromenv. Returns the new value
935 // if everything went ok, or empty-string if not. (Actually, the
936 // return-string could hold many flag/value pairs due to --flagfile.)
937 // NB: Must have called registry_->Lock() before calling this function.
938 string ProcessSingleOptionLocked(CommandLineFlag* flag,
939 const char* value,
940 FlagSettingMode set_mode);
941
942 // Set a whole batch of command line options as specified by contentdata,
943 // which is in flagfile format (and probably has been read from a flagfile).
944 // Returns the new value if everything went ok, or empty-string if
945 // not. (Actually, the return-string could hold many flag/value
946 // pairs due to --flagfile.)
947 // NB: Must have called registry_->Lock() before calling this function.
948 string ProcessOptionsFromStringLocked(const string& contentdata,
949 FlagSettingMode set_mode);
950
951 // These are the 'recursive' flags, defined at the top of this file.
952 // Whenever we see these flags on the commandline, we must take action.
953 // These are called by ProcessSingleOptionLocked and, similarly, return
954 // new values if everything went ok, or the empty-string if not.
955 string ProcessFlagfileLocked(const string& flagval, FlagSettingMode set_mode);
Craig Silverstein67914682008-08-21 00:50:59 +0000956 // diff fromenv/tryfromenv
Craig Silversteinb9f23482007-03-22 00:15:41 +0000957 string ProcessFromenvLocked(const string& flagval, FlagSettingMode set_mode,
Craig Silverstein67914682008-08-21 00:50:59 +0000958 bool errors_are_fatal);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000959
960 private:
961 FlagRegistry* const registry_;
Craig Silverstein67914682008-08-21 00:50:59 +0000962 map<string, string> error_flags_; // map from name to error message
Craig Silversteinb9f23482007-03-22 00:15:41 +0000963 // This could be a set<string>, but we reuse the map to minimize the .o size
Craig Silverstein67914682008-08-21 00:50:59 +0000964 map<string, string> undefined_names_; // --[flag] name was not registered
Craig Silversteinb9f23482007-03-22 00:15:41 +0000965};
966
967
968// Parse a list of (comma-separated) flags.
969static void ParseFlagList(const char* value, vector<string>* flags) {
970 for (const char *p = value; p && *p; value = p) {
971 p = strchr(value, ',');
Craig Silverstein917f4e72011-07-29 04:26:49 +0000972 size_t len;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000973 if (p) {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000974 len = p - value;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000975 p++;
976 } else {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000977 len = strlen(value);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000978 }
979
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000980 if (len == 0)
981 ReportError(DIE, "ERROR: empty flaglist entry\n");
982 if (value[0] == '-')
983 ReportError(DIE, "ERROR: flag \"%*s\" begins with '-'\n", len, value);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000984
985 flags->push_back(string(value, len));
986 }
987}
988
989// Snarf an entire file into a C++ string. This is just so that we
990// can do all the I/O in one place and not worry about it everywhere.
991// Plus, it's convenient to have the whole file contents at hand.
992// Adds a newline at the end of the file.
Craig Silverstein917f4e72011-07-29 04:26:49 +0000993#define PFATAL(s) do { perror(s); gflags_exitfunc(1); } while (0)
Craig Silversteinb9f23482007-03-22 00:15:41 +0000994
995static string ReadFileIntoString(const char* filename) {
Craig Silverstein67914682008-08-21 00:50:59 +0000996 const int kBufSize = 8092;
997 char buffer[kBufSize];
Craig Silversteinb9f23482007-03-22 00:15:41 +0000998 string s;
999 FILE* fp = fopen(filename, "r");
1000 if (!fp) PFATAL(filename);
Craig Silverstein67914682008-08-21 00:50:59 +00001001 size_t n;
1002 while ( (n=fread(buffer, 1, kBufSize, fp)) > 0 ) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001003 if (ferror(fp)) PFATAL(filename);
1004 s.append(buffer, n);
1005 }
1006 fclose(fp);
1007 return s;
1008}
1009
1010uint32 CommandLineFlagParser::ParseNewCommandLineFlags(int* argc, char*** argv,
1011 bool remove_flags) {
1012 const char *program_name = strrchr((*argv)[0], PATH_SEPARATOR); // nix path
1013 program_name = (program_name == NULL ? (*argv)[0] : program_name+1);
1014
1015 int first_nonopt = *argc; // for non-options moved to the end
1016
1017 registry_->Lock();
1018 for (int i = 1; i < first_nonopt; i++) {
1019 char* arg = (*argv)[i];
1020
1021 // Like getopt(), we permute non-option flags to be at the end.
Craig Silverstein83911c12008-03-27 20:11:07 +00001022 if (arg[0] != '-' || // must be a program argument
1023 (arg[0] == '-' && arg[1] == '\0')) { // "-" is an argument, not a flag
Craig Silversteinb9f23482007-03-22 00:15:41 +00001024 memmove((*argv) + i, (*argv) + i+1, (*argc - (i+1)) * sizeof((*argv)[i]));
1025 (*argv)[*argc-1] = arg; // we go last
1026 first_nonopt--; // we've been pushed onto the stack
1027 i--; // to undo the i++ in the loop
1028 continue;
1029 }
1030
1031 if (arg[0] == '-') arg++; // allow leading '-'
1032 if (arg[0] == '-') arg++; // or leading '--'
1033
Craig Silverstein83911c12008-03-27 20:11:07 +00001034 // -- alone means what it does for GNU: stop options parsing
Craig Silversteinb9f23482007-03-22 00:15:41 +00001035 if (*arg == '\0') {
1036 first_nonopt = i+1;
1037 break;
1038 }
1039
1040 // Find the flag object for this option
1041 string key;
1042 const char* value;
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001043 string error_message;
1044 CommandLineFlag* flag = registry_->SplitArgumentLocked(arg, &key, &value,
1045 &error_message);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001046 if (flag == NULL) {
1047 undefined_names_[key] = ""; // value isn't actually used
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001048 error_flags_[key] = error_message;
Craig Silversteinb9f23482007-03-22 00:15:41 +00001049 continue;
1050 }
1051
1052 if (value == NULL) {
1053 // Boolean options are always assigned a value by SplitArgumentLocked()
1054 assert(strcmp(flag->type_name(), "bool") != 0);
1055 if (i+1 >= first_nonopt) {
1056 // This flag needs a value, but there is nothing available
Craig Silverstein67914682008-08-21 00:50:59 +00001057 error_flags_[key] = (string(kError) + "flag '" + (*argv)[i] + "'"
1058 + " is missing its argument");
1059 if (flag->help() && flag->help()[0] > '\001') {
1060 // Be useful in case we have a non-stripped description.
1061 error_flags_[key] += string("; flag description: ") + flag->help();
1062 }
1063 error_flags_[key] += "\n";
Craig Silversteinb9f23482007-03-22 00:15:41 +00001064 break; // we treat this as an unrecoverable error
1065 } else {
1066 value = (*argv)[++i]; // read next arg for value
Craig Silverstein688ea022009-09-11 00:15:50 +00001067
1068 // Heuristic to detect the case where someone treats a string arg
1069 // like a bool:
1070 // --my_string_var --foo=bar
1071 // We look for a flag of string type, whose value begins with a
1072 // dash, and where the flag-name and value are separated by a
1073 // space rather than an '='.
1074 // To avoid false positives, we also require the word "true"
1075 // or "false" in the help string. Without this, a valid usage
1076 // "-lat -30.5" would trigger the warning. The common cases we
1077 // want to solve talk about true and false as values.
1078 if (value[0] == '-'
1079 && strcmp(flag->type_name(), "string") == 0
1080 && (strstr(flag->help(), "true")
1081 || strstr(flag->help(), "false"))) {
Craig Silverstein917f4e72011-07-29 04:26:49 +00001082 LOG(WARNING) << "Did you really mean to set flag '"
1083 << flag->name() << "' to the value '"
1084 << value << "'?";
Craig Silverstein688ea022009-09-11 00:15:50 +00001085 }
Craig Silversteinb9f23482007-03-22 00:15:41 +00001086 }
1087 }
1088
1089 // TODO(csilvers): only set a flag if we hadn't set it before here
1090 ProcessSingleOptionLocked(flag, value, SET_FLAGS_VALUE);
1091 }
1092 registry_->Unlock();
1093
1094 if (remove_flags) { // Fix up argc and argv by removing command line flags
1095 (*argv)[first_nonopt-1] = (*argv)[0];
1096 (*argv) += (first_nonopt-1);
1097 (*argc) -= (first_nonopt-1);
1098 first_nonopt = 1; // because we still don't count argv[0]
1099 }
1100
1101 logging_is_probably_set_up = true; // because we've parsed --logdir, etc.
1102
1103 return first_nonopt;
1104}
1105
1106string CommandLineFlagParser::ProcessFlagfileLocked(const string& flagval,
1107 FlagSettingMode set_mode) {
1108 if (flagval.empty())
1109 return "";
1110
1111 string msg;
1112 vector<string> filename_list;
1113 ParseFlagList(flagval.c_str(), &filename_list); // take a list of filenames
Craig Silverstein67914682008-08-21 00:50:59 +00001114 for (size_t i = 0; i < filename_list.size(); ++i) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001115 const char* file = filename_list[i].c_str();
1116 msg += ProcessOptionsFromStringLocked(ReadFileIntoString(file), set_mode);
1117 }
1118 return msg;
1119}
1120
1121string CommandLineFlagParser::ProcessFromenvLocked(const string& flagval,
1122 FlagSettingMode set_mode,
1123 bool errors_are_fatal) {
1124 if (flagval.empty())
1125 return "";
1126
1127 string msg;
1128 vector<string> flaglist;
1129 ParseFlagList(flagval.c_str(), &flaglist);
1130
Craig Silverstein67914682008-08-21 00:50:59 +00001131 for (size_t i = 0; i < flaglist.size(); ++i) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001132 const char* flagname = flaglist[i].c_str();
1133 CommandLineFlag* flag = registry_->FindFlagLocked(flagname);
1134 if (flag == NULL) {
Craig Silverstein917f4e72011-07-29 04:26:49 +00001135 error_flags_[flagname] =
1136 StringPrintf("%sunknown command line flag '%s' "
1137 "(via --fromenv or --tryfromenv)\n",
1138 kError, flagname);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001139 undefined_names_[flagname] = "";
1140 continue;
1141 }
1142
1143 const string envname = string("FLAGS_") + string(flagname);
1144 const char* envval = getenv(envname.c_str());
1145 if (!envval) {
1146 if (errors_are_fatal) {
1147 error_flags_[flagname] = (string(kError) + envname +
1148 " not found in environment\n");
1149 }
1150 continue;
1151 }
1152
1153 // Avoid infinite recursion.
1154 if ((strcmp(envval, "fromenv") == 0) ||
1155 (strcmp(envval, "tryfromenv") == 0)) {
Craig Silverstein917f4e72011-07-29 04:26:49 +00001156 error_flags_[flagname] =
1157 StringPrintf("%sinfinite recursion on environment flag '%s'\n",
1158 kError, envval);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001159 continue;
1160 }
1161
1162 msg += ProcessSingleOptionLocked(flag, envval, set_mode);
1163 }
1164 return msg;
1165}
1166
1167string CommandLineFlagParser::ProcessSingleOptionLocked(
1168 CommandLineFlag* flag, const char* value, FlagSettingMode set_mode) {
1169 string msg;
1170 if (value && !registry_->SetFlagLocked(flag, value, set_mode, &msg)) {
1171 error_flags_[flag->name()] = msg;
1172 return "";
1173 }
1174
1175 // The recursive flags, --flagfile and --fromenv and --tryfromenv,
1176 // must be dealt with as soon as they're seen. They will emit
1177 // messages of their own.
1178 if (strcmp(flag->name(), "flagfile") == 0) {
1179 msg += ProcessFlagfileLocked(FLAGS_flagfile, set_mode);
1180
1181 } else if (strcmp(flag->name(), "fromenv") == 0) {
1182 // last arg indicates envval-not-found is fatal (unlike in --tryfromenv)
1183 msg += ProcessFromenvLocked(FLAGS_fromenv, set_mode, true);
1184
1185 } else if (strcmp(flag->name(), "tryfromenv") == 0) {
1186 msg += ProcessFromenvLocked(FLAGS_tryfromenv, set_mode, false);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001187 }
1188
1189 return msg;
1190}
1191
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001192void CommandLineFlagParser::ValidateAllFlags() {
1193 FlagRegistryLock frl(registry_);
1194 for (FlagRegistry::FlagConstIterator i = registry_->flags_.begin();
1195 i != registry_->flags_.end(); ++i) {
1196 if (!i->second->ValidateCurrent()) {
1197 // only set a message if one isn't already there. (If there's
1198 // an error message, our job is done, even if it's not exactly
1199 // the same error.)
1200 if (error_flags_[i->second->name()].empty())
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001201 error_flags_[i->second->name()] =
1202 string(kError) + "--" + i->second->name() +
1203 " must be set on the commandline"
1204 " (default value fails validation)\n";
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001205 }
1206 }
1207}
1208
Craig Silversteinb9f23482007-03-22 00:15:41 +00001209bool CommandLineFlagParser::ReportErrors() {
1210 // error_flags_ indicates errors we saw while parsing.
1211 // But we ignore undefined-names if ok'ed by --undef_ok
1212 if (!FLAGS_undefok.empty()) {
1213 vector<string> flaglist;
1214 ParseFlagList(FLAGS_undefok.c_str(), &flaglist);
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001215 for (size_t i = 0; i < flaglist.size(); ++i) {
1216 // We also deal with --no<flag>, in case the flagname was boolean
1217 const string no_version = string("no") + flaglist[i];
Craig Silversteinb9f23482007-03-22 00:15:41 +00001218 if (undefined_names_.find(flaglist[i]) != undefined_names_.end()) {
1219 error_flags_[flaglist[i]] = ""; // clear the error message
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001220 } else if (undefined_names_.find(no_version) != undefined_names_.end()) {
1221 error_flags_[no_version] = "";
Craig Silversteinb9f23482007-03-22 00:15:41 +00001222 }
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001223 }
Craig Silversteinb9f23482007-03-22 00:15:41 +00001224 }
1225 // Likewise, if they decided to allow reparsing, all undefined-names
1226 // are ok; we just silently ignore them now, and hope that a future
1227 // parse will pick them up somehow.
1228 if (allow_command_line_reparsing) {
Craig Silverstein67914682008-08-21 00:50:59 +00001229 for (map<string, string>::const_iterator it = undefined_names_.begin();
Craig Silversteinb9f23482007-03-22 00:15:41 +00001230 it != undefined_names_.end(); ++it)
1231 error_flags_[it->first] = ""; // clear the error message
1232 }
1233
1234 bool found_error = false;
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001235 string error_message;
Craig Silverstein67914682008-08-21 00:50:59 +00001236 for (map<string, string>::const_iterator it = error_flags_.begin();
Craig Silversteinb9f23482007-03-22 00:15:41 +00001237 it != error_flags_.end(); ++it) {
1238 if (!it->second.empty()) {
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001239 error_message.append(it->second.data(), it->second.size());
Craig Silversteinb9f23482007-03-22 00:15:41 +00001240 found_error = true;
1241 }
1242 }
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001243 if (found_error)
1244 ReportError(DO_NOT_DIE, "%s", error_message.c_str());
Craig Silversteinb9f23482007-03-22 00:15:41 +00001245 return found_error;
1246}
1247
1248string CommandLineFlagParser::ProcessOptionsFromStringLocked(
1249 const string& contentdata, FlagSettingMode set_mode) {
1250 string retval;
1251 const char* flagfile_contents = contentdata.c_str();
1252 bool flags_are_relevant = true; // set to false when filenames don't match
1253 bool in_filename_section = false;
1254
1255 const char* line_end = flagfile_contents;
1256 // We read this file a line at a time.
1257 for (; line_end; flagfile_contents = line_end + 1) {
1258 while (*flagfile_contents && isspace(*flagfile_contents))
1259 ++flagfile_contents;
1260 line_end = strchr(flagfile_contents, '\n');
Craig Silverstein917f4e72011-07-29 04:26:49 +00001261 size_t len = line_end ? line_end - flagfile_contents
Craig Silverstein67914682008-08-21 00:50:59 +00001262 : strlen(flagfile_contents);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001263 string line(flagfile_contents, len);
1264
1265 // Each line can be one of four things:
1266 // 1) A comment line -- we skip it
1267 // 2) An empty line -- we skip it
1268 // 3) A list of filenames -- starts a new filenames+flags section
1269 // 4) A --flag=value line -- apply if previous filenames match
1270 if (line.empty() || line[0] == '#') {
1271 // comment or empty line; just ignore
1272
1273 } else if (line[0] == '-') { // flag
1274 in_filename_section = false; // instead, it was a flag-line
1275 if (!flags_are_relevant) // skip this flag; applies to someone else
1276 continue;
1277
1278 const char* name_and_val = line.c_str() + 1; // skip the leading -
1279 if (*name_and_val == '-')
1280 name_and_val++; // skip second - too
1281 string key;
1282 const char* value;
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001283 string error_message;
Craig Silversteinb9f23482007-03-22 00:15:41 +00001284 CommandLineFlag* flag = registry_->SplitArgumentLocked(name_and_val,
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001285 &key, &value,
1286 &error_message);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001287 // By API, errors parsing flagfile lines are silently ignored.
1288 if (flag == NULL) {
1289 // "WARNING: flagname '" + key + "' not found\n"
1290 } else if (value == NULL) {
1291 // "WARNING: flagname '" + key + "' missing a value\n"
1292 } else {
1293 retval += ProcessSingleOptionLocked(flag, value, set_mode);
1294 }
1295
1296 } else { // a filename!
1297 if (!in_filename_section) { // start over: assume filenames don't match
1298 in_filename_section = true;
1299 flags_are_relevant = false;
1300 }
1301
1302 // Split the line up at spaces into glob-patterns
1303 const char* space = line.c_str(); // just has to be non-NULL
1304 for (const char* word = line.c_str(); *space; word = space+1) {
1305 if (flags_are_relevant) // we can stop as soon as we match
1306 break;
1307 space = strchr(word, ' ');
1308 if (space == NULL)
1309 space = word + strlen(word);
1310 const string glob(word, space - word);
1311 // We try matching both against the full argv0 and basename(argv0)
Craig Silverstein917f4e72011-07-29 04:26:49 +00001312 if (glob == ProgramInvocationName() // small optimization
1313 || glob == ProgramInvocationShortName()
Andreas Schuh392eb672013-04-21 03:05:35 +01001314#if HAVE_FNMATCH_H
Craig Silverstein917f4e72011-07-29 04:26:49 +00001315 || fnmatch(glob.c_str(),
1316 ProgramInvocationName(),
1317 FNM_PATHNAME) == 0
1318 || fnmatch(glob.c_str(),
1319 ProgramInvocationShortName(),
1320 FNM_PATHNAME) == 0
1321#endif
1322 ) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001323 flags_are_relevant = true;
1324 }
1325 }
1326 }
1327 }
1328 return retval;
1329}
1330
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001331// --------------------------------------------------------------------
1332// GetFromEnv()
1333// AddFlagValidator()
1334// These are helper functions for routines like BoolFromEnv() and
1335// RegisterFlagValidator, defined below. They're defined here so
1336// they can live in the unnamed namespace (which makes friendship
1337// declarations for these classes possible).
1338// --------------------------------------------------------------------
1339
1340template<typename T>
1341T GetFromEnv(const char *varname, const char* type, T dflt) {
1342 const char* const valstr = getenv(varname);
1343 if (!valstr)
1344 return dflt;
Craig Silverstein0baf4ab2011-01-14 21:58:28 +00001345 FlagValue ifv(new T, type, true);
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001346 if (!ifv.ParseFrom(valstr))
1347 ReportError(DIE, "ERROR: error parsing env variable '%s' with value '%s'\n",
1348 varname, valstr);
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001349 return OTHER_VALUE_AS(ifv, T);
1350}
1351
1352bool AddFlagValidator(const void* flag_ptr, ValidateFnProto validate_fn_proto) {
1353 // We want a lock around this routine, in case two threads try to
1354 // add a validator (hopefully the same one!) at once. We could use
1355 // our own thread, but we need to loook at the registry anyway, so
1356 // we just steal that one.
1357 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1358 FlagRegistryLock frl(registry);
1359 // First, find the flag whose current-flag storage is 'flag'.
1360 // This is the CommandLineFlag whose current_->value_buffer_ == flag
1361 CommandLineFlag* flag = registry->FindFlagViaPtrLocked(flag_ptr);
1362 if (!flag) {
Craig Silverstein917f4e72011-07-29 04:26:49 +00001363 LOG(WARNING) << "Ignoring RegisterValidateFunction() for flag pointer "
1364 << flag_ptr << ": no flag found at that address";
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001365 return false;
1366 } else if (validate_fn_proto == flag->validate_function()) {
1367 return true; // ok to register the same function over and over again
1368 } else if (validate_fn_proto != NULL && flag->validate_function() != NULL) {
Craig Silverstein917f4e72011-07-29 04:26:49 +00001369 LOG(WARNING) << "Ignoring RegisterValidateFunction() for flag '"
1370 << flag->name() << "': validate-fn already registered";
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001371 return false;
1372 } else {
1373 flag->validate_fn_proto_ = validate_fn_proto;
1374 return true;
1375 }
1376}
1377
1378} // end unnamed namespaces
1379
1380
1381// Now define the functions that are exported via the .h file
1382
1383// --------------------------------------------------------------------
1384// FlagRegisterer
1385// This class exists merely to have a global constructor (the
1386// kind that runs before main(), that goes an initializes each
1387// flag that's been declared. Note that it's very important we
1388// don't have a destructor that deletes flag_, because that would
1389// cause us to delete current_storage/defvalue_storage as well,
1390// which can cause a crash if anything tries to access the flag
1391// values in a global destructor.
1392// --------------------------------------------------------------------
1393
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001394FlagRegisterer::FlagRegisterer(const char* name, const char* type,
1395 const char* help, const char* filename,
Craig Silversteinc23c6c62011-11-03 23:25:32 +00001396 void* current_storage, void* defvalue_storage) {
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001397 if (help == NULL)
1398 help = "";
1399 // FlagValue expects the type-name to not include any namespace
1400 // components, so we get rid of those, if any.
1401 if (strchr(type, ':'))
1402 type = strrchr(type, ':') + 1;
Craig Silverstein0baf4ab2011-01-14 21:58:28 +00001403 FlagValue* current = new FlagValue(current_storage, type, false);
1404 FlagValue* defvalue = new FlagValue(defvalue_storage, type, false);
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001405 // Importantly, flag_ will never be deleted, so storage is always good.
1406 CommandLineFlag* flag = new CommandLineFlag(name, help, filename,
Craig Silversteinc23c6c62011-11-03 23:25:32 +00001407 current, defvalue);
1408 FlagRegistry::GlobalRegistry()->RegisterFlag(flag); // default registry
1409}
1410
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001411// --------------------------------------------------------------------
1412// GetAllFlags()
1413// The main way the FlagRegistry class exposes its data. This
1414// returns, as strings, all the info about all the flags in
1415// the main registry, sorted first by filename they are defined
1416// in, and then by flagname.
1417// --------------------------------------------------------------------
1418
1419struct FilenameFlagnameCmp {
1420 bool operator()(const CommandLineFlagInfo& a,
1421 const CommandLineFlagInfo& b) const {
1422 int cmp = strcmp(a.filename.c_str(), b.filename.c_str());
1423 if (cmp == 0)
1424 cmp = strcmp(a.name.c_str(), b.name.c_str()); // secondary sort key
1425 return cmp < 0;
1426 }
1427};
1428
1429void GetAllFlags(vector<CommandLineFlagInfo>* OUTPUT) {
1430 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1431 registry->Lock();
1432 for (FlagRegistry::FlagConstIterator i = registry->flags_.begin();
1433 i != registry->flags_.end(); ++i) {
1434 CommandLineFlagInfo fi;
1435 i->second->FillCommandLineFlagInfo(&fi);
1436 OUTPUT->push_back(fi);
1437 }
1438 registry->Unlock();
1439 // Now sort the flags, first by filename they occur in, then alphabetically
1440 sort(OUTPUT->begin(), OUTPUT->end(), FilenameFlagnameCmp());
1441}
1442
1443// --------------------------------------------------------------------
1444// SetArgv()
1445// GetArgvs()
1446// GetArgv()
1447// GetArgv0()
1448// ProgramInvocationName()
1449// ProgramInvocationShortName()
1450// SetUsageMessage()
1451// ProgramUsage()
1452// Functions to set and get argv. Typically the setter is called
1453// by ParseCommandLineFlags. Also can get the ProgramUsage string,
Craig Silverstein917f4e72011-07-29 04:26:49 +00001454// set by SetUsageMessage.
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001455// --------------------------------------------------------------------
1456
1457// These values are not protected by a Mutex because they are normally
1458// set only once during program startup.
1459static const char* argv0 = "UNKNOWN"; // just the program name
1460static const char* cmdline = ""; // the entire command-line
1461static vector<string> argvs;
1462static uint32 argv_sum = 0;
Craig Silverstein67914682008-08-21 00:50:59 +00001463static const char* program_usage = NULL;
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001464
1465void SetArgv(int argc, const char** argv) {
1466 static bool called_set_argv = false;
1467 if (called_set_argv) // we already have an argv for you
1468 return;
1469
1470 called_set_argv = true;
1471
1472 assert(argc > 0); // every program has at least a progname
1473 argv0 = strdup(argv[0]); // small memory leak, but fn only called once
1474 assert(argv0);
1475
Craig Silverstein67914682008-08-21 00:50:59 +00001476 string cmdline_string; // easier than doing strcats
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001477 for (int i = 0; i < argc; i++) {
Craig Silverstein67914682008-08-21 00:50:59 +00001478 if (i != 0) {
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001479 cmdline_string += " ";
Craig Silverstein67914682008-08-21 00:50:59 +00001480 }
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001481 cmdline_string += argv[i];
1482 argvs.push_back(argv[i]);
1483 }
1484 cmdline = strdup(cmdline_string.c_str()); // another small memory leak
1485 assert(cmdline);
1486
1487 // Compute a simple sum of all the chars in argv
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001488 for (const char* c = cmdline; *c; c++)
1489 argv_sum += *c;
1490}
1491
1492const vector<string>& GetArgvs() { return argvs; }
1493const char* GetArgv() { return cmdline; }
1494const char* GetArgv0() { return argv0; }
1495uint32 GetArgvSum() { return argv_sum; }
1496const char* ProgramInvocationName() { // like the GNU libc fn
1497 return GetArgv0();
1498}
1499const char* ProgramInvocationShortName() { // like the GNU libc fn
1500 const char* slash = strrchr(argv0, '/');
Andreas Schuh392eb672013-04-21 03:05:35 +01001501#ifdef WINDOWS
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001502 if (!slash) slash = strrchr(argv0, '\\');
1503#endif
1504 return slash ? slash + 1 : argv0;
1505}
1506
1507void SetUsageMessage(const string& usage) {
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001508 if (program_usage != NULL)
1509 ReportError(DIE, "ERROR: SetUsageMessage() called twice\n");
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001510 program_usage = strdup(usage.c_str()); // small memory leak
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001511}
1512
1513const char* ProgramUsage() {
Craig Silverstein67914682008-08-21 00:50:59 +00001514 if (program_usage) {
1515 return program_usage;
1516 }
1517 return "Warning: SetUsageMessage() never called";
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001518}
Craig Silversteinb9f23482007-03-22 00:15:41 +00001519
Craig Silverstein917f4e72011-07-29 04:26:49 +00001520// --------------------------------------------------------------------
1521// SetVersionString()
1522// VersionString()
1523// --------------------------------------------------------------------
1524
1525static const char* version_string = NULL;
1526
1527void SetVersionString(const string& version) {
1528 if (version_string != NULL)
1529 ReportError(DIE, "ERROR: SetVersionString() called twice\n");
1530 version_string = strdup(version.c_str()); // small memory leak
1531}
1532
Craig Silversteinb4bf72b2011-03-03 22:26:24 +00001533const char* VersionString() {
1534 return version_string ? version_string : "";
1535}
1536
Craig Silverstein917f4e72011-07-29 04:26:49 +00001537
Craig Silversteinb9f23482007-03-22 00:15:41 +00001538// --------------------------------------------------------------------
1539// GetCommandLineOption()
1540// GetCommandLineFlagInfo()
Craig Silverstein290da382007-03-28 21:54:07 +00001541// GetCommandLineFlagInfoOrDie()
Craig Silversteinb9f23482007-03-22 00:15:41 +00001542// SetCommandLineOption()
1543// SetCommandLineOptionWithMode()
1544// The programmatic way to set a flag's value, using a string
1545// for its name rather than the variable itself (that is,
1546// SetCommandLineOption("foo", x) rather than FLAGS_foo = x).
1547// There's also a bit more flexibility here due to the various
1548// set-modes, but typically these are used when you only have
1549// that flag's name as a string, perhaps at runtime.
1550// All of these work on the default, global registry.
1551// For GetCommandLineOption, return false if no such flag
1552// is known, true otherwise. We clear "value" if a suitable
Craig Silverstein690172b2007-04-20 21:16:33 +00001553// flag is found.
Craig Silversteinb9f23482007-03-22 00:15:41 +00001554// --------------------------------------------------------------------
1555
1556
Craig Silverstein690172b2007-04-20 21:16:33 +00001557bool GetCommandLineOption(const char* name, string* value) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001558 if (NULL == name)
1559 return false;
1560 assert(value);
1561
1562 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001563 FlagRegistryLock frl(registry);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001564 CommandLineFlag* flag = registry->FindFlagLocked(name);
1565 if (flag == NULL) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001566 return false;
1567 } else {
1568 *value = flag->current_value();
Craig Silversteinb9f23482007-03-22 00:15:41 +00001569 return true;
1570 }
1571}
1572
1573bool GetCommandLineFlagInfo(const char* name, CommandLineFlagInfo* OUTPUT) {
1574 if (NULL == name) return false;
1575 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001576 FlagRegistryLock frl(registry);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001577 CommandLineFlag* flag = registry->FindFlagLocked(name);
1578 if (flag == NULL) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001579 return false;
1580 } else {
1581 assert(OUTPUT);
1582 flag->FillCommandLineFlagInfo(OUTPUT);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001583 return true;
1584 }
1585}
1586
Craig Silverstein290da382007-03-28 21:54:07 +00001587CommandLineFlagInfo GetCommandLineFlagInfoOrDie(const char* name) {
1588 CommandLineFlagInfo info;
1589 if (!GetCommandLineFlagInfo(name, &info)) {
Craig Silverstein688ea022009-09-11 00:15:50 +00001590 fprintf(stderr, "FATAL ERROR: flag name '%s' doesn't exist\n", name);
Craig Silverstein917f4e72011-07-29 04:26:49 +00001591 gflags_exitfunc(1); // almost certainly gflags_exitfunc()
Craig Silverstein290da382007-03-28 21:54:07 +00001592 }
1593 return info;
1594}
1595
Craig Silversteinb9f23482007-03-22 00:15:41 +00001596string SetCommandLineOptionWithMode(const char* name, const char* value,
1597 FlagSettingMode set_mode) {
1598 string result;
1599 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001600 FlagRegistryLock frl(registry);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001601 CommandLineFlag* flag = registry->FindFlagLocked(name);
1602 if (flag) {
1603 CommandLineFlagParser parser(registry);
1604 result = parser.ProcessSingleOptionLocked(flag, value, set_mode);
1605 if (!result.empty()) { // in the error case, we've already logged
Craig Silverstein917f4e72011-07-29 04:26:49 +00001606 // Could consider logging this change
Craig Silversteinb9f23482007-03-22 00:15:41 +00001607 }
1608 }
Craig Silversteinb9f23482007-03-22 00:15:41 +00001609 // The API of this function is that we return empty string on error
1610 return result;
1611}
1612
1613string SetCommandLineOption(const char* name, const char* value) {
1614 return SetCommandLineOptionWithMode(name, value, SET_FLAGS_VALUE);
1615}
1616
Craig Silversteinb9f23482007-03-22 00:15:41 +00001617// --------------------------------------------------------------------
1618// FlagSaver
1619// FlagSaverImpl
1620// This class stores the states of all flags at construct time,
1621// and restores all flags to that state at destruct time.
1622// Its major implementation challenge is that it never modifies
1623// pointers in the 'main' registry, so global FLAG_* vars always
1624// point to the right place.
1625// --------------------------------------------------------------------
1626
1627class FlagSaverImpl {
1628 public:
1629 // Constructs an empty FlagSaverImpl object.
1630 explicit FlagSaverImpl(FlagRegistry* main_registry)
1631 : main_registry_(main_registry) { }
1632 ~FlagSaverImpl() {
1633 // reclaim memory from each of our CommandLineFlags
1634 vector<CommandLineFlag*>::const_iterator it;
1635 for (it = backup_registry_.begin(); it != backup_registry_.end(); ++it)
1636 delete *it;
1637 }
1638
1639 // Saves the flag states from the flag registry into this object.
1640 // It's an error to call this more than once.
1641 // Must be called when the registry mutex is not held.
1642 void SaveFromRegistry() {
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001643 FlagRegistryLock frl(main_registry_);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001644 assert(backup_registry_.empty()); // call only once!
1645 for (FlagRegistry::FlagConstIterator it = main_registry_->flags_.begin();
1646 it != main_registry_->flags_.end();
1647 ++it) {
1648 const CommandLineFlag* main = it->second;
1649 // Sets up all the const variables in backup correctly
1650 CommandLineFlag* backup = new CommandLineFlag(
Craig Silversteinc23c6c62011-11-03 23:25:32 +00001651 main->name(), main->help(), main->filename(),
Craig Silversteinb9f23482007-03-22 00:15:41 +00001652 main->current_->New(), main->defvalue_->New());
1653 // Sets up all the non-const variables in backup correctly
1654 backup->CopyFrom(*main);
1655 backup_registry_.push_back(backup); // add it to a convenient list
1656 }
Craig Silversteinb9f23482007-03-22 00:15:41 +00001657 }
1658
1659 // Restores the saved flag states into the flag registry. We
1660 // assume no flags were added or deleted from the registry since
1661 // the SaveFromRegistry; if they were, that's trouble! Must be
1662 // called when the registry mutex is not held.
1663 void RestoreToRegistry() {
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001664 FlagRegistryLock frl(main_registry_);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001665 vector<CommandLineFlag*>::const_iterator it;
1666 for (it = backup_registry_.begin(); it != backup_registry_.end(); ++it) {
1667 CommandLineFlag* main = main_registry_->FindFlagLocked((*it)->name());
1668 if (main != NULL) { // if NULL, flag got deleted from registry(!)
1669 main->CopyFrom(**it);
1670 }
1671 }
Craig Silversteinb9f23482007-03-22 00:15:41 +00001672 }
1673
1674 private:
1675 FlagRegistry* const main_registry_;
1676 vector<CommandLineFlag*> backup_registry_;
1677
1678 FlagSaverImpl(const FlagSaverImpl&); // no copying!
1679 void operator=(const FlagSaverImpl&);
1680};
1681
Craig Silverstein67914682008-08-21 00:50:59 +00001682FlagSaver::FlagSaver()
1683 : impl_(new FlagSaverImpl(FlagRegistry::GlobalRegistry())) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001684 impl_->SaveFromRegistry();
1685}
1686
1687FlagSaver::~FlagSaver() {
1688 impl_->RestoreToRegistry();
1689 delete impl_;
1690}
1691
1692
1693// --------------------------------------------------------------------
1694// CommandlineFlagsIntoString()
1695// ReadFlagsFromString()
1696// AppendFlagsIntoFile()
1697// ReadFromFlagsFile()
1698// These are mostly-deprecated routines that stick the
1699// commandline flags into a file/string and read them back
1700// out again. I can see a use for CommandlineFlagsIntoString,
1701// for creating a flagfile, but the rest don't seem that useful
1702// -- some, I think, are a poor-man's attempt at FlagSaver --
1703// and are included only until we can delete them from callers.
1704// Note they don't save --flagfile flags (though they do save
1705// the result of having called the flagfile, of course).
1706// --------------------------------------------------------------------
1707
1708static string TheseCommandlineFlagsIntoString(
1709 const vector<CommandLineFlagInfo>& flags) {
1710 vector<CommandLineFlagInfo>::const_iterator i;
1711
Craig Silverstein67914682008-08-21 00:50:59 +00001712 size_t retval_space = 0;
Craig Silversteinb9f23482007-03-22 00:15:41 +00001713 for (i = flags.begin(); i != flags.end(); ++i) {
1714 // An (over)estimate of how much space it will take to print this flag
1715 retval_space += i->name.length() + i->current_value.length() + 5;
1716 }
1717
1718 string retval;
1719 retval.reserve(retval_space);
1720 for (i = flags.begin(); i != flags.end(); ++i) {
1721 retval += "--";
1722 retval += i->name;
1723 retval += "=";
1724 retval += i->current_value;
1725 retval += "\n";
1726 }
1727 return retval;
1728}
1729
1730string CommandlineFlagsIntoString() {
1731 vector<CommandLineFlagInfo> sorted_flags;
1732 GetAllFlags(&sorted_flags);
1733 return TheseCommandlineFlagsIntoString(sorted_flags);
1734}
1735
1736bool ReadFlagsFromString(const string& flagfilecontents,
Craig Silverstein67914682008-08-21 00:50:59 +00001737 const char* /*prog_name*/, // TODO(csilvers): nix this
Craig Silversteinb9f23482007-03-22 00:15:41 +00001738 bool errors_are_fatal) {
1739 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1740 FlagSaverImpl saved_states(registry);
1741 saved_states.SaveFromRegistry();
1742
1743 CommandLineFlagParser parser(registry);
1744 registry->Lock();
1745 parser.ProcessOptionsFromStringLocked(flagfilecontents, SET_FLAGS_VALUE);
1746 registry->Unlock();
1747 // Should we handle --help and such when reading flags from a string? Sure.
1748 HandleCommandLineHelpFlags();
1749 if (parser.ReportErrors()) {
1750 // Error. Restore all global flags to their previous values.
1751 if (errors_are_fatal)
Craig Silverstein917f4e72011-07-29 04:26:49 +00001752 gflags_exitfunc(1);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001753 saved_states.RestoreToRegistry();
1754 return false;
1755 }
1756 return true;
1757}
1758
1759// TODO(csilvers): nix prog_name in favor of ProgramInvocationShortName()
1760bool AppendFlagsIntoFile(const string& filename, const char *prog_name) {
1761 FILE *fp = fopen(filename.c_str(), "a");
1762 if (!fp) {
1763 return false;
1764 }
1765
1766 if (prog_name)
1767 fprintf(fp, "%s\n", prog_name);
1768
1769 vector<CommandLineFlagInfo> flags;
1770 GetAllFlags(&flags);
1771 // But we don't want --flagfile, which leads to weird recursion issues
1772 vector<CommandLineFlagInfo>::iterator i;
1773 for (i = flags.begin(); i != flags.end(); ++i) {
1774 if (strcmp(i->name.c_str(), "flagfile") == 0) {
1775 flags.erase(i);
1776 break;
1777 }
1778 }
1779 fprintf(fp, "%s", TheseCommandlineFlagsIntoString(flags).c_str());
1780
1781 fclose(fp);
1782 return true;
1783}
1784
1785bool ReadFromFlagsFile(const string& filename, const char* prog_name,
1786 bool errors_are_fatal) {
1787 return ReadFlagsFromString(ReadFileIntoString(filename.c_str()),
1788 prog_name, errors_are_fatal);
1789}
1790
1791
1792// --------------------------------------------------------------------
1793// BoolFromEnv()
1794// Int32FromEnv()
1795// Int64FromEnv()
1796// Uint64FromEnv()
1797// DoubleFromEnv()
1798// StringFromEnv()
1799// Reads the value from the environment and returns it.
1800// We use an FlagValue to make the parsing easy.
1801// Example usage:
Craig Silverstein2b66a842007-06-12 23:59:42 +00001802// DEFINE_bool(myflag, BoolFromEnv("MYFLAG_DEFAULT", false), "whatever");
Craig Silversteinb9f23482007-03-22 00:15:41 +00001803// --------------------------------------------------------------------
1804
Craig Silversteinb9f23482007-03-22 00:15:41 +00001805bool BoolFromEnv(const char *v, bool dflt) {
1806 return GetFromEnv(v, "bool", dflt);
1807}
1808int32 Int32FromEnv(const char *v, int32 dflt) {
1809 return GetFromEnv(v, "int32", dflt);
1810}
1811int64 Int64FromEnv(const char *v, int64 dflt) {
1812 return GetFromEnv(v, "int64", dflt);
1813}
1814uint64 Uint64FromEnv(const char *v, uint64 dflt) {
1815 return GetFromEnv(v, "uint64", dflt);
1816}
1817double DoubleFromEnv(const char *v, double dflt) {
1818 return GetFromEnv(v, "double", dflt);
1819}
1820const char *StringFromEnv(const char *varname, const char *dflt) {
1821 const char* const val = getenv(varname);
1822 return val ? val : dflt;
1823}
1824
1825
1826// --------------------------------------------------------------------
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001827// RegisterFlagValidator()
1828// RegisterFlagValidator() is the function that clients use to
1829// 'decorate' a flag with a validation function. Once this is
1830// done, every time the flag is set (including when the flag
1831// is parsed from argv), the validator-function is called.
1832// These functions return true if the validator was added
1833// successfully, or false if not: the flag already has a validator,
1834// (only one allowed per flag), the 1st arg isn't a flag, etc.
1835// This function is not thread-safe.
1836// --------------------------------------------------------------------
1837
1838bool RegisterFlagValidator(const bool* flag,
1839 bool (*validate_fn)(const char*, bool)) {
1840 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1841}
1842bool RegisterFlagValidator(const int32* flag,
1843 bool (*validate_fn)(const char*, int32)) {
1844 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1845}
1846bool RegisterFlagValidator(const int64* flag,
1847 bool (*validate_fn)(const char*, int64)) {
1848 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1849}
1850bool RegisterFlagValidator(const uint64* flag,
1851 bool (*validate_fn)(const char*, uint64)) {
1852 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1853}
1854bool RegisterFlagValidator(const double* flag,
1855 bool (*validate_fn)(const char*, double)) {
1856 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1857}
1858bool RegisterFlagValidator(const string* flag,
1859 bool (*validate_fn)(const char*, const string&)) {
1860 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1861}
1862
1863
1864// --------------------------------------------------------------------
Craig Silversteinb9f23482007-03-22 00:15:41 +00001865// ParseCommandLineFlags()
1866// ParseCommandLineNonHelpFlags()
1867// HandleCommandLineHelpFlags()
1868// This is the main function called from main(), to actually
1869// parse the commandline. It modifies argc and argv as described
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001870// at the top of gflags.h. You can also divide this
Craig Silversteinb9f23482007-03-22 00:15:41 +00001871// function into two parts, if you want to do work between
1872// the parsing of the flags and the printing of any help output.
1873// --------------------------------------------------------------------
1874
1875static uint32 ParseCommandLineFlagsInternal(int* argc, char*** argv,
1876 bool remove_flags, bool do_report) {
1877 SetArgv(*argc, const_cast<const char**>(*argv)); // save it for later
1878
1879 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1880 CommandLineFlagParser parser(registry);
1881
1882 // When we parse the commandline flags, we'll handle --flagfile,
1883 // --tryfromenv, etc. as we see them (since flag-evaluation order
1884 // may be important). But sometimes apps set FLAGS_tryfromenv/etc.
1885 // manually before calling ParseCommandLineFlags. We want to evaluate
1886 // those too, as if they were the first flags on the commandline.
1887 registry->Lock();
1888 parser.ProcessFlagfileLocked(FLAGS_flagfile, SET_FLAGS_VALUE);
1889 // Last arg here indicates whether flag-not-found is a fatal error or not
1890 parser.ProcessFromenvLocked(FLAGS_fromenv, SET_FLAGS_VALUE, true);
1891 parser.ProcessFromenvLocked(FLAGS_tryfromenv, SET_FLAGS_VALUE, false);
1892 registry->Unlock();
1893
1894 // Now get the flags specified on the commandline
1895 const int r = parser.ParseNewCommandLineFlags(argc, argv, remove_flags);
1896
1897 if (do_report)
1898 HandleCommandLineHelpFlags(); // may cause us to exit on --help, etc.
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001899
1900 // See if any of the unset flags fail their validation checks
1901 parser.ValidateAllFlags();
1902
Craig Silversteinb9f23482007-03-22 00:15:41 +00001903 if (parser.ReportErrors()) // may cause us to exit on illegal flags
Craig Silverstein917f4e72011-07-29 04:26:49 +00001904 gflags_exitfunc(1);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001905 return r;
1906}
1907
1908uint32 ParseCommandLineFlags(int* argc, char*** argv, bool remove_flags) {
1909 return ParseCommandLineFlagsInternal(argc, argv, remove_flags, true);
1910}
1911
1912uint32 ParseCommandLineNonHelpFlags(int* argc, char*** argv,
1913 bool remove_flags) {
1914 return ParseCommandLineFlagsInternal(argc, argv, remove_flags, false);
1915}
1916
1917// --------------------------------------------------------------------
1918// AllowCommandLineReparsing()
1919// ReparseCommandLineNonHelpFlags()
1920// This is most useful for shared libraries. The idea is if
1921// a flag is defined in a shared library that is dlopen'ed
1922// sometime after main(), you can ParseCommandLineFlags before
1923// the dlopen, then ReparseCommandLineNonHelpFlags() after the
1924// dlopen, to get the new flags. But you have to explicitly
1925// Allow() it; otherwise, you get the normal default behavior
1926// of unrecognized flags calling a fatal error.
Craig Silverstein67914682008-08-21 00:50:59 +00001927// TODO(csilvers): this isn't used. Just delete it?
Craig Silversteinb9f23482007-03-22 00:15:41 +00001928// --------------------------------------------------------------------
1929
1930void AllowCommandLineReparsing() {
1931 allow_command_line_reparsing = true;
1932}
1933
Craig Silverstein71e1be92011-03-02 08:05:17 +00001934void ReparseCommandLineNonHelpFlags() {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001935 // We make a copy of argc and argv to pass in
1936 const vector<string>& argvs = GetArgvs();
Craig Silverstein67914682008-08-21 00:50:59 +00001937 int tmp_argc = static_cast<int>(argvs.size());
Craig Silversteinb9f23482007-03-22 00:15:41 +00001938 char** tmp_argv = new char* [tmp_argc + 1];
1939 for (int i = 0; i < tmp_argc; ++i)
1940 tmp_argv[i] = strdup(argvs[i].c_str()); // TODO(csilvers): don't dup
1941
Craig Silverstein71e1be92011-03-02 08:05:17 +00001942 ParseCommandLineNonHelpFlags(&tmp_argc, &tmp_argv, false);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001943
1944 for (int i = 0; i < tmp_argc; ++i)
1945 free(tmp_argv[i]);
1946 delete[] tmp_argv;
Craig Silversteinb9f23482007-03-22 00:15:41 +00001947}
1948
Craig Silverstein0baf4ab2011-01-14 21:58:28 +00001949void ShutDownCommandLineFlags() {
1950 FlagRegistry::DeleteGlobalRegistry();
1951}
1952
Andreas Schuh392eb672013-04-21 03:05:35 +01001953
1954} // namespace GFLAGS_NAMESPACE