blob: ffb0955cea87327d45c92555dad2b82371d438a2 [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
Craig Silverstein67914682008-08-21 00:50:59 +000090// This comes first to ensure we define __STDC_FORMAT_MACROS in time.
Craig Silverstein917f4e72011-07-29 04:26:49 +000091#include <config.h>
92#if defined(HAVE_INTTYPES_H) && !defined(__STDC_FORMAT_MACROS)
Craig Silverstein67914682008-08-21 00:50:59 +000093# define __STDC_FORMAT_MACROS 1 // gcc requires this to get PRId64, etc.
94#endif
Craig Silverstein917f4e72011-07-29 04:26:49 +000095
96#include <gflags/gflags.h>
97#include <assert.h>
Craig Silversteinb9f23482007-03-22 00:15:41 +000098#include <ctype.h>
99#include <errno.h>
Craig Silverstein67914682008-08-21 00:50:59 +0000100#ifdef HAVE_FNMATCH_H
Craig Silverstein917f4e72011-07-29 04:26:49 +0000101# include <fnmatch.h>
102#endif
103#include <stdarg.h> // For va_list and related operations
104#include <stdio.h>
105#include <string.h>
106
Craig Silversteinb9f23482007-03-22 00:15:41 +0000107#include <algorithm>
Craig Silverstein917f4e72011-07-29 04:26:49 +0000108#include <map>
109#include <string>
110#include <utility> // for pair<>
111#include <vector>
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000112#include "mutex.h"
Craig Silverstein917f4e72011-07-29 04:26:49 +0000113#include "util.h"
Craig Silversteinb9f23482007-03-22 00:15:41 +0000114
Craig Silverstein874aed52011-11-03 23:08:41 +0000115using fL::OptionalDefineArgs;
116
Craig Silversteinb9f23482007-03-22 00:15:41 +0000117#ifndef PATH_SEPARATOR
118#define PATH_SEPARATOR '/'
119#endif
120
Craig Silversteinc44e0552010-09-16 18:53:42 +0000121
Craig Silversteinb9f23482007-03-22 00:15:41 +0000122// Special flags, type 1: the 'recursive' flags. They set another flag's val.
123DEFINE_string(flagfile, "",
124 "load flags from file");
125DEFINE_string(fromenv, "",
Craig Silverstein67914682008-08-21 00:50:59 +0000126 "set flags from the environment"
127 " [use 'export FLAGS_flag1=value']");
Craig Silversteinb9f23482007-03-22 00:15:41 +0000128DEFINE_string(tryfromenv, "",
129 "set flags from the environment if present");
130
131// Special flags, type 2: the 'parsing' flags. They modify how we parse.
132DEFINE_string(undefok, "",
133 "comma-separated list of flag names that it is okay to specify "
134 "on the command line even if the program does not define a flag "
135 "with that name. IMPORTANT: flags in this list that have "
136 "arguments MUST use the flag=value format");
137
138_START_GOOGLE_NAMESPACE_
139
Craig Silverstein31c8edc2010-01-05 02:25:45 +0000140using std::map;
141using std::pair;
142using std::sort;
143using std::string;
144using std::vector;
145
Craig Silverstein917f4e72011-07-29 04:26:49 +0000146// This is used by the unittest to test error-exit code
147void GFLAGS_DLL_DECL (*gflags_exitfunc)(int) = &exit; // from stdlib.h
148
149
Craig Silverstein585a44a2007-10-18 20:08:26 +0000150// The help message indicating that the commandline flag has been
151// 'stripped'. It will not show up when doing "-help" and its
152// variants. The flag is stripped if STRIP_FLAG_HELP is set to 1
Craig Silverstein917f4e72011-07-29 04:26:49 +0000153// before including base/gflags.h
Craig Silverstein585a44a2007-10-18 20:08:26 +0000154
Craig Silverstein917f4e72011-07-29 04:26:49 +0000155// This is used by this file, and also in gflags_reporting.cc
Craig Silverstein585a44a2007-10-18 20:08:26 +0000156const char kStrippedFlagHelp[] = "\001\002\003\004 (unknown) \004\003\002\001";
Craig Silversteinb9f23482007-03-22 00:15:41 +0000157
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000158namespace {
159
Craig Silverstein917f4e72011-07-29 04:26:49 +0000160// There are also 'reporting' flags, in gflags_reporting.cc.
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000161
162static const char kError[] = "ERROR: ";
163
Craig Silversteinb9f23482007-03-22 00:15:41 +0000164// Indicates that undefined options are to be ignored.
165// Enables deferred processing of flags in dynamically loaded libraries.
166static bool allow_command_line_reparsing = false;
167
Craig Silverstein83911c12008-03-27 20:11:07 +0000168static bool logging_is_probably_set_up = false;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000169
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000170// This is a 'prototype' validate-function. 'Real' validate
171// functions, take a flag-value as an argument: ValidateFn(bool) or
172// ValidateFn(uint64). However, for easier storage, we strip off this
173// argument and then restore it when actually calling the function on
174// a flag value.
175typedef bool (*ValidateFnProto)();
176
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000177// Whether we should die when reporting an error.
178enum DieWhenReporting { DIE, DO_NOT_DIE };
179
180// Report Error and exit if requested.
181static void ReportError(DieWhenReporting should_die, const char* format, ...) {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000182 char error_message[255];
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000183 va_list ap;
184 va_start(ap, format);
Craig Silverstein917f4e72011-07-29 04:26:49 +0000185 vsnprintf(error_message, sizeof(error_message), format, ap);
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000186 va_end(ap);
Craig Silverstein917f4e72011-07-29 04:26:49 +0000187 fprintf(stderr, "%s", error_message);
Craig Silverstein6b70a752011-11-03 23:11:24 +0000188 fflush(stderr); // should be unnecessary, but cygwin's rxvt buffers stderr
Craig Silverstein917f4e72011-07-29 04:26:49 +0000189 if (should_die == DIE) gflags_exitfunc(1);
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000190}
191
Craig Silversteinb9f23482007-03-22 00:15:41 +0000192
193// --------------------------------------------------------------------
194// FlagValue
195// This represent the value a single flag might have. The major
196// functionality is to convert from a string to an object of a
Craig Silverstein83911c12008-03-27 20:11:07 +0000197// given type, and back. Thread-compatible.
Craig Silversteinb9f23482007-03-22 00:15:41 +0000198// --------------------------------------------------------------------
199
Craig Silversteine0b71e52008-09-19 19:32:05 +0000200class CommandLineFlag;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000201class FlagValue {
202 public:
Craig Silverstein0baf4ab2011-01-14 21:58:28 +0000203 FlagValue(void* valbuf, const char* type, bool transfer_ownership_of_value);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000204 ~FlagValue();
205
206 bool ParseFrom(const char* spec);
207 string ToString() const;
208
209 private:
Craig Silverstein67914682008-08-21 00:50:59 +0000210 friend class CommandLineFlag; // for many things, including Validate()
211 friend class GOOGLE_NAMESPACE::FlagSaverImpl; // calls New()
212 friend class FlagRegistry; // checks value_buffer_ for flags_by_ptr_ map
Craig Silversteinb9f23482007-03-22 00:15:41 +0000213 template <typename T> friend T GetFromEnv(const char*, const char*, T);
Craig Silversteine0b71e52008-09-19 19:32:05 +0000214 friend bool TryParseLocked(const CommandLineFlag*, FlagValue*,
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000215 const char*, string*); // for New(), CopyFrom()
Craig Silversteinb9f23482007-03-22 00:15:41 +0000216
Craig Silversteinc44e0552010-09-16 18:53:42 +0000217 enum ValueType {
218 FV_BOOL = 0,
219 FV_INT32 = 1,
220 FV_INT64 = 2,
221 FV_UINT64 = 3,
222 FV_DOUBLE = 4,
223 FV_STRING = 5,
224 FV_MAX_INDEX = 5,
225 };
Craig Silversteinb9f23482007-03-22 00:15:41 +0000226 const char* TypeName() const;
227 bool Equal(const FlagValue& x) const;
228 FlagValue* New() const; // creates a new one with default value
229 void CopyFrom(const FlagValue& x);
Craig Silverstein20500a92010-05-07 21:33:49 +0000230 int ValueSize() const;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000231
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000232 // Calls the given validate-fn on value_buffer_, and returns
233 // whatever it returns. But first casts validate_fn_proto to a
234 // function that takes our value as an argument (eg void
235 // (*validate_fn)(bool) for a bool flag).
236 bool Validate(const char* flagname, ValidateFnProto validate_fn_proto) const;
237
Craig Silversteinb9f23482007-03-22 00:15:41 +0000238 void* value_buffer_; // points to the buffer holding our data
Craig Silverstein0baf4ab2011-01-14 21:58:28 +0000239 int8 type_; // how to interpret value_
240 bool owns_value_; // whether to free value on destruct
Craig Silversteinb9f23482007-03-22 00:15:41 +0000241
242 FlagValue(const FlagValue&); // no copying!
243 void operator=(const FlagValue&);
244};
245
246
247// This could be a templated method of FlagValue, but doing so adds to the
248// size of the .o. Since there's no type-safety here anyway, macro is ok.
249#define VALUE_AS(type) *reinterpret_cast<type*>(value_buffer_)
250#define OTHER_VALUE_AS(fv, type) *reinterpret_cast<type*>(fv.value_buffer_)
251#define SET_VALUE_AS(type, value) VALUE_AS(type) = (value)
252
Craig Silverstein0baf4ab2011-01-14 21:58:28 +0000253FlagValue::FlagValue(void* valbuf, const char* type,
254 bool transfer_ownership_of_value)
255 : value_buffer_(valbuf),
256 owns_value_(transfer_ownership_of_value) {
Craig Silversteinc44e0552010-09-16 18:53:42 +0000257 for (type_ = 0; type_ <= FV_MAX_INDEX; ++type_) {
258 if (!strcmp(type, TypeName())) {
259 break;
260 }
261 }
262 assert(type_ <= FV_MAX_INDEX); // Unknown typename
Craig Silversteinb9f23482007-03-22 00:15:41 +0000263}
264
265FlagValue::~FlagValue() {
Craig Silverstein0baf4ab2011-01-14 21:58:28 +0000266 if (!owns_value_) {
267 return;
268 }
Craig Silversteinb9f23482007-03-22 00:15:41 +0000269 switch (type_) {
270 case FV_BOOL: delete reinterpret_cast<bool*>(value_buffer_); break;
271 case FV_INT32: delete reinterpret_cast<int32*>(value_buffer_); break;
272 case FV_INT64: delete reinterpret_cast<int64*>(value_buffer_); break;
273 case FV_UINT64: delete reinterpret_cast<uint64*>(value_buffer_); break;
274 case FV_DOUBLE: delete reinterpret_cast<double*>(value_buffer_); break;
275 case FV_STRING: delete reinterpret_cast<string*>(value_buffer_); break;
276 }
277}
278
279bool FlagValue::ParseFrom(const char* value) {
280 if (type_ == FV_BOOL) {
281 const char* kTrue[] = { "1", "t", "true", "y", "yes" };
282 const char* kFalse[] = { "0", "f", "false", "n", "no" };
Craig Silverstein917f4e72011-07-29 04:26:49 +0000283 COMPILE_ASSERT(sizeof(kTrue) == sizeof(kFalse), true_false_equal);
Craig Silverstein67914682008-08-21 00:50:59 +0000284 for (size_t i = 0; i < sizeof(kTrue)/sizeof(*kTrue); ++i) {
Craig Silversteinb9f23482007-03-22 00:15:41 +0000285 if (strcasecmp(value, kTrue[i]) == 0) {
286 SET_VALUE_AS(bool, true);
287 return true;
288 } else if (strcasecmp(value, kFalse[i]) == 0) {
289 SET_VALUE_AS(bool, false);
290 return true;
291 }
292 }
293 return false; // didn't match a legal input
294
295 } else if (type_ == FV_STRING) {
296 SET_VALUE_AS(string, value);
297 return true;
298 }
299
300 // OK, it's likely to be numeric, and we'll be using a strtoXXX method.
301 if (value[0] == '\0') // empty-string is only allowed for string type.
302 return false;
303 char* end;
304 // Leading 0x puts us in base 16. But leading 0 does not put us in base 8!
305 // It caused too many bugs when we had that behavior.
306 int base = 10; // by default
307 if (value[0] == '0' && (value[1] == 'x' || value[1] == 'X'))
308 base = 16;
309 errno = 0;
310
311 switch (type_) {
312 case FV_INT32: {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000313 const int64 r = strto64(value, &end, base);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000314 if (errno || end != value + strlen(value)) return false; // bad parse
315 if (static_cast<int32>(r) != r) // worked, but number out of range
316 return false;
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000317 SET_VALUE_AS(int32, static_cast<int32>(r));
Craig Silversteinb9f23482007-03-22 00:15:41 +0000318 return true;
319 }
320 case FV_INT64: {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000321 const int64 r = strto64(value, &end, base);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000322 if (errno || end != value + strlen(value)) return false; // bad parse
323 SET_VALUE_AS(int64, r);
324 return true;
325 }
326 case FV_UINT64: {
327 while (*value == ' ') value++;
328 if (*value == '-') return false; // negative number
Craig Silverstein917f4e72011-07-29 04:26:49 +0000329 const uint64 r = strtou64(value, &end, base);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000330 if (errno || end != value + strlen(value)) return false; // bad parse
331 SET_VALUE_AS(uint64, r);
332 return true;
333 }
334 case FV_DOUBLE: {
335 const double r = strtod(value, &end);
336 if (errno || end != value + strlen(value)) return false; // bad parse
337 SET_VALUE_AS(double, r);
338 return true;
339 }
340 default: {
Craig Silverstein67914682008-08-21 00:50:59 +0000341 assert(false); // unknown type
Craig Silversteinb9f23482007-03-22 00:15:41 +0000342 return false;
343 }
344 }
345}
346
347string FlagValue::ToString() const {
348 char intbuf[64]; // enough to hold even the biggest number
349 switch (type_) {
350 case FV_BOOL:
351 return VALUE_AS(bool) ? "true" : "false";
352 case FV_INT32:
Craig Silverstein67914682008-08-21 00:50:59 +0000353 snprintf(intbuf, sizeof(intbuf), "%"PRId32, VALUE_AS(int32));
Craig Silversteinb9f23482007-03-22 00:15:41 +0000354 return intbuf;
355 case FV_INT64:
Craig Silverstein67914682008-08-21 00:50:59 +0000356 snprintf(intbuf, sizeof(intbuf), "%"PRId64, VALUE_AS(int64));
Craig Silversteinb9f23482007-03-22 00:15:41 +0000357 return intbuf;
358 case FV_UINT64:
Craig Silverstein67914682008-08-21 00:50:59 +0000359 snprintf(intbuf, sizeof(intbuf), "%"PRIu64, VALUE_AS(uint64));
Craig Silversteinb9f23482007-03-22 00:15:41 +0000360 return intbuf;
361 case FV_DOUBLE:
362 snprintf(intbuf, sizeof(intbuf), "%.17g", VALUE_AS(double));
363 return intbuf;
364 case FV_STRING:
365 return VALUE_AS(string);
366 default:
Craig Silverstein67914682008-08-21 00:50:59 +0000367 assert(false);
368 return ""; // unknown type
Craig Silversteinb9f23482007-03-22 00:15:41 +0000369 }
370}
371
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000372bool FlagValue::Validate(const char* flagname,
373 ValidateFnProto validate_fn_proto) const {
374 switch (type_) {
375 case FV_BOOL:
376 return reinterpret_cast<bool (*)(const char*, bool)>(
377 validate_fn_proto)(flagname, VALUE_AS(bool));
378 case FV_INT32:
379 return reinterpret_cast<bool (*)(const char*, int32)>(
380 validate_fn_proto)(flagname, VALUE_AS(int32));
381 case FV_INT64:
382 return reinterpret_cast<bool (*)(const char*, int64)>(
383 validate_fn_proto)(flagname, VALUE_AS(int64));
384 case FV_UINT64:
385 return reinterpret_cast<bool (*)(const char*, uint64)>(
386 validate_fn_proto)(flagname, VALUE_AS(uint64));
387 case FV_DOUBLE:
388 return reinterpret_cast<bool (*)(const char*, double)>(
389 validate_fn_proto)(flagname, VALUE_AS(double));
390 case FV_STRING:
391 return reinterpret_cast<bool (*)(const char*, const string&)>(
392 validate_fn_proto)(flagname, VALUE_AS(string));
393 default:
Craig Silverstein67914682008-08-21 00:50:59 +0000394 assert(false); // unknown type
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000395 return false;
396 }
397}
398
Craig Silversteinb9f23482007-03-22 00:15:41 +0000399const char* FlagValue::TypeName() const {
Craig Silversteinc44e0552010-09-16 18:53:42 +0000400 static const char types[] =
401 "bool\0xx"
402 "int32\0x"
403 "int64\0x"
404 "uint64\0"
405 "double\0"
406 "string";
407 if (type_ > FV_MAX_INDEX) {
408 assert(false);
409 return "";
Craig Silversteinb9f23482007-03-22 00:15:41 +0000410 }
Craig Silversteinc44e0552010-09-16 18:53:42 +0000411 // Directly indexing the strigns in the 'types' string, each of them
412 // is 7 bytes long.
413 return &types[type_ * 7];
Craig Silversteinb9f23482007-03-22 00:15:41 +0000414}
415
416bool FlagValue::Equal(const FlagValue& x) const {
417 if (type_ != x.type_)
418 return false;
419 switch (type_) {
420 case FV_BOOL: return VALUE_AS(bool) == OTHER_VALUE_AS(x, bool);
421 case FV_INT32: return VALUE_AS(int32) == OTHER_VALUE_AS(x, int32);
422 case FV_INT64: return VALUE_AS(int64) == OTHER_VALUE_AS(x, int64);
423 case FV_UINT64: return VALUE_AS(uint64) == OTHER_VALUE_AS(x, uint64);
424 case FV_DOUBLE: return VALUE_AS(double) == OTHER_VALUE_AS(x, double);
425 case FV_STRING: return VALUE_AS(string) == OTHER_VALUE_AS(x, string);
Craig Silverstein67914682008-08-21 00:50:59 +0000426 default: assert(false); return false; // unknown type
Craig Silversteinb9f23482007-03-22 00:15:41 +0000427 }
428}
429
430FlagValue* FlagValue::New() const {
Craig Silversteinc44e0552010-09-16 18:53:42 +0000431 const char *type = TypeName();
Craig Silversteinb9f23482007-03-22 00:15:41 +0000432 switch (type_) {
Craig Silverstein0baf4ab2011-01-14 21:58:28 +0000433 case FV_BOOL: return new FlagValue(new bool(false), type, true);
434 case FV_INT32: return new FlagValue(new int32(0), type, true);
435 case FV_INT64: return new FlagValue(new int64(0), type, true);
436 case FV_UINT64: return new FlagValue(new uint64(0), type, true);
437 case FV_DOUBLE: return new FlagValue(new double(0.0), type, true);
438 case FV_STRING: return new FlagValue(new string, type, true);
Craig Silverstein67914682008-08-21 00:50:59 +0000439 default: assert(false); return NULL; // unknown type
Craig Silversteinb9f23482007-03-22 00:15:41 +0000440 }
441}
442
443void FlagValue::CopyFrom(const FlagValue& x) {
444 assert(type_ == x.type_);
445 switch (type_) {
446 case FV_BOOL: SET_VALUE_AS(bool, OTHER_VALUE_AS(x, bool)); break;
447 case FV_INT32: SET_VALUE_AS(int32, OTHER_VALUE_AS(x, int32)); break;
448 case FV_INT64: SET_VALUE_AS(int64, OTHER_VALUE_AS(x, int64)); break;
449 case FV_UINT64: SET_VALUE_AS(uint64, OTHER_VALUE_AS(x, uint64)); break;
450 case FV_DOUBLE: SET_VALUE_AS(double, OTHER_VALUE_AS(x, double)); break;
451 case FV_STRING: SET_VALUE_AS(string, OTHER_VALUE_AS(x, string)); break;
Craig Silverstein67914682008-08-21 00:50:59 +0000452 default: assert(false); // unknown type
Craig Silversteinb9f23482007-03-22 00:15:41 +0000453 }
454}
455
Craig Silverstein20500a92010-05-07 21:33:49 +0000456int FlagValue::ValueSize() const {
Craig Silversteinc44e0552010-09-16 18:53:42 +0000457 if (type_ > FV_MAX_INDEX) {
458 assert(false); // unknown type
459 return 0;
Craig Silverstein20500a92010-05-07 21:33:49 +0000460 }
Craig Silversteinc44e0552010-09-16 18:53:42 +0000461 static const uint8 valuesize[] = {
462 sizeof(bool),
463 sizeof(int32),
464 sizeof(int64),
465 sizeof(uint64),
466 sizeof(double),
467 sizeof(string),
468 };
469 return valuesize[type_];
Craig Silverstein20500a92010-05-07 21:33:49 +0000470}
471
Craig Silversteinb9f23482007-03-22 00:15:41 +0000472// --------------------------------------------------------------------
473// CommandLineFlag
474// This represents a single flag, including its name, description,
475// default value, and current value. Mostly this serves as a
476// struct, though it also knows how to register itself.
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000477// All CommandLineFlags are owned by a (exactly one)
478// FlagRegistry. If you wish to modify fields in this class, you
479// should acquire the FlagRegistry lock for the registry that owns
480// this flag.
Craig Silversteinb9f23482007-03-22 00:15:41 +0000481// --------------------------------------------------------------------
482
483class CommandLineFlag {
484 public:
485 // Note: we take over memory-ownership of current_val and default_val.
486 CommandLineFlag(const char* name, const char* help, const char* filename,
Craig Silverstein874aed52011-11-03 23:08:41 +0000487 const char* categories,
Craig Silversteinb9f23482007-03-22 00:15:41 +0000488 FlagValue* current_val, FlagValue* default_val);
489 ~CommandLineFlag();
490
491 const char* name() const { return name_; }
492 const char* help() const { return help_; }
493 const char* filename() const { return file_; }
Craig Silverstein874aed52011-11-03 23:08:41 +0000494 const char* categories() const { return categories_ ? categories_ : ""; }
Craig Silversteinb9f23482007-03-22 00:15:41 +0000495 const char* CleanFileName() const; // nixes irrelevant prefix such as homedir
496 string current_value() const { return current_->ToString(); }
497 string default_value() const { return defvalue_->ToString(); }
498 const char* type_name() const { return defvalue_->TypeName(); }
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000499 ValidateFnProto validate_function() const { return validate_fn_proto_; }
Craig Silverstein17a627a2011-11-03 23:18:00 +0000500 const void* flag_ptr() const { return current_->value_buffer_; }
Craig Silversteinb9f23482007-03-22 00:15:41 +0000501
Craig Silverstein290da382007-03-28 21:54:07 +0000502 void FillCommandLineFlagInfo(struct CommandLineFlagInfo* result);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000503
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000504 // If validate_fn_proto_ is non-NULL, calls it on value, returns result.
505 bool Validate(const FlagValue& value) const;
506 bool ValidateCurrent() const { return Validate(*current_); }
507
Craig Silversteinb9f23482007-03-22 00:15:41 +0000508 private:
Craig Silverstein67914682008-08-21 00:50:59 +0000509 // for SetFlagLocked() and setting flags_by_ptr_
510 friend class FlagRegistry;
511 friend class GOOGLE_NAMESPACE::FlagSaverImpl; // for cloning the values
Craig Silverstein67914682008-08-21 00:50:59 +0000512 // set validate_fn
513 friend bool AddFlagValidator(const void*, ValidateFnProto);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000514
515 // This copies all the non-const members: modified, processed, defvalue, etc.
516 void CopyFrom(const CommandLineFlag& src);
517
518 void UpdateModifiedBit();
519
520 const char* const name_; // Flag name
521 const char* const help_; // Help message
522 const char* const file_; // Which file did this come from?
Craig Silverstein874aed52011-11-03 23:08:41 +0000523 const char* categories_; // Comma-separated list of flag's 'categories'
Craig Silversteinb9f23482007-03-22 00:15:41 +0000524 bool modified_; // Set after default assignment?
525 FlagValue* defvalue_; // Default value for flag
526 FlagValue* current_; // Current value for flag
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000527 // This is a casted, 'generic' version of validate_fn, which actually
528 // takes a flag-value as an arg (void (*validate_fn)(bool), say).
529 // When we pass this to current_->Validate(), it will cast it back to
530 // the proper type. This may be NULL to mean we have no validate_fn.
531 ValidateFnProto validate_fn_proto_;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000532
533 CommandLineFlag(const CommandLineFlag&); // no copying!
534 void operator=(const CommandLineFlag&);
535};
536
537CommandLineFlag::CommandLineFlag(const char* name, const char* help,
Craig Silverstein874aed52011-11-03 23:08:41 +0000538 const char* filename, const char* categories,
Craig Silversteinb9f23482007-03-22 00:15:41 +0000539 FlagValue* current_val, FlagValue* default_val)
Craig Silverstein874aed52011-11-03 23:08:41 +0000540 : name_(name), help_(help), file_(filename), categories_(categories),
541 modified_(false), defvalue_(default_val), current_(current_val),
542 validate_fn_proto_(NULL) {
Craig Silversteinb9f23482007-03-22 00:15:41 +0000543}
544
545CommandLineFlag::~CommandLineFlag() {
546 delete current_;
547 delete defvalue_;
548}
549
550const char* CommandLineFlag::CleanFileName() const {
551 // Compute top-level directory & file that this appears in
Craig Silversteineb208392007-08-15 19:44:54 +0000552 // search full path backwards.
Craig Silverstein83911c12008-03-27 20:11:07 +0000553 // Stop going backwards at kRootDir; and skip by the first slash.
554 static const char kRootDir[] = ""; // can set this to root directory,
Craig Silversteinb9f23482007-03-22 00:15:41 +0000555
Craig Silverstein83911c12008-03-27 20:11:07 +0000556 if (sizeof(kRootDir)-1 == 0) // no prefix to strip
Craig Silversteinb9f23482007-03-22 00:15:41 +0000557 return filename();
558
559 const char* clean_name = filename() + strlen(filename()) - 1;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000560 while ( clean_name > filename() ) {
561 if (*clean_name == PATH_SEPARATOR) {
Craig Silverstein83911c12008-03-27 20:11:07 +0000562 if (strncmp(clean_name, kRootDir, sizeof(kRootDir)-1) == 0) {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000563 clean_name += sizeof(kRootDir)-1; // past root-dir
Craig Silversteinb9f23482007-03-22 00:15:41 +0000564 break;
565 }
566 }
567 --clean_name;
568 }
569 while ( *clean_name == PATH_SEPARATOR ) ++clean_name; // Skip any slashes
570 return clean_name;
571}
572
573void CommandLineFlag::FillCommandLineFlagInfo(
Craig Silverstein290da382007-03-28 21:54:07 +0000574 CommandLineFlagInfo* result) {
Craig Silversteinb9f23482007-03-22 00:15:41 +0000575 result->name = name();
576 result->type = type_name();
577 result->description = help();
Craig Silverstein874aed52011-11-03 23:08:41 +0000578 result->categories = categories();
Craig Silversteinb9f23482007-03-22 00:15:41 +0000579 result->current_value = current_value();
580 result->default_value = default_value();
581 result->filename = CleanFileName();
Craig Silverstein290da382007-03-28 21:54:07 +0000582 UpdateModifiedBit();
583 result->is_default = !modified_;
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000584 result->has_validator_fn = validate_function() != NULL;
Craig Silverstein17a627a2011-11-03 23:18:00 +0000585 result->flag_ptr = flag_ptr();
Craig Silversteinb9f23482007-03-22 00:15:41 +0000586}
587
588void CommandLineFlag::UpdateModifiedBit() {
589 // Update the "modified" bit in case somebody bypassed the
590 // Flags API and wrote directly through the FLAGS_name variable.
591 if (!modified_ && !current_->Equal(*defvalue_)) {
592 modified_ = true;
593 }
594}
595
596void CommandLineFlag::CopyFrom(const CommandLineFlag& src) {
597 // Note we only copy the non-const members; others are fixed at construct time
Craig Silverstein67914682008-08-21 00:50:59 +0000598 if (modified_ != src.modified_) modified_ = src.modified_;
599 if (!current_->Equal(*src.current_)) current_->CopyFrom(*src.current_);
600 if (!defvalue_->Equal(*src.defvalue_)) defvalue_->CopyFrom(*src.defvalue_);
601 if (validate_fn_proto_ != src.validate_fn_proto_)
602 validate_fn_proto_ = src.validate_fn_proto_;
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000603}
604
605bool CommandLineFlag::Validate(const FlagValue& value) const {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000606
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000607 if (validate_function() == NULL)
608 return true;
609 else
610 return value.Validate(name(), validate_function());
Craig Silversteinb9f23482007-03-22 00:15:41 +0000611}
612
613
614// --------------------------------------------------------------------
615// FlagRegistry
616// A FlagRegistry singleton object holds all flag objects indexed
617// by their names so that if you know a flag's name (as a C
618// string), you can access or set it. If the function is named
619// FooLocked(), you must own the registry lock before calling
620// the function; otherwise, you should *not* hold the lock, and
621// the function will acquire it itself if needed.
622// --------------------------------------------------------------------
623
624struct StringCmp { // Used by the FlagRegistry map class to compare char*'s
625 bool operator() (const char* s1, const char* s2) const {
626 return (strcmp(s1, s2) < 0);
627 }
628};
629
Craig Silverstein917f4e72011-07-29 04:26:49 +0000630
Craig Silversteinb9f23482007-03-22 00:15:41 +0000631class FlagRegistry {
632 public:
Craig Silverstein917f4e72011-07-29 04:26:49 +0000633 FlagRegistry() {
634 }
Craig Silverstein0baf4ab2011-01-14 21:58:28 +0000635 ~FlagRegistry() {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000636 // Not using STLDeleteElements as that resides in util and this
637 // class is base.
Craig Silverstein0baf4ab2011-01-14 21:58:28 +0000638 for (FlagMap::iterator p = flags_.begin(), e = flags_.end(); p != e; ++p) {
639 CommandLineFlag* flag = p->second;
640 delete flag;
641 }
642 }
643
644 static void DeleteGlobalRegistry() {
645 delete global_registry_;
646 global_registry_ = NULL;
647 }
Craig Silverstein67914682008-08-21 00:50:59 +0000648
Craig Silversteinb9f23482007-03-22 00:15:41 +0000649 // Store a flag in this registry. Takes ownership of the given pointer.
650 void RegisterFlag(CommandLineFlag* flag);
651
Craig Silverstein917f4e72011-07-29 04:26:49 +0000652 void Lock() { lock_.Lock(); }
653 void Unlock() { lock_.Unlock(); }
654
Craig Silversteinb9f23482007-03-22 00:15:41 +0000655 // Returns the flag object for the specified name, or NULL if not found.
656 CommandLineFlag* FindFlagLocked(const char* name);
657
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000658 // Returns the flag object whose current-value is stored at flag_ptr.
659 // That is, for whom current_->value_buffer_ == flag_ptr
660 CommandLineFlag* FindFlagViaPtrLocked(const void* flag_ptr);
661
Craig Silversteinb9f23482007-03-22 00:15:41 +0000662 // A fancier form of FindFlag that works correctly if name is of the
663 // form flag=value. In that case, we set key to point to flag, and
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000664 // modify v to point to the value (if present), and return the flag
665 // with the given name. If the flag does not exist, returns NULL
666 // and sets error_message.
Craig Silversteinb9f23482007-03-22 00:15:41 +0000667 CommandLineFlag* SplitArgumentLocked(const char* argument,
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000668 string* key, const char** v,
669 string* error_message);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000670
671 // Set the value of a flag. If the flag was successfully set to
672 // value, set msg to indicate the new flag-value, and return true.
673 // Otherwise, set msg to indicate the error, leave flag unchanged,
674 // and return false. msg can be NULL.
675 bool SetFlagLocked(CommandLineFlag* flag, const char* value,
676 FlagSettingMode set_mode, string* msg);
677
678 static FlagRegistry* GlobalRegistry(); // returns a singleton registry
679
680 private:
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000681 friend class GOOGLE_NAMESPACE::FlagSaverImpl; // reads all the flags in order to copy them
682 friend class CommandLineFlagParser; // for ValidateAllFlags
683 friend void GOOGLE_NAMESPACE::GetAllFlags(vector<CommandLineFlagInfo>*);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000684
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000685 // The map from name to flag, for FindFlagLocked().
Craig Silversteinb9f23482007-03-22 00:15:41 +0000686 typedef map<const char*, CommandLineFlag*, StringCmp> FlagMap;
687 typedef FlagMap::iterator FlagIterator;
688 typedef FlagMap::const_iterator FlagConstIterator;
689 FlagMap flags_;
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000690
691 // The map from current-value pointer to flag, fo FindFlagViaPtrLocked().
692 typedef map<const void*, CommandLineFlag*> FlagPtrMap;
693 FlagPtrMap flags_by_ptr_;
694
Craig Silversteinb9f23482007-03-22 00:15:41 +0000695 static FlagRegistry* global_registry_; // a singleton registry
Craig Silverstein917f4e72011-07-29 04:26:49 +0000696
697 Mutex lock_;
698 static Mutex global_registry_lock_;
699
700 static void InitGlobalRegistry();
Craig Silversteinb9f23482007-03-22 00:15:41 +0000701
702 // Disallow
703 FlagRegistry(const FlagRegistry&);
704 FlagRegistry& operator=(const FlagRegistry&);
705};
706
Craig Silverstein917f4e72011-07-29 04:26:49 +0000707class FlagRegistryLock {
708 public:
709 explicit FlagRegistryLock(FlagRegistry* fr) : fr_(fr) { fr_->Lock(); }
710 ~FlagRegistryLock() { fr_->Unlock(); }
711 private:
712 FlagRegistry *const fr_;
713};
Craig Silverstein67914682008-08-21 00:50:59 +0000714
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000715
Craig Silversteinb9f23482007-03-22 00:15:41 +0000716void FlagRegistry::RegisterFlag(CommandLineFlag* flag) {
717 Lock();
718 pair<FlagIterator, bool> ins =
719 flags_.insert(pair<const char*, CommandLineFlag*>(flag->name(), flag));
720 if (ins.second == false) { // means the name was already in the map
721 if (strcmp(ins.first->second->filename(), flag->filename()) != 0) {
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000722 ReportError(DIE, "ERROR: flag '%s' was defined more than once "
723 "(in files '%s' and '%s').\n",
724 flag->name(),
725 ins.first->second->filename(),
726 flag->filename());
Craig Silversteinb9f23482007-03-22 00:15:41 +0000727 } else {
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000728 ReportError(DIE, "ERROR: something wrong with flag '%s' in file '%s'. "
729 "One possibility: file '%s' is being linked both statically "
730 "and dynamically into this executable.\n",
731 flag->name(),
732 flag->filename(), flag->filename());
Craig Silversteinb9f23482007-03-22 00:15:41 +0000733 }
Craig Silversteinb9f23482007-03-22 00:15:41 +0000734 }
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000735 // Also add to the flags_by_ptr_ map.
736 flags_by_ptr_[flag->current_->value_buffer_] = flag;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000737 Unlock();
738}
739
740CommandLineFlag* FlagRegistry::FindFlagLocked(const char* name) {
741 FlagConstIterator i = flags_.find(name);
742 if (i == flags_.end()) {
743 return NULL;
744 } else {
745 return i->second;
746 }
747}
748
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000749CommandLineFlag* FlagRegistry::FindFlagViaPtrLocked(const void* flag_ptr) {
750 FlagPtrMap::const_iterator i = flags_by_ptr_.find(flag_ptr);
751 if (i == flags_by_ptr_.end()) {
752 return NULL;
753 } else {
754 return i->second;
755 }
756}
757
Craig Silversteinb9f23482007-03-22 00:15:41 +0000758CommandLineFlag* FlagRegistry::SplitArgumentLocked(const char* arg,
759 string* key,
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000760 const char** v,
761 string* error_message) {
Craig Silversteinb9f23482007-03-22 00:15:41 +0000762 // Find the flag object for this option
763 const char* flag_name;
764 const char* value = strchr(arg, '=');
765 if (value == NULL) {
766 key->assign(arg);
767 *v = NULL;
768 } else {
769 // Strip out the "=value" portion from arg
770 key->assign(arg, value-arg);
771 *v = ++value; // advance past the '='
772 }
773 flag_name = key->c_str();
774
775 CommandLineFlag* flag = FindFlagLocked(flag_name);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000776
777 if (flag == NULL) {
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000778 // If we can't find the flag-name, then we should return an error.
779 // The one exception is if 1) the flag-name is 'nox', 2) there
780 // exists a flag named 'x', and 3) 'x' is a boolean flag.
781 // In that case, we want to return flag 'x'.
782 if (!(flag_name[0] == 'n' && flag_name[1] == 'o')) {
783 // flag-name is not 'nox', so we're not in the exception case.
Craig Silverstein917f4e72011-07-29 04:26:49 +0000784 *error_message = StringPrintf("%sunknown command line flag '%s'\n",
785 kError, key->c_str());
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000786 return NULL;
787 }
788 flag = FindFlagLocked(flag_name+2);
789 if (flag == NULL) {
790 // No flag named 'x' exists, so we're not in the exception case.
Craig Silverstein917f4e72011-07-29 04:26:49 +0000791 *error_message = StringPrintf("%sunknown command line flag '%s'\n",
792 kError, key->c_str());
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000793 return NULL;
794 }
795 if (strcmp(flag->type_name(), "bool") != 0) {
796 // 'x' exists but is not boolean, so we're not in the exception case.
Craig Silverstein917f4e72011-07-29 04:26:49 +0000797 *error_message = StringPrintf(
798 "%sboolean value (%s) specified for %s command line flag\n",
799 kError, key->c_str(), flag->type_name());
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000800 return NULL;
801 }
802 // We're in the exception case!
803 // Make up a fake value to replace the "no" we stripped out
804 key->assign(flag_name+2); // the name without the "no"
805 *v = "0";
Craig Silversteinb9f23482007-03-22 00:15:41 +0000806 }
807
808 // Assign a value if this is a boolean flag
809 if (*v == NULL && strcmp(flag->type_name(), "bool") == 0) {
810 *v = "1"; // the --nox case was already handled, so this is the --x case
811 }
812
813 return flag;
814}
815
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000816bool TryParseLocked(const CommandLineFlag* flag, FlagValue* flag_value,
817 const char* value, string* msg) {
818 // Use tenative_value, not flag_value, until we know value is valid.
819 FlagValue* tentative_value = flag_value->New();
820 if (!tentative_value->ParseFrom(value)) {
821 if (msg) {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000822 StringAppendF(msg,
823 "%sillegal value '%s' specified for %s flag '%s'\n",
824 kError, value,
825 flag->type_name(), flag->name());
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000826 }
827 delete tentative_value;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000828 return false;
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000829 } else if (!flag->Validate(*tentative_value)) {
Craig Silverstein67914682008-08-21 00:50:59 +0000830 if (msg) {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000831 StringAppendF(msg,
832 "%sfailed validation of new value '%s' for flag '%s'\n",
833 kError, tentative_value->ToString().c_str(),
834 flag->name());
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000835 }
836 delete tentative_value;
837 return false;
838 } else {
839 flag_value->CopyFrom(*tentative_value);
840 if (msg) {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000841 StringAppendF(msg, "%s set to %s\n",
842 flag->name(), flag_value->ToString().c_str());
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000843 }
844 delete tentative_value;
845 return true;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000846 }
847}
848
849bool FlagRegistry::SetFlagLocked(CommandLineFlag* flag,
850 const char* value,
851 FlagSettingMode set_mode,
852 string* msg) {
853 flag->UpdateModifiedBit();
854 switch (set_mode) {
855 case SET_FLAGS_VALUE: {
856 // set or modify the flag's value
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000857 if (!TryParseLocked(flag, flag->current_, value, msg))
Craig Silversteinb9f23482007-03-22 00:15:41 +0000858 return false;
859 flag->modified_ = true;
860 break;
861 }
862 case SET_FLAG_IF_DEFAULT: {
863 // set the flag's value, but only if it hasn't been set by someone else
864 if (!flag->modified_) {
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000865 if (!TryParseLocked(flag, flag->current_, value, msg))
Craig Silversteinb9f23482007-03-22 00:15:41 +0000866 return false;
867 flag->modified_ = true;
868 } else {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000869 *msg = StringPrintf("%s set to %s",
870 flag->name(), flag->current_value().c_str());
Craig Silversteinb9f23482007-03-22 00:15:41 +0000871 }
872 break;
873 }
874 case SET_FLAGS_DEFAULT: {
875 // modify the flag's default-value
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000876 if (!TryParseLocked(flag, flag->defvalue_, value, msg))
Craig Silversteinb9f23482007-03-22 00:15:41 +0000877 return false;
878 if (!flag->modified_) {
879 // Need to set both defvalue *and* current, in this case
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000880 TryParseLocked(flag, flag->current_, value, NULL);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000881 }
882 break;
883 }
884 default: {
Craig Silverstein690172b2007-04-20 21:16:33 +0000885 // unknown set_mode
Craig Silverstein67914682008-08-21 00:50:59 +0000886 assert(false);
887 return false;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000888 }
889 }
890
891 return true;
892}
893
Craig Silverstein917f4e72011-07-29 04:26:49 +0000894// Get the singleton FlagRegistry object
895FlagRegistry* FlagRegistry::global_registry_ = NULL;
896Mutex FlagRegistry::global_registry_lock_(Mutex::LINKER_INITIALIZED);
897
898FlagRegistry* FlagRegistry::GlobalRegistry() {
899 MutexLock acquire_lock(&global_registry_lock_);
900 if (!global_registry_) {
901 global_registry_ = new FlagRegistry;
902 }
903 return global_registry_;
904}
Craig Silversteinb9f23482007-03-22 00:15:41 +0000905
Craig Silversteinb9f23482007-03-22 00:15:41 +0000906// --------------------------------------------------------------------
907// CommandLineFlagParser
908// Parsing is done in two stages. In the first, we go through
909// argv. For every flag-like arg we can make sense of, we parse
910// it and set the appropriate FLAGS_* variable. For every flag-
911// like arg we can't make sense of, we store it in a vector,
912// along with an explanation of the trouble. In stage 2, we
913// handle the 'reporting' flags like --help and --mpm_version.
914// (This is via a call to HandleCommandLineHelpFlags(), in
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000915// gflags_reporting.cc.)
Craig Silversteinb9f23482007-03-22 00:15:41 +0000916// An optional stage 3 prints out the error messages.
917// This is a bit of a simplification. For instance, --flagfile
918// is handled as soon as it's seen in stage 1, not in stage 2.
919// --------------------------------------------------------------------
920
921class CommandLineFlagParser {
922 public:
923 // The argument is the flag-registry to register the parsed flags in
924 explicit CommandLineFlagParser(FlagRegistry* reg) : registry_(reg) {}
925 ~CommandLineFlagParser() {}
926
927 // Stage 1: Every time this is called, it reads all flags in argv.
928 // However, it ignores all flags that have been successfully set
929 // before. Typically this is only called once, so this 'reparsing'
930 // behavior isn't important. It can be useful when trying to
931 // reparse after loading a dll, though.
932 uint32 ParseNewCommandLineFlags(int* argc, char*** argv, bool remove_flags);
933
934 // Stage 2: print reporting info and exit, if requested.
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000935 // In gflags_reporting.cc:HandleCommandLineHelpFlags().
Craig Silversteinb9f23482007-03-22 00:15:41 +0000936
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000937 // Stage 3: validate all the commandline flags that have validators
938 // registered.
939 void ValidateAllFlags();
940
941 // Stage 4: report any errors and return true if any were found.
Craig Silversteinb9f23482007-03-22 00:15:41 +0000942 bool ReportErrors();
943
944 // Set a particular command line option. "newval" is a string
945 // describing the new value that the option has been set to. If
946 // option_name does not specify a valid option name, or value is not
947 // a valid value for option_name, newval is empty. Does recursive
948 // processing for --flagfile and --fromenv. Returns the new value
949 // if everything went ok, or empty-string if not. (Actually, the
950 // return-string could hold many flag/value pairs due to --flagfile.)
951 // NB: Must have called registry_->Lock() before calling this function.
952 string ProcessSingleOptionLocked(CommandLineFlag* flag,
953 const char* value,
954 FlagSettingMode set_mode);
955
956 // Set a whole batch of command line options as specified by contentdata,
957 // which is in flagfile format (and probably has been read from a flagfile).
958 // Returns the new value if everything went ok, or empty-string if
959 // not. (Actually, the return-string could hold many flag/value
960 // pairs due to --flagfile.)
961 // NB: Must have called registry_->Lock() before calling this function.
962 string ProcessOptionsFromStringLocked(const string& contentdata,
963 FlagSettingMode set_mode);
964
965 // These are the 'recursive' flags, defined at the top of this file.
966 // Whenever we see these flags on the commandline, we must take action.
967 // These are called by ProcessSingleOptionLocked and, similarly, return
968 // new values if everything went ok, or the empty-string if not.
969 string ProcessFlagfileLocked(const string& flagval, FlagSettingMode set_mode);
Craig Silverstein67914682008-08-21 00:50:59 +0000970 // diff fromenv/tryfromenv
Craig Silversteinb9f23482007-03-22 00:15:41 +0000971 string ProcessFromenvLocked(const string& flagval, FlagSettingMode set_mode,
Craig Silverstein67914682008-08-21 00:50:59 +0000972 bool errors_are_fatal);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000973
974 private:
975 FlagRegistry* const registry_;
Craig Silverstein67914682008-08-21 00:50:59 +0000976 map<string, string> error_flags_; // map from name to error message
Craig Silversteinb9f23482007-03-22 00:15:41 +0000977 // This could be a set<string>, but we reuse the map to minimize the .o size
Craig Silverstein67914682008-08-21 00:50:59 +0000978 map<string, string> undefined_names_; // --[flag] name was not registered
Craig Silversteinb9f23482007-03-22 00:15:41 +0000979};
980
981
982// Parse a list of (comma-separated) flags.
983static void ParseFlagList(const char* value, vector<string>* flags) {
984 for (const char *p = value; p && *p; value = p) {
985 p = strchr(value, ',');
Craig Silverstein917f4e72011-07-29 04:26:49 +0000986 size_t len;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000987 if (p) {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000988 len = p - value;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000989 p++;
990 } else {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000991 len = strlen(value);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000992 }
993
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000994 if (len == 0)
995 ReportError(DIE, "ERROR: empty flaglist entry\n");
996 if (value[0] == '-')
997 ReportError(DIE, "ERROR: flag \"%*s\" begins with '-'\n", len, value);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000998
999 flags->push_back(string(value, len));
1000 }
1001}
1002
1003// Snarf an entire file into a C++ string. This is just so that we
1004// can do all the I/O in one place and not worry about it everywhere.
1005// Plus, it's convenient to have the whole file contents at hand.
1006// Adds a newline at the end of the file.
Craig Silverstein917f4e72011-07-29 04:26:49 +00001007#define PFATAL(s) do { perror(s); gflags_exitfunc(1); } while (0)
Craig Silversteinb9f23482007-03-22 00:15:41 +00001008
1009static string ReadFileIntoString(const char* filename) {
Craig Silverstein67914682008-08-21 00:50:59 +00001010 const int kBufSize = 8092;
1011 char buffer[kBufSize];
Craig Silversteinb9f23482007-03-22 00:15:41 +00001012 string s;
1013 FILE* fp = fopen(filename, "r");
1014 if (!fp) PFATAL(filename);
Craig Silverstein67914682008-08-21 00:50:59 +00001015 size_t n;
1016 while ( (n=fread(buffer, 1, kBufSize, fp)) > 0 ) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001017 if (ferror(fp)) PFATAL(filename);
1018 s.append(buffer, n);
1019 }
1020 fclose(fp);
1021 return s;
1022}
1023
1024uint32 CommandLineFlagParser::ParseNewCommandLineFlags(int* argc, char*** argv,
1025 bool remove_flags) {
1026 const char *program_name = strrchr((*argv)[0], PATH_SEPARATOR); // nix path
1027 program_name = (program_name == NULL ? (*argv)[0] : program_name+1);
1028
1029 int first_nonopt = *argc; // for non-options moved to the end
1030
1031 registry_->Lock();
1032 for (int i = 1; i < first_nonopt; i++) {
1033 char* arg = (*argv)[i];
1034
1035 // Like getopt(), we permute non-option flags to be at the end.
Craig Silverstein83911c12008-03-27 20:11:07 +00001036 if (arg[0] != '-' || // must be a program argument
1037 (arg[0] == '-' && arg[1] == '\0')) { // "-" is an argument, not a flag
Craig Silversteinb9f23482007-03-22 00:15:41 +00001038 memmove((*argv) + i, (*argv) + i+1, (*argc - (i+1)) * sizeof((*argv)[i]));
1039 (*argv)[*argc-1] = arg; // we go last
1040 first_nonopt--; // we've been pushed onto the stack
1041 i--; // to undo the i++ in the loop
1042 continue;
1043 }
1044
1045 if (arg[0] == '-') arg++; // allow leading '-'
1046 if (arg[0] == '-') arg++; // or leading '--'
1047
Craig Silverstein83911c12008-03-27 20:11:07 +00001048 // -- alone means what it does for GNU: stop options parsing
Craig Silversteinb9f23482007-03-22 00:15:41 +00001049 if (*arg == '\0') {
1050 first_nonopt = i+1;
1051 break;
1052 }
1053
1054 // Find the flag object for this option
1055 string key;
1056 const char* value;
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001057 string error_message;
1058 CommandLineFlag* flag = registry_->SplitArgumentLocked(arg, &key, &value,
1059 &error_message);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001060 if (flag == NULL) {
1061 undefined_names_[key] = ""; // value isn't actually used
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001062 error_flags_[key] = error_message;
Craig Silversteinb9f23482007-03-22 00:15:41 +00001063 continue;
1064 }
1065
1066 if (value == NULL) {
1067 // Boolean options are always assigned a value by SplitArgumentLocked()
1068 assert(strcmp(flag->type_name(), "bool") != 0);
1069 if (i+1 >= first_nonopt) {
1070 // This flag needs a value, but there is nothing available
Craig Silverstein67914682008-08-21 00:50:59 +00001071 error_flags_[key] = (string(kError) + "flag '" + (*argv)[i] + "'"
1072 + " is missing its argument");
1073 if (flag->help() && flag->help()[0] > '\001') {
1074 // Be useful in case we have a non-stripped description.
1075 error_flags_[key] += string("; flag description: ") + flag->help();
1076 }
1077 error_flags_[key] += "\n";
Craig Silversteinb9f23482007-03-22 00:15:41 +00001078 break; // we treat this as an unrecoverable error
1079 } else {
1080 value = (*argv)[++i]; // read next arg for value
Craig Silverstein688ea022009-09-11 00:15:50 +00001081
1082 // Heuristic to detect the case where someone treats a string arg
1083 // like a bool:
1084 // --my_string_var --foo=bar
1085 // We look for a flag of string type, whose value begins with a
1086 // dash, and where the flag-name and value are separated by a
1087 // space rather than an '='.
1088 // To avoid false positives, we also require the word "true"
1089 // or "false" in the help string. Without this, a valid usage
1090 // "-lat -30.5" would trigger the warning. The common cases we
1091 // want to solve talk about true and false as values.
1092 if (value[0] == '-'
1093 && strcmp(flag->type_name(), "string") == 0
1094 && (strstr(flag->help(), "true")
1095 || strstr(flag->help(), "false"))) {
Craig Silverstein917f4e72011-07-29 04:26:49 +00001096 LOG(WARNING) << "Did you really mean to set flag '"
1097 << flag->name() << "' to the value '"
1098 << value << "'?";
Craig Silverstein688ea022009-09-11 00:15:50 +00001099 }
Craig Silversteinb9f23482007-03-22 00:15:41 +00001100 }
1101 }
1102
1103 // TODO(csilvers): only set a flag if we hadn't set it before here
1104 ProcessSingleOptionLocked(flag, value, SET_FLAGS_VALUE);
1105 }
1106 registry_->Unlock();
1107
1108 if (remove_flags) { // Fix up argc and argv by removing command line flags
1109 (*argv)[first_nonopt-1] = (*argv)[0];
1110 (*argv) += (first_nonopt-1);
1111 (*argc) -= (first_nonopt-1);
1112 first_nonopt = 1; // because we still don't count argv[0]
1113 }
1114
1115 logging_is_probably_set_up = true; // because we've parsed --logdir, etc.
1116
1117 return first_nonopt;
1118}
1119
1120string CommandLineFlagParser::ProcessFlagfileLocked(const string& flagval,
1121 FlagSettingMode set_mode) {
1122 if (flagval.empty())
1123 return "";
1124
1125 string msg;
1126 vector<string> filename_list;
1127 ParseFlagList(flagval.c_str(), &filename_list); // take a list of filenames
Craig Silverstein67914682008-08-21 00:50:59 +00001128 for (size_t i = 0; i < filename_list.size(); ++i) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001129 const char* file = filename_list[i].c_str();
1130 msg += ProcessOptionsFromStringLocked(ReadFileIntoString(file), set_mode);
1131 }
1132 return msg;
1133}
1134
1135string CommandLineFlagParser::ProcessFromenvLocked(const string& flagval,
1136 FlagSettingMode set_mode,
1137 bool errors_are_fatal) {
1138 if (flagval.empty())
1139 return "";
1140
1141 string msg;
1142 vector<string> flaglist;
1143 ParseFlagList(flagval.c_str(), &flaglist);
1144
Craig Silverstein67914682008-08-21 00:50:59 +00001145 for (size_t i = 0; i < flaglist.size(); ++i) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001146 const char* flagname = flaglist[i].c_str();
1147 CommandLineFlag* flag = registry_->FindFlagLocked(flagname);
1148 if (flag == NULL) {
Craig Silverstein917f4e72011-07-29 04:26:49 +00001149 error_flags_[flagname] =
1150 StringPrintf("%sunknown command line flag '%s' "
1151 "(via --fromenv or --tryfromenv)\n",
1152 kError, flagname);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001153 undefined_names_[flagname] = "";
1154 continue;
1155 }
1156
1157 const string envname = string("FLAGS_") + string(flagname);
1158 const char* envval = getenv(envname.c_str());
1159 if (!envval) {
1160 if (errors_are_fatal) {
1161 error_flags_[flagname] = (string(kError) + envname +
1162 " not found in environment\n");
1163 }
1164 continue;
1165 }
1166
1167 // Avoid infinite recursion.
1168 if ((strcmp(envval, "fromenv") == 0) ||
1169 (strcmp(envval, "tryfromenv") == 0)) {
Craig Silverstein917f4e72011-07-29 04:26:49 +00001170 error_flags_[flagname] =
1171 StringPrintf("%sinfinite recursion on environment flag '%s'\n",
1172 kError, envval);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001173 continue;
1174 }
1175
1176 msg += ProcessSingleOptionLocked(flag, envval, set_mode);
1177 }
1178 return msg;
1179}
1180
1181string CommandLineFlagParser::ProcessSingleOptionLocked(
1182 CommandLineFlag* flag, const char* value, FlagSettingMode set_mode) {
1183 string msg;
1184 if (value && !registry_->SetFlagLocked(flag, value, set_mode, &msg)) {
1185 error_flags_[flag->name()] = msg;
1186 return "";
1187 }
1188
1189 // The recursive flags, --flagfile and --fromenv and --tryfromenv,
1190 // must be dealt with as soon as they're seen. They will emit
1191 // messages of their own.
1192 if (strcmp(flag->name(), "flagfile") == 0) {
1193 msg += ProcessFlagfileLocked(FLAGS_flagfile, set_mode);
1194
1195 } else if (strcmp(flag->name(), "fromenv") == 0) {
1196 // last arg indicates envval-not-found is fatal (unlike in --tryfromenv)
1197 msg += ProcessFromenvLocked(FLAGS_fromenv, set_mode, true);
1198
1199 } else if (strcmp(flag->name(), "tryfromenv") == 0) {
1200 msg += ProcessFromenvLocked(FLAGS_tryfromenv, set_mode, false);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001201 }
1202
1203 return msg;
1204}
1205
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001206void CommandLineFlagParser::ValidateAllFlags() {
1207 FlagRegistryLock frl(registry_);
1208 for (FlagRegistry::FlagConstIterator i = registry_->flags_.begin();
1209 i != registry_->flags_.end(); ++i) {
1210 if (!i->second->ValidateCurrent()) {
1211 // only set a message if one isn't already there. (If there's
1212 // an error message, our job is done, even if it's not exactly
1213 // the same error.)
1214 if (error_flags_[i->second->name()].empty())
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001215 error_flags_[i->second->name()] =
1216 string(kError) + "--" + i->second->name() +
1217 " must be set on the commandline"
1218 " (default value fails validation)\n";
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001219 }
1220 }
1221}
1222
Craig Silversteinb9f23482007-03-22 00:15:41 +00001223bool CommandLineFlagParser::ReportErrors() {
1224 // error_flags_ indicates errors we saw while parsing.
1225 // But we ignore undefined-names if ok'ed by --undef_ok
1226 if (!FLAGS_undefok.empty()) {
1227 vector<string> flaglist;
1228 ParseFlagList(FLAGS_undefok.c_str(), &flaglist);
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001229 for (size_t i = 0; i < flaglist.size(); ++i) {
1230 // We also deal with --no<flag>, in case the flagname was boolean
1231 const string no_version = string("no") + flaglist[i];
Craig Silversteinb9f23482007-03-22 00:15:41 +00001232 if (undefined_names_.find(flaglist[i]) != undefined_names_.end()) {
1233 error_flags_[flaglist[i]] = ""; // clear the error message
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001234 } else if (undefined_names_.find(no_version) != undefined_names_.end()) {
1235 error_flags_[no_version] = "";
Craig Silversteinb9f23482007-03-22 00:15:41 +00001236 }
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001237 }
Craig Silversteinb9f23482007-03-22 00:15:41 +00001238 }
1239 // Likewise, if they decided to allow reparsing, all undefined-names
1240 // are ok; we just silently ignore them now, and hope that a future
1241 // parse will pick them up somehow.
1242 if (allow_command_line_reparsing) {
Craig Silverstein67914682008-08-21 00:50:59 +00001243 for (map<string, string>::const_iterator it = undefined_names_.begin();
Craig Silversteinb9f23482007-03-22 00:15:41 +00001244 it != undefined_names_.end(); ++it)
1245 error_flags_[it->first] = ""; // clear the error message
1246 }
1247
1248 bool found_error = false;
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001249 string error_message;
Craig Silverstein67914682008-08-21 00:50:59 +00001250 for (map<string, string>::const_iterator it = error_flags_.begin();
Craig Silversteinb9f23482007-03-22 00:15:41 +00001251 it != error_flags_.end(); ++it) {
1252 if (!it->second.empty()) {
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001253 error_message.append(it->second.data(), it->second.size());
Craig Silversteinb9f23482007-03-22 00:15:41 +00001254 found_error = true;
1255 }
1256 }
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001257 if (found_error)
1258 ReportError(DO_NOT_DIE, "%s", error_message.c_str());
Craig Silversteinb9f23482007-03-22 00:15:41 +00001259 return found_error;
1260}
1261
1262string CommandLineFlagParser::ProcessOptionsFromStringLocked(
1263 const string& contentdata, FlagSettingMode set_mode) {
1264 string retval;
1265 const char* flagfile_contents = contentdata.c_str();
1266 bool flags_are_relevant = true; // set to false when filenames don't match
1267 bool in_filename_section = false;
1268
1269 const char* line_end = flagfile_contents;
1270 // We read this file a line at a time.
1271 for (; line_end; flagfile_contents = line_end + 1) {
1272 while (*flagfile_contents && isspace(*flagfile_contents))
1273 ++flagfile_contents;
1274 line_end = strchr(flagfile_contents, '\n');
Craig Silverstein917f4e72011-07-29 04:26:49 +00001275 size_t len = line_end ? line_end - flagfile_contents
Craig Silverstein67914682008-08-21 00:50:59 +00001276 : strlen(flagfile_contents);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001277 string line(flagfile_contents, len);
1278
1279 // Each line can be one of four things:
1280 // 1) A comment line -- we skip it
1281 // 2) An empty line -- we skip it
1282 // 3) A list of filenames -- starts a new filenames+flags section
1283 // 4) A --flag=value line -- apply if previous filenames match
1284 if (line.empty() || line[0] == '#') {
1285 // comment or empty line; just ignore
1286
1287 } else if (line[0] == '-') { // flag
1288 in_filename_section = false; // instead, it was a flag-line
1289 if (!flags_are_relevant) // skip this flag; applies to someone else
1290 continue;
1291
1292 const char* name_and_val = line.c_str() + 1; // skip the leading -
1293 if (*name_and_val == '-')
1294 name_and_val++; // skip second - too
1295 string key;
1296 const char* value;
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001297 string error_message;
Craig Silversteinb9f23482007-03-22 00:15:41 +00001298 CommandLineFlag* flag = registry_->SplitArgumentLocked(name_and_val,
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001299 &key, &value,
1300 &error_message);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001301 // By API, errors parsing flagfile lines are silently ignored.
1302 if (flag == NULL) {
1303 // "WARNING: flagname '" + key + "' not found\n"
1304 } else if (value == NULL) {
1305 // "WARNING: flagname '" + key + "' missing a value\n"
1306 } else {
1307 retval += ProcessSingleOptionLocked(flag, value, set_mode);
1308 }
1309
1310 } else { // a filename!
1311 if (!in_filename_section) { // start over: assume filenames don't match
1312 in_filename_section = true;
1313 flags_are_relevant = false;
1314 }
1315
1316 // Split the line up at spaces into glob-patterns
1317 const char* space = line.c_str(); // just has to be non-NULL
1318 for (const char* word = line.c_str(); *space; word = space+1) {
1319 if (flags_are_relevant) // we can stop as soon as we match
1320 break;
1321 space = strchr(word, ' ');
1322 if (space == NULL)
1323 space = word + strlen(word);
1324 const string glob(word, space - word);
1325 // We try matching both against the full argv0 and basename(argv0)
Craig Silverstein917f4e72011-07-29 04:26:49 +00001326 if (glob == ProgramInvocationName() // small optimization
1327 || glob == ProgramInvocationShortName()
Craig Silverstein67914682008-08-21 00:50:59 +00001328#ifdef HAVE_FNMATCH_H
Craig Silverstein917f4e72011-07-29 04:26:49 +00001329 || fnmatch(glob.c_str(),
1330 ProgramInvocationName(),
1331 FNM_PATHNAME) == 0
1332 || fnmatch(glob.c_str(),
1333 ProgramInvocationShortName(),
1334 FNM_PATHNAME) == 0
1335#endif
1336 ) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001337 flags_are_relevant = true;
1338 }
1339 }
1340 }
1341 }
1342 return retval;
1343}
1344
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001345// --------------------------------------------------------------------
1346// GetFromEnv()
1347// AddFlagValidator()
1348// These are helper functions for routines like BoolFromEnv() and
1349// RegisterFlagValidator, defined below. They're defined here so
1350// they can live in the unnamed namespace (which makes friendship
1351// declarations for these classes possible).
1352// --------------------------------------------------------------------
1353
1354template<typename T>
1355T GetFromEnv(const char *varname, const char* type, T dflt) {
1356 const char* const valstr = getenv(varname);
1357 if (!valstr)
1358 return dflt;
Craig Silverstein0baf4ab2011-01-14 21:58:28 +00001359 FlagValue ifv(new T, type, true);
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001360 if (!ifv.ParseFrom(valstr))
1361 ReportError(DIE, "ERROR: error parsing env variable '%s' with value '%s'\n",
1362 varname, valstr);
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001363 return OTHER_VALUE_AS(ifv, T);
1364}
1365
1366bool AddFlagValidator(const void* flag_ptr, ValidateFnProto validate_fn_proto) {
1367 // We want a lock around this routine, in case two threads try to
1368 // add a validator (hopefully the same one!) at once. We could use
1369 // our own thread, but we need to loook at the registry anyway, so
1370 // we just steal that one.
1371 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1372 FlagRegistryLock frl(registry);
1373 // First, find the flag whose current-flag storage is 'flag'.
1374 // This is the CommandLineFlag whose current_->value_buffer_ == flag
1375 CommandLineFlag* flag = registry->FindFlagViaPtrLocked(flag_ptr);
1376 if (!flag) {
Craig Silverstein917f4e72011-07-29 04:26:49 +00001377 LOG(WARNING) << "Ignoring RegisterValidateFunction() for flag pointer "
1378 << flag_ptr << ": no flag found at that address";
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001379 return false;
1380 } else if (validate_fn_proto == flag->validate_function()) {
1381 return true; // ok to register the same function over and over again
1382 } else if (validate_fn_proto != NULL && flag->validate_function() != NULL) {
Craig Silverstein917f4e72011-07-29 04:26:49 +00001383 LOG(WARNING) << "Ignoring RegisterValidateFunction() for flag '"
1384 << flag->name() << "': validate-fn already registered";
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001385 return false;
1386 } else {
1387 flag->validate_fn_proto_ = validate_fn_proto;
1388 return true;
1389 }
1390}
1391
1392} // end unnamed namespaces
1393
1394
1395// Now define the functions that are exported via the .h file
1396
1397// --------------------------------------------------------------------
1398// FlagRegisterer
1399// This class exists merely to have a global constructor (the
1400// kind that runs before main(), that goes an initializes each
1401// flag that's been declared. Note that it's very important we
1402// don't have a destructor that deletes flag_, because that would
1403// cause us to delete current_storage/defvalue_storage as well,
1404// which can cause a crash if anything tries to access the flag
1405// values in a global destructor.
1406// --------------------------------------------------------------------
1407
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001408FlagRegisterer::FlagRegisterer(const char* name, const char* type,
1409 const char* help, const char* filename,
Craig Silverstein874aed52011-11-03 23:08:41 +00001410 void* current_storage, void* defvalue_storage,
1411 const OptionalDefineArgs& optional_args) {
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001412 if (help == NULL)
1413 help = "";
1414 // FlagValue expects the type-name to not include any namespace
1415 // components, so we get rid of those, if any.
1416 if (strchr(type, ':'))
1417 type = strrchr(type, ':') + 1;
Craig Silverstein0baf4ab2011-01-14 21:58:28 +00001418 FlagValue* current = new FlagValue(current_storage, type, false);
1419 FlagValue* defvalue = new FlagValue(defvalue_storage, type, false);
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001420 // Importantly, flag_ will never be deleted, so storage is always good.
1421 CommandLineFlag* flag = new CommandLineFlag(name, help, filename,
Craig Silverstein874aed52011-11-03 23:08:41 +00001422 optional_args.categories,
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001423 current, defvalue);
1424 FlagRegistry::GlobalRegistry()->RegisterFlag(flag); // default registry
1425}
1426
1427// --------------------------------------------------------------------
1428// GetAllFlags()
1429// The main way the FlagRegistry class exposes its data. This
1430// returns, as strings, all the info about all the flags in
1431// the main registry, sorted first by filename they are defined
1432// in, and then by flagname.
1433// --------------------------------------------------------------------
1434
1435struct FilenameFlagnameCmp {
1436 bool operator()(const CommandLineFlagInfo& a,
1437 const CommandLineFlagInfo& b) const {
1438 int cmp = strcmp(a.filename.c_str(), b.filename.c_str());
1439 if (cmp == 0)
1440 cmp = strcmp(a.name.c_str(), b.name.c_str()); // secondary sort key
1441 return cmp < 0;
1442 }
1443};
1444
1445void GetAllFlags(vector<CommandLineFlagInfo>* OUTPUT) {
1446 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1447 registry->Lock();
1448 for (FlagRegistry::FlagConstIterator i = registry->flags_.begin();
1449 i != registry->flags_.end(); ++i) {
1450 CommandLineFlagInfo fi;
1451 i->second->FillCommandLineFlagInfo(&fi);
1452 OUTPUT->push_back(fi);
1453 }
1454 registry->Unlock();
1455 // Now sort the flags, first by filename they occur in, then alphabetically
1456 sort(OUTPUT->begin(), OUTPUT->end(), FilenameFlagnameCmp());
1457}
1458
1459// --------------------------------------------------------------------
1460// SetArgv()
1461// GetArgvs()
1462// GetArgv()
1463// GetArgv0()
1464// ProgramInvocationName()
1465// ProgramInvocationShortName()
1466// SetUsageMessage()
1467// ProgramUsage()
1468// Functions to set and get argv. Typically the setter is called
1469// by ParseCommandLineFlags. Also can get the ProgramUsage string,
Craig Silverstein917f4e72011-07-29 04:26:49 +00001470// set by SetUsageMessage.
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001471// --------------------------------------------------------------------
1472
1473// These values are not protected by a Mutex because they are normally
1474// set only once during program startup.
1475static const char* argv0 = "UNKNOWN"; // just the program name
1476static const char* cmdline = ""; // the entire command-line
1477static vector<string> argvs;
1478static uint32 argv_sum = 0;
Craig Silverstein67914682008-08-21 00:50:59 +00001479static const char* program_usage = NULL;
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001480
1481void SetArgv(int argc, const char** argv) {
1482 static bool called_set_argv = false;
1483 if (called_set_argv) // we already have an argv for you
1484 return;
1485
1486 called_set_argv = true;
1487
1488 assert(argc > 0); // every program has at least a progname
1489 argv0 = strdup(argv[0]); // small memory leak, but fn only called once
1490 assert(argv0);
1491
Craig Silverstein67914682008-08-21 00:50:59 +00001492 string cmdline_string; // easier than doing strcats
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001493 for (int i = 0; i < argc; i++) {
Craig Silverstein67914682008-08-21 00:50:59 +00001494 if (i != 0) {
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001495 cmdline_string += " ";
Craig Silverstein67914682008-08-21 00:50:59 +00001496 }
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001497 cmdline_string += argv[i];
1498 argvs.push_back(argv[i]);
1499 }
1500 cmdline = strdup(cmdline_string.c_str()); // another small memory leak
1501 assert(cmdline);
1502
1503 // Compute a simple sum of all the chars in argv
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001504 for (const char* c = cmdline; *c; c++)
1505 argv_sum += *c;
1506}
1507
1508const vector<string>& GetArgvs() { return argvs; }
1509const char* GetArgv() { return cmdline; }
1510const char* GetArgv0() { return argv0; }
1511uint32 GetArgvSum() { return argv_sum; }
1512const char* ProgramInvocationName() { // like the GNU libc fn
1513 return GetArgv0();
1514}
1515const char* ProgramInvocationShortName() { // like the GNU libc fn
1516 const char* slash = strrchr(argv0, '/');
1517#ifdef OS_WINDOWS
1518 if (!slash) slash = strrchr(argv0, '\\');
1519#endif
1520 return slash ? slash + 1 : argv0;
1521}
1522
1523void SetUsageMessage(const string& usage) {
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001524 if (program_usage != NULL)
1525 ReportError(DIE, "ERROR: SetUsageMessage() called twice\n");
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001526 program_usage = strdup(usage.c_str()); // small memory leak
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001527}
1528
1529const char* ProgramUsage() {
Craig Silverstein67914682008-08-21 00:50:59 +00001530 if (program_usage) {
1531 return program_usage;
1532 }
1533 return "Warning: SetUsageMessage() never called";
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001534}
Craig Silversteinb9f23482007-03-22 00:15:41 +00001535
Craig Silverstein917f4e72011-07-29 04:26:49 +00001536// --------------------------------------------------------------------
1537// SetVersionString()
1538// VersionString()
1539// --------------------------------------------------------------------
1540
1541static const char* version_string = NULL;
1542
1543void SetVersionString(const string& version) {
1544 if (version_string != NULL)
1545 ReportError(DIE, "ERROR: SetVersionString() called twice\n");
1546 version_string = strdup(version.c_str()); // small memory leak
1547}
1548
Craig Silversteinb4bf72b2011-03-03 22:26:24 +00001549const char* VersionString() {
1550 return version_string ? version_string : "";
1551}
1552
Craig Silverstein917f4e72011-07-29 04:26:49 +00001553
Craig Silversteinb9f23482007-03-22 00:15:41 +00001554// --------------------------------------------------------------------
1555// GetCommandLineOption()
1556// GetCommandLineFlagInfo()
Craig Silverstein290da382007-03-28 21:54:07 +00001557// GetCommandLineFlagInfoOrDie()
Craig Silversteinb9f23482007-03-22 00:15:41 +00001558// SetCommandLineOption()
1559// SetCommandLineOptionWithMode()
1560// The programmatic way to set a flag's value, using a string
1561// for its name rather than the variable itself (that is,
1562// SetCommandLineOption("foo", x) rather than FLAGS_foo = x).
1563// There's also a bit more flexibility here due to the various
1564// set-modes, but typically these are used when you only have
1565// that flag's name as a string, perhaps at runtime.
1566// All of these work on the default, global registry.
1567// For GetCommandLineOption, return false if no such flag
1568// is known, true otherwise. We clear "value" if a suitable
Craig Silverstein690172b2007-04-20 21:16:33 +00001569// flag is found.
Craig Silversteinb9f23482007-03-22 00:15:41 +00001570// --------------------------------------------------------------------
1571
1572
Craig Silverstein690172b2007-04-20 21:16:33 +00001573bool GetCommandLineOption(const char* name, string* value) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001574 if (NULL == name)
1575 return false;
1576 assert(value);
1577
1578 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001579 FlagRegistryLock frl(registry);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001580 CommandLineFlag* flag = registry->FindFlagLocked(name);
1581 if (flag == NULL) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001582 return false;
1583 } else {
1584 *value = flag->current_value();
Craig Silversteinb9f23482007-03-22 00:15:41 +00001585 return true;
1586 }
1587}
1588
1589bool GetCommandLineFlagInfo(const char* name, CommandLineFlagInfo* OUTPUT) {
1590 if (NULL == name) return false;
1591 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001592 FlagRegistryLock frl(registry);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001593 CommandLineFlag* flag = registry->FindFlagLocked(name);
1594 if (flag == NULL) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001595 return false;
1596 } else {
1597 assert(OUTPUT);
1598 flag->FillCommandLineFlagInfo(OUTPUT);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001599 return true;
1600 }
1601}
1602
Craig Silverstein290da382007-03-28 21:54:07 +00001603CommandLineFlagInfo GetCommandLineFlagInfoOrDie(const char* name) {
1604 CommandLineFlagInfo info;
1605 if (!GetCommandLineFlagInfo(name, &info)) {
Craig Silverstein688ea022009-09-11 00:15:50 +00001606 fprintf(stderr, "FATAL ERROR: flag name '%s' doesn't exist\n", name);
Craig Silverstein917f4e72011-07-29 04:26:49 +00001607 gflags_exitfunc(1); // almost certainly gflags_exitfunc()
Craig Silverstein290da382007-03-28 21:54:07 +00001608 }
1609 return info;
1610}
1611
Craig Silversteinb9f23482007-03-22 00:15:41 +00001612string SetCommandLineOptionWithMode(const char* name, const char* value,
1613 FlagSettingMode set_mode) {
1614 string result;
1615 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001616 FlagRegistryLock frl(registry);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001617 CommandLineFlag* flag = registry->FindFlagLocked(name);
1618 if (flag) {
1619 CommandLineFlagParser parser(registry);
1620 result = parser.ProcessSingleOptionLocked(flag, value, set_mode);
1621 if (!result.empty()) { // in the error case, we've already logged
Craig Silverstein917f4e72011-07-29 04:26:49 +00001622 // Could consider logging this change
Craig Silversteinb9f23482007-03-22 00:15:41 +00001623 }
1624 }
Craig Silversteinb9f23482007-03-22 00:15:41 +00001625 // The API of this function is that we return empty string on error
1626 return result;
1627}
1628
1629string SetCommandLineOption(const char* name, const char* value) {
1630 return SetCommandLineOptionWithMode(name, value, SET_FLAGS_VALUE);
1631}
1632
Craig Silversteinb9f23482007-03-22 00:15:41 +00001633// --------------------------------------------------------------------
1634// FlagSaver
1635// FlagSaverImpl
1636// This class stores the states of all flags at construct time,
1637// and restores all flags to that state at destruct time.
1638// Its major implementation challenge is that it never modifies
1639// pointers in the 'main' registry, so global FLAG_* vars always
1640// point to the right place.
1641// --------------------------------------------------------------------
1642
1643class FlagSaverImpl {
1644 public:
1645 // Constructs an empty FlagSaverImpl object.
1646 explicit FlagSaverImpl(FlagRegistry* main_registry)
1647 : main_registry_(main_registry) { }
1648 ~FlagSaverImpl() {
1649 // reclaim memory from each of our CommandLineFlags
1650 vector<CommandLineFlag*>::const_iterator it;
1651 for (it = backup_registry_.begin(); it != backup_registry_.end(); ++it)
1652 delete *it;
1653 }
1654
1655 // Saves the flag states from the flag registry into this object.
1656 // It's an error to call this more than once.
1657 // Must be called when the registry mutex is not held.
1658 void SaveFromRegistry() {
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001659 FlagRegistryLock frl(main_registry_);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001660 assert(backup_registry_.empty()); // call only once!
1661 for (FlagRegistry::FlagConstIterator it = main_registry_->flags_.begin();
1662 it != main_registry_->flags_.end();
1663 ++it) {
1664 const CommandLineFlag* main = it->second;
1665 // Sets up all the const variables in backup correctly
1666 CommandLineFlag* backup = new CommandLineFlag(
Craig Silverstein874aed52011-11-03 23:08:41 +00001667 main->name(), main->help(), main->filename(), main->categories(),
Craig Silversteinb9f23482007-03-22 00:15:41 +00001668 main->current_->New(), main->defvalue_->New());
1669 // Sets up all the non-const variables in backup correctly
1670 backup->CopyFrom(*main);
1671 backup_registry_.push_back(backup); // add it to a convenient list
1672 }
Craig Silversteinb9f23482007-03-22 00:15:41 +00001673 }
1674
1675 // Restores the saved flag states into the flag registry. We
1676 // assume no flags were added or deleted from the registry since
1677 // the SaveFromRegistry; if they were, that's trouble! Must be
1678 // called when the registry mutex is not held.
1679 void RestoreToRegistry() {
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001680 FlagRegistryLock frl(main_registry_);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001681 vector<CommandLineFlag*>::const_iterator it;
1682 for (it = backup_registry_.begin(); it != backup_registry_.end(); ++it) {
1683 CommandLineFlag* main = main_registry_->FindFlagLocked((*it)->name());
1684 if (main != NULL) { // if NULL, flag got deleted from registry(!)
1685 main->CopyFrom(**it);
1686 }
1687 }
Craig Silversteinb9f23482007-03-22 00:15:41 +00001688 }
1689
1690 private:
1691 FlagRegistry* const main_registry_;
1692 vector<CommandLineFlag*> backup_registry_;
1693
1694 FlagSaverImpl(const FlagSaverImpl&); // no copying!
1695 void operator=(const FlagSaverImpl&);
1696};
1697
Craig Silverstein67914682008-08-21 00:50:59 +00001698FlagSaver::FlagSaver()
1699 : impl_(new FlagSaverImpl(FlagRegistry::GlobalRegistry())) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001700 impl_->SaveFromRegistry();
1701}
1702
1703FlagSaver::~FlagSaver() {
1704 impl_->RestoreToRegistry();
1705 delete impl_;
1706}
1707
1708
1709// --------------------------------------------------------------------
1710// CommandlineFlagsIntoString()
1711// ReadFlagsFromString()
1712// AppendFlagsIntoFile()
1713// ReadFromFlagsFile()
1714// These are mostly-deprecated routines that stick the
1715// commandline flags into a file/string and read them back
1716// out again. I can see a use for CommandlineFlagsIntoString,
1717// for creating a flagfile, but the rest don't seem that useful
1718// -- some, I think, are a poor-man's attempt at FlagSaver --
1719// and are included only until we can delete them from callers.
1720// Note they don't save --flagfile flags (though they do save
1721// the result of having called the flagfile, of course).
1722// --------------------------------------------------------------------
1723
1724static string TheseCommandlineFlagsIntoString(
1725 const vector<CommandLineFlagInfo>& flags) {
1726 vector<CommandLineFlagInfo>::const_iterator i;
1727
Craig Silverstein67914682008-08-21 00:50:59 +00001728 size_t retval_space = 0;
Craig Silversteinb9f23482007-03-22 00:15:41 +00001729 for (i = flags.begin(); i != flags.end(); ++i) {
1730 // An (over)estimate of how much space it will take to print this flag
1731 retval_space += i->name.length() + i->current_value.length() + 5;
1732 }
1733
1734 string retval;
1735 retval.reserve(retval_space);
1736 for (i = flags.begin(); i != flags.end(); ++i) {
1737 retval += "--";
1738 retval += i->name;
1739 retval += "=";
1740 retval += i->current_value;
1741 retval += "\n";
1742 }
1743 return retval;
1744}
1745
1746string CommandlineFlagsIntoString() {
1747 vector<CommandLineFlagInfo> sorted_flags;
1748 GetAllFlags(&sorted_flags);
1749 return TheseCommandlineFlagsIntoString(sorted_flags);
1750}
1751
1752bool ReadFlagsFromString(const string& flagfilecontents,
Craig Silverstein67914682008-08-21 00:50:59 +00001753 const char* /*prog_name*/, // TODO(csilvers): nix this
Craig Silversteinb9f23482007-03-22 00:15:41 +00001754 bool errors_are_fatal) {
1755 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1756 FlagSaverImpl saved_states(registry);
1757 saved_states.SaveFromRegistry();
1758
1759 CommandLineFlagParser parser(registry);
1760 registry->Lock();
1761 parser.ProcessOptionsFromStringLocked(flagfilecontents, SET_FLAGS_VALUE);
1762 registry->Unlock();
1763 // Should we handle --help and such when reading flags from a string? Sure.
1764 HandleCommandLineHelpFlags();
1765 if (parser.ReportErrors()) {
1766 // Error. Restore all global flags to their previous values.
1767 if (errors_are_fatal)
Craig Silverstein917f4e72011-07-29 04:26:49 +00001768 gflags_exitfunc(1);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001769 saved_states.RestoreToRegistry();
1770 return false;
1771 }
1772 return true;
1773}
1774
1775// TODO(csilvers): nix prog_name in favor of ProgramInvocationShortName()
1776bool AppendFlagsIntoFile(const string& filename, const char *prog_name) {
1777 FILE *fp = fopen(filename.c_str(), "a");
1778 if (!fp) {
1779 return false;
1780 }
1781
1782 if (prog_name)
1783 fprintf(fp, "%s\n", prog_name);
1784
1785 vector<CommandLineFlagInfo> flags;
1786 GetAllFlags(&flags);
1787 // But we don't want --flagfile, which leads to weird recursion issues
1788 vector<CommandLineFlagInfo>::iterator i;
1789 for (i = flags.begin(); i != flags.end(); ++i) {
1790 if (strcmp(i->name.c_str(), "flagfile") == 0) {
1791 flags.erase(i);
1792 break;
1793 }
1794 }
1795 fprintf(fp, "%s", TheseCommandlineFlagsIntoString(flags).c_str());
1796
1797 fclose(fp);
1798 return true;
1799}
1800
1801bool ReadFromFlagsFile(const string& filename, const char* prog_name,
1802 bool errors_are_fatal) {
1803 return ReadFlagsFromString(ReadFileIntoString(filename.c_str()),
1804 prog_name, errors_are_fatal);
1805}
1806
1807
1808// --------------------------------------------------------------------
1809// BoolFromEnv()
1810// Int32FromEnv()
1811// Int64FromEnv()
1812// Uint64FromEnv()
1813// DoubleFromEnv()
1814// StringFromEnv()
1815// Reads the value from the environment and returns it.
1816// We use an FlagValue to make the parsing easy.
1817// Example usage:
Craig Silverstein2b66a842007-06-12 23:59:42 +00001818// DEFINE_bool(myflag, BoolFromEnv("MYFLAG_DEFAULT", false), "whatever");
Craig Silversteinb9f23482007-03-22 00:15:41 +00001819// --------------------------------------------------------------------
1820
Craig Silversteinb9f23482007-03-22 00:15:41 +00001821bool BoolFromEnv(const char *v, bool dflt) {
1822 return GetFromEnv(v, "bool", dflt);
1823}
1824int32 Int32FromEnv(const char *v, int32 dflt) {
1825 return GetFromEnv(v, "int32", dflt);
1826}
1827int64 Int64FromEnv(const char *v, int64 dflt) {
1828 return GetFromEnv(v, "int64", dflt);
1829}
1830uint64 Uint64FromEnv(const char *v, uint64 dflt) {
1831 return GetFromEnv(v, "uint64", dflt);
1832}
1833double DoubleFromEnv(const char *v, double dflt) {
1834 return GetFromEnv(v, "double", dflt);
1835}
1836const char *StringFromEnv(const char *varname, const char *dflt) {
1837 const char* const val = getenv(varname);
1838 return val ? val : dflt;
1839}
1840
1841
1842// --------------------------------------------------------------------
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001843// RegisterFlagValidator()
1844// RegisterFlagValidator() is the function that clients use to
1845// 'decorate' a flag with a validation function. Once this is
1846// done, every time the flag is set (including when the flag
1847// is parsed from argv), the validator-function is called.
1848// These functions return true if the validator was added
1849// successfully, or false if not: the flag already has a validator,
1850// (only one allowed per flag), the 1st arg isn't a flag, etc.
1851// This function is not thread-safe.
1852// --------------------------------------------------------------------
1853
1854bool RegisterFlagValidator(const bool* flag,
1855 bool (*validate_fn)(const char*, bool)) {
1856 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1857}
1858bool RegisterFlagValidator(const int32* flag,
1859 bool (*validate_fn)(const char*, int32)) {
1860 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1861}
1862bool RegisterFlagValidator(const int64* flag,
1863 bool (*validate_fn)(const char*, int64)) {
1864 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1865}
1866bool RegisterFlagValidator(const uint64* flag,
1867 bool (*validate_fn)(const char*, uint64)) {
1868 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1869}
1870bool RegisterFlagValidator(const double* flag,
1871 bool (*validate_fn)(const char*, double)) {
1872 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1873}
1874bool RegisterFlagValidator(const string* flag,
1875 bool (*validate_fn)(const char*, const string&)) {
1876 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1877}
1878
1879
1880// --------------------------------------------------------------------
Craig Silversteinb9f23482007-03-22 00:15:41 +00001881// ParseCommandLineFlags()
1882// ParseCommandLineNonHelpFlags()
1883// HandleCommandLineHelpFlags()
1884// This is the main function called from main(), to actually
1885// parse the commandline. It modifies argc and argv as described
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001886// at the top of gflags.h. You can also divide this
Craig Silversteinb9f23482007-03-22 00:15:41 +00001887// function into two parts, if you want to do work between
1888// the parsing of the flags and the printing of any help output.
1889// --------------------------------------------------------------------
1890
1891static uint32 ParseCommandLineFlagsInternal(int* argc, char*** argv,
1892 bool remove_flags, bool do_report) {
1893 SetArgv(*argc, const_cast<const char**>(*argv)); // save it for later
1894
1895 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1896 CommandLineFlagParser parser(registry);
1897
1898 // When we parse the commandline flags, we'll handle --flagfile,
1899 // --tryfromenv, etc. as we see them (since flag-evaluation order
1900 // may be important). But sometimes apps set FLAGS_tryfromenv/etc.
1901 // manually before calling ParseCommandLineFlags. We want to evaluate
1902 // those too, as if they were the first flags on the commandline.
1903 registry->Lock();
1904 parser.ProcessFlagfileLocked(FLAGS_flagfile, SET_FLAGS_VALUE);
1905 // Last arg here indicates whether flag-not-found is a fatal error or not
1906 parser.ProcessFromenvLocked(FLAGS_fromenv, SET_FLAGS_VALUE, true);
1907 parser.ProcessFromenvLocked(FLAGS_tryfromenv, SET_FLAGS_VALUE, false);
1908 registry->Unlock();
1909
1910 // Now get the flags specified on the commandline
1911 const int r = parser.ParseNewCommandLineFlags(argc, argv, remove_flags);
1912
1913 if (do_report)
1914 HandleCommandLineHelpFlags(); // may cause us to exit on --help, etc.
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001915
1916 // See if any of the unset flags fail their validation checks
1917 parser.ValidateAllFlags();
1918
Craig Silversteinb9f23482007-03-22 00:15:41 +00001919 if (parser.ReportErrors()) // may cause us to exit on illegal flags
Craig Silverstein917f4e72011-07-29 04:26:49 +00001920 gflags_exitfunc(1);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001921 return r;
1922}
1923
1924uint32 ParseCommandLineFlags(int* argc, char*** argv, bool remove_flags) {
1925 return ParseCommandLineFlagsInternal(argc, argv, remove_flags, true);
1926}
1927
1928uint32 ParseCommandLineNonHelpFlags(int* argc, char*** argv,
1929 bool remove_flags) {
1930 return ParseCommandLineFlagsInternal(argc, argv, remove_flags, false);
1931}
1932
1933// --------------------------------------------------------------------
1934// AllowCommandLineReparsing()
1935// ReparseCommandLineNonHelpFlags()
1936// This is most useful for shared libraries. The idea is if
1937// a flag is defined in a shared library that is dlopen'ed
1938// sometime after main(), you can ParseCommandLineFlags before
1939// the dlopen, then ReparseCommandLineNonHelpFlags() after the
1940// dlopen, to get the new flags. But you have to explicitly
1941// Allow() it; otherwise, you get the normal default behavior
1942// of unrecognized flags calling a fatal error.
Craig Silverstein67914682008-08-21 00:50:59 +00001943// TODO(csilvers): this isn't used. Just delete it?
Craig Silversteinb9f23482007-03-22 00:15:41 +00001944// --------------------------------------------------------------------
1945
1946void AllowCommandLineReparsing() {
1947 allow_command_line_reparsing = true;
1948}
1949
Craig Silverstein71e1be92011-03-02 08:05:17 +00001950void ReparseCommandLineNonHelpFlags() {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001951 // We make a copy of argc and argv to pass in
1952 const vector<string>& argvs = GetArgvs();
Craig Silverstein67914682008-08-21 00:50:59 +00001953 int tmp_argc = static_cast<int>(argvs.size());
Craig Silversteinb9f23482007-03-22 00:15:41 +00001954 char** tmp_argv = new char* [tmp_argc + 1];
1955 for (int i = 0; i < tmp_argc; ++i)
1956 tmp_argv[i] = strdup(argvs[i].c_str()); // TODO(csilvers): don't dup
1957
Craig Silverstein71e1be92011-03-02 08:05:17 +00001958 ParseCommandLineNonHelpFlags(&tmp_argc, &tmp_argv, false);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001959
1960 for (int i = 0; i < tmp_argc; ++i)
1961 free(tmp_argv[i]);
1962 delete[] tmp_argv;
Craig Silversteinb9f23482007-03-22 00:15:41 +00001963}
1964
Craig Silverstein0baf4ab2011-01-14 21:58:28 +00001965void ShutDownCommandLineFlags() {
1966 FlagRegistry::DeleteGlobalRegistry();
1967}
1968
Craig Silversteinb9f23482007-03-22 00:15:41 +00001969_END_GOOGLE_NAMESPACE_