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