Newer
Older
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
string msg;
vector<string> filename_list;
ParseFlagList(flagval.c_str(), &filename_list); // take a list of filenames
for (int i = 0; i < filename_list.size(); ++i) {
const char* file = filename_list[i].c_str();
msg += ProcessOptionsFromStringLocked(ReadFileIntoString(file), set_mode);
}
return msg;
}
string CommandLineFlagParser::ProcessFromenvLocked(const string& flagval,
FlagSettingMode set_mode,
bool errors_are_fatal) {
if (flagval.empty())
return "";
string msg;
vector<string> flaglist;
ParseFlagList(flagval.c_str(), &flaglist);
for (int i = 0; i < flaglist.size(); ++i) {
const char* flagname = flaglist[i].c_str();
CommandLineFlag* flag = registry_->FindFlagLocked(flagname);
if (flag == NULL) {
error_flags_[flagname] = (string(kError) + "unknown command line flag"
+ " '" + flagname + "'"
+ " (via --fromenv or --tryfromenv)\n");
undefined_names_[flagname] = "";
continue;
}
const string envname = string("FLAGS_") + string(flagname);
const char* envval = getenv(envname.c_str());
if (!envval) {
if (errors_are_fatal) {
error_flags_[flagname] = (string(kError) + envname +
" not found in environment\n");
}
continue;
}
// Avoid infinite recursion.
if ((strcmp(envval, "fromenv") == 0) ||
(strcmp(envval, "tryfromenv") == 0)) {
error_flags_[flagname] = (string(kError) + "infinite recursion on " +
"environment flag '" + envval + "'\n");
continue;
}
msg += ProcessSingleOptionLocked(flag, envval, set_mode);
}
return msg;
}
string CommandLineFlagParser::ProcessSingleOptionLocked(
CommandLineFlag* flag, const char* value, FlagSettingMode set_mode) {
string msg;
if (value && !registry_->SetFlagLocked(flag, value, set_mode, &msg)) {
error_flags_[flag->name()] = msg;
return "";
}
// The recursive flags, --flagfile and --fromenv and --tryfromenv,
// must be dealt with as soon as they're seen. They will emit
// messages of their own.
if (strcmp(flag->name(), "flagfile") == 0) {
msg += ProcessFlagfileLocked(FLAGS_flagfile, set_mode);
} else if (strcmp(flag->name(), "fromenv") == 0) {
// last arg indicates envval-not-found is fatal (unlike in --tryfromenv)
msg += ProcessFromenvLocked(FLAGS_fromenv, set_mode, true);
} else if (strcmp(flag->name(), "tryfromenv") == 0) {
msg += ProcessFromenvLocked(FLAGS_tryfromenv, set_mode, false);
}
return msg;
}
bool CommandLineFlagParser::ReportErrors() {
// error_flags_ indicates errors we saw while parsing.
// But we ignore undefined-names if ok'ed by --undef_ok
if (!FLAGS_undefok.empty()) {
vector<string> flaglist;
ParseFlagList(FLAGS_undefok.c_str(), &flaglist);
for (int i = 0; i < flaglist.size(); ++i)
if (undefined_names_.find(flaglist[i]) != undefined_names_.end()) {
error_flags_[flaglist[i]] = ""; // clear the error message
}
}
// Likewise, if they decided to allow reparsing, all undefined-names
// are ok; we just silently ignore them now, and hope that a future
// parse will pick them up somehow.
if (allow_command_line_reparsing) {
for (map<string,string>::const_iterator it = undefined_names_.begin();
it != undefined_names_.end(); ++it)
error_flags_[it->first] = ""; // clear the error message
}
bool found_error = false;
for (map<string,string>::const_iterator it = error_flags_.begin();
it != error_flags_.end(); ++it) {
if (!it->second.empty()) {
fprintf(stderr, "%s", it->second.c_str());
found_error = true;
}
}
return found_error;
}
string CommandLineFlagParser::ProcessOptionsFromStringLocked(
const string& contentdata, FlagSettingMode set_mode) {
string retval;
const char* flagfile_contents = contentdata.c_str();
bool flags_are_relevant = true; // set to false when filenames don't match
bool in_filename_section = false;
const char* line_end = flagfile_contents;
// We read this file a line at a time.
for (; line_end; flagfile_contents = line_end + 1) {
while (*flagfile_contents && isspace(*flagfile_contents))
++flagfile_contents;
line_end = strchr(flagfile_contents, '\n');
int len = line_end ? line_end-flagfile_contents : strlen(flagfile_contents);
string line(flagfile_contents, len);
// Each line can be one of four things:
// 1) A comment line -- we skip it
// 2) An empty line -- we skip it
// 3) A list of filenames -- starts a new filenames+flags section
// 4) A --flag=value line -- apply if previous filenames match
if (line.empty() || line[0] == '#') {
// comment or empty line; just ignore
} else if (line[0] == '-') { // flag
in_filename_section = false; // instead, it was a flag-line
if (!flags_are_relevant) // skip this flag; applies to someone else
continue;
const char* name_and_val = line.c_str() + 1; // skip the leading -
if (*name_and_val == '-')
name_and_val++; // skip second - too
string key;
const char* value;
CommandLineFlag* flag = registry_->SplitArgumentLocked(name_and_val,
&key, &value);
// By API, errors parsing flagfile lines are silently ignored.
if (flag == NULL) {
// "WARNING: flagname '" + key + "' not found\n"
} else if (value == NULL) {
// "WARNING: flagname '" + key + "' missing a value\n"
} else {
retval += ProcessSingleOptionLocked(flag, value, set_mode);
}
} else { // a filename!
if (!in_filename_section) { // start over: assume filenames don't match
in_filename_section = true;
flags_are_relevant = false;
}
// Split the line up at spaces into glob-patterns
const char* space = line.c_str(); // just has to be non-NULL
for (const char* word = line.c_str(); *space; word = space+1) {
if (flags_are_relevant) // we can stop as soon as we match
break;
space = strchr(word, ' ');
if (space == NULL)
space = word + strlen(word);
const string glob(word, space - word);
// We try matching both against the full argv0 and basename(argv0)
if (fnmatch(glob.c_str(), ProgramInvocationName(), FNM_PATHNAME) == 0 ||
fnmatch(glob.c_str(), ProgramInvocationShortName(), FNM_PATHNAME) == 0) {
flags_are_relevant = true;
}
}
}
}
return retval;
}
// --------------------------------------------------------------------
// GetCommandLineOption()
// GetCommandLineFlagInfo()
// GetCommandLineFlagInfoOrDie()
// SetCommandLineOption()
// SetCommandLineOptionWithMode()
// The programmatic way to set a flag's value, using a string
// for its name rather than the variable itself (that is,
// SetCommandLineOption("foo", x) rather than FLAGS_foo = x).
// There's also a bit more flexibility here due to the various
// set-modes, but typically these are used when you only have
// that flag's name as a string, perhaps at runtime.
// All of these work on the default, global registry.
// For GetCommandLineOption, return false if no such flag
// is known, true otherwise. We clear "value" if a suitable
// flag is found.
// --------------------------------------------------------------------
bool GetCommandLineOption(const char* name, string* value) {
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
if (NULL == name)
return false;
assert(value);
FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
registry->Lock();
CommandLineFlag* flag = registry->FindFlagLocked(name);
if (flag == NULL) {
registry->Unlock();
return false;
} else {
*value = flag->current_value();
registry->Unlock();
return true;
}
}
bool GetCommandLineFlagInfo(const char* name, CommandLineFlagInfo* OUTPUT) {
if (NULL == name) return false;
FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
registry->Lock();
CommandLineFlag* flag = registry->FindFlagLocked(name);
if (flag == NULL) {
registry->Unlock();
return false;
} else {
assert(OUTPUT);
flag->FillCommandLineFlagInfo(OUTPUT);
registry->Unlock();
return true;
}
}
CommandLineFlagInfo GetCommandLineFlagInfoOrDie(const char* name) {
CommandLineFlagInfo info;
if (!GetCommandLineFlagInfo(name, &info)) {
fprintf(stderr, "FATAL ERROR: flag name '%s' doesn't exit", name);
commandlineflags_exitfunc(1); // almost certainly exit()
}
return info;
}
string SetCommandLineOptionWithMode(const char* name, const char* value,
FlagSettingMode set_mode) {
string result;
FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
registry->Lock();
CommandLineFlag* flag = registry->FindFlagLocked(name);
if (flag) {
CommandLineFlagParser parser(registry);
result = parser.ProcessSingleOptionLocked(flag, value, set_mode);
if (!result.empty()) { // in the error case, we've already logged
// You could consider logging this change, if you wanted to know it:
//fprintf(stderr, "%sFLAGS_%s\n",
// (set_mode == SET_FLAGS_DEFAULT ? "default value of " : ""),
// result);
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
}
}
registry->Unlock();
// The API of this function is that we return empty string on error
return result;
}
string SetCommandLineOption(const char* name, const char* value) {
return SetCommandLineOptionWithMode(name, value, SET_FLAGS_VALUE);
}
// --------------------------------------------------------------------
// FlagSaver
// FlagSaverImpl
// This class stores the states of all flags at construct time,
// and restores all flags to that state at destruct time.
// Its major implementation challenge is that it never modifies
// pointers in the 'main' registry, so global FLAG_* vars always
// point to the right place.
// --------------------------------------------------------------------
class FlagSaverImpl {
public:
// Constructs an empty FlagSaverImpl object.
explicit FlagSaverImpl(FlagRegistry* main_registry)
: main_registry_(main_registry) { }
~FlagSaverImpl() {
// reclaim memory from each of our CommandLineFlags
vector<CommandLineFlag*>::const_iterator it;
for (it = backup_registry_.begin(); it != backup_registry_.end(); ++it)
delete *it;
}
// Saves the flag states from the flag registry into this object.
// It's an error to call this more than once.
// Must be called when the registry mutex is not held.
void SaveFromRegistry() {
main_registry_->Lock();
assert(backup_registry_.empty()); // call only once!
for (FlagRegistry::FlagConstIterator it = main_registry_->flags_.begin();
it != main_registry_->flags_.end();
++it) {
const CommandLineFlag* main = it->second;
// Sets up all the const variables in backup correctly
CommandLineFlag* backup = new CommandLineFlag(
main->name(), main->help(), main->filename(),
main->current_->New(), main->defvalue_->New());
// Sets up all the non-const variables in backup correctly
backup->CopyFrom(*main);
backup_registry_.push_back(backup); // add it to a convenient list
}
main_registry_->Unlock();
}
// Restores the saved flag states into the flag registry. We
// assume no flags were added or deleted from the registry since
// the SaveFromRegistry; if they were, that's trouble! Must be
// called when the registry mutex is not held.
void RestoreToRegistry() {
main_registry_->Lock();
vector<CommandLineFlag*>::const_iterator it;
for (it = backup_registry_.begin(); it != backup_registry_.end(); ++it) {
CommandLineFlag* main = main_registry_->FindFlagLocked((*it)->name());
if (main != NULL) { // if NULL, flag got deleted from registry(!)
main->CopyFrom(**it);
}
}
main_registry_->Unlock();
}
private:
FlagRegistry* const main_registry_;
vector<CommandLineFlag*> backup_registry_;
FlagSaverImpl(const FlagSaverImpl&); // no copying!
void operator=(const FlagSaverImpl&);
};
FlagSaver::FlagSaver() : impl_(new FlagSaverImpl(FlagRegistry::GlobalRegistry())) {
impl_->SaveFromRegistry();
}
FlagSaver::~FlagSaver() {
impl_->RestoreToRegistry();
delete impl_;
}
// --------------------------------------------------------------------
// CommandlineFlagsIntoString()
// ReadFlagsFromString()
// AppendFlagsIntoFile()
// ReadFromFlagsFile()
// These are mostly-deprecated routines that stick the
// commandline flags into a file/string and read them back
// out again. I can see a use for CommandlineFlagsIntoString,
// for creating a flagfile, but the rest don't seem that useful
// -- some, I think, are a poor-man's attempt at FlagSaver --
// and are included only until we can delete them from callers.
// Note they don't save --flagfile flags (though they do save
// the result of having called the flagfile, of course).
// --------------------------------------------------------------------
static string TheseCommandlineFlagsIntoString(
const vector<CommandLineFlagInfo>& flags) {
vector<CommandLineFlagInfo>::const_iterator i;
int retval_space = 0;
for (i = flags.begin(); i != flags.end(); ++i) {
// An (over)estimate of how much space it will take to print this flag
retval_space += i->name.length() + i->current_value.length() + 5;
}
string retval;
retval.reserve(retval_space);
for (i = flags.begin(); i != flags.end(); ++i) {
retval += "--";
retval += i->name;
retval += "=";
retval += i->current_value;
retval += "\n";
}
return retval;
}
string CommandlineFlagsIntoString() {
vector<CommandLineFlagInfo> sorted_flags;
GetAllFlags(&sorted_flags);
return TheseCommandlineFlagsIntoString(sorted_flags);
}
bool ReadFlagsFromString(const string& flagfilecontents,
const char* prog_name, // TODO(csilvers): nix this
bool errors_are_fatal) {
FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
FlagSaverImpl saved_states(registry);
saved_states.SaveFromRegistry();
CommandLineFlagParser parser(registry);
registry->Lock();
parser.ProcessOptionsFromStringLocked(flagfilecontents, SET_FLAGS_VALUE);
registry->Unlock();
// Should we handle --help and such when reading flags from a string? Sure.
HandleCommandLineHelpFlags();
if (parser.ReportErrors()) {
// Error. Restore all global flags to their previous values.
if (errors_are_fatal)
commandlineflags_exitfunc(1); // almost certainly exit()
saved_states.RestoreToRegistry();
return false;
}
return true;
}
// TODO(csilvers): nix prog_name in favor of ProgramInvocationShortName()
bool AppendFlagsIntoFile(const string& filename, const char *prog_name) {
FILE *fp = fopen(filename.c_str(), "a");
if (!fp) {
return false;
}
if (prog_name)
fprintf(fp, "%s\n", prog_name);
vector<CommandLineFlagInfo> flags;
GetAllFlags(&flags);
// But we don't want --flagfile, which leads to weird recursion issues
vector<CommandLineFlagInfo>::iterator i;
for (i = flags.begin(); i != flags.end(); ++i) {
if (strcmp(i->name.c_str(), "flagfile") == 0) {
flags.erase(i);
break;
}
}
fprintf(fp, "%s", TheseCommandlineFlagsIntoString(flags).c_str());
fclose(fp);
return true;
}
bool ReadFromFlagsFile(const string& filename, const char* prog_name,
bool errors_are_fatal) {
return ReadFlagsFromString(ReadFileIntoString(filename.c_str()),
prog_name, errors_are_fatal);
}
// --------------------------------------------------------------------
// BoolFromEnv()
// Int32FromEnv()
// Int64FromEnv()
// Uint64FromEnv()
// DoubleFromEnv()
// StringFromEnv()
// Reads the value from the environment and returns it.
// We use an FlagValue to make the parsing easy.
// Example usage:
// DEFINE_bool(myflag, BoolFromEnv("MYFLAG_DEFAULT", false), "whatever");
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
// --------------------------------------------------------------------
template<typename T>
T GetFromEnv(const char *varname, const char* type, T dflt) {
const char* const valstr = getenv(varname);
if (!valstr)
return dflt;
FlagValue ifv(new T, type);
if (!ifv.ParseFrom(valstr)) {
fprintf(stderr, "ERROR: error parsing env variable '%s' with value '%s'\n",
varname, valstr);
commandlineflags_exitfunc(1); // almost certainly exit()
}
return OTHER_VALUE_AS(ifv, T);
}
bool BoolFromEnv(const char *v, bool dflt) {
return GetFromEnv(v, "bool", dflt);
}
int32 Int32FromEnv(const char *v, int32 dflt) {
return GetFromEnv(v, "int32", dflt);
}
int64 Int64FromEnv(const char *v, int64 dflt) {
return GetFromEnv(v, "int64", dflt);
}
uint64 Uint64FromEnv(const char *v, uint64 dflt) {
return GetFromEnv(v, "uint64", dflt);
}
double DoubleFromEnv(const char *v, double dflt) {
return GetFromEnv(v, "double", dflt);
}
const char *StringFromEnv(const char *varname, const char *dflt) {
const char* const val = getenv(varname);
return val ? val : dflt;
}
// --------------------------------------------------------------------
// ParseCommandLineFlags()
// ParseCommandLineNonHelpFlags()
// HandleCommandLineHelpFlags()
// This is the main function called from main(), to actually
// parse the commandline. It modifies argc and argv as described
// at the top of commandlineflags.h. You can also divide this
// function into two parts, if you want to do work between
// the parsing of the flags and the printing of any help output.
// --------------------------------------------------------------------
static uint32 ParseCommandLineFlagsInternal(int* argc, char*** argv,
bool remove_flags, bool do_report) {
SetArgv(*argc, const_cast<const char**>(*argv)); // save it for later
FlagRegistry* const registry = FlagRegistry::GlobalRegistry();
CommandLineFlagParser parser(registry);
// When we parse the commandline flags, we'll handle --flagfile,
// --tryfromenv, etc. as we see them (since flag-evaluation order
// may be important). But sometimes apps set FLAGS_tryfromenv/etc.
// manually before calling ParseCommandLineFlags. We want to evaluate
// those too, as if they were the first flags on the commandline.
registry->Lock();
parser.ProcessFlagfileLocked(FLAGS_flagfile, SET_FLAGS_VALUE);
// Last arg here indicates whether flag-not-found is a fatal error or not
parser.ProcessFromenvLocked(FLAGS_fromenv, SET_FLAGS_VALUE, true);
parser.ProcessFromenvLocked(FLAGS_tryfromenv, SET_FLAGS_VALUE, false);
registry->Unlock();
// Now get the flags specified on the commandline
const int r = parser.ParseNewCommandLineFlags(argc, argv, remove_flags);
if (do_report)
HandleCommandLineHelpFlags(); // may cause us to exit on --help, etc.
if (parser.ReportErrors()) // may cause us to exit on illegal flags
commandlineflags_exitfunc(1); // almost certainly exit()
return r;
}
uint32 ParseCommandLineFlags(int* argc, char*** argv, bool remove_flags) {
return ParseCommandLineFlagsInternal(argc, argv, remove_flags, true);
}
uint32 ParseCommandLineNonHelpFlags(int* argc, char*** argv,
bool remove_flags) {
return ParseCommandLineFlagsInternal(argc, argv, remove_flags, false);
}
// --------------------------------------------------------------------
// AllowCommandLineReparsing()
// ReparseCommandLineNonHelpFlags()
// This is most useful for shared libraries. The idea is if
// a flag is defined in a shared library that is dlopen'ed
// sometime after main(), you can ParseCommandLineFlags before
// the dlopen, then ReparseCommandLineNonHelpFlags() after the
// dlopen, to get the new flags. But you have to explicitly
// Allow() it; otherwise, you get the normal default behavior
// of unrecognized flags calling a fatal error.
// TODO(csilvers): this isn't used. Just delete it?
// --------------------------------------------------------------------
void AllowCommandLineReparsing() {
allow_command_line_reparsing = true;
}
uint32 ReparseCommandLineNonHelpFlags() {
// We make a copy of argc and argv to pass in
const vector<string>& argvs = GetArgvs();
int tmp_argc = argvs.size();
char** tmp_argv = new char* [tmp_argc + 1];
for (int i = 0; i < tmp_argc; ++i)
tmp_argv[i] = strdup(argvs[i].c_str()); // TODO(csilvers): don't dup
const int retval = ParseCommandLineNonHelpFlags(&tmp_argc, &tmp_argv, false);
for (int i = 0; i < tmp_argc; ++i)
free(tmp_argv[i]);
delete[] tmp_argv;
return retval;
}
_END_GOOGLE_NAMESPACE_