• 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 #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 successful.
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 corresponding 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 corresponding 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 additional 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 returning the function
231 // pointer (&T::NonConst) generating 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 =
312     std::integral_constant<bool, std::is_trivially_copyable<T>::value &&
313                                      std::is_default_constructible<T>::value &&
314                                      (sizeof(T) < 8)>;
315 
316 template <typename T>
317 using FlagUseOneWordStorage =
318     std::integral_constant<bool, std::is_trivially_copyable<T>::value &&
319                                      (sizeof(T) <= 8)>;
320 
321 template <class T>
322 using FlagUseSequenceLockStorage =
323     std::integral_constant<bool, std::is_trivially_copyable<T>::value &&
324                                      (sizeof(T) > 8)>;
325 
326 enum class FlagValueStorageKind : uint8_t {
327   kValueAndInitBit = 0,
328   kOneWordAtomic = 1,
329   kSequenceLocked = 2,
330   kAlignedBuffer = 3,
331 };
332 
333 template <typename T>
StorageKind()334 static constexpr FlagValueStorageKind StorageKind() {
335   return FlagUseValueAndInitBitStorage<T>::value
336              ? FlagValueStorageKind::kValueAndInitBit
337          : FlagUseOneWordStorage<T>::value
338              ? FlagValueStorageKind::kOneWordAtomic
339          : FlagUseSequenceLockStorage<T>::value
340              ? FlagValueStorageKind::kSequenceLocked
341              : FlagValueStorageKind::kAlignedBuffer;
342 }
343 
344 struct FlagOneWordValue {
FlagOneWordValueFlagOneWordValue345   constexpr explicit FlagOneWordValue(int64_t v) : value(v) {}
346   std::atomic<int64_t> value;
347 };
348 
349 template <typename T>
350 struct alignas(8) FlagValueAndInitBit {
351   T value;
352   // Use an int instead of a bool to guarantee that a non-zero value has
353   // a bit set.
354   uint8_t init;
355 };
356 
357 template <typename T,
358           FlagValueStorageKind Kind = flags_internal::StorageKind<T>()>
359 struct FlagValue;
360 
361 template <typename T>
362 struct FlagValue<T, FlagValueStorageKind::kValueAndInitBit> : FlagOneWordValue {
363   constexpr FlagValue() : FlagOneWordValue(0) {}
364   bool Get(const SequenceLock&, T& dst) const {
365     int64_t storage = value.load(std::memory_order_acquire);
366     if (ABSL_PREDICT_FALSE(storage == 0)) {
367       return false;
368     }
369     dst = absl::bit_cast<FlagValueAndInitBit<T>>(storage).value;
370     return true;
371   }
372 };
373 
374 template <typename T>
375 struct FlagValue<T, FlagValueStorageKind::kOneWordAtomic> : FlagOneWordValue {
376   constexpr FlagValue() : FlagOneWordValue(UninitializedFlagValue()) {}
377   bool Get(const SequenceLock&, T& dst) const {
378     int64_t one_word_val = value.load(std::memory_order_acquire);
379     if (ABSL_PREDICT_FALSE(one_word_val == UninitializedFlagValue())) {
380       return false;
381     }
382     std::memcpy(&dst, static_cast<const void*>(&one_word_val), sizeof(T));
383     return true;
384   }
385 };
386 
387 template <typename T>
388 struct FlagValue<T, FlagValueStorageKind::kSequenceLocked> {
389   bool Get(const SequenceLock& lock, T& dst) const {
390     return lock.TryRead(&dst, value_words, sizeof(T));
391   }
392 
393   static constexpr int kNumWords =
394       flags_internal::AlignUp(sizeof(T), sizeof(uint64_t)) / sizeof(uint64_t);
395 
396   alignas(T) alignas(
397       std::atomic<uint64_t>) std::atomic<uint64_t> value_words[kNumWords];
398 };
399 
400 template <typename T>
401 struct FlagValue<T, FlagValueStorageKind::kAlignedBuffer> {
402   bool Get(const SequenceLock&, T&) const { return false; }
403 
404   alignas(T) char value[sizeof(T)];
405 };
406 
407 ///////////////////////////////////////////////////////////////////////////////
408 // Flag callback auxiliary structs.
409 
410 // Signature for the mutation callback used by watched Flags
411 // The callback is noexcept.
412 // TODO(rogeeff): add noexcept after C++17 support is added.
413 using FlagCallbackFunc = void (*)();
414 
415 struct FlagCallback {
416   FlagCallbackFunc func;
417   absl::Mutex guard;  // Guard for concurrent callback invocations.
418 };
419 
420 ///////////////////////////////////////////////////////////////////////////////
421 // Flag implementation, which does not depend on flag value type.
422 // The class encapsulates the Flag's data and access to it.
423 
424 struct DynValueDeleter {
425   explicit DynValueDeleter(FlagOpFn op_arg = nullptr);
426   void operator()(void* ptr) const;
427 
428   FlagOpFn op;
429 };
430 
431 class FlagState;
432 
433 class FlagImpl final : public CommandLineFlag {
434  public:
435   constexpr FlagImpl(const char* name, const char* filename, FlagOpFn op,
436                      FlagHelpArg help, FlagValueStorageKind value_kind,
437                      FlagDefaultArg default_arg)
438       : name_(name),
439         filename_(filename),
440         op_(op),
441         help_(help.source),
442         help_source_kind_(static_cast<uint8_t>(help.kind)),
443         value_storage_kind_(static_cast<uint8_t>(value_kind)),
444         def_kind_(static_cast<uint8_t>(default_arg.kind)),
445         modified_(false),
446         on_command_line_(false),
447         callback_(nullptr),
448         default_value_(default_arg.source),
449         data_guard_{} {}
450 
451   // Constant access methods
452   int64_t ReadOneWord() const ABSL_LOCKS_EXCLUDED(*DataGuard());
453   bool ReadOneBool() const ABSL_LOCKS_EXCLUDED(*DataGuard());
454   void Read(void* dst) const override ABSL_LOCKS_EXCLUDED(*DataGuard());
455   void Read(bool* value) const ABSL_LOCKS_EXCLUDED(*DataGuard()) {
456     *value = ReadOneBool();
457   }
458   template <typename T,
459             absl::enable_if_t<flags_internal::StorageKind<T>() ==
460                                   FlagValueStorageKind::kOneWordAtomic,
461                               int> = 0>
462   void Read(T* value) const ABSL_LOCKS_EXCLUDED(*DataGuard()) {
463     int64_t v = ReadOneWord();
464     std::memcpy(value, static_cast<const void*>(&v), sizeof(T));
465   }
466   template <typename T,
467             typename std::enable_if<flags_internal::StorageKind<T>() ==
468                                         FlagValueStorageKind::kValueAndInitBit,
469                                     int>::type = 0>
470   void Read(T* value) const ABSL_LOCKS_EXCLUDED(*DataGuard()) {
471     *value = absl::bit_cast<FlagValueAndInitBit<T>>(ReadOneWord()).value;
472   }
473 
474   // Mutating access methods
475   void Write(const void* src) ABSL_LOCKS_EXCLUDED(*DataGuard());
476 
477   // Interfaces to operate on callbacks.
478   void SetCallback(const FlagCallbackFunc mutation_callback)
479       ABSL_LOCKS_EXCLUDED(*DataGuard());
480   void InvokeCallback() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
481 
482   // Used in read/write operations to validate source/target has correct type.
483   // For example if flag is declared as absl::Flag<int> FLAGS_foo, a call to
484   // absl::GetFlag(FLAGS_foo) validates that the type of FLAGS_foo is indeed
485   // int. To do that we pass the "assumed" type id (which is deduced from type
486   // int) as an argument `type_id`, which is in turn is validated against the
487   // type id stored in flag object by flag definition statement.
488   void AssertValidType(FlagFastTypeId type_id,
489                        const std::type_info* (*gen_rtti)()) const;
490 
491  private:
492   template <typename T>
493   friend class Flag;
494   friend class FlagState;
495 
496   // Ensures that `data_guard_` is initialized and returns it.
497   absl::Mutex* DataGuard() const
498       ABSL_LOCK_RETURNED(reinterpret_cast<absl::Mutex*>(data_guard_));
499   // Returns heap allocated value of type T initialized with default value.
500   std::unique_ptr<void, DynValueDeleter> MakeInitValue() const
501       ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
502   // Flag initialization called via absl::call_once.
503   void Init();
504 
505   // Offset value access methods. One per storage kind. These methods to not
506   // respect const correctness, so be very carefull using them.
507 
508   // This is a shared helper routine which encapsulates most of the magic. Since
509   // it is only used inside the three routines below, which are defined in
510   // flag.cc, we can define it in that file as well.
511   template <typename StorageT>
512   StorageT* OffsetValue() const;
513   // This is an accessor for a value stored in an aligned buffer storage
514   // used for non-trivially-copyable data types.
515   // Returns a mutable pointer to the start of a buffer.
516   void* AlignedBufferValue() const;
517 
518   // The same as above, but used for sequencelock-protected storage.
519   std::atomic<uint64_t>* AtomicBufferValue() const;
520 
521   // This is an accessor for a value stored as one word atomic. Returns a
522   // mutable reference to an atomic value.
523   std::atomic<int64_t>& OneWordValue() const;
524 
525   // Attempts to parse supplied `value` string. If parsing is successful,
526   // returns new value. Otherwise returns nullptr.
527   std::unique_ptr<void, DynValueDeleter> TryParse(absl::string_view value,
528                                                   std::string& err) const
529       ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
530   // Stores the flag value based on the pointer to the source.
531   void StoreValue(const void* src) ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
532 
533   // Copy the flag data, protected by `seq_lock_` into `dst`.
534   //
535   // REQUIRES: ValueStorageKind() == kSequenceLocked.
536   void ReadSequenceLockedData(void* dst) const
537       ABSL_LOCKS_EXCLUDED(*DataGuard());
538 
539   FlagHelpKind HelpSourceKind() const {
540     return static_cast<FlagHelpKind>(help_source_kind_);
541   }
542   FlagValueStorageKind ValueStorageKind() const {
543     return static_cast<FlagValueStorageKind>(value_storage_kind_);
544   }
545   FlagDefaultKind DefaultKind() const
546       ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard()) {
547     return static_cast<FlagDefaultKind>(def_kind_);
548   }
549 
550   // CommandLineFlag interface implementation
551   absl::string_view Name() const override;
552   std::string Filename() const override;
553   std::string Help() const override;
554   FlagFastTypeId TypeId() const override;
555   bool IsSpecifiedOnCommandLine() const override
556       ABSL_LOCKS_EXCLUDED(*DataGuard());
557   std::string DefaultValue() const override ABSL_LOCKS_EXCLUDED(*DataGuard());
558   std::string CurrentValue() const override ABSL_LOCKS_EXCLUDED(*DataGuard());
559   bool ValidateInputValue(absl::string_view value) const override
560       ABSL_LOCKS_EXCLUDED(*DataGuard());
561   void CheckDefaultValueParsingRoundtrip() const override
562       ABSL_LOCKS_EXCLUDED(*DataGuard());
563 
564   int64_t ModificationCount() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
565 
566   // Interfaces to save and restore flags to/from persistent state.
567   // Returns current flag state or nullptr if flag does not support
568   // saving and restoring a state.
569   std::unique_ptr<FlagStateInterface> SaveState() override
570       ABSL_LOCKS_EXCLUDED(*DataGuard());
571 
572   // Restores the flag state to the supplied state object. If there is
573   // nothing to restore returns false. Otherwise returns true.
574   bool RestoreState(const FlagState& flag_state)
575       ABSL_LOCKS_EXCLUDED(*DataGuard());
576 
577   bool ParseFrom(absl::string_view value, FlagSettingMode set_mode,
578                  ValueSource source, std::string& error) override
579       ABSL_LOCKS_EXCLUDED(*DataGuard());
580 
581   // Immutable flag's state.
582 
583   // Flags name passed to ABSL_FLAG as second arg.
584   const char* const name_;
585   // The file name where ABSL_FLAG resides.
586   const char* const filename_;
587   // Type-specific operations "vtable".
588   const FlagOpFn op_;
589   // Help message literal or function to generate it.
590   const FlagHelpMsg help_;
591   // Indicates if help message was supplied as literal or generator func.
592   const uint8_t help_source_kind_ : 1;
593   // Kind of storage this flag is using for the flag's value.
594   const uint8_t value_storage_kind_ : 2;
595 
596   uint8_t : 0;  // The bytes containing the const bitfields must not be
597                 // shared with bytes containing the mutable bitfields.
598 
599   // Mutable flag's state (guarded by `data_guard_`).
600 
601   // def_kind_ is not guard by DataGuard() since it is accessed in Init without
602   // locks.
603   uint8_t def_kind_ : 2;
604   // Has this flag's value been modified?
605   bool modified_ : 1 ABSL_GUARDED_BY(*DataGuard());
606   // Has this flag been specified on command line.
607   bool on_command_line_ : 1 ABSL_GUARDED_BY(*DataGuard());
608 
609   // Unique tag for absl::call_once call to initialize this flag.
610   absl::once_flag init_control_;
611 
612   // Sequence lock / mutation counter.
613   flags_internal::SequenceLock seq_lock_;
614 
615   // Optional flag's callback and absl::Mutex to guard the invocations.
616   FlagCallback* callback_ ABSL_GUARDED_BY(*DataGuard());
617   // Either a pointer to the function generating the default value based on the
618   // value specified in ABSL_FLAG or pointer to the dynamically set default
619   // value via SetCommandLineOptionWithMode. def_kind_ is used to distinguish
620   // these two cases.
621   FlagDefaultSrc default_value_;
622 
623   // This is reserved space for an absl::Mutex to guard flag data. It will be
624   // initialized in FlagImpl::Init via placement new.
625   // We can't use "absl::Mutex data_guard_", since this class is not literal.
626   // We do not want to use "absl::Mutex* data_guard_", since this would require
627   // heap allocation during initialization, which is both slows program startup
628   // and can fail. Using reserved space + placement new allows us to avoid both
629   // problems.
630   alignas(absl::Mutex) mutable char data_guard_[sizeof(absl::Mutex)];
631 };
632 
633 ///////////////////////////////////////////////////////////////////////////////
634 // The Flag object parameterized by the flag's value type. This class implements
635 // flag reflection handle interface.
636 
637 template <typename T>
638 class Flag {
639  public:
640   constexpr Flag(const char* name, const char* filename, FlagHelpArg help,
641                  const FlagDefaultArg default_arg)
642       : impl_(name, filename, &FlagOps<T>, help,
643               flags_internal::StorageKind<T>(), default_arg),
644         value_() {}
645 
646   // CommandLineFlag interface
647   absl::string_view Name() const { return impl_.Name(); }
648   std::string Filename() const { return impl_.Filename(); }
649   std::string Help() const { return impl_.Help(); }
650   // Do not use. To be removed.
651   bool IsSpecifiedOnCommandLine() const {
652     return impl_.IsSpecifiedOnCommandLine();
653   }
654   std::string DefaultValue() const { return impl_.DefaultValue(); }
655   std::string CurrentValue() const { return impl_.CurrentValue(); }
656 
657  private:
658   template <typename, bool>
659   friend class FlagRegistrar;
660   friend class FlagImplPeer;
661 
662   T Get() const {
663     // See implementation notes in CommandLineFlag::Get().
664     union U {
665       T value;
666       U() {}
667       ~U() { value.~T(); }
668     };
669     U u;
670 
671 #if !defined(NDEBUG)
672     impl_.AssertValidType(base_internal::FastTypeId<T>(), &GenRuntimeTypeId<T>);
673 #endif
674 
675     if (ABSL_PREDICT_FALSE(!value_.Get(impl_.seq_lock_, u.value))) {
676       impl_.Read(&u.value);
677     }
678     return std::move(u.value);
679   }
680   void Set(const T& v) {
681     impl_.AssertValidType(base_internal::FastTypeId<T>(), &GenRuntimeTypeId<T>);
682     impl_.Write(&v);
683   }
684 
685   // Access to the reflection.
686   const CommandLineFlag& Reflect() const { return impl_; }
687 
688   // Flag's data
689   // The implementation depends on value_ field to be placed exactly after the
690   // impl_ field, so that impl_ can figure out the offset to the value and
691   // access it.
692   FlagImpl impl_;
693   FlagValue<T> value_;
694 };
695 
696 ///////////////////////////////////////////////////////////////////////////////
697 // Trampoline for friend access
698 
699 class FlagImplPeer {
700  public:
701   template <typename T, typename FlagType>
702   static T InvokeGet(const FlagType& flag) {
703     return flag.Get();
704   }
705   template <typename FlagType, typename T>
706   static void InvokeSet(FlagType& flag, const T& v) {
707     flag.Set(v);
708   }
709   template <typename FlagType>
710   static const CommandLineFlag& InvokeReflect(const FlagType& f) {
711     return f.Reflect();
712   }
713 };
714 
715 ///////////////////////////////////////////////////////////////////////////////
716 // Implementation of Flag value specific operations routine.
717 template <typename T>
718 void* FlagOps(FlagOp op, const void* v1, void* v2, void* v3) {
719   switch (op) {
720     case FlagOp::kAlloc: {
721       std::allocator<T> alloc;
722       return std::allocator_traits<std::allocator<T>>::allocate(alloc, 1);
723     }
724     case FlagOp::kDelete: {
725       T* p = static_cast<T*>(v2);
726       p->~T();
727       std::allocator<T> alloc;
728       std::allocator_traits<std::allocator<T>>::deallocate(alloc, p, 1);
729       return nullptr;
730     }
731     case FlagOp::kCopy:
732       *static_cast<T*>(v2) = *static_cast<const T*>(v1);
733       return nullptr;
734     case FlagOp::kCopyConstruct:
735       new (v2) T(*static_cast<const T*>(v1));
736       return nullptr;
737     case FlagOp::kSizeof:
738       return reinterpret_cast<void*>(static_cast<uintptr_t>(sizeof(T)));
739     case FlagOp::kFastTypeId:
740       return const_cast<void*>(base_internal::FastTypeId<T>());
741     case FlagOp::kRuntimeTypeId:
742       return const_cast<std::type_info*>(GenRuntimeTypeId<T>());
743     case FlagOp::kParse: {
744       // Initialize the temporary instance of type T based on current value in
745       // destination (which is going to be flag's default value).
746       T temp(*static_cast<T*>(v2));
747       if (!absl::ParseFlag<T>(*static_cast<const absl::string_view*>(v1), &temp,
748                               static_cast<std::string*>(v3))) {
749         return nullptr;
750       }
751       *static_cast<T*>(v2) = std::move(temp);
752       return v2;
753     }
754     case FlagOp::kUnparse:
755       *static_cast<std::string*>(v2) =
756           absl::UnparseFlag<T>(*static_cast<const T*>(v1));
757       return nullptr;
758     case FlagOp::kValueOffset: {
759       // Round sizeof(FlagImp) to a multiple of alignof(FlagValue<T>) to get the
760       // offset of the data.
761       size_t round_to = alignof(FlagValue<T>);
762       size_t offset =
763           (sizeof(FlagImpl) + round_to - 1) / round_to * round_to;
764       return reinterpret_cast<void*>(offset);
765     }
766   }
767   return nullptr;
768 }
769 
770 ///////////////////////////////////////////////////////////////////////////////
771 // This class facilitates Flag object registration and tail expression-based
772 // flag definition, for example:
773 // ABSL_FLAG(int, foo, 42, "Foo help").OnUpdate(NotifyFooWatcher);
774 struct FlagRegistrarEmpty {};
775 template <typename T, bool do_register>
776 class FlagRegistrar {
777  public:
778   explicit FlagRegistrar(Flag<T>& flag, const char* filename) : flag_(flag) {
779     if (do_register)
780       flags_internal::RegisterCommandLineFlag(flag_.impl_, filename);
781   }
782 
783   FlagRegistrar OnUpdate(FlagCallbackFunc cb) && {
784     flag_.impl_.SetCallback(cb);
785     return *this;
786   }
787 
788   // Make the registrar "die" gracefully as an empty struct on a line where
789   // registration happens. Registrar objects are intended to live only as
790   // temporary.
791   operator FlagRegistrarEmpty() const { return {}; }  // NOLINT
792 
793  private:
794   Flag<T>& flag_;  // Flag being registered (not owned).
795 };
796 
797 }  // namespace flags_internal
798 ABSL_NAMESPACE_END
799 }  // namespace absl
800 
801 #endif  // ABSL_FLAGS_INTERNAL_FLAG_H_
802