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