blob: a136fde829a83b6b7270157b7d5f7faef9105fb9 [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 Silversteinb9f23482007-03-22 00:15:41 +0000500
Craig Silverstein290da382007-03-28 21:54:07 +0000501 void FillCommandLineFlagInfo(struct CommandLineFlagInfo* result);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000502
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000503 // If validate_fn_proto_ is non-NULL, calls it on value, returns result.
504 bool Validate(const FlagValue& value) const;
505 bool ValidateCurrent() const { return Validate(*current_); }
506
Craig Silversteinb9f23482007-03-22 00:15:41 +0000507 private:
Craig Silverstein67914682008-08-21 00:50:59 +0000508 // for SetFlagLocked() and setting flags_by_ptr_
509 friend class FlagRegistry;
510 friend class GOOGLE_NAMESPACE::FlagSaverImpl; // for cloning the values
Craig Silverstein67914682008-08-21 00:50:59 +0000511 // set validate_fn
512 friend bool AddFlagValidator(const void*, ValidateFnProto);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000513
514 // This copies all the non-const members: modified, processed, defvalue, etc.
515 void CopyFrom(const CommandLineFlag& src);
516
517 void UpdateModifiedBit();
518
519 const char* const name_; // Flag name
520 const char* const help_; // Help message
521 const char* const file_; // Which file did this come from?
Craig Silverstein874aed52011-11-03 23:08:41 +0000522 const char* categories_; // Comma-separated list of flag's 'categories'
Craig Silversteinb9f23482007-03-22 00:15:41 +0000523 bool modified_; // Set after default assignment?
524 FlagValue* defvalue_; // Default value for flag
525 FlagValue* current_; // Current value for flag
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000526 // This is a casted, 'generic' version of validate_fn, which actually
527 // takes a flag-value as an arg (void (*validate_fn)(bool), say).
528 // When we pass this to current_->Validate(), it will cast it back to
529 // the proper type. This may be NULL to mean we have no validate_fn.
530 ValidateFnProto validate_fn_proto_;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000531
532 CommandLineFlag(const CommandLineFlag&); // no copying!
533 void operator=(const CommandLineFlag&);
534};
535
536CommandLineFlag::CommandLineFlag(const char* name, const char* help,
Craig Silverstein874aed52011-11-03 23:08:41 +0000537 const char* filename, const char* categories,
Craig Silversteinb9f23482007-03-22 00:15:41 +0000538 FlagValue* current_val, FlagValue* default_val)
Craig Silverstein874aed52011-11-03 23:08:41 +0000539 : name_(name), help_(help), file_(filename), categories_(categories),
540 modified_(false), defvalue_(default_val), current_(current_val),
541 validate_fn_proto_(NULL) {
Craig Silversteinb9f23482007-03-22 00:15:41 +0000542}
543
544CommandLineFlag::~CommandLineFlag() {
545 delete current_;
546 delete defvalue_;
547}
548
549const char* CommandLineFlag::CleanFileName() const {
550 // Compute top-level directory & file that this appears in
Craig Silversteineb208392007-08-15 19:44:54 +0000551 // search full path backwards.
Craig Silverstein83911c12008-03-27 20:11:07 +0000552 // Stop going backwards at kRootDir; and skip by the first slash.
553 static const char kRootDir[] = ""; // can set this to root directory,
Craig Silversteinb9f23482007-03-22 00:15:41 +0000554
Craig Silverstein83911c12008-03-27 20:11:07 +0000555 if (sizeof(kRootDir)-1 == 0) // no prefix to strip
Craig Silversteinb9f23482007-03-22 00:15:41 +0000556 return filename();
557
558 const char* clean_name = filename() + strlen(filename()) - 1;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000559 while ( clean_name > filename() ) {
560 if (*clean_name == PATH_SEPARATOR) {
Craig Silverstein83911c12008-03-27 20:11:07 +0000561 if (strncmp(clean_name, kRootDir, sizeof(kRootDir)-1) == 0) {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000562 clean_name += sizeof(kRootDir)-1; // past root-dir
Craig Silversteinb9f23482007-03-22 00:15:41 +0000563 break;
564 }
565 }
566 --clean_name;
567 }
568 while ( *clean_name == PATH_SEPARATOR ) ++clean_name; // Skip any slashes
569 return clean_name;
570}
571
572void CommandLineFlag::FillCommandLineFlagInfo(
Craig Silverstein290da382007-03-28 21:54:07 +0000573 CommandLineFlagInfo* result) {
Craig Silversteinb9f23482007-03-22 00:15:41 +0000574 result->name = name();
575 result->type = type_name();
576 result->description = help();
Craig Silverstein874aed52011-11-03 23:08:41 +0000577 result->categories = categories();
Craig Silversteinb9f23482007-03-22 00:15:41 +0000578 result->current_value = current_value();
579 result->default_value = default_value();
580 result->filename = CleanFileName();
Craig Silverstein290da382007-03-28 21:54:07 +0000581 UpdateModifiedBit();
582 result->is_default = !modified_;
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000583 result->has_validator_fn = validate_function() != NULL;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000584}
585
586void CommandLineFlag::UpdateModifiedBit() {
587 // Update the "modified" bit in case somebody bypassed the
588 // Flags API and wrote directly through the FLAGS_name variable.
589 if (!modified_ && !current_->Equal(*defvalue_)) {
590 modified_ = true;
591 }
592}
593
594void CommandLineFlag::CopyFrom(const CommandLineFlag& src) {
595 // Note we only copy the non-const members; others are fixed at construct time
Craig Silverstein67914682008-08-21 00:50:59 +0000596 if (modified_ != src.modified_) modified_ = src.modified_;
597 if (!current_->Equal(*src.current_)) current_->CopyFrom(*src.current_);
598 if (!defvalue_->Equal(*src.defvalue_)) defvalue_->CopyFrom(*src.defvalue_);
599 if (validate_fn_proto_ != src.validate_fn_proto_)
600 validate_fn_proto_ = src.validate_fn_proto_;
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000601}
602
603bool CommandLineFlag::Validate(const FlagValue& value) const {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000604
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000605 if (validate_function() == NULL)
606 return true;
607 else
608 return value.Validate(name(), validate_function());
Craig Silversteinb9f23482007-03-22 00:15:41 +0000609}
610
611
612// --------------------------------------------------------------------
613// FlagRegistry
614// A FlagRegistry singleton object holds all flag objects indexed
615// by their names so that if you know a flag's name (as a C
616// string), you can access or set it. If the function is named
617// FooLocked(), you must own the registry lock before calling
618// the function; otherwise, you should *not* hold the lock, and
619// the function will acquire it itself if needed.
620// --------------------------------------------------------------------
621
622struct StringCmp { // Used by the FlagRegistry map class to compare char*'s
623 bool operator() (const char* s1, const char* s2) const {
624 return (strcmp(s1, s2) < 0);
625 }
626};
627
Craig Silverstein917f4e72011-07-29 04:26:49 +0000628
Craig Silversteinb9f23482007-03-22 00:15:41 +0000629class FlagRegistry {
630 public:
Craig Silverstein917f4e72011-07-29 04:26:49 +0000631 FlagRegistry() {
632 }
Craig Silverstein0baf4ab2011-01-14 21:58:28 +0000633 ~FlagRegistry() {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000634 // Not using STLDeleteElements as that resides in util and this
635 // class is base.
Craig Silverstein0baf4ab2011-01-14 21:58:28 +0000636 for (FlagMap::iterator p = flags_.begin(), e = flags_.end(); p != e; ++p) {
637 CommandLineFlag* flag = p->second;
638 delete flag;
639 }
640 }
641
642 static void DeleteGlobalRegistry() {
643 delete global_registry_;
644 global_registry_ = NULL;
645 }
Craig Silverstein67914682008-08-21 00:50:59 +0000646
Craig Silversteinb9f23482007-03-22 00:15:41 +0000647 // Store a flag in this registry. Takes ownership of the given pointer.
648 void RegisterFlag(CommandLineFlag* flag);
649
Craig Silverstein917f4e72011-07-29 04:26:49 +0000650 void Lock() { lock_.Lock(); }
651 void Unlock() { lock_.Unlock(); }
652
Craig Silversteinb9f23482007-03-22 00:15:41 +0000653 // Returns the flag object for the specified name, or NULL if not found.
654 CommandLineFlag* FindFlagLocked(const char* name);
655
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000656 // Returns the flag object whose current-value is stored at flag_ptr.
657 // That is, for whom current_->value_buffer_ == flag_ptr
658 CommandLineFlag* FindFlagViaPtrLocked(const void* flag_ptr);
659
Craig Silversteinb9f23482007-03-22 00:15:41 +0000660 // A fancier form of FindFlag that works correctly if name is of the
661 // form flag=value. In that case, we set key to point to flag, and
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000662 // modify v to point to the value (if present), and return the flag
663 // with the given name. If the flag does not exist, returns NULL
664 // and sets error_message.
Craig Silversteinb9f23482007-03-22 00:15:41 +0000665 CommandLineFlag* SplitArgumentLocked(const char* argument,
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000666 string* key, const char** v,
667 string* error_message);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000668
669 // Set the value of a flag. If the flag was successfully set to
670 // value, set msg to indicate the new flag-value, and return true.
671 // Otherwise, set msg to indicate the error, leave flag unchanged,
672 // and return false. msg can be NULL.
673 bool SetFlagLocked(CommandLineFlag* flag, const char* value,
674 FlagSettingMode set_mode, string* msg);
675
676 static FlagRegistry* GlobalRegistry(); // returns a singleton registry
677
678 private:
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000679 friend class GOOGLE_NAMESPACE::FlagSaverImpl; // reads all the flags in order to copy them
680 friend class CommandLineFlagParser; // for ValidateAllFlags
681 friend void GOOGLE_NAMESPACE::GetAllFlags(vector<CommandLineFlagInfo>*);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000682
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000683 // The map from name to flag, for FindFlagLocked().
Craig Silversteinb9f23482007-03-22 00:15:41 +0000684 typedef map<const char*, CommandLineFlag*, StringCmp> FlagMap;
685 typedef FlagMap::iterator FlagIterator;
686 typedef FlagMap::const_iterator FlagConstIterator;
687 FlagMap flags_;
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000688
689 // The map from current-value pointer to flag, fo FindFlagViaPtrLocked().
690 typedef map<const void*, CommandLineFlag*> FlagPtrMap;
691 FlagPtrMap flags_by_ptr_;
692
Craig Silversteinb9f23482007-03-22 00:15:41 +0000693 static FlagRegistry* global_registry_; // a singleton registry
Craig Silverstein917f4e72011-07-29 04:26:49 +0000694
695 Mutex lock_;
696 static Mutex global_registry_lock_;
697
698 static void InitGlobalRegistry();
Craig Silversteinb9f23482007-03-22 00:15:41 +0000699
700 // Disallow
701 FlagRegistry(const FlagRegistry&);
702 FlagRegistry& operator=(const FlagRegistry&);
703};
704
Craig Silverstein917f4e72011-07-29 04:26:49 +0000705class FlagRegistryLock {
706 public:
707 explicit FlagRegistryLock(FlagRegistry* fr) : fr_(fr) { fr_->Lock(); }
708 ~FlagRegistryLock() { fr_->Unlock(); }
709 private:
710 FlagRegistry *const fr_;
711};
Craig Silverstein67914682008-08-21 00:50:59 +0000712
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000713
Craig Silversteinb9f23482007-03-22 00:15:41 +0000714void FlagRegistry::RegisterFlag(CommandLineFlag* flag) {
715 Lock();
716 pair<FlagIterator, bool> ins =
717 flags_.insert(pair<const char*, CommandLineFlag*>(flag->name(), flag));
718 if (ins.second == false) { // means the name was already in the map
719 if (strcmp(ins.first->second->filename(), flag->filename()) != 0) {
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000720 ReportError(DIE, "ERROR: flag '%s' was defined more than once "
721 "(in files '%s' and '%s').\n",
722 flag->name(),
723 ins.first->second->filename(),
724 flag->filename());
Craig Silversteinb9f23482007-03-22 00:15:41 +0000725 } else {
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000726 ReportError(DIE, "ERROR: something wrong with flag '%s' in file '%s'. "
727 "One possibility: file '%s' is being linked both statically "
728 "and dynamically into this executable.\n",
729 flag->name(),
730 flag->filename(), flag->filename());
Craig Silversteinb9f23482007-03-22 00:15:41 +0000731 }
Craig Silversteinb9f23482007-03-22 00:15:41 +0000732 }
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000733 // Also add to the flags_by_ptr_ map.
734 flags_by_ptr_[flag->current_->value_buffer_] = flag;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000735 Unlock();
736}
737
738CommandLineFlag* FlagRegistry::FindFlagLocked(const char* name) {
739 FlagConstIterator i = flags_.find(name);
740 if (i == flags_.end()) {
741 return NULL;
742 } else {
743 return i->second;
744 }
745}
746
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000747CommandLineFlag* FlagRegistry::FindFlagViaPtrLocked(const void* flag_ptr) {
748 FlagPtrMap::const_iterator i = flags_by_ptr_.find(flag_ptr);
749 if (i == flags_by_ptr_.end()) {
750 return NULL;
751 } else {
752 return i->second;
753 }
754}
755
Craig Silversteinb9f23482007-03-22 00:15:41 +0000756CommandLineFlag* FlagRegistry::SplitArgumentLocked(const char* arg,
757 string* key,
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000758 const char** v,
759 string* error_message) {
Craig Silversteinb9f23482007-03-22 00:15:41 +0000760 // Find the flag object for this option
761 const char* flag_name;
762 const char* value = strchr(arg, '=');
763 if (value == NULL) {
764 key->assign(arg);
765 *v = NULL;
766 } else {
767 // Strip out the "=value" portion from arg
768 key->assign(arg, value-arg);
769 *v = ++value; // advance past the '='
770 }
771 flag_name = key->c_str();
772
773 CommandLineFlag* flag = FindFlagLocked(flag_name);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000774
775 if (flag == NULL) {
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000776 // If we can't find the flag-name, then we should return an error.
777 // The one exception is if 1) the flag-name is 'nox', 2) there
778 // exists a flag named 'x', and 3) 'x' is a boolean flag.
779 // In that case, we want to return flag 'x'.
780 if (!(flag_name[0] == 'n' && flag_name[1] == 'o')) {
781 // flag-name is not 'nox', so we're not in the exception case.
Craig Silverstein917f4e72011-07-29 04:26:49 +0000782 *error_message = StringPrintf("%sunknown command line flag '%s'\n",
783 kError, key->c_str());
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000784 return NULL;
785 }
786 flag = FindFlagLocked(flag_name+2);
787 if (flag == NULL) {
788 // No flag named 'x' exists, so we're not in the exception case.
Craig Silverstein917f4e72011-07-29 04:26:49 +0000789 *error_message = StringPrintf("%sunknown command line flag '%s'\n",
790 kError, key->c_str());
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000791 return NULL;
792 }
793 if (strcmp(flag->type_name(), "bool") != 0) {
794 // 'x' exists but is not boolean, so we're not in the exception case.
Craig Silverstein917f4e72011-07-29 04:26:49 +0000795 *error_message = StringPrintf(
796 "%sboolean value (%s) specified for %s command line flag\n",
797 kError, key->c_str(), flag->type_name());
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000798 return NULL;
799 }
800 // We're in the exception case!
801 // Make up a fake value to replace the "no" we stripped out
802 key->assign(flag_name+2); // the name without the "no"
803 *v = "0";
Craig Silversteinb9f23482007-03-22 00:15:41 +0000804 }
805
806 // Assign a value if this is a boolean flag
807 if (*v == NULL && strcmp(flag->type_name(), "bool") == 0) {
808 *v = "1"; // the --nox case was already handled, so this is the --x case
809 }
810
811 return flag;
812}
813
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000814bool TryParseLocked(const CommandLineFlag* flag, FlagValue* flag_value,
815 const char* value, string* msg) {
816 // Use tenative_value, not flag_value, until we know value is valid.
817 FlagValue* tentative_value = flag_value->New();
818 if (!tentative_value->ParseFrom(value)) {
819 if (msg) {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000820 StringAppendF(msg,
821 "%sillegal value '%s' specified for %s flag '%s'\n",
822 kError, value,
823 flag->type_name(), flag->name());
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000824 }
825 delete tentative_value;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000826 return false;
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000827 } else if (!flag->Validate(*tentative_value)) {
Craig Silverstein67914682008-08-21 00:50:59 +0000828 if (msg) {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000829 StringAppendF(msg,
830 "%sfailed validation of new value '%s' for flag '%s'\n",
831 kError, tentative_value->ToString().c_str(),
832 flag->name());
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000833 }
834 delete tentative_value;
835 return false;
836 } else {
837 flag_value->CopyFrom(*tentative_value);
838 if (msg) {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000839 StringAppendF(msg, "%s set to %s\n",
840 flag->name(), flag_value->ToString().c_str());
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000841 }
842 delete tentative_value;
843 return true;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000844 }
845}
846
847bool FlagRegistry::SetFlagLocked(CommandLineFlag* flag,
848 const char* value,
849 FlagSettingMode set_mode,
850 string* msg) {
851 flag->UpdateModifiedBit();
852 switch (set_mode) {
853 case SET_FLAGS_VALUE: {
854 // set or modify the flag's value
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000855 if (!TryParseLocked(flag, flag->current_, value, msg))
Craig Silversteinb9f23482007-03-22 00:15:41 +0000856 return false;
857 flag->modified_ = true;
858 break;
859 }
860 case SET_FLAG_IF_DEFAULT: {
861 // set the flag's value, but only if it hasn't been set by someone else
862 if (!flag->modified_) {
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000863 if (!TryParseLocked(flag, flag->current_, value, msg))
Craig Silversteinb9f23482007-03-22 00:15:41 +0000864 return false;
865 flag->modified_ = true;
866 } else {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000867 *msg = StringPrintf("%s set to %s",
868 flag->name(), flag->current_value().c_str());
Craig Silversteinb9f23482007-03-22 00:15:41 +0000869 }
870 break;
871 }
872 case SET_FLAGS_DEFAULT: {
873 // modify the flag's default-value
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000874 if (!TryParseLocked(flag, flag->defvalue_, value, msg))
Craig Silversteinb9f23482007-03-22 00:15:41 +0000875 return false;
876 if (!flag->modified_) {
877 // Need to set both defvalue *and* current, in this case
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000878 TryParseLocked(flag, flag->current_, value, NULL);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000879 }
880 break;
881 }
882 default: {
Craig Silverstein690172b2007-04-20 21:16:33 +0000883 // unknown set_mode
Craig Silverstein67914682008-08-21 00:50:59 +0000884 assert(false);
885 return false;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000886 }
887 }
888
889 return true;
890}
891
Craig Silverstein917f4e72011-07-29 04:26:49 +0000892// Get the singleton FlagRegistry object
893FlagRegistry* FlagRegistry::global_registry_ = NULL;
894Mutex FlagRegistry::global_registry_lock_(Mutex::LINKER_INITIALIZED);
895
896FlagRegistry* FlagRegistry::GlobalRegistry() {
897 MutexLock acquire_lock(&global_registry_lock_);
898 if (!global_registry_) {
899 global_registry_ = new FlagRegistry;
900 }
901 return global_registry_;
902}
Craig Silversteinb9f23482007-03-22 00:15:41 +0000903
Craig Silversteinb9f23482007-03-22 00:15:41 +0000904// --------------------------------------------------------------------
905// CommandLineFlagParser
906// Parsing is done in two stages. In the first, we go through
907// argv. For every flag-like arg we can make sense of, we parse
908// it and set the appropriate FLAGS_* variable. For every flag-
909// like arg we can't make sense of, we store it in a vector,
910// along with an explanation of the trouble. In stage 2, we
911// handle the 'reporting' flags like --help and --mpm_version.
912// (This is via a call to HandleCommandLineHelpFlags(), in
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000913// gflags_reporting.cc.)
Craig Silversteinb9f23482007-03-22 00:15:41 +0000914// An optional stage 3 prints out the error messages.
915// This is a bit of a simplification. For instance, --flagfile
916// is handled as soon as it's seen in stage 1, not in stage 2.
917// --------------------------------------------------------------------
918
919class CommandLineFlagParser {
920 public:
921 // The argument is the flag-registry to register the parsed flags in
922 explicit CommandLineFlagParser(FlagRegistry* reg) : registry_(reg) {}
923 ~CommandLineFlagParser() {}
924
925 // Stage 1: Every time this is called, it reads all flags in argv.
926 // However, it ignores all flags that have been successfully set
927 // before. Typically this is only called once, so this 'reparsing'
928 // behavior isn't important. It can be useful when trying to
929 // reparse after loading a dll, though.
930 uint32 ParseNewCommandLineFlags(int* argc, char*** argv, bool remove_flags);
931
932 // Stage 2: print reporting info and exit, if requested.
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000933 // In gflags_reporting.cc:HandleCommandLineHelpFlags().
Craig Silversteinb9f23482007-03-22 00:15:41 +0000934
Craig Silversteinc79c32d2008-07-22 23:29:39 +0000935 // Stage 3: validate all the commandline flags that have validators
936 // registered.
937 void ValidateAllFlags();
938
939 // Stage 4: report any errors and return true if any were found.
Craig Silversteinb9f23482007-03-22 00:15:41 +0000940 bool ReportErrors();
941
942 // Set a particular command line option. "newval" is a string
943 // describing the new value that the option has been set to. If
944 // option_name does not specify a valid option name, or value is not
945 // a valid value for option_name, newval is empty. Does recursive
946 // processing for --flagfile and --fromenv. Returns the new value
947 // if everything went ok, or empty-string if not. (Actually, the
948 // return-string could hold many flag/value pairs due to --flagfile.)
949 // NB: Must have called registry_->Lock() before calling this function.
950 string ProcessSingleOptionLocked(CommandLineFlag* flag,
951 const char* value,
952 FlagSettingMode set_mode);
953
954 // Set a whole batch of command line options as specified by contentdata,
955 // which is in flagfile format (and probably has been read from a flagfile).
956 // Returns the new value if everything went ok, or empty-string if
957 // not. (Actually, the return-string could hold many flag/value
958 // pairs due to --flagfile.)
959 // NB: Must have called registry_->Lock() before calling this function.
960 string ProcessOptionsFromStringLocked(const string& contentdata,
961 FlagSettingMode set_mode);
962
963 // These are the 'recursive' flags, defined at the top of this file.
964 // Whenever we see these flags on the commandline, we must take action.
965 // These are called by ProcessSingleOptionLocked and, similarly, return
966 // new values if everything went ok, or the empty-string if not.
967 string ProcessFlagfileLocked(const string& flagval, FlagSettingMode set_mode);
Craig Silverstein67914682008-08-21 00:50:59 +0000968 // diff fromenv/tryfromenv
Craig Silversteinb9f23482007-03-22 00:15:41 +0000969 string ProcessFromenvLocked(const string& flagval, FlagSettingMode set_mode,
Craig Silverstein67914682008-08-21 00:50:59 +0000970 bool errors_are_fatal);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000971
972 private:
973 FlagRegistry* const registry_;
Craig Silverstein67914682008-08-21 00:50:59 +0000974 map<string, string> error_flags_; // map from name to error message
Craig Silversteinb9f23482007-03-22 00:15:41 +0000975 // This could be a set<string>, but we reuse the map to minimize the .o size
Craig Silverstein67914682008-08-21 00:50:59 +0000976 map<string, string> undefined_names_; // --[flag] name was not registered
Craig Silversteinb9f23482007-03-22 00:15:41 +0000977};
978
979
980// Parse a list of (comma-separated) flags.
981static void ParseFlagList(const char* value, vector<string>* flags) {
982 for (const char *p = value; p && *p; value = p) {
983 p = strchr(value, ',');
Craig Silverstein917f4e72011-07-29 04:26:49 +0000984 size_t len;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000985 if (p) {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000986 len = p - value;
Craig Silversteinb9f23482007-03-22 00:15:41 +0000987 p++;
988 } else {
Craig Silverstein917f4e72011-07-29 04:26:49 +0000989 len = strlen(value);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000990 }
991
Craig Silverstein5a3c7f82009-04-15 21:57:04 +0000992 if (len == 0)
993 ReportError(DIE, "ERROR: empty flaglist entry\n");
994 if (value[0] == '-')
995 ReportError(DIE, "ERROR: flag \"%*s\" begins with '-'\n", len, value);
Craig Silversteinb9f23482007-03-22 00:15:41 +0000996
997 flags->push_back(string(value, len));
998 }
999}
1000
1001// Snarf an entire file into a C++ string. This is just so that we
1002// can do all the I/O in one place and not worry about it everywhere.
1003// Plus, it's convenient to have the whole file contents at hand.
1004// Adds a newline at the end of the file.
Craig Silverstein917f4e72011-07-29 04:26:49 +00001005#define PFATAL(s) do { perror(s); gflags_exitfunc(1); } while (0)
Craig Silversteinb9f23482007-03-22 00:15:41 +00001006
1007static string ReadFileIntoString(const char* filename) {
Craig Silverstein67914682008-08-21 00:50:59 +00001008 const int kBufSize = 8092;
1009 char buffer[kBufSize];
Craig Silversteinb9f23482007-03-22 00:15:41 +00001010 string s;
1011 FILE* fp = fopen(filename, "r");
1012 if (!fp) PFATAL(filename);
Craig Silverstein67914682008-08-21 00:50:59 +00001013 size_t n;
1014 while ( (n=fread(buffer, 1, kBufSize, fp)) > 0 ) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001015 if (ferror(fp)) PFATAL(filename);
1016 s.append(buffer, n);
1017 }
1018 fclose(fp);
1019 return s;
1020}
1021
1022uint32 CommandLineFlagParser::ParseNewCommandLineFlags(int* argc, char*** argv,
1023 bool remove_flags) {
1024 const char *program_name = strrchr((*argv)[0], PATH_SEPARATOR); // nix path
1025 program_name = (program_name == NULL ? (*argv)[0] : program_name+1);
1026
1027 int first_nonopt = *argc; // for non-options moved to the end
1028
1029 registry_->Lock();
1030 for (int i = 1; i < first_nonopt; i++) {
1031 char* arg = (*argv)[i];
1032
1033 // Like getopt(), we permute non-option flags to be at the end.
Craig Silverstein83911c12008-03-27 20:11:07 +00001034 if (arg[0] != '-' || // must be a program argument
1035 (arg[0] == '-' && arg[1] == '\0')) { // "-" is an argument, not a flag
Craig Silversteinb9f23482007-03-22 00:15:41 +00001036 memmove((*argv) + i, (*argv) + i+1, (*argc - (i+1)) * sizeof((*argv)[i]));
1037 (*argv)[*argc-1] = arg; // we go last
1038 first_nonopt--; // we've been pushed onto the stack
1039 i--; // to undo the i++ in the loop
1040 continue;
1041 }
1042
1043 if (arg[0] == '-') arg++; // allow leading '-'
1044 if (arg[0] == '-') arg++; // or leading '--'
1045
Craig Silverstein83911c12008-03-27 20:11:07 +00001046 // -- alone means what it does for GNU: stop options parsing
Craig Silversteinb9f23482007-03-22 00:15:41 +00001047 if (*arg == '\0') {
1048 first_nonopt = i+1;
1049 break;
1050 }
1051
1052 // Find the flag object for this option
1053 string key;
1054 const char* value;
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001055 string error_message;
1056 CommandLineFlag* flag = registry_->SplitArgumentLocked(arg, &key, &value,
1057 &error_message);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001058 if (flag == NULL) {
1059 undefined_names_[key] = ""; // value isn't actually used
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001060 error_flags_[key] = error_message;
Craig Silversteinb9f23482007-03-22 00:15:41 +00001061 continue;
1062 }
1063
1064 if (value == NULL) {
1065 // Boolean options are always assigned a value by SplitArgumentLocked()
1066 assert(strcmp(flag->type_name(), "bool") != 0);
1067 if (i+1 >= first_nonopt) {
1068 // This flag needs a value, but there is nothing available
Craig Silverstein67914682008-08-21 00:50:59 +00001069 error_flags_[key] = (string(kError) + "flag '" + (*argv)[i] + "'"
1070 + " is missing its argument");
1071 if (flag->help() && flag->help()[0] > '\001') {
1072 // Be useful in case we have a non-stripped description.
1073 error_flags_[key] += string("; flag description: ") + flag->help();
1074 }
1075 error_flags_[key] += "\n";
Craig Silversteinb9f23482007-03-22 00:15:41 +00001076 break; // we treat this as an unrecoverable error
1077 } else {
1078 value = (*argv)[++i]; // read next arg for value
Craig Silverstein688ea022009-09-11 00:15:50 +00001079
1080 // Heuristic to detect the case where someone treats a string arg
1081 // like a bool:
1082 // --my_string_var --foo=bar
1083 // We look for a flag of string type, whose value begins with a
1084 // dash, and where the flag-name and value are separated by a
1085 // space rather than an '='.
1086 // To avoid false positives, we also require the word "true"
1087 // or "false" in the help string. Without this, a valid usage
1088 // "-lat -30.5" would trigger the warning. The common cases we
1089 // want to solve talk about true and false as values.
1090 if (value[0] == '-'
1091 && strcmp(flag->type_name(), "string") == 0
1092 && (strstr(flag->help(), "true")
1093 || strstr(flag->help(), "false"))) {
Craig Silverstein917f4e72011-07-29 04:26:49 +00001094 LOG(WARNING) << "Did you really mean to set flag '"
1095 << flag->name() << "' to the value '"
1096 << value << "'?";
Craig Silverstein688ea022009-09-11 00:15:50 +00001097 }
Craig Silversteinb9f23482007-03-22 00:15:41 +00001098 }
1099 }
1100
1101 // TODO(csilvers): only set a flag if we hadn't set it before here
1102 ProcessSingleOptionLocked(flag, value, SET_FLAGS_VALUE);
1103 }
1104 registry_->Unlock();
1105
1106 if (remove_flags) { // Fix up argc and argv by removing command line flags
1107 (*argv)[first_nonopt-1] = (*argv)[0];
1108 (*argv) += (first_nonopt-1);
1109 (*argc) -= (first_nonopt-1);
1110 first_nonopt = 1; // because we still don't count argv[0]
1111 }
1112
1113 logging_is_probably_set_up = true; // because we've parsed --logdir, etc.
1114
1115 return first_nonopt;
1116}
1117
1118string CommandLineFlagParser::ProcessFlagfileLocked(const string& flagval,
1119 FlagSettingMode set_mode) {
1120 if (flagval.empty())
1121 return "";
1122
1123 string msg;
1124 vector<string> filename_list;
1125 ParseFlagList(flagval.c_str(), &filename_list); // take a list of filenames
Craig Silverstein67914682008-08-21 00:50:59 +00001126 for (size_t i = 0; i < filename_list.size(); ++i) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001127 const char* file = filename_list[i].c_str();
1128 msg += ProcessOptionsFromStringLocked(ReadFileIntoString(file), set_mode);
1129 }
1130 return msg;
1131}
1132
1133string CommandLineFlagParser::ProcessFromenvLocked(const string& flagval,
1134 FlagSettingMode set_mode,
1135 bool errors_are_fatal) {
1136 if (flagval.empty())
1137 return "";
1138
1139 string msg;
1140 vector<string> flaglist;
1141 ParseFlagList(flagval.c_str(), &flaglist);
1142
Craig Silverstein67914682008-08-21 00:50:59 +00001143 for (size_t i = 0; i < flaglist.size(); ++i) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001144 const char* flagname = flaglist[i].c_str();
1145 CommandLineFlag* flag = registry_->FindFlagLocked(flagname);
1146 if (flag == NULL) {
Craig Silverstein917f4e72011-07-29 04:26:49 +00001147 error_flags_[flagname] =
1148 StringPrintf("%sunknown command line flag '%s' "
1149 "(via --fromenv or --tryfromenv)\n",
1150 kError, flagname);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001151 undefined_names_[flagname] = "";
1152 continue;
1153 }
1154
1155 const string envname = string("FLAGS_") + string(flagname);
1156 const char* envval = getenv(envname.c_str());
1157 if (!envval) {
1158 if (errors_are_fatal) {
1159 error_flags_[flagname] = (string(kError) + envname +
1160 " not found in environment\n");
1161 }
1162 continue;
1163 }
1164
1165 // Avoid infinite recursion.
1166 if ((strcmp(envval, "fromenv") == 0) ||
1167 (strcmp(envval, "tryfromenv") == 0)) {
Craig Silverstein917f4e72011-07-29 04:26:49 +00001168 error_flags_[flagname] =
1169 StringPrintf("%sinfinite recursion on environment flag '%s'\n",
1170 kError, envval);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001171 continue;
1172 }
1173
1174 msg += ProcessSingleOptionLocked(flag, envval, set_mode);
1175 }
1176 return msg;
1177}
1178
1179string CommandLineFlagParser::ProcessSingleOptionLocked(
1180 CommandLineFlag* flag, const char* value, FlagSettingMode set_mode) {
1181 string msg;
1182 if (value && !registry_->SetFlagLocked(flag, value, set_mode, &msg)) {
1183 error_flags_[flag->name()] = msg;
1184 return "";
1185 }
1186
1187 // The recursive flags, --flagfile and --fromenv and --tryfromenv,
1188 // must be dealt with as soon as they're seen. They will emit
1189 // messages of their own.
1190 if (strcmp(flag->name(), "flagfile") == 0) {
1191 msg += ProcessFlagfileLocked(FLAGS_flagfile, set_mode);
1192
1193 } else if (strcmp(flag->name(), "fromenv") == 0) {
1194 // last arg indicates envval-not-found is fatal (unlike in --tryfromenv)
1195 msg += ProcessFromenvLocked(FLAGS_fromenv, set_mode, true);
1196
1197 } else if (strcmp(flag->name(), "tryfromenv") == 0) {
1198 msg += ProcessFromenvLocked(FLAGS_tryfromenv, set_mode, false);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001199 }
1200
1201 return msg;
1202}
1203
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001204void CommandLineFlagParser::ValidateAllFlags() {
1205 FlagRegistryLock frl(registry_);
1206 for (FlagRegistry::FlagConstIterator i = registry_->flags_.begin();
1207 i != registry_->flags_.end(); ++i) {
1208 if (!i->second->ValidateCurrent()) {
1209 // only set a message if one isn't already there. (If there's
1210 // an error message, our job is done, even if it's not exactly
1211 // the same error.)
1212 if (error_flags_[i->second->name()].empty())
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001213 error_flags_[i->second->name()] =
1214 string(kError) + "--" + i->second->name() +
1215 " must be set on the commandline"
1216 " (default value fails validation)\n";
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001217 }
1218 }
1219}
1220
Craig Silversteinb9f23482007-03-22 00:15:41 +00001221bool CommandLineFlagParser::ReportErrors() {
1222 // error_flags_ indicates errors we saw while parsing.
1223 // But we ignore undefined-names if ok'ed by --undef_ok
1224 if (!FLAGS_undefok.empty()) {
1225 vector<string> flaglist;
1226 ParseFlagList(FLAGS_undefok.c_str(), &flaglist);
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001227 for (size_t i = 0; i < flaglist.size(); ++i) {
1228 // We also deal with --no<flag>, in case the flagname was boolean
1229 const string no_version = string("no") + flaglist[i];
Craig Silversteinb9f23482007-03-22 00:15:41 +00001230 if (undefined_names_.find(flaglist[i]) != undefined_names_.end()) {
1231 error_flags_[flaglist[i]] = ""; // clear the error message
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001232 } else if (undefined_names_.find(no_version) != undefined_names_.end()) {
1233 error_flags_[no_version] = "";
Craig Silversteinb9f23482007-03-22 00:15:41 +00001234 }
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001235 }
Craig Silversteinb9f23482007-03-22 00:15:41 +00001236 }
1237 // Likewise, if they decided to allow reparsing, all undefined-names
1238 // are ok; we just silently ignore them now, and hope that a future
1239 // parse will pick them up somehow.
1240 if (allow_command_line_reparsing) {
Craig Silverstein67914682008-08-21 00:50:59 +00001241 for (map<string, string>::const_iterator it = undefined_names_.begin();
Craig Silversteinb9f23482007-03-22 00:15:41 +00001242 it != undefined_names_.end(); ++it)
1243 error_flags_[it->first] = ""; // clear the error message
1244 }
1245
1246 bool found_error = false;
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001247 string error_message;
Craig Silverstein67914682008-08-21 00:50:59 +00001248 for (map<string, string>::const_iterator it = error_flags_.begin();
Craig Silversteinb9f23482007-03-22 00:15:41 +00001249 it != error_flags_.end(); ++it) {
1250 if (!it->second.empty()) {
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001251 error_message.append(it->second.data(), it->second.size());
Craig Silversteinb9f23482007-03-22 00:15:41 +00001252 found_error = true;
1253 }
1254 }
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001255 if (found_error)
1256 ReportError(DO_NOT_DIE, "%s", error_message.c_str());
Craig Silversteinb9f23482007-03-22 00:15:41 +00001257 return found_error;
1258}
1259
1260string CommandLineFlagParser::ProcessOptionsFromStringLocked(
1261 const string& contentdata, FlagSettingMode set_mode) {
1262 string retval;
1263 const char* flagfile_contents = contentdata.c_str();
1264 bool flags_are_relevant = true; // set to false when filenames don't match
1265 bool in_filename_section = false;
1266
1267 const char* line_end = flagfile_contents;
1268 // We read this file a line at a time.
1269 for (; line_end; flagfile_contents = line_end + 1) {
1270 while (*flagfile_contents && isspace(*flagfile_contents))
1271 ++flagfile_contents;
1272 line_end = strchr(flagfile_contents, '\n');
Craig Silverstein917f4e72011-07-29 04:26:49 +00001273 size_t len = line_end ? line_end - flagfile_contents
Craig Silverstein67914682008-08-21 00:50:59 +00001274 : strlen(flagfile_contents);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001275 string line(flagfile_contents, len);
1276
1277 // Each line can be one of four things:
1278 // 1) A comment line -- we skip it
1279 // 2) An empty line -- we skip it
1280 // 3) A list of filenames -- starts a new filenames+flags section
1281 // 4) A --flag=value line -- apply if previous filenames match
1282 if (line.empty() || line[0] == '#') {
1283 // comment or empty line; just ignore
1284
1285 } else if (line[0] == '-') { // flag
1286 in_filename_section = false; // instead, it was a flag-line
1287 if (!flags_are_relevant) // skip this flag; applies to someone else
1288 continue;
1289
1290 const char* name_and_val = line.c_str() + 1; // skip the leading -
1291 if (*name_and_val == '-')
1292 name_and_val++; // skip second - too
1293 string key;
1294 const char* value;
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001295 string error_message;
Craig Silversteinb9f23482007-03-22 00:15:41 +00001296 CommandLineFlag* flag = registry_->SplitArgumentLocked(name_and_val,
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001297 &key, &value,
1298 &error_message);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001299 // By API, errors parsing flagfile lines are silently ignored.
1300 if (flag == NULL) {
1301 // "WARNING: flagname '" + key + "' not found\n"
1302 } else if (value == NULL) {
1303 // "WARNING: flagname '" + key + "' missing a value\n"
1304 } else {
1305 retval += ProcessSingleOptionLocked(flag, value, set_mode);
1306 }
1307
1308 } else { // a filename!
1309 if (!in_filename_section) { // start over: assume filenames don't match
1310 in_filename_section = true;
1311 flags_are_relevant = false;
1312 }
1313
1314 // Split the line up at spaces into glob-patterns
1315 const char* space = line.c_str(); // just has to be non-NULL
1316 for (const char* word = line.c_str(); *space; word = space+1) {
1317 if (flags_are_relevant) // we can stop as soon as we match
1318 break;
1319 space = strchr(word, ' ');
1320 if (space == NULL)
1321 space = word + strlen(word);
1322 const string glob(word, space - word);
1323 // We try matching both against the full argv0 and basename(argv0)
Craig Silverstein917f4e72011-07-29 04:26:49 +00001324 if (glob == ProgramInvocationName() // small optimization
1325 || glob == ProgramInvocationShortName()
Craig Silverstein67914682008-08-21 00:50:59 +00001326#ifdef HAVE_FNMATCH_H
Craig Silverstein917f4e72011-07-29 04:26:49 +00001327 || fnmatch(glob.c_str(),
1328 ProgramInvocationName(),
1329 FNM_PATHNAME) == 0
1330 || fnmatch(glob.c_str(),
1331 ProgramInvocationShortName(),
1332 FNM_PATHNAME) == 0
1333#endif
1334 ) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001335 flags_are_relevant = true;
1336 }
1337 }
1338 }
1339 }
1340 return retval;
1341}
1342
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001343// --------------------------------------------------------------------
1344// GetFromEnv()
1345// AddFlagValidator()
1346// These are helper functions for routines like BoolFromEnv() and
1347// RegisterFlagValidator, defined below. They're defined here so
1348// they can live in the unnamed namespace (which makes friendship
1349// declarations for these classes possible).
1350// --------------------------------------------------------------------
1351
1352template<typename T>
1353T GetFromEnv(const char *varname, const char* type, T dflt) {
1354 const char* const valstr = getenv(varname);
1355 if (!valstr)
1356 return dflt;
Craig Silverstein0baf4ab2011-01-14 21:58:28 +00001357 FlagValue ifv(new T, type, true);
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001358 if (!ifv.ParseFrom(valstr))
1359 ReportError(DIE, "ERROR: error parsing env variable '%s' with value '%s'\n",
1360 varname, valstr);
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001361 return OTHER_VALUE_AS(ifv, T);
1362}
1363
1364bool AddFlagValidator(const void* flag_ptr, ValidateFnProto validate_fn_proto) {
1365 // We want a lock around this routine, in case two threads try to
1366 // add a validator (hopefully the same one!) at once. We could use
1367 // our own thread, but we need to loook at the registry anyway, so
1368 // we just steal that one.
1369 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1370 FlagRegistryLock frl(registry);
1371 // First, find the flag whose current-flag storage is 'flag'.
1372 // This is the CommandLineFlag whose current_->value_buffer_ == flag
1373 CommandLineFlag* flag = registry->FindFlagViaPtrLocked(flag_ptr);
1374 if (!flag) {
Craig Silverstein917f4e72011-07-29 04:26:49 +00001375 LOG(WARNING) << "Ignoring RegisterValidateFunction() for flag pointer "
1376 << flag_ptr << ": no flag found at that address";
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001377 return false;
1378 } else if (validate_fn_proto == flag->validate_function()) {
1379 return true; // ok to register the same function over and over again
1380 } else if (validate_fn_proto != NULL && flag->validate_function() != NULL) {
Craig Silverstein917f4e72011-07-29 04:26:49 +00001381 LOG(WARNING) << "Ignoring RegisterValidateFunction() for flag '"
1382 << flag->name() << "': validate-fn already registered";
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001383 return false;
1384 } else {
1385 flag->validate_fn_proto_ = validate_fn_proto;
1386 return true;
1387 }
1388}
1389
1390} // end unnamed namespaces
1391
1392
1393// Now define the functions that are exported via the .h file
1394
1395// --------------------------------------------------------------------
1396// FlagRegisterer
1397// This class exists merely to have a global constructor (the
1398// kind that runs before main(), that goes an initializes each
1399// flag that's been declared. Note that it's very important we
1400// don't have a destructor that deletes flag_, because that would
1401// cause us to delete current_storage/defvalue_storage as well,
1402// which can cause a crash if anything tries to access the flag
1403// values in a global destructor.
1404// --------------------------------------------------------------------
1405
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001406FlagRegisterer::FlagRegisterer(const char* name, const char* type,
1407 const char* help, const char* filename,
Craig Silverstein874aed52011-11-03 23:08:41 +00001408 void* current_storage, void* defvalue_storage,
1409 const OptionalDefineArgs& optional_args) {
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001410 if (help == NULL)
1411 help = "";
1412 // FlagValue expects the type-name to not include any namespace
1413 // components, so we get rid of those, if any.
1414 if (strchr(type, ':'))
1415 type = strrchr(type, ':') + 1;
Craig Silverstein0baf4ab2011-01-14 21:58:28 +00001416 FlagValue* current = new FlagValue(current_storage, type, false);
1417 FlagValue* defvalue = new FlagValue(defvalue_storage, type, false);
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001418 // Importantly, flag_ will never be deleted, so storage is always good.
1419 CommandLineFlag* flag = new CommandLineFlag(name, help, filename,
Craig Silverstein874aed52011-11-03 23:08:41 +00001420 optional_args.categories,
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001421 current, defvalue);
1422 FlagRegistry::GlobalRegistry()->RegisterFlag(flag); // default registry
1423}
1424
Craig Silverstein10caa992011-11-03 23:09:19 +00001425// TODO(csilvers): remove this by 1 Sept 2011.
1426FlagRegisterer::FlagRegisterer(const char* name, const char* type,
1427 const char* help, const char* filename,
1428 void* current_storage, void* defvalue_storage) {
1429 if (help == NULL)
1430 help = "";
1431 // FlagValue expects the type-name to not include any namespace
1432 // components, so we get rid of those, if any.
1433 if (strchr(type, ':'))
1434 type = strrchr(type, ':') + 1;
1435 FlagValue* current = new FlagValue(current_storage, type, false);
1436 FlagValue* defvalue = new FlagValue(defvalue_storage, type, false);
1437 // Importantly, flag_ will never be deleted, so storage is always good.
1438 CommandLineFlag* flag = new CommandLineFlag(name, help, filename,
1439 NULL, current, defvalue);
1440 FlagRegistry::GlobalRegistry()->RegisterFlag(flag); // default registry
1441}
1442
1443
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001444// --------------------------------------------------------------------
1445// GetAllFlags()
1446// The main way the FlagRegistry class exposes its data. This
1447// returns, as strings, all the info about all the flags in
1448// the main registry, sorted first by filename they are defined
1449// in, and then by flagname.
1450// --------------------------------------------------------------------
1451
1452struct FilenameFlagnameCmp {
1453 bool operator()(const CommandLineFlagInfo& a,
1454 const CommandLineFlagInfo& b) const {
1455 int cmp = strcmp(a.filename.c_str(), b.filename.c_str());
1456 if (cmp == 0)
1457 cmp = strcmp(a.name.c_str(), b.name.c_str()); // secondary sort key
1458 return cmp < 0;
1459 }
1460};
1461
1462void GetAllFlags(vector<CommandLineFlagInfo>* OUTPUT) {
1463 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1464 registry->Lock();
1465 for (FlagRegistry::FlagConstIterator i = registry->flags_.begin();
1466 i != registry->flags_.end(); ++i) {
1467 CommandLineFlagInfo fi;
1468 i->second->FillCommandLineFlagInfo(&fi);
1469 OUTPUT->push_back(fi);
1470 }
1471 registry->Unlock();
1472 // Now sort the flags, first by filename they occur in, then alphabetically
1473 sort(OUTPUT->begin(), OUTPUT->end(), FilenameFlagnameCmp());
1474}
1475
1476// --------------------------------------------------------------------
1477// SetArgv()
1478// GetArgvs()
1479// GetArgv()
1480// GetArgv0()
1481// ProgramInvocationName()
1482// ProgramInvocationShortName()
1483// SetUsageMessage()
1484// ProgramUsage()
1485// Functions to set and get argv. Typically the setter is called
1486// by ParseCommandLineFlags. Also can get the ProgramUsage string,
Craig Silverstein917f4e72011-07-29 04:26:49 +00001487// set by SetUsageMessage.
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001488// --------------------------------------------------------------------
1489
1490// These values are not protected by a Mutex because they are normally
1491// set only once during program startup.
1492static const char* argv0 = "UNKNOWN"; // just the program name
1493static const char* cmdline = ""; // the entire command-line
1494static vector<string> argvs;
1495static uint32 argv_sum = 0;
Craig Silverstein67914682008-08-21 00:50:59 +00001496static const char* program_usage = NULL;
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001497
1498void SetArgv(int argc, const char** argv) {
1499 static bool called_set_argv = false;
1500 if (called_set_argv) // we already have an argv for you
1501 return;
1502
1503 called_set_argv = true;
1504
1505 assert(argc > 0); // every program has at least a progname
1506 argv0 = strdup(argv[0]); // small memory leak, but fn only called once
1507 assert(argv0);
1508
Craig Silverstein67914682008-08-21 00:50:59 +00001509 string cmdline_string; // easier than doing strcats
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001510 for (int i = 0; i < argc; i++) {
Craig Silverstein67914682008-08-21 00:50:59 +00001511 if (i != 0) {
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001512 cmdline_string += " ";
Craig Silverstein67914682008-08-21 00:50:59 +00001513 }
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001514 cmdline_string += argv[i];
1515 argvs.push_back(argv[i]);
1516 }
1517 cmdline = strdup(cmdline_string.c_str()); // another small memory leak
1518 assert(cmdline);
1519
1520 // Compute a simple sum of all the chars in argv
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001521 for (const char* c = cmdline; *c; c++)
1522 argv_sum += *c;
1523}
1524
1525const vector<string>& GetArgvs() { return argvs; }
1526const char* GetArgv() { return cmdline; }
1527const char* GetArgv0() { return argv0; }
1528uint32 GetArgvSum() { return argv_sum; }
1529const char* ProgramInvocationName() { // like the GNU libc fn
1530 return GetArgv0();
1531}
1532const char* ProgramInvocationShortName() { // like the GNU libc fn
1533 const char* slash = strrchr(argv0, '/');
1534#ifdef OS_WINDOWS
1535 if (!slash) slash = strrchr(argv0, '\\');
1536#endif
1537 return slash ? slash + 1 : argv0;
1538}
1539
1540void SetUsageMessage(const string& usage) {
Craig Silverstein5a3c7f82009-04-15 21:57:04 +00001541 if (program_usage != NULL)
1542 ReportError(DIE, "ERROR: SetUsageMessage() called twice\n");
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001543 program_usage = strdup(usage.c_str()); // small memory leak
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001544}
1545
1546const char* ProgramUsage() {
Craig Silverstein67914682008-08-21 00:50:59 +00001547 if (program_usage) {
1548 return program_usage;
1549 }
1550 return "Warning: SetUsageMessage() never called";
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001551}
Craig Silversteinb9f23482007-03-22 00:15:41 +00001552
Craig Silverstein917f4e72011-07-29 04:26:49 +00001553// --------------------------------------------------------------------
1554// SetVersionString()
1555// VersionString()
1556// --------------------------------------------------------------------
1557
1558static const char* version_string = NULL;
1559
1560void SetVersionString(const string& version) {
1561 if (version_string != NULL)
1562 ReportError(DIE, "ERROR: SetVersionString() called twice\n");
1563 version_string = strdup(version.c_str()); // small memory leak
1564}
1565
Craig Silversteinb4bf72b2011-03-03 22:26:24 +00001566const char* VersionString() {
1567 return version_string ? version_string : "";
1568}
1569
Craig Silverstein917f4e72011-07-29 04:26:49 +00001570
Craig Silversteinb9f23482007-03-22 00:15:41 +00001571// --------------------------------------------------------------------
1572// GetCommandLineOption()
1573// GetCommandLineFlagInfo()
Craig Silverstein290da382007-03-28 21:54:07 +00001574// GetCommandLineFlagInfoOrDie()
Craig Silversteinb9f23482007-03-22 00:15:41 +00001575// SetCommandLineOption()
1576// SetCommandLineOptionWithMode()
1577// The programmatic way to set a flag's value, using a string
1578// for its name rather than the variable itself (that is,
1579// SetCommandLineOption("foo", x) rather than FLAGS_foo = x).
1580// There's also a bit more flexibility here due to the various
1581// set-modes, but typically these are used when you only have
1582// that flag's name as a string, perhaps at runtime.
1583// All of these work on the default, global registry.
1584// For GetCommandLineOption, return false if no such flag
1585// is known, true otherwise. We clear "value" if a suitable
Craig Silverstein690172b2007-04-20 21:16:33 +00001586// flag is found.
Craig Silversteinb9f23482007-03-22 00:15:41 +00001587// --------------------------------------------------------------------
1588
1589
Craig Silverstein690172b2007-04-20 21:16:33 +00001590bool GetCommandLineOption(const char* name, string* value) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001591 if (NULL == name)
1592 return false;
1593 assert(value);
1594
1595 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001596 FlagRegistryLock frl(registry);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001597 CommandLineFlag* flag = registry->FindFlagLocked(name);
1598 if (flag == NULL) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001599 return false;
1600 } else {
1601 *value = flag->current_value();
Craig Silversteinb9f23482007-03-22 00:15:41 +00001602 return true;
1603 }
1604}
1605
1606bool GetCommandLineFlagInfo(const char* name, CommandLineFlagInfo* OUTPUT) {
1607 if (NULL == name) return false;
1608 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001609 FlagRegistryLock frl(registry);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001610 CommandLineFlag* flag = registry->FindFlagLocked(name);
1611 if (flag == NULL) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001612 return false;
1613 } else {
1614 assert(OUTPUT);
1615 flag->FillCommandLineFlagInfo(OUTPUT);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001616 return true;
1617 }
1618}
1619
Craig Silverstein290da382007-03-28 21:54:07 +00001620CommandLineFlagInfo GetCommandLineFlagInfoOrDie(const char* name) {
1621 CommandLineFlagInfo info;
1622 if (!GetCommandLineFlagInfo(name, &info)) {
Craig Silverstein688ea022009-09-11 00:15:50 +00001623 fprintf(stderr, "FATAL ERROR: flag name '%s' doesn't exist\n", name);
Craig Silverstein917f4e72011-07-29 04:26:49 +00001624 gflags_exitfunc(1); // almost certainly gflags_exitfunc()
Craig Silverstein290da382007-03-28 21:54:07 +00001625 }
1626 return info;
1627}
1628
Craig Silversteinb9f23482007-03-22 00:15:41 +00001629string SetCommandLineOptionWithMode(const char* name, const char* value,
1630 FlagSettingMode set_mode) {
1631 string result;
1632 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001633 FlagRegistryLock frl(registry);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001634 CommandLineFlag* flag = registry->FindFlagLocked(name);
1635 if (flag) {
1636 CommandLineFlagParser parser(registry);
1637 result = parser.ProcessSingleOptionLocked(flag, value, set_mode);
1638 if (!result.empty()) { // in the error case, we've already logged
Craig Silverstein917f4e72011-07-29 04:26:49 +00001639 // Could consider logging this change
Craig Silversteinb9f23482007-03-22 00:15:41 +00001640 }
1641 }
Craig Silversteinb9f23482007-03-22 00:15:41 +00001642 // The API of this function is that we return empty string on error
1643 return result;
1644}
1645
1646string SetCommandLineOption(const char* name, const char* value) {
1647 return SetCommandLineOptionWithMode(name, value, SET_FLAGS_VALUE);
1648}
1649
Craig Silversteinb9f23482007-03-22 00:15:41 +00001650// --------------------------------------------------------------------
1651// FlagSaver
1652// FlagSaverImpl
1653// This class stores the states of all flags at construct time,
1654// and restores all flags to that state at destruct time.
1655// Its major implementation challenge is that it never modifies
1656// pointers in the 'main' registry, so global FLAG_* vars always
1657// point to the right place.
1658// --------------------------------------------------------------------
1659
1660class FlagSaverImpl {
1661 public:
1662 // Constructs an empty FlagSaverImpl object.
1663 explicit FlagSaverImpl(FlagRegistry* main_registry)
1664 : main_registry_(main_registry) { }
1665 ~FlagSaverImpl() {
1666 // reclaim memory from each of our CommandLineFlags
1667 vector<CommandLineFlag*>::const_iterator it;
1668 for (it = backup_registry_.begin(); it != backup_registry_.end(); ++it)
1669 delete *it;
1670 }
1671
1672 // Saves the flag states from the flag registry into this object.
1673 // It's an error to call this more than once.
1674 // Must be called when the registry mutex is not held.
1675 void SaveFromRegistry() {
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001676 FlagRegistryLock frl(main_registry_);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001677 assert(backup_registry_.empty()); // call only once!
1678 for (FlagRegistry::FlagConstIterator it = main_registry_->flags_.begin();
1679 it != main_registry_->flags_.end();
1680 ++it) {
1681 const CommandLineFlag* main = it->second;
1682 // Sets up all the const variables in backup correctly
1683 CommandLineFlag* backup = new CommandLineFlag(
Craig Silverstein874aed52011-11-03 23:08:41 +00001684 main->name(), main->help(), main->filename(), main->categories(),
Craig Silversteinb9f23482007-03-22 00:15:41 +00001685 main->current_->New(), main->defvalue_->New());
1686 // Sets up all the non-const variables in backup correctly
1687 backup->CopyFrom(*main);
1688 backup_registry_.push_back(backup); // add it to a convenient list
1689 }
Craig Silversteinb9f23482007-03-22 00:15:41 +00001690 }
1691
1692 // Restores the saved flag states into the flag registry. We
1693 // assume no flags were added or deleted from the registry since
1694 // the SaveFromRegistry; if they were, that's trouble! Must be
1695 // called when the registry mutex is not held.
1696 void RestoreToRegistry() {
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001697 FlagRegistryLock frl(main_registry_);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001698 vector<CommandLineFlag*>::const_iterator it;
1699 for (it = backup_registry_.begin(); it != backup_registry_.end(); ++it) {
1700 CommandLineFlag* main = main_registry_->FindFlagLocked((*it)->name());
1701 if (main != NULL) { // if NULL, flag got deleted from registry(!)
1702 main->CopyFrom(**it);
1703 }
1704 }
Craig Silversteinb9f23482007-03-22 00:15:41 +00001705 }
1706
1707 private:
1708 FlagRegistry* const main_registry_;
1709 vector<CommandLineFlag*> backup_registry_;
1710
1711 FlagSaverImpl(const FlagSaverImpl&); // no copying!
1712 void operator=(const FlagSaverImpl&);
1713};
1714
Craig Silverstein67914682008-08-21 00:50:59 +00001715FlagSaver::FlagSaver()
1716 : impl_(new FlagSaverImpl(FlagRegistry::GlobalRegistry())) {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001717 impl_->SaveFromRegistry();
1718}
1719
1720FlagSaver::~FlagSaver() {
1721 impl_->RestoreToRegistry();
1722 delete impl_;
1723}
1724
1725
1726// --------------------------------------------------------------------
1727// CommandlineFlagsIntoString()
1728// ReadFlagsFromString()
1729// AppendFlagsIntoFile()
1730// ReadFromFlagsFile()
1731// These are mostly-deprecated routines that stick the
1732// commandline flags into a file/string and read them back
1733// out again. I can see a use for CommandlineFlagsIntoString,
1734// for creating a flagfile, but the rest don't seem that useful
1735// -- some, I think, are a poor-man's attempt at FlagSaver --
1736// and are included only until we can delete them from callers.
1737// Note they don't save --flagfile flags (though they do save
1738// the result of having called the flagfile, of course).
1739// --------------------------------------------------------------------
1740
1741static string TheseCommandlineFlagsIntoString(
1742 const vector<CommandLineFlagInfo>& flags) {
1743 vector<CommandLineFlagInfo>::const_iterator i;
1744
Craig Silverstein67914682008-08-21 00:50:59 +00001745 size_t retval_space = 0;
Craig Silversteinb9f23482007-03-22 00:15:41 +00001746 for (i = flags.begin(); i != flags.end(); ++i) {
1747 // An (over)estimate of how much space it will take to print this flag
1748 retval_space += i->name.length() + i->current_value.length() + 5;
1749 }
1750
1751 string retval;
1752 retval.reserve(retval_space);
1753 for (i = flags.begin(); i != flags.end(); ++i) {
1754 retval += "--";
1755 retval += i->name;
1756 retval += "=";
1757 retval += i->current_value;
1758 retval += "\n";
1759 }
1760 return retval;
1761}
1762
1763string CommandlineFlagsIntoString() {
1764 vector<CommandLineFlagInfo> sorted_flags;
1765 GetAllFlags(&sorted_flags);
1766 return TheseCommandlineFlagsIntoString(sorted_flags);
1767}
1768
1769bool ReadFlagsFromString(const string& flagfilecontents,
Craig Silverstein67914682008-08-21 00:50:59 +00001770 const char* /*prog_name*/, // TODO(csilvers): nix this
Craig Silversteinb9f23482007-03-22 00:15:41 +00001771 bool errors_are_fatal) {
1772 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1773 FlagSaverImpl saved_states(registry);
1774 saved_states.SaveFromRegistry();
1775
1776 CommandLineFlagParser parser(registry);
1777 registry->Lock();
1778 parser.ProcessOptionsFromStringLocked(flagfilecontents, SET_FLAGS_VALUE);
1779 registry->Unlock();
1780 // Should we handle --help and such when reading flags from a string? Sure.
1781 HandleCommandLineHelpFlags();
1782 if (parser.ReportErrors()) {
1783 // Error. Restore all global flags to their previous values.
1784 if (errors_are_fatal)
Craig Silverstein917f4e72011-07-29 04:26:49 +00001785 gflags_exitfunc(1);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001786 saved_states.RestoreToRegistry();
1787 return false;
1788 }
1789 return true;
1790}
1791
1792// TODO(csilvers): nix prog_name in favor of ProgramInvocationShortName()
1793bool AppendFlagsIntoFile(const string& filename, const char *prog_name) {
1794 FILE *fp = fopen(filename.c_str(), "a");
1795 if (!fp) {
1796 return false;
1797 }
1798
1799 if (prog_name)
1800 fprintf(fp, "%s\n", prog_name);
1801
1802 vector<CommandLineFlagInfo> flags;
1803 GetAllFlags(&flags);
1804 // But we don't want --flagfile, which leads to weird recursion issues
1805 vector<CommandLineFlagInfo>::iterator i;
1806 for (i = flags.begin(); i != flags.end(); ++i) {
1807 if (strcmp(i->name.c_str(), "flagfile") == 0) {
1808 flags.erase(i);
1809 break;
1810 }
1811 }
1812 fprintf(fp, "%s", TheseCommandlineFlagsIntoString(flags).c_str());
1813
1814 fclose(fp);
1815 return true;
1816}
1817
1818bool ReadFromFlagsFile(const string& filename, const char* prog_name,
1819 bool errors_are_fatal) {
1820 return ReadFlagsFromString(ReadFileIntoString(filename.c_str()),
1821 prog_name, errors_are_fatal);
1822}
1823
1824
1825// --------------------------------------------------------------------
1826// BoolFromEnv()
1827// Int32FromEnv()
1828// Int64FromEnv()
1829// Uint64FromEnv()
1830// DoubleFromEnv()
1831// StringFromEnv()
1832// Reads the value from the environment and returns it.
1833// We use an FlagValue to make the parsing easy.
1834// Example usage:
Craig Silverstein2b66a842007-06-12 23:59:42 +00001835// DEFINE_bool(myflag, BoolFromEnv("MYFLAG_DEFAULT", false), "whatever");
Craig Silversteinb9f23482007-03-22 00:15:41 +00001836// --------------------------------------------------------------------
1837
Craig Silversteinb9f23482007-03-22 00:15:41 +00001838bool BoolFromEnv(const char *v, bool dflt) {
1839 return GetFromEnv(v, "bool", dflt);
1840}
1841int32 Int32FromEnv(const char *v, int32 dflt) {
1842 return GetFromEnv(v, "int32", dflt);
1843}
1844int64 Int64FromEnv(const char *v, int64 dflt) {
1845 return GetFromEnv(v, "int64", dflt);
1846}
1847uint64 Uint64FromEnv(const char *v, uint64 dflt) {
1848 return GetFromEnv(v, "uint64", dflt);
1849}
1850double DoubleFromEnv(const char *v, double dflt) {
1851 return GetFromEnv(v, "double", dflt);
1852}
1853const char *StringFromEnv(const char *varname, const char *dflt) {
1854 const char* const val = getenv(varname);
1855 return val ? val : dflt;
1856}
1857
1858
1859// --------------------------------------------------------------------
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001860// RegisterFlagValidator()
1861// RegisterFlagValidator() is the function that clients use to
1862// 'decorate' a flag with a validation function. Once this is
1863// done, every time the flag is set (including when the flag
1864// is parsed from argv), the validator-function is called.
1865// These functions return true if the validator was added
1866// successfully, or false if not: the flag already has a validator,
1867// (only one allowed per flag), the 1st arg isn't a flag, etc.
1868// This function is not thread-safe.
1869// --------------------------------------------------------------------
1870
1871bool RegisterFlagValidator(const bool* flag,
1872 bool (*validate_fn)(const char*, bool)) {
1873 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1874}
1875bool RegisterFlagValidator(const int32* flag,
1876 bool (*validate_fn)(const char*, int32)) {
1877 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1878}
1879bool RegisterFlagValidator(const int64* flag,
1880 bool (*validate_fn)(const char*, int64)) {
1881 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1882}
1883bool RegisterFlagValidator(const uint64* flag,
1884 bool (*validate_fn)(const char*, uint64)) {
1885 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1886}
1887bool RegisterFlagValidator(const double* flag,
1888 bool (*validate_fn)(const char*, double)) {
1889 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1890}
1891bool RegisterFlagValidator(const string* flag,
1892 bool (*validate_fn)(const char*, const string&)) {
1893 return AddFlagValidator(flag, reinterpret_cast<ValidateFnProto>(validate_fn));
1894}
1895
1896
1897// --------------------------------------------------------------------
Craig Silversteinb9f23482007-03-22 00:15:41 +00001898// ParseCommandLineFlags()
1899// ParseCommandLineNonHelpFlags()
1900// HandleCommandLineHelpFlags()
1901// This is the main function called from main(), to actually
1902// parse the commandline. It modifies argc and argv as described
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001903// at the top of gflags.h. You can also divide this
Craig Silversteinb9f23482007-03-22 00:15:41 +00001904// function into two parts, if you want to do work between
1905// the parsing of the flags and the printing of any help output.
1906// --------------------------------------------------------------------
1907
1908static uint32 ParseCommandLineFlagsInternal(int* argc, char*** argv,
1909 bool remove_flags, bool do_report) {
1910 SetArgv(*argc, const_cast<const char**>(*argv)); // save it for later
1911
1912 FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
1913 CommandLineFlagParser parser(registry);
1914
1915 // When we parse the commandline flags, we'll handle --flagfile,
1916 // --tryfromenv, etc. as we see them (since flag-evaluation order
1917 // may be important). But sometimes apps set FLAGS_tryfromenv/etc.
1918 // manually before calling ParseCommandLineFlags. We want to evaluate
1919 // those too, as if they were the first flags on the commandline.
1920 registry->Lock();
1921 parser.ProcessFlagfileLocked(FLAGS_flagfile, SET_FLAGS_VALUE);
1922 // Last arg here indicates whether flag-not-found is a fatal error or not
1923 parser.ProcessFromenvLocked(FLAGS_fromenv, SET_FLAGS_VALUE, true);
1924 parser.ProcessFromenvLocked(FLAGS_tryfromenv, SET_FLAGS_VALUE, false);
1925 registry->Unlock();
1926
1927 // Now get the flags specified on the commandline
1928 const int r = parser.ParseNewCommandLineFlags(argc, argv, remove_flags);
1929
1930 if (do_report)
1931 HandleCommandLineHelpFlags(); // may cause us to exit on --help, etc.
Craig Silversteinc79c32d2008-07-22 23:29:39 +00001932
1933 // See if any of the unset flags fail their validation checks
1934 parser.ValidateAllFlags();
1935
Craig Silversteinb9f23482007-03-22 00:15:41 +00001936 if (parser.ReportErrors()) // may cause us to exit on illegal flags
Craig Silverstein917f4e72011-07-29 04:26:49 +00001937 gflags_exitfunc(1);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001938 return r;
1939}
1940
1941uint32 ParseCommandLineFlags(int* argc, char*** argv, bool remove_flags) {
1942 return ParseCommandLineFlagsInternal(argc, argv, remove_flags, true);
1943}
1944
1945uint32 ParseCommandLineNonHelpFlags(int* argc, char*** argv,
1946 bool remove_flags) {
1947 return ParseCommandLineFlagsInternal(argc, argv, remove_flags, false);
1948}
1949
1950// --------------------------------------------------------------------
1951// AllowCommandLineReparsing()
1952// ReparseCommandLineNonHelpFlags()
1953// This is most useful for shared libraries. The idea is if
1954// a flag is defined in a shared library that is dlopen'ed
1955// sometime after main(), you can ParseCommandLineFlags before
1956// the dlopen, then ReparseCommandLineNonHelpFlags() after the
1957// dlopen, to get the new flags. But you have to explicitly
1958// Allow() it; otherwise, you get the normal default behavior
1959// of unrecognized flags calling a fatal error.
Craig Silverstein67914682008-08-21 00:50:59 +00001960// TODO(csilvers): this isn't used. Just delete it?
Craig Silversteinb9f23482007-03-22 00:15:41 +00001961// --------------------------------------------------------------------
1962
1963void AllowCommandLineReparsing() {
1964 allow_command_line_reparsing = true;
1965}
1966
Craig Silverstein71e1be92011-03-02 08:05:17 +00001967void ReparseCommandLineNonHelpFlags() {
Craig Silversteinb9f23482007-03-22 00:15:41 +00001968 // We make a copy of argc and argv to pass in
1969 const vector<string>& argvs = GetArgvs();
Craig Silverstein67914682008-08-21 00:50:59 +00001970 int tmp_argc = static_cast<int>(argvs.size());
Craig Silversteinb9f23482007-03-22 00:15:41 +00001971 char** tmp_argv = new char* [tmp_argc + 1];
1972 for (int i = 0; i < tmp_argc; ++i)
1973 tmp_argv[i] = strdup(argvs[i].c_str()); // TODO(csilvers): don't dup
1974
Craig Silverstein71e1be92011-03-02 08:05:17 +00001975 ParseCommandLineNonHelpFlags(&tmp_argc, &tmp_argv, false);
Craig Silversteinb9f23482007-03-22 00:15:41 +00001976
1977 for (int i = 0; i < tmp_argc; ++i)
1978 free(tmp_argv[i]);
1979 delete[] tmp_argv;
Craig Silversteinb9f23482007-03-22 00:15:41 +00001980}
1981
Craig Silverstein0baf4ab2011-01-14 21:58:28 +00001982void ShutDownCommandLineFlags() {
1983 FlagRegistry::DeleteGlobalRegistry();
1984}
1985
Craig Silversteinb9f23482007-03-22 00:15:41 +00001986_END_GOOGLE_NAMESPACE_