flag.h 28 KB

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