flag.h 35 KB

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