blob: 53e2b84ecc1369b74bef5ec81169e94d6a48f441 [file] [log] [blame]
Abseil Teamaa468ad2019-05-07 12:56:42 -07001//
2// Copyright 2019 The Abseil Authors.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// https://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16#include "absl/flags/internal/commandlineflag.h"
17
18#include <cassert>
19
20#include "absl/base/internal/raw_logging.h"
21#include "absl/base/optimization.h"
22#include "absl/flags/config.h"
23#include "absl/flags/usage_config.h"
24#include "absl/strings/str_cat.h"
25#include "absl/synchronization/mutex.h"
26
27namespace absl {
28namespace flags_internal {
29
30// The help message indicating that the commandline flag has been
31// 'stripped'. It will not show up when doing "-help" and its
32// variants. The flag is stripped if ABSL_FLAGS_STRIP_HELP is set to 1
33// before including absl/flags/flag.h
34
35// This is used by this file, and also in commandlineflags_reporting.cc
36const char kStrippedFlagHelp[] = "\001\002\003\004 (unknown) \004\003\002\001";
37
38namespace {
39
Abseil Teamaa468ad2019-05-07 12:56:42 -070040// Currently we only validate flag values for user-defined flag types.
41bool ShouldValidateFlagValue(const CommandLineFlag& flag) {
42#define DONT_VALIDATE(T) \
43 if (flag.IsOfType<T>()) return false;
44 ABSL_FLAGS_INTERNAL_FOR_EACH_LOCK_FREE(DONT_VALIDATE)
45 DONT_VALIDATE(std::string)
46 DONT_VALIDATE(std::vector<std::string>)
47#undef DONT_VALIDATE
48
49 return true;
50}
51
52} // namespace
53
Abseil Teamc6c3c1b2019-07-17 16:35:47 -040054absl::Mutex* InitFlag(CommandLineFlag* flag) {
55 ABSL_CONST_INIT static absl::Mutex init_lock(absl::kConstInit);
56 absl::Mutex* mu;
57
58 {
59 absl::MutexLock lock(&init_lock);
60
Abseil Team83c1d652019-09-05 02:54:58 -070061 if (flag->locks_ == nullptr) { // Must initialize Mutexes for this flag.
62 flag->locks_ = new flags_internal::CommandLineFlagLocks;
Abseil Teamc6c3c1b2019-07-17 16:35:47 -040063 }
64
Abseil Team83c1d652019-09-05 02:54:58 -070065 mu = &flag->locks_->primary_mu;
Abseil Teamaa468ad2019-05-07 12:56:42 -070066 }
67
Abseil Teamc6c3c1b2019-07-17 16:35:47 -040068 {
69 absl::MutexLock lock(mu);
Abseil Teamaa468ad2019-05-07 12:56:42 -070070
Abseil Team83c1d652019-09-05 02:54:58 -070071 if (!flag->IsRetired() && flag->def_ == nullptr) {
Abseil Teamc6c3c1b2019-07-17 16:35:47 -040072 // Need to initialize def and cur fields.
Abseil Team83c1d652019-09-05 02:54:58 -070073 flag->def_ = (*flag->make_init_value_)();
74 flag->cur_ = Clone(flag->op_, flag->def_);
Abseil Teamc6c3c1b2019-07-17 16:35:47 -040075 UpdateCopy(flag);
Abseil Team83c1d652019-09-05 02:54:58 -070076 flag->inited_.store(true, std::memory_order_release);
Abseil Teamc6c3c1b2019-07-17 16:35:47 -040077 flag->InvokeCallback();
78 }
79 }
80
Abseil Team83c1d652019-09-05 02:54:58 -070081 flag->inited_.store(true, std::memory_order_release);
Abseil Teamc6c3c1b2019-07-17 16:35:47 -040082 return mu;
Abseil Teamaa468ad2019-05-07 12:56:42 -070083}
84
85// Ensure that the lazily initialized fields of *flag have been initialized,
Abseil Team83c1d652019-09-05 02:54:58 -070086// and return &flag->locks_->primary_mu.
Abseil Teamc6c3c1b2019-07-17 16:35:47 -040087absl::Mutex* CommandLineFlag::InitFlagIfNecessary() const
Abseil Team83c1d652019-09-05 02:54:58 -070088 ABSL_LOCK_RETURNED(locks_->primary_mu) {
89 if (!inited_.load(std::memory_order_acquire)) {
Abseil Teamc6c3c1b2019-07-17 16:35:47 -040090 return InitFlag(const_cast<CommandLineFlag*>(this));
Abseil Teamaa468ad2019-05-07 12:56:42 -070091 }
Abseil Teamc6c3c1b2019-07-17 16:35:47 -040092
Abseil Team83c1d652019-09-05 02:54:58 -070093 // All fields initialized; locks_ is therefore safe to read.
94 return &locks_->primary_mu;
Abseil Teamaa468ad2019-05-07 12:56:42 -070095}
96
Abseil Teamc6c3c1b2019-07-17 16:35:47 -040097bool CommandLineFlag::IsModified() const {
98 absl::MutexLock l(InitFlagIfNecessary());
Abseil Team83c1d652019-09-05 02:54:58 -070099 return modified_;
Abseil Teamaa468ad2019-05-07 12:56:42 -0700100}
101
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400102void CommandLineFlag::SetModified(bool is_modified) {
103 absl::MutexLock l(InitFlagIfNecessary());
Abseil Team83c1d652019-09-05 02:54:58 -0700104 modified_ = is_modified;
Abseil Teamaa468ad2019-05-07 12:56:42 -0700105}
106
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400107bool CommandLineFlag::IsSpecifiedOnCommandLine() const {
108 absl::MutexLock l(InitFlagIfNecessary());
Abseil Team83c1d652019-09-05 02:54:58 -0700109 return on_command_line_;
Abseil Teamaa468ad2019-05-07 12:56:42 -0700110}
111
112absl::string_view CommandLineFlag::Typename() const {
113 // We do not store/report type in Abseil Flags, so that user do not rely on in
114 // at runtime
115 if (IsAbseilFlag() || IsRetired()) return "";
116
117#define HANDLE_V1_BUILTIN_TYPE(t) \
118 if (IsOfType<t>()) { \
119 return #t; \
120 }
121
122 HANDLE_V1_BUILTIN_TYPE(bool);
123 HANDLE_V1_BUILTIN_TYPE(int32_t);
124 HANDLE_V1_BUILTIN_TYPE(int64_t);
125 HANDLE_V1_BUILTIN_TYPE(uint64_t);
126 HANDLE_V1_BUILTIN_TYPE(double);
127#undef HANDLE_V1_BUILTIN_TYPE
128
129 if (IsOfType<std::string>()) {
130 return "string";
131 }
132
133 return "";
134}
135
136std::string CommandLineFlag::Filename() const {
Abseil Team83c1d652019-09-05 02:54:58 -0700137 return flags_internal::GetUsageConfig().normalize_filename(filename_);
Abseil Teamaa468ad2019-05-07 12:56:42 -0700138}
139
140std::string CommandLineFlag::DefaultValue() const {
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400141 absl::MutexLock l(InitFlagIfNecessary());
142
Abseil Team83c1d652019-09-05 02:54:58 -0700143 return Unparse(marshalling_op_, def_);
Abseil Teamaa468ad2019-05-07 12:56:42 -0700144}
145
146std::string CommandLineFlag::CurrentValue() const {
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400147 absl::MutexLock l(InitFlagIfNecessary());
148
Abseil Team83c1d652019-09-05 02:54:58 -0700149 return Unparse(marshalling_op_, cur_);
Abseil Teamaa468ad2019-05-07 12:56:42 -0700150}
151
Abseil Teamaa468ad2019-05-07 12:56:42 -0700152// Attempts to parse supplied `value` string using parsing routine in the `flag`
153// argument. If parsing is successful, it will try to validate that the parsed
154// value is valid for the specified 'flag'. Finally this function stores the
155// parsed value in 'dst' assuming it is a pointer to the flag's value type. In
156// case if any error is encountered in either step, the error message is stored
157// in 'err'
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400158bool TryParseLocked(CommandLineFlag* flag, void* dst, absl::string_view value,
159 std::string* err)
Abseil Team83c1d652019-09-05 02:54:58 -0700160 ABSL_EXCLUSIVE_LOCKS_REQUIRED(flag->locks_->primary_mu) {
161 void* tentative_value = Clone(flag->op_, flag->def_);
Abseil Teamaa468ad2019-05-07 12:56:42 -0700162 std::string parse_err;
Abseil Team83c1d652019-09-05 02:54:58 -0700163 if (!Parse(flag->marshalling_op_, value, tentative_value, &parse_err)) {
Abseil Teamaa468ad2019-05-07 12:56:42 -0700164 auto type_name = flag->Typename();
165 absl::string_view err_sep = parse_err.empty() ? "" : "; ";
166 absl::string_view typename_sep = type_name.empty() ? "" : " ";
167 *err = absl::StrCat("Illegal value '", value, "' specified for",
168 typename_sep, type_name, " flag '", flag->Name(), "'",
169 err_sep, parse_err);
Abseil Team83c1d652019-09-05 02:54:58 -0700170 Delete(flag->op_, tentative_value);
Abseil Teamaa468ad2019-05-07 12:56:42 -0700171 return false;
172 }
173
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400174 if (!flag->InvokeValidator(tentative_value)) {
Abseil Teamaa468ad2019-05-07 12:56:42 -0700175 *err = absl::StrCat("Failed validation of new value '",
Abseil Team83c1d652019-09-05 02:54:58 -0700176 Unparse(flag->marshalling_op_, tentative_value),
Abseil Teamaa468ad2019-05-07 12:56:42 -0700177 "' for flag '", flag->Name(), "'");
Abseil Team83c1d652019-09-05 02:54:58 -0700178 Delete(flag->op_, tentative_value);
Abseil Teamaa468ad2019-05-07 12:56:42 -0700179 return false;
180 }
181
Abseil Team83c1d652019-09-05 02:54:58 -0700182 flag->counter_++;
183 Copy(flag->op_, tentative_value, dst);
184 Delete(flag->op_, tentative_value);
Abseil Teamaa468ad2019-05-07 12:56:42 -0700185 return true;
186}
187
188// Sets the value of the flag based on specified string `value`. If the flag
189// was successfully set to new value, it returns true. Otherwise, sets `err`
190// to indicate the error, leaves the flag unchanged, and returns false. There
191// are three ways to set the flag's value:
192// * Update the current flag value
193// * Update the flag's default value
194// * Update the current flag value if it was never set before
195// The mode is selected based on 'set_mode' parameter.
196bool CommandLineFlag::SetFromString(absl::string_view value,
197 FlagSettingMode set_mode,
198 ValueSource source, std::string* err) {
199 if (IsRetired()) return false;
200
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400201 absl::MutexLock l(InitFlagIfNecessary());
Abseil Teamaa468ad2019-05-07 12:56:42 -0700202
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400203 // Direct-access flags can be modified without going through the
Abseil Team83c1d652019-09-05 02:54:58 -0700204 // flag API. Detect such changes and update the flag->modified_ bit.
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400205 if (!IsAbseilFlag()) {
Abseil Team83c1d652019-09-05 02:54:58 -0700206 if (!modified_ && ChangedDirectly(this, cur_, def_)) {
207 modified_ = true;
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400208 }
209 }
Abseil Teamaa468ad2019-05-07 12:56:42 -0700210
211 switch (set_mode) {
212 case SET_FLAGS_VALUE: {
213 // set or modify the flag's value
Abseil Team83c1d652019-09-05 02:54:58 -0700214 if (!TryParseLocked(this, cur_, value, err)) return false;
215 modified_ = true;
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400216 UpdateCopy(this);
217 InvokeCallback();
Abseil Teamaa468ad2019-05-07 12:56:42 -0700218
219 if (source == kCommandLine) {
Abseil Team83c1d652019-09-05 02:54:58 -0700220 on_command_line_ = true;
Abseil Teamaa468ad2019-05-07 12:56:42 -0700221 }
222 break;
223 }
224 case SET_FLAG_IF_DEFAULT: {
225 // set the flag's value, but only if it hasn't been set by someone else
Abseil Team83c1d652019-09-05 02:54:58 -0700226 if (!modified_) {
227 if (!TryParseLocked(this, cur_, value, err)) return false;
228 modified_ = true;
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400229 UpdateCopy(this);
230 InvokeCallback();
Abseil Teamaa468ad2019-05-07 12:56:42 -0700231 } else {
232 // TODO(rogeeff): review and fix this semantic. Currently we do not fail
233 // in this case if flag is modified. This is misleading since the flag's
234 // value is not updated even though we return true.
Abseil Team83c1d652019-09-05 02:54:58 -0700235 // *err = absl::StrCat(Name(), " is already set to ",
Abseil Teamaa468ad2019-05-07 12:56:42 -0700236 // CurrentValue(), "\n");
237 // return false;
238 return true;
239 }
240 break;
241 }
242 case SET_FLAGS_DEFAULT: {
243 // modify the flag's default-value
Abseil Team83c1d652019-09-05 02:54:58 -0700244 if (!TryParseLocked(this, def_, value, err)) return false;
Abseil Teamaa468ad2019-05-07 12:56:42 -0700245
Abseil Team83c1d652019-09-05 02:54:58 -0700246 if (!modified_) {
Abseil Teamaa468ad2019-05-07 12:56:42 -0700247 // Need to set both defvalue *and* current, in this case
Abseil Team83c1d652019-09-05 02:54:58 -0700248 Copy(op_, def_, cur_);
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400249 UpdateCopy(this);
250 InvokeCallback();
Abseil Teamaa468ad2019-05-07 12:56:42 -0700251 }
252 break;
253 }
254 default: {
255 // unknown set_mode
256 assert(false);
257 return false;
258 }
259 }
260
261 return true;
262}
263
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400264void CommandLineFlag::CheckDefaultValueParsingRoundtrip() const {
265 std::string v = DefaultValue();
266
267 absl::MutexLock lock(InitFlagIfNecessary());
268
Abseil Team83c1d652019-09-05 02:54:58 -0700269 void* dst = Clone(op_, def_);
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400270 std::string error;
Abseil Team83c1d652019-09-05 02:54:58 -0700271 if (!flags_internal::Parse(marshalling_op_, v, dst, &error)) {
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400272 ABSL_INTERNAL_LOG(
273 FATAL,
274 absl::StrCat("Flag ", Name(), " (from ", Filename(),
275 "): std::string form of default value '", v,
276 "' could not be parsed; error=", error));
277 }
278
279 // We do not compare dst to def since parsing/unparsing may make
280 // small changes, e.g., precision loss for floating point types.
Abseil Team83c1d652019-09-05 02:54:58 -0700281 Delete(op_, dst);
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400282}
283
284bool CommandLineFlag::ValidateDefaultValue() const {
285 absl::MutexLock lock(InitFlagIfNecessary());
Abseil Team83c1d652019-09-05 02:54:58 -0700286 return InvokeValidator(def_);
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400287}
288
289bool CommandLineFlag::ValidateInputValue(absl::string_view value) const {
290 absl::MutexLock l(InitFlagIfNecessary()); // protect default value access
291
Abseil Team83c1d652019-09-05 02:54:58 -0700292 void* obj = Clone(op_, def_);
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400293 std::string ignored_error;
294 const bool result =
Abseil Team83c1d652019-09-05 02:54:58 -0700295 flags_internal::Parse(marshalling_op_, value, obj, &ignored_error) &&
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400296 InvokeValidator(obj);
Abseil Team83c1d652019-09-05 02:54:58 -0700297 Delete(op_, obj);
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400298 return result;
299}
300
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400301void CommandLineFlag::Read(void* dst,
302 const flags_internal::FlagOpFn dst_op) const {
303 absl::ReaderMutexLock l(InitFlagIfNecessary());
304
305 // `dst_op` is the unmarshaling operation corresponding to the declaration
306 // visibile at the call site. `op` is the Flag's defined unmarshalling
307 // operation. They must match for this operation to be well-defined.
Abseil Team83c1d652019-09-05 02:54:58 -0700308 if (ABSL_PREDICT_FALSE(dst_op != op_)) {
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400309 ABSL_INTERNAL_LOG(
310 ERROR,
Abseil Team83c1d652019-09-05 02:54:58 -0700311 absl::StrCat("Flag '", Name(),
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400312 "' is defined as one type and declared as another"));
313 }
Abseil Team83c1d652019-09-05 02:54:58 -0700314 CopyConstruct(op_, cur_, dst);
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400315}
316
317void CommandLineFlag::Write(const void* src,
318 const flags_internal::FlagOpFn src_op) {
319 absl::MutexLock l(InitFlagIfNecessary());
320
321 // `src_op` is the marshalling operation corresponding to the declaration
322 // visible at the call site. `op` is the Flag's defined marshalling operation.
323 // They must match for this operation to be well-defined.
Abseil Team83c1d652019-09-05 02:54:58 -0700324 if (ABSL_PREDICT_FALSE(src_op != op_)) {
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400325 ABSL_INTERNAL_LOG(
326 ERROR,
Abseil Team83c1d652019-09-05 02:54:58 -0700327 absl::StrCat("Flag '", Name(),
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400328 "' is defined as one type and declared as another"));
329 }
330
331 if (ShouldValidateFlagValue(*this)) {
Abseil Team83c1d652019-09-05 02:54:58 -0700332 void* obj = Clone(op_, src);
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400333 std::string ignored_error;
Abseil Team83c1d652019-09-05 02:54:58 -0700334 std::string src_as_str = Unparse(marshalling_op_, src);
335 if (!Parse(marshalling_op_, src_as_str, obj, &ignored_error) ||
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400336 !InvokeValidator(obj)) {
Abseil Team83c1d652019-09-05 02:54:58 -0700337 ABSL_INTERNAL_LOG(ERROR, absl::StrCat("Attempt to set flag '", Name(),
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400338 "' to invalid value ", src_as_str));
339 }
Abseil Team83c1d652019-09-05 02:54:58 -0700340 Delete(op_, obj);
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400341 }
342
Abseil Team83c1d652019-09-05 02:54:58 -0700343 modified_ = true;
344 counter_++;
345 Copy(op_, src, cur_);
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400346
347 UpdateCopy(this);
348 InvokeCallback();
349}
350
351std::string HelpText::GetHelpText() const {
352 if (help_function_) return help_function_();
353 if (help_message_) return help_message_;
354
355 return {};
356}
357
358// Update any copy of the flag value that is stored in an atomic word.
359// In addition if flag has a mutation callback this function invokes it.
360void UpdateCopy(CommandLineFlag* flag) {
361#define STORE_ATOMIC(T) \
362 else if (flag->IsOfType<T>()) { \
Abseil Team325fd7b2019-09-06 02:25:12 -0700363 flag->StoreAtomic(); \
Abseil Teamc6c3c1b2019-07-17 16:35:47 -0400364 }
365
366 if (false) {
367 }
368 ABSL_FLAGS_INTERNAL_FOR_EACH_LOCK_FREE(STORE_ATOMIC)
369#undef STORE_ATOMIC
370}
371
372// Return true iff flag value was changed via direct-access.
373bool ChangedDirectly(CommandLineFlag* flag, const void* a, const void* b) {
374 if (!flag->IsAbseilFlag()) {
375// Need to compare values for direct-access flags.
376#define CHANGED_FOR_TYPE(T) \
377 if (flag->IsOfType<T>()) { \
378 return *reinterpret_cast<const T*>(a) != *reinterpret_cast<const T*>(b); \
379 }
380
381 CHANGED_FOR_TYPE(bool);
382 CHANGED_FOR_TYPE(int32_t);
383 CHANGED_FOR_TYPE(int64_t);
384 CHANGED_FOR_TYPE(uint64_t);
385 CHANGED_FOR_TYPE(double);
386 CHANGED_FOR_TYPE(std::string);
387#undef CHANGED_FOR_TYPE
388 }
389
390 return false;
391}
392
Abseil Teamaa468ad2019-05-07 12:56:42 -0700393} // namespace flags_internal
394} // namespace absl