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