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