1 //
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 #ifndef ABSL_FLAGS_INTERNAL_FLAG_H_
17 #define ABSL_FLAGS_INTERNAL_FLAG_H_
18
19 #include <stddef.h>
20 #include <stdint.h>
21
22 #include <atomic>
23 #include <cstring>
24 #include <memory>
25 #include <string>
26 #include <type_traits>
27 #include <typeinfo>
28
29 #include "absl/base/attributes.h"
30 #include "absl/base/call_once.h"
31 #include "absl/base/casts.h"
32 #include "absl/base/config.h"
33 #include "absl/base/optimization.h"
34 #include "absl/base/thread_annotations.h"
35 #include "absl/flags/commandlineflag.h"
36 #include "absl/flags/config.h"
37 #include "absl/flags/internal/commandlineflag.h"
38 #include "absl/flags/internal/registry.h"
39 #include "absl/flags/internal/sequence_lock.h"
40 #include "absl/flags/marshalling.h"
41 #include "absl/meta/type_traits.h"
42 #include "absl/strings/string_view.h"
43 #include "absl/synchronization/mutex.h"
44 #include "absl/utility/utility.h"
45
46 namespace absl {
47 ABSL_NAMESPACE_BEGIN
48
49 ///////////////////////////////////////////////////////////////////////////////
50 // Forward declaration of absl::Flag<T> public API.
51 namespace flags_internal {
52 template <typename T>
53 class Flag;
54 } // namespace flags_internal
55
56 template <typename T>
57 using Flag = flags_internal::Flag<T>;
58
59 template <typename T>
60 ABSL_MUST_USE_RESULT T GetFlag(const absl::Flag<T>& flag);
61
62 template <typename T>
63 void SetFlag(absl::Flag<T>* flag, const T& v);
64
65 template <typename T, typename V>
66 void SetFlag(absl::Flag<T>* flag, const V& v);
67
68 template <typename U>
69 const CommandLineFlag& GetFlagReflectionHandle(const absl::Flag<U>& f);
70
71 ///////////////////////////////////////////////////////////////////////////////
72 // Flag value type operations, eg., parsing, copying, etc. are provided
73 // by function specific to that type with a signature matching FlagOpFn.
74
75 namespace flags_internal {
76
77 enum class FlagOp {
78 kAlloc,
79 kDelete,
80 kCopy,
81 kCopyConstruct,
82 kSizeof,
83 kFastTypeId,
84 kRuntimeTypeId,
85 kParse,
86 kUnparse,
87 kValueOffset,
88 };
89 using FlagOpFn = void* (*)(FlagOp, const void*, void*, void*);
90
91 // Forward declaration for Flag value specific operations.
92 template <typename T>
93 void* FlagOps(FlagOp op, const void* v1, void* v2, void* v3);
94
95 // Allocate aligned memory for a flag value.
Alloc(FlagOpFn op)96 inline void* Alloc(FlagOpFn op) {
97 return op(FlagOp::kAlloc, nullptr, nullptr, nullptr);
98 }
99 // Deletes memory interpreting obj as flag value type pointer.
Delete(FlagOpFn op,void * obj)100 inline void Delete(FlagOpFn op, void* obj) {
101 op(FlagOp::kDelete, nullptr, obj, nullptr);
102 }
103 // Copies src to dst interpreting as flag value type pointers.
Copy(FlagOpFn op,const void * src,void * dst)104 inline void Copy(FlagOpFn op, const void* src, void* dst) {
105 op(FlagOp::kCopy, src, dst, nullptr);
106 }
107 // Construct a copy of flag value in a location pointed by dst
108 // based on src - pointer to the flag's value.
CopyConstruct(FlagOpFn op,const void * src,void * dst)109 inline void CopyConstruct(FlagOpFn op, const void* src, void* dst) {
110 op(FlagOp::kCopyConstruct, src, dst, nullptr);
111 }
112 // Makes a copy of flag value pointed by obj.
Clone(FlagOpFn op,const void * obj)113 inline void* Clone(FlagOpFn op, const void* obj) {
114 void* res = flags_internal::Alloc(op);
115 flags_internal::CopyConstruct(op, obj, res);
116 return res;
117 }
118 // Returns true if parsing of input text is successful.
Parse(FlagOpFn op,absl::string_view text,void * dst,std::string * error)119 inline bool Parse(FlagOpFn op, absl::string_view text, void* dst,
120 std::string* error) {
121 return op(FlagOp::kParse, &text, dst, error) != nullptr;
122 }
123 // Returns string representing supplied value.
Unparse(FlagOpFn op,const void * val)124 inline std::string Unparse(FlagOpFn op, const void* val) {
125 std::string result;
126 op(FlagOp::kUnparse, val, &result, nullptr);
127 return result;
128 }
129 // Returns size of flag value type.
Sizeof(FlagOpFn op)130 inline size_t Sizeof(FlagOpFn op) {
131 // This sequence of casts reverses the sequence from
132 // `flags_internal::FlagOps()`
133 return static_cast<size_t>(reinterpret_cast<intptr_t>(
134 op(FlagOp::kSizeof, nullptr, nullptr, nullptr)));
135 }
136 // Returns fast type id corresponding to the value type.
FastTypeId(FlagOpFn op)137 inline FlagFastTypeId FastTypeId(FlagOpFn op) {
138 return reinterpret_cast<FlagFastTypeId>(
139 op(FlagOp::kFastTypeId, nullptr, nullptr, nullptr));
140 }
141 // Returns fast type id corresponding to the value type.
RuntimeTypeId(FlagOpFn op)142 inline const std::type_info* RuntimeTypeId(FlagOpFn op) {
143 return reinterpret_cast<const std::type_info*>(
144 op(FlagOp::kRuntimeTypeId, nullptr, nullptr, nullptr));
145 }
146 // Returns offset of the field value_ from the field impl_ inside of
147 // absl::Flag<T> data. Given FlagImpl pointer p you can get the
148 // location of the corresponding value as:
149 // reinterpret_cast<char*>(p) + ValueOffset().
ValueOffset(FlagOpFn op)150 inline ptrdiff_t ValueOffset(FlagOpFn op) {
151 // This sequence of casts reverses the sequence from
152 // `flags_internal::FlagOps()`
153 return static_cast<ptrdiff_t>(reinterpret_cast<intptr_t>(
154 op(FlagOp::kValueOffset, nullptr, nullptr, nullptr)));
155 }
156
157 // Returns an address of RTTI's typeid(T).
158 template <typename T>
GenRuntimeTypeId()159 inline const std::type_info* GenRuntimeTypeId() {
160 #ifdef ABSL_INTERNAL_HAS_RTTI
161 return &typeid(T);
162 #else
163 return nullptr;
164 #endif
165 }
166
167 ///////////////////////////////////////////////////////////////////////////////
168 // Flag help auxiliary structs.
169
170 // This is help argument for absl::Flag encapsulating the string literal pointer
171 // or pointer to function generating it as well as enum descriminating two
172 // cases.
173 using HelpGenFunc = std::string (*)();
174
175 template <size_t N>
176 struct FixedCharArray {
177 char value[N];
178
179 template <size_t... I>
FromLiteralStringFixedCharArray180 static constexpr FixedCharArray<N> FromLiteralString(
181 absl::string_view str, absl::index_sequence<I...>) {
182 return (void)str, FixedCharArray<N>({{str[I]..., '\0'}});
183 }
184 };
185
186 template <typename Gen, size_t N = Gen::Value().size()>
HelpStringAsArray(int)187 constexpr FixedCharArray<N + 1> HelpStringAsArray(int) {
188 return FixedCharArray<N + 1>::FromLiteralString(
189 Gen::Value(), absl::make_index_sequence<N>{});
190 }
191
192 template <typename Gen>
HelpStringAsArray(char)193 constexpr std::false_type HelpStringAsArray(char) {
194 return std::false_type{};
195 }
196
197 union FlagHelpMsg {
FlagHelpMsg(const char * help_msg)198 constexpr explicit FlagHelpMsg(const char* help_msg) : literal(help_msg) {}
FlagHelpMsg(HelpGenFunc help_gen)199 constexpr explicit FlagHelpMsg(HelpGenFunc help_gen) : gen_func(help_gen) {}
200
201 const char* literal;
202 HelpGenFunc gen_func;
203 };
204
205 enum class FlagHelpKind : uint8_t { kLiteral = 0, kGenFunc = 1 };
206
207 struct FlagHelpArg {
208 FlagHelpMsg source;
209 FlagHelpKind kind;
210 };
211
212 extern const char kStrippedFlagHelp[];
213
214 // These two HelpArg overloads allows us to select at compile time one of two
215 // way to pass Help argument to absl::Flag. We'll be passing
216 // AbslFlagHelpGenFor##name as Gen and integer 0 as a single argument to prefer
217 // first overload if possible. If help message is evaluatable on constexpr
218 // context We'll be able to make FixedCharArray out of it and we'll choose first
219 // overload. In this case the help message expression is immediately evaluated
220 // and is used to construct the absl::Flag. No additional code is generated by
221 // ABSL_FLAG Otherwise SFINAE kicks in and first overload is dropped from the
222 // consideration, in which case the second overload will be used. The second
223 // overload does not attempt to evaluate the help message expression
224 // immediately and instead delays the evaluation by returning the function
225 // pointer (&T::NonConst) generating the help message when necessary. This is
226 // evaluatable in constexpr context, but the cost is an extra function being
227 // generated in the ABSL_FLAG code.
228 template <typename Gen, size_t N>
HelpArg(const FixedCharArray<N> & value)229 constexpr FlagHelpArg HelpArg(const FixedCharArray<N>& value) {
230 return {FlagHelpMsg(value.value), FlagHelpKind::kLiteral};
231 }
232
233 template <typename Gen>
HelpArg(std::false_type)234 constexpr FlagHelpArg HelpArg(std::false_type) {
235 return {FlagHelpMsg(&Gen::NonConst), FlagHelpKind::kGenFunc};
236 }
237
238 ///////////////////////////////////////////////////////////////////////////////
239 // Flag default value auxiliary structs.
240
241 // Signature for the function generating the initial flag value (usually
242 // based on default value supplied in flag's definition)
243 using FlagDfltGenFunc = void (*)(void*);
244
245 union FlagDefaultSrc {
FlagDefaultSrc(FlagDfltGenFunc gen_func_arg)246 constexpr explicit FlagDefaultSrc(FlagDfltGenFunc gen_func_arg)
247 : gen_func(gen_func_arg) {}
248
249 #define ABSL_FLAGS_INTERNAL_DFLT_FOR_TYPE(T, name) \
250 T name##_value; \
251 constexpr explicit FlagDefaultSrc(T value) : name##_value(value) {} // NOLINT
252 ABSL_FLAGS_INTERNAL_BUILTIN_TYPES(ABSL_FLAGS_INTERNAL_DFLT_FOR_TYPE)
253 #undef ABSL_FLAGS_INTERNAL_DFLT_FOR_TYPE
254
255 void* dynamic_value;
256 FlagDfltGenFunc gen_func;
257 };
258
259 enum class FlagDefaultKind : uint8_t {
260 kDynamicValue = 0,
261 kGenFunc = 1,
262 kOneWord = 2 // for default values UP to one word in size
263 };
264
265 struct FlagDefaultArg {
266 FlagDefaultSrc source;
267 FlagDefaultKind kind;
268 };
269
270 // This struct and corresponding overload to InitDefaultValue are used to
271 // facilitate usage of {} as default value in ABSL_FLAG macro.
272 // TODO(rogeeff): Fix handling types with explicit constructors.
273 struct EmptyBraces {};
274
275 template <typename T>
InitDefaultValue(T t)276 constexpr T InitDefaultValue(T t) {
277 return t;
278 }
279
280 template <typename T>
InitDefaultValue(EmptyBraces)281 constexpr T InitDefaultValue(EmptyBraces) {
282 return T{};
283 }
284
285 template <typename ValueT, typename GenT,
286 typename std::enable_if<std::is_integral<ValueT>::value, int>::type =
287 ((void)GenT{}, 0)>
DefaultArg(int)288 constexpr FlagDefaultArg DefaultArg(int) {
289 return {FlagDefaultSrc(GenT{}.value), FlagDefaultKind::kOneWord};
290 }
291
292 template <typename ValueT, typename GenT>
DefaultArg(char)293 constexpr FlagDefaultArg DefaultArg(char) {
294 return {FlagDefaultSrc(&GenT::Gen), FlagDefaultKind::kGenFunc};
295 }
296
297 ///////////////////////////////////////////////////////////////////////////////
298 // Flag current value auxiliary structs.
299
UninitializedFlagValue()300 constexpr int64_t UninitializedFlagValue() {
301 return static_cast<int64_t>(0xababababababababll);
302 }
303
304 template <typename T>
305 using FlagUseValueAndInitBitStorage =
306 std::integral_constant<bool, std::is_trivially_copyable<T>::value &&
307 std::is_default_constructible<T>::value &&
308 (sizeof(T) < 8)>;
309
310 template <typename T>
311 using FlagUseOneWordStorage =
312 std::integral_constant<bool, std::is_trivially_copyable<T>::value &&
313 (sizeof(T) <= 8)>;
314
315 template <class T>
316 using FlagUseSequenceLockStorage =
317 std::integral_constant<bool, std::is_trivially_copyable<T>::value &&
318 (sizeof(T) > 8)>;
319
320 enum class FlagValueStorageKind : uint8_t {
321 kValueAndInitBit = 0,
322 kOneWordAtomic = 1,
323 kSequenceLocked = 2,
324 kAlignedBuffer = 3,
325 };
326
327 template <typename T>
StorageKind()328 static constexpr FlagValueStorageKind StorageKind() {
329 return FlagUseValueAndInitBitStorage<T>::value
330 ? FlagValueStorageKind::kValueAndInitBit
331 : FlagUseOneWordStorage<T>::value
332 ? FlagValueStorageKind::kOneWordAtomic
333 : FlagUseSequenceLockStorage<T>::value
334 ? FlagValueStorageKind::kSequenceLocked
335 : FlagValueStorageKind::kAlignedBuffer;
336 }
337
338 struct FlagOneWordValue {
FlagOneWordValueFlagOneWordValue339 constexpr explicit FlagOneWordValue(int64_t v) : value(v) {}
340 std::atomic<int64_t> value;
341 };
342
343 template <typename T>
344 struct alignas(8) FlagValueAndInitBit {
345 T value;
346 // Use an int instead of a bool to guarantee that a non-zero value has
347 // a bit set.
348 uint8_t init;
349 };
350
351 template <typename T,
352 FlagValueStorageKind Kind = flags_internal::StorageKind<T>()>
353 struct FlagValue;
354
355 template <typename T>
356 struct FlagValue<T, FlagValueStorageKind::kValueAndInitBit> : FlagOneWordValue {
357 constexpr FlagValue() : FlagOneWordValue(0) {}
358 bool Get(const SequenceLock&, T& dst) const {
359 int64_t storage = value.load(std::memory_order_acquire);
360 if (ABSL_PREDICT_FALSE(storage == 0)) {
361 return false;
362 }
363 dst = absl::bit_cast<FlagValueAndInitBit<T>>(storage).value;
364 return true;
365 }
366 };
367
368 template <typename T>
369 struct FlagValue<T, FlagValueStorageKind::kOneWordAtomic> : FlagOneWordValue {
370 constexpr FlagValue() : FlagOneWordValue(UninitializedFlagValue()) {}
371 bool Get(const SequenceLock&, T& dst) const {
372 int64_t one_word_val = value.load(std::memory_order_acquire);
373 if (ABSL_PREDICT_FALSE(one_word_val == UninitializedFlagValue())) {
374 return false;
375 }
376 std::memcpy(&dst, static_cast<const void*>(&one_word_val), sizeof(T));
377 return true;
378 }
379 };
380
381 template <typename T>
382 struct FlagValue<T, FlagValueStorageKind::kSequenceLocked> {
383 bool Get(const SequenceLock& lock, T& dst) const {
384 return lock.TryRead(&dst, value_words, sizeof(T));
385 }
386
387 static constexpr int kNumWords =
388 flags_internal::AlignUp(sizeof(T), sizeof(uint64_t)) / sizeof(uint64_t);
389
390 alignas(T) alignas(
391 std::atomic<uint64_t>) std::atomic<uint64_t> value_words[kNumWords];
392 };
393
394 template <typename T>
395 struct FlagValue<T, FlagValueStorageKind::kAlignedBuffer> {
396 bool Get(const SequenceLock&, T&) const { return false; }
397
398 alignas(T) char value[sizeof(T)];
399 };
400
401 ///////////////////////////////////////////////////////////////////////////////
402 // Flag callback auxiliary structs.
403
404 // Signature for the mutation callback used by watched Flags
405 // The callback is noexcept.
406 // TODO(rogeeff): add noexcept after C++17 support is added.
407 using FlagCallbackFunc = void (*)();
408
409 struct FlagCallback {
410 FlagCallbackFunc func;
411 absl::Mutex guard; // Guard for concurrent callback invocations.
412 };
413
414 ///////////////////////////////////////////////////////////////////////////////
415 // Flag implementation, which does not depend on flag value type.
416 // The class encapsulates the Flag's data and access to it.
417
418 struct DynValueDeleter {
419 explicit DynValueDeleter(FlagOpFn op_arg = nullptr);
420 void operator()(void* ptr) const;
421
422 FlagOpFn op;
423 };
424
425 class FlagState;
426
427 // These are only used as constexpr global objects.
428 // They do not use a virtual destructor to simplify their implementation.
429 // They are not destroyed except at program exit, so leaks do not matter.
430 #if defined(__GNUC__) && !defined(__clang__)
431 #pragma GCC diagnostic push
432 #pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
433 #endif
434 class FlagImpl final : public CommandLineFlag {
435 public:
436 constexpr FlagImpl(const char* name, const char* filename, FlagOpFn op,
437 FlagHelpArg help, FlagValueStorageKind value_kind,
438 FlagDefaultArg default_arg)
439 : name_(name),
440 filename_(filename),
441 op_(op),
442 help_(help.source),
443 help_source_kind_(static_cast<uint8_t>(help.kind)),
444 value_storage_kind_(static_cast<uint8_t>(value_kind)),
445 def_kind_(static_cast<uint8_t>(default_arg.kind)),
446 modified_(false),
447 on_command_line_(false),
448 callback_(nullptr),
449 default_value_(default_arg.source),
450 data_guard_{} {}
451
452 // Constant access methods
453 int64_t ReadOneWord() const ABSL_LOCKS_EXCLUDED(*DataGuard());
454 bool ReadOneBool() const ABSL_LOCKS_EXCLUDED(*DataGuard());
455 void Read(void* dst) const override ABSL_LOCKS_EXCLUDED(*DataGuard());
456 void Read(bool* value) const ABSL_LOCKS_EXCLUDED(*DataGuard()) {
457 *value = ReadOneBool();
458 }
459 template <typename T,
460 absl::enable_if_t<flags_internal::StorageKind<T>() ==
461 FlagValueStorageKind::kOneWordAtomic,
462 int> = 0>
463 void Read(T* value) const ABSL_LOCKS_EXCLUDED(*DataGuard()) {
464 int64_t v = ReadOneWord();
465 std::memcpy(value, static_cast<const void*>(&v), sizeof(T));
466 }
467 template <typename T,
468 typename std::enable_if<flags_internal::StorageKind<T>() ==
469 FlagValueStorageKind::kValueAndInitBit,
470 int>::type = 0>
471 void Read(T* value) const ABSL_LOCKS_EXCLUDED(*DataGuard()) {
472 *value = absl::bit_cast<FlagValueAndInitBit<T>>(ReadOneWord()).value;
473 }
474
475 // Mutating access methods
476 void Write(const void* src) ABSL_LOCKS_EXCLUDED(*DataGuard());
477
478 // Interfaces to operate on callbacks.
479 void SetCallback(const FlagCallbackFunc mutation_callback)
480 ABSL_LOCKS_EXCLUDED(*DataGuard());
481 void InvokeCallback() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
482
483 // Used in read/write operations to validate source/target has correct type.
484 // For example if flag is declared as absl::Flag<int> FLAGS_foo, a call to
485 // absl::GetFlag(FLAGS_foo) validates that the type of FLAGS_foo is indeed
486 // int. To do that we pass the "assumed" type id (which is deduced from type
487 // int) as an argument `type_id`, which is in turn is validated against the
488 // type id stored in flag object by flag definition statement.
489 void AssertValidType(FlagFastTypeId type_id,
490 const std::type_info* (*gen_rtti)()) const;
491
492 private:
493 template <typename T>
494 friend class Flag;
495 friend class FlagState;
496
497 // Ensures that `data_guard_` is initialized and returns it.
498 absl::Mutex* DataGuard() const
499 ABSL_LOCK_RETURNED(reinterpret_cast<absl::Mutex*>(data_guard_));
500 // Returns heap allocated value of type T initialized with default value.
501 std::unique_ptr<void, DynValueDeleter> MakeInitValue() const
502 ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
503 // Flag initialization called via absl::call_once.
504 void Init();
505
506 // Offset value access methods. One per storage kind. These methods to not
507 // respect const correctness, so be very carefull using them.
508
509 // This is a shared helper routine which encapsulates most of the magic. Since
510 // it is only used inside the three routines below, which are defined in
511 // flag.cc, we can define it in that file as well.
512 template <typename StorageT>
513 StorageT* OffsetValue() const;
514 // This is an accessor for a value stored in an aligned buffer storage
515 // used for non-trivially-copyable data types.
516 // Returns a mutable pointer to the start of a buffer.
517 void* AlignedBufferValue() const;
518
519 // The same as above, but used for sequencelock-protected storage.
520 std::atomic<uint64_t>* AtomicBufferValue() const;
521
522 // This is an accessor for a value stored as one word atomic. Returns a
523 // mutable reference to an atomic value.
524 std::atomic<int64_t>& OneWordValue() const;
525
526 // Attempts to parse supplied `value` string. If parsing is successful,
527 // returns new value. Otherwise returns nullptr.
528 std::unique_ptr<void, DynValueDeleter> TryParse(absl::string_view value,
529 std::string& err) const
530 ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
531 // Stores the flag value based on the pointer to the source.
532 void StoreValue(const void* src) ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
533
534 // Copy the flag data, protected by `seq_lock_` into `dst`.
535 //
536 // REQUIRES: ValueStorageKind() == kSequenceLocked.
537 void ReadSequenceLockedData(void* dst) const
538 ABSL_LOCKS_EXCLUDED(*DataGuard());
539
540 FlagHelpKind HelpSourceKind() const {
541 return static_cast<FlagHelpKind>(help_source_kind_);
542 }
543 FlagValueStorageKind ValueStorageKind() const {
544 return static_cast<FlagValueStorageKind>(value_storage_kind_);
545 }
546 FlagDefaultKind DefaultKind() const
547 ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard()) {
548 return static_cast<FlagDefaultKind>(def_kind_);
549 }
550
551 // CommandLineFlag interface implementation
552 absl::string_view Name() const override;
553 std::string Filename() const override;
554 std::string Help() const override;
555 FlagFastTypeId TypeId() const override;
556 bool IsSpecifiedOnCommandLine() const override
557 ABSL_LOCKS_EXCLUDED(*DataGuard());
558 std::string DefaultValue() const override ABSL_LOCKS_EXCLUDED(*DataGuard());
559 std::string CurrentValue() const override ABSL_LOCKS_EXCLUDED(*DataGuard());
560 bool ValidateInputValue(absl::string_view value) const override
561 ABSL_LOCKS_EXCLUDED(*DataGuard());
562 void CheckDefaultValueParsingRoundtrip() const override
563 ABSL_LOCKS_EXCLUDED(*DataGuard());
564
565 int64_t ModificationCount() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
566
567 // Interfaces to save and restore flags to/from persistent state.
568 // Returns current flag state or nullptr if flag does not support
569 // saving and restoring a state.
570 std::unique_ptr<FlagStateInterface> SaveState() override
571 ABSL_LOCKS_EXCLUDED(*DataGuard());
572
573 // Restores the flag state to the supplied state object. If there is
574 // nothing to restore returns false. Otherwise returns true.
575 bool RestoreState(const FlagState& flag_state)
576 ABSL_LOCKS_EXCLUDED(*DataGuard());
577
578 bool ParseFrom(absl::string_view value, FlagSettingMode set_mode,
579 ValueSource source, std::string& error) override
580 ABSL_LOCKS_EXCLUDED(*DataGuard());
581
582 // Immutable flag's state.
583
584 // Flags name passed to ABSL_FLAG as second arg.
585 const char* const name_;
586 // The file name where ABSL_FLAG resides.
587 const char* const filename_;
588 // Type-specific operations "vtable".
589 const FlagOpFn op_;
590 // Help message literal or function to generate it.
591 const FlagHelpMsg help_;
592 // Indicates if help message was supplied as literal or generator func.
593 const uint8_t help_source_kind_ : 1;
594 // Kind of storage this flag is using for the flag's value.
595 const uint8_t value_storage_kind_ : 2;
596
597 uint8_t : 0; // The bytes containing the const bitfields must not be
598 // shared with bytes containing the mutable bitfields.
599
600 // Mutable flag's state (guarded by `data_guard_`).
601
602 // def_kind_ is not guard by DataGuard() since it is accessed in Init without
603 // locks.
604 uint8_t def_kind_ : 2;
605 // Has this flag's value been modified?
606 bool modified_ : 1 ABSL_GUARDED_BY(*DataGuard());
607 // Has this flag been specified on command line.
608 bool on_command_line_ : 1 ABSL_GUARDED_BY(*DataGuard());
609
610 // Unique tag for absl::call_once call to initialize this flag.
611 absl::once_flag init_control_;
612
613 // Sequence lock / mutation counter.
614 flags_internal::SequenceLock seq_lock_;
615
616 // Optional flag's callback and absl::Mutex to guard the invocations.
617 FlagCallback* callback_ ABSL_GUARDED_BY(*DataGuard());
618 // Either a pointer to the function generating the default value based on the
619 // value specified in ABSL_FLAG or pointer to the dynamically set default
620 // value via SetCommandLineOptionWithMode. def_kind_ is used to distinguish
621 // these two cases.
622 FlagDefaultSrc default_value_;
623
624 // This is reserved space for an absl::Mutex to guard flag data. It will be
625 // initialized in FlagImpl::Init via placement new.
626 // We can't use "absl::Mutex data_guard_", since this class is not literal.
627 // We do not want to use "absl::Mutex* data_guard_", since this would require
628 // heap allocation during initialization, which is both slows program startup
629 // and can fail. Using reserved space + placement new allows us to avoid both
630 // problems.
631 alignas(absl::Mutex) mutable char data_guard_[sizeof(absl::Mutex)];
632 };
633 #if defined(__GNUC__) && !defined(__clang__)
634 #pragma GCC diagnostic pop
635 #endif
636
637 ///////////////////////////////////////////////////////////////////////////////
638 // The Flag object parameterized by the flag's value type. This class implements
639 // flag reflection handle interface.
640
641 template <typename T>
642 class Flag {
643 public:
644 constexpr Flag(const char* name, const char* filename, FlagHelpArg help,
645 const FlagDefaultArg default_arg)
646 : impl_(name, filename, &FlagOps<T>, help,
647 flags_internal::StorageKind<T>(), default_arg),
648 value_() {}
649
650 // CommandLineFlag interface
651 absl::string_view Name() const { return impl_.Name(); }
652 std::string Filename() const { return impl_.Filename(); }
653 std::string Help() const { return impl_.Help(); }
654 // Do not use. To be removed.
655 bool IsSpecifiedOnCommandLine() const {
656 return impl_.IsSpecifiedOnCommandLine();
657 }
658 std::string DefaultValue() const { return impl_.DefaultValue(); }
659 std::string CurrentValue() const { return impl_.CurrentValue(); }
660
661 private:
662 template <typename, bool>
663 friend class FlagRegistrar;
664 friend class FlagImplPeer;
665
666 T Get() const {
667 // See implementation notes in CommandLineFlag::Get().
668 union U {
669 T value;
670 U() {}
671 ~U() { value.~T(); }
672 };
673 U u;
674
675 #if !defined(NDEBUG)
676 impl_.AssertValidType(base_internal::FastTypeId<T>(), &GenRuntimeTypeId<T>);
677 #endif
678
679 if (ABSL_PREDICT_FALSE(!value_.Get(impl_.seq_lock_, u.value))) {
680 impl_.Read(&u.value);
681 }
682 return std::move(u.value);
683 }
684 void Set(const T& v) {
685 impl_.AssertValidType(base_internal::FastTypeId<T>(), &GenRuntimeTypeId<T>);
686 impl_.Write(&v);
687 }
688
689 // Access to the reflection.
690 const CommandLineFlag& Reflect() const { return impl_; }
691
692 // Flag's data
693 // The implementation depends on value_ field to be placed exactly after the
694 // impl_ field, so that impl_ can figure out the offset to the value and
695 // access it.
696 FlagImpl impl_;
697 FlagValue<T> value_;
698 };
699
700 ///////////////////////////////////////////////////////////////////////////////
701 // Trampoline for friend access
702
703 class FlagImplPeer {
704 public:
705 template <typename T, typename FlagType>
706 static T InvokeGet(const FlagType& flag) {
707 return flag.Get();
708 }
709 template <typename FlagType, typename T>
710 static void InvokeSet(FlagType& flag, const T& v) {
711 flag.Set(v);
712 }
713 template <typename FlagType>
714 static const CommandLineFlag& InvokeReflect(const FlagType& f) {
715 return f.Reflect();
716 }
717 };
718
719 ///////////////////////////////////////////////////////////////////////////////
720 // Implementation of Flag value specific operations routine.
721 template <typename T>
722 void* FlagOps(FlagOp op, const void* v1, void* v2, void* v3) {
723 switch (op) {
724 case FlagOp::kAlloc: {
725 std::allocator<T> alloc;
726 return std::allocator_traits<std::allocator<T>>::allocate(alloc, 1);
727 }
728 case FlagOp::kDelete: {
729 T* p = static_cast<T*>(v2);
730 p->~T();
731 std::allocator<T> alloc;
732 std::allocator_traits<std::allocator<T>>::deallocate(alloc, p, 1);
733 return nullptr;
734 }
735 case FlagOp::kCopy:
736 *static_cast<T*>(v2) = *static_cast<const T*>(v1);
737 return nullptr;
738 case FlagOp::kCopyConstruct:
739 new (v2) T(*static_cast<const T*>(v1));
740 return nullptr;
741 case FlagOp::kSizeof:
742 return reinterpret_cast<void*>(static_cast<uintptr_t>(sizeof(T)));
743 case FlagOp::kFastTypeId:
744 return const_cast<void*>(base_internal::FastTypeId<T>());
745 case FlagOp::kRuntimeTypeId:
746 return const_cast<std::type_info*>(GenRuntimeTypeId<T>());
747 case FlagOp::kParse: {
748 // Initialize the temporary instance of type T based on current value in
749 // destination (which is going to be flag's default value).
750 T temp(*static_cast<T*>(v2));
751 if (!absl::ParseFlag<T>(*static_cast<const absl::string_view*>(v1), &temp,
752 static_cast<std::string*>(v3))) {
753 return nullptr;
754 }
755 *static_cast<T*>(v2) = std::move(temp);
756 return v2;
757 }
758 case FlagOp::kUnparse:
759 *static_cast<std::string*>(v2) =
760 absl::UnparseFlag<T>(*static_cast<const T*>(v1));
761 return nullptr;
762 case FlagOp::kValueOffset: {
763 // Round sizeof(FlagImp) to a multiple of alignof(FlagValue<T>) to get the
764 // offset of the data.
765 size_t round_to = alignof(FlagValue<T>);
766 size_t offset = (sizeof(FlagImpl) + round_to - 1) / round_to * round_to;
767 return reinterpret_cast<void*>(offset);
768 }
769 }
770 return nullptr;
771 }
772
773 ///////////////////////////////////////////////////////////////////////////////
774 // This class facilitates Flag object registration and tail expression-based
775 // flag definition, for example:
776 // ABSL_FLAG(int, foo, 42, "Foo help").OnUpdate(NotifyFooWatcher);
777 struct FlagRegistrarEmpty {};
778 template <typename T, bool do_register>
779 class FlagRegistrar {
780 public:
781 constexpr explicit FlagRegistrar(Flag<T>& flag, const char* filename)
782 : flag_(flag) {
783 if (do_register)
784 flags_internal::RegisterCommandLineFlag(flag_.impl_, filename);
785 }
786
787 FlagRegistrar OnUpdate(FlagCallbackFunc cb) && {
788 flag_.impl_.SetCallback(cb);
789 return *this;
790 }
791
792 // Make the registrar "die" gracefully as an empty struct on a line where
793 // registration happens. Registrar objects are intended to live only as
794 // temporary.
795 constexpr operator FlagRegistrarEmpty() const { return {}; } // NOLINT
796
797 private:
798 Flag<T>& flag_; // Flag being registered (not owned).
799 };
800
801 } // namespace flags_internal
802 ABSL_NAMESPACE_END
803 } // namespace absl
804
805 #endif // ABSL_FLAGS_INTERNAL_FLAG_H_
806