You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

flag.h 36 kB

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