flag.h 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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. #ifdef ABSL_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() {
  263. return static_cast<int64_t>(0xababababababababll);
  264. }
  265. template <typename T>
  266. using FlagUseValueAndInitBitStorage = std::integral_constant<
  267. bool, absl::type_traits_internal::is_trivially_copyable<T>::value &&
  268. std::is_default_constructible<T>::value && (sizeof(T) < 8)>;
  269. template <typename T>
  270. using FlagUseOneWordStorage = std::integral_constant<
  271. bool, absl::type_traits_internal::is_trivially_copyable<T>::value &&
  272. (sizeof(T) <= 8)>;
  273. template <class T>
  274. using FlagUseSequenceLockStorage = std::integral_constant<
  275. bool, absl::type_traits_internal::is_trivially_copyable<T>::value &&
  276. (sizeof(T) > 8)>;
  277. enum class FlagValueStorageKind : uint8_t {
  278. kValueAndInitBit = 0,
  279. kOneWordAtomic = 1,
  280. kSequenceLocked = 2,
  281. kAlignedBuffer = 3,
  282. };
  283. template <typename T>
  284. static constexpr FlagValueStorageKind StorageKind() {
  285. return FlagUseValueAndInitBitStorage<T>::value
  286. ? FlagValueStorageKind::kValueAndInitBit
  287. : FlagUseOneWordStorage<T>::value
  288. ? FlagValueStorageKind::kOneWordAtomic
  289. : FlagUseSequenceLockStorage<T>::value
  290. ? FlagValueStorageKind::kSequenceLocked
  291. : FlagValueStorageKind::kAlignedBuffer;
  292. }
  293. struct FlagOneWordValue {
  294. constexpr explicit FlagOneWordValue(int64_t v) : value(v) {}
  295. std::atomic<int64_t> value;
  296. };
  297. template <typename T>
  298. struct alignas(8) FlagValueAndInitBit {
  299. T value;
  300. // Use an int instead of a bool to guarantee that a non-zero value has
  301. // a bit set.
  302. uint8_t init;
  303. };
  304. template <typename T,
  305. FlagValueStorageKind Kind = flags_internal::StorageKind<T>()>
  306. struct FlagValue;
  307. template <typename T>
  308. struct FlagValue<T, FlagValueStorageKind::kValueAndInitBit> : FlagOneWordValue {
  309. constexpr FlagValue() : FlagOneWordValue(0) {}
  310. bool Get(const SequenceLock&, T& dst) const {
  311. int64_t storage = value.load(std::memory_order_acquire);
  312. if (ABSL_PREDICT_FALSE(storage == 0)) {
  313. return false;
  314. }
  315. dst = absl::bit_cast<FlagValueAndInitBit<T>>(storage).value;
  316. return true;
  317. }
  318. };
  319. template <typename T>
  320. struct FlagValue<T, FlagValueStorageKind::kOneWordAtomic> : FlagOneWordValue {
  321. constexpr FlagValue() : FlagOneWordValue(UninitializedFlagValue()) {}
  322. bool Get(const SequenceLock&, T& dst) const {
  323. int64_t one_word_val = value.load(std::memory_order_acquire);
  324. if (ABSL_PREDICT_FALSE(one_word_val == UninitializedFlagValue())) {
  325. return false;
  326. }
  327. std::memcpy(&dst, static_cast<const void*>(&one_word_val), sizeof(T));
  328. return true;
  329. }
  330. };
  331. template <typename T>
  332. struct FlagValue<T, FlagValueStorageKind::kSequenceLocked> {
  333. bool Get(const SequenceLock& lock, T& dst) const {
  334. return lock.TryRead(&dst, value_words, sizeof(T));
  335. }
  336. static constexpr int kNumWords =
  337. flags_internal::AlignUp(sizeof(T), sizeof(uint64_t)) / sizeof(uint64_t);
  338. alignas(T) alignas(
  339. std::atomic<uint64_t>) std::atomic<uint64_t> value_words[kNumWords];
  340. };
  341. template <typename T>
  342. struct FlagValue<T, FlagValueStorageKind::kAlignedBuffer> {
  343. bool Get(const SequenceLock&, T&) const { return false; }
  344. alignas(T) char value[sizeof(T)];
  345. };
  346. ///////////////////////////////////////////////////////////////////////////////
  347. // Flag callback auxiliary structs.
  348. // Signature for the mutation callback used by watched Flags
  349. // The callback is noexcept.
  350. // TODO(rogeeff): add noexcept after C++17 support is added.
  351. using FlagCallbackFunc = void (*)();
  352. struct FlagCallback {
  353. FlagCallbackFunc func;
  354. absl::Mutex guard; // Guard for concurrent callback invocations.
  355. };
  356. ///////////////////////////////////////////////////////////////////////////////
  357. // Flag implementation, which does not depend on flag value type.
  358. // The class encapsulates the Flag's data and access to it.
  359. struct DynValueDeleter {
  360. explicit DynValueDeleter(FlagOpFn op_arg = nullptr);
  361. void operator()(void* ptr) const;
  362. FlagOpFn op;
  363. };
  364. class FlagState;
  365. class FlagImpl final : public CommandLineFlag {
  366. public:
  367. constexpr FlagImpl(const char* name, const char* filename, FlagOpFn op,
  368. FlagHelpArg help, FlagValueStorageKind value_kind,
  369. FlagDefaultArg default_arg)
  370. : name_(name),
  371. filename_(filename),
  372. op_(op),
  373. help_(help.source),
  374. help_source_kind_(static_cast<uint8_t>(help.kind)),
  375. value_storage_kind_(static_cast<uint8_t>(value_kind)),
  376. def_kind_(static_cast<uint8_t>(default_arg.kind)),
  377. modified_(false),
  378. on_command_line_(false),
  379. callback_(nullptr),
  380. default_value_(default_arg.source),
  381. data_guard_{} {}
  382. // Constant access methods
  383. int64_t ReadOneWord() const ABSL_LOCKS_EXCLUDED(*DataGuard());
  384. bool ReadOneBool() const ABSL_LOCKS_EXCLUDED(*DataGuard());
  385. void Read(void* dst) const override ABSL_LOCKS_EXCLUDED(*DataGuard());
  386. void Read(bool* value) const ABSL_LOCKS_EXCLUDED(*DataGuard()) {
  387. *value = ReadOneBool();
  388. }
  389. template <typename T,
  390. absl::enable_if_t<flags_internal::StorageKind<T>() ==
  391. FlagValueStorageKind::kOneWordAtomic,
  392. int> = 0>
  393. void Read(T* value) const ABSL_LOCKS_EXCLUDED(*DataGuard()) {
  394. int64_t v = ReadOneWord();
  395. std::memcpy(value, static_cast<const void*>(&v), sizeof(T));
  396. }
  397. template <typename T,
  398. typename std::enable_if<flags_internal::StorageKind<T>() ==
  399. FlagValueStorageKind::kValueAndInitBit,
  400. int>::type = 0>
  401. void Read(T* value) const ABSL_LOCKS_EXCLUDED(*DataGuard()) {
  402. *value = absl::bit_cast<FlagValueAndInitBit<T>>(ReadOneWord()).value;
  403. }
  404. // Mutating access methods
  405. void Write(const void* src) ABSL_LOCKS_EXCLUDED(*DataGuard());
  406. // Interfaces to operate on callbacks.
  407. void SetCallback(const FlagCallbackFunc mutation_callback)
  408. ABSL_LOCKS_EXCLUDED(*DataGuard());
  409. void InvokeCallback() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
  410. // Used in read/write operations to validate source/target has correct type.
  411. // For example if flag is declared as absl::Flag<int> FLAGS_foo, a call to
  412. // absl::GetFlag(FLAGS_foo) validates that the type of FLAGS_foo is indeed
  413. // int. To do that we pass the "assumed" type id (which is deduced from type
  414. // int) as an argument `type_id`, which is in turn is validated against the
  415. // type id stored in flag object by flag definition statement.
  416. void AssertValidType(FlagFastTypeId type_id,
  417. const std::type_info* (*gen_rtti)()) const;
  418. private:
  419. template <typename T>
  420. friend class Flag;
  421. friend class FlagState;
  422. // Ensures that `data_guard_` is initialized and returns it.
  423. absl::Mutex* DataGuard() const
  424. ABSL_LOCK_RETURNED(reinterpret_cast<absl::Mutex*>(data_guard_));
  425. // Returns heap allocated value of type T initialized with default value.
  426. std::unique_ptr<void, DynValueDeleter> MakeInitValue() const
  427. ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
  428. // Flag initialization called via absl::call_once.
  429. void Init();
  430. // Offset value access methods. One per storage kind. These methods to not
  431. // respect const correctness, so be very carefull using them.
  432. // This is a shared helper routine which encapsulates most of the magic. Since
  433. // it is only used inside the three routines below, which are defined in
  434. // flag.cc, we can define it in that file as well.
  435. template <typename StorageT>
  436. StorageT* OffsetValue() const;
  437. // This is an accessor for a value stored in an aligned buffer storage
  438. // used for non-trivially-copyable data types.
  439. // Returns a mutable pointer to the start of a buffer.
  440. void* AlignedBufferValue() const;
  441. // The same as above, but used for sequencelock-protected storage.
  442. std::atomic<uint64_t>* AtomicBufferValue() const;
  443. // This is an accessor for a value stored as one word atomic. Returns a
  444. // mutable reference to an atomic value.
  445. std::atomic<int64_t>& OneWordValue() const;
  446. // Attempts to parse supplied `value` string. If parsing is successful,
  447. // returns new value. Otherwise returns nullptr.
  448. std::unique_ptr<void, DynValueDeleter> TryParse(absl::string_view value,
  449. std::string& err) const
  450. ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
  451. // Stores the flag value based on the pointer to the source.
  452. void StoreValue(const void* src) ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
  453. // Copy the flag data, protected by `seq_lock_` into `dst`.
  454. //
  455. // REQUIRES: ValueStorageKind() == kSequenceLocked.
  456. void ReadSequenceLockedData(void* dst) const
  457. ABSL_LOCKS_EXCLUDED(*DataGuard());
  458. FlagHelpKind HelpSourceKind() const {
  459. return static_cast<FlagHelpKind>(help_source_kind_);
  460. }
  461. FlagValueStorageKind ValueStorageKind() const {
  462. return static_cast<FlagValueStorageKind>(value_storage_kind_);
  463. }
  464. FlagDefaultKind DefaultKind() const
  465. ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard()) {
  466. return static_cast<FlagDefaultKind>(def_kind_);
  467. }
  468. // CommandLineFlag interface implementation
  469. absl::string_view Name() const override;
  470. std::string Filename() const override;
  471. std::string Help() const override;
  472. FlagFastTypeId TypeId() const override;
  473. bool IsSpecifiedOnCommandLine() const override
  474. ABSL_LOCKS_EXCLUDED(*DataGuard());
  475. std::string DefaultValue() const override ABSL_LOCKS_EXCLUDED(*DataGuard());
  476. std::string CurrentValue() const override ABSL_LOCKS_EXCLUDED(*DataGuard());
  477. bool ValidateInputValue(absl::string_view value) const override
  478. ABSL_LOCKS_EXCLUDED(*DataGuard());
  479. void CheckDefaultValueParsingRoundtrip() const override
  480. ABSL_LOCKS_EXCLUDED(*DataGuard());
  481. int64_t ModificationCount() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
  482. // Interfaces to save and restore flags to/from persistent state.
  483. // Returns current flag state or nullptr if flag does not support
  484. // saving and restoring a state.
  485. std::unique_ptr<FlagStateInterface> SaveState() override
  486. ABSL_LOCKS_EXCLUDED(*DataGuard());
  487. // Restores the flag state to the supplied state object. If there is
  488. // nothing to restore returns false. Otherwise returns true.
  489. bool RestoreState(const FlagState& flag_state)
  490. ABSL_LOCKS_EXCLUDED(*DataGuard());
  491. bool ParseFrom(absl::string_view value, FlagSettingMode set_mode,
  492. ValueSource source, std::string& error) override
  493. ABSL_LOCKS_EXCLUDED(*DataGuard());
  494. // Immutable flag's state.
  495. // Flags name passed to ABSL_FLAG as second arg.
  496. const char* const name_;
  497. // The file name where ABSL_FLAG resides.
  498. const char* const filename_;
  499. // Type-specific operations "vtable".
  500. const FlagOpFn op_;
  501. // Help message literal or function to generate it.
  502. const FlagHelpMsg help_;
  503. // Indicates if help message was supplied as literal or generator func.
  504. const uint8_t help_source_kind_ : 1;
  505. // Kind of storage this flag is using for the flag's value.
  506. const uint8_t value_storage_kind_ : 2;
  507. uint8_t : 0; // The bytes containing the const bitfields must not be
  508. // shared with bytes containing the mutable bitfields.
  509. // Mutable flag's state (guarded by `data_guard_`).
  510. // def_kind_ is not guard by DataGuard() since it is accessed in Init without
  511. // locks.
  512. uint8_t def_kind_ : 2;
  513. // Has this flag's value been modified?
  514. bool modified_ : 1 ABSL_GUARDED_BY(*DataGuard());
  515. // Has this flag been specified on command line.
  516. bool on_command_line_ : 1 ABSL_GUARDED_BY(*DataGuard());
  517. // Unique tag for absl::call_once call to initialize this flag.
  518. absl::once_flag init_control_;
  519. // Sequence lock / mutation counter.
  520. flags_internal::SequenceLock seq_lock_;
  521. // Optional flag's callback and absl::Mutex to guard the invocations.
  522. FlagCallback* callback_ ABSL_GUARDED_BY(*DataGuard());
  523. // Either a pointer to the function generating the default value based on the
  524. // value specified in ABSL_FLAG or pointer to the dynamically set default
  525. // value via SetCommandLineOptionWithMode. def_kind_ is used to distinguish
  526. // these two cases.
  527. FlagDefaultSrc default_value_;
  528. // This is reserved space for an absl::Mutex to guard flag data. It will be
  529. // initialized in FlagImpl::Init via placement new.
  530. // We can't use "absl::Mutex data_guard_", since this class is not literal.
  531. // We do not want to use "absl::Mutex* data_guard_", since this would require
  532. // heap allocation during initialization, which is both slows program startup
  533. // and can fail. Using reserved space + placement new allows us to avoid both
  534. // problems.
  535. alignas(absl::Mutex) mutable char data_guard_[sizeof(absl::Mutex)];
  536. };
  537. ///////////////////////////////////////////////////////////////////////////////
  538. // The Flag object parameterized by the flag's value type. This class implements
  539. // flag reflection handle interface.
  540. template <typename T>
  541. class Flag {
  542. public:
  543. constexpr Flag(const char* name, const char* filename, FlagHelpArg help,
  544. const FlagDefaultArg default_arg)
  545. : impl_(name, filename, &FlagOps<T>, help,
  546. flags_internal::StorageKind<T>(), default_arg),
  547. value_() {}
  548. // CommandLineFlag interface
  549. absl::string_view Name() const { return impl_.Name(); }
  550. std::string Filename() const { return impl_.Filename(); }
  551. std::string Help() const { return impl_.Help(); }
  552. // Do not use. To be removed.
  553. bool IsSpecifiedOnCommandLine() const {
  554. return impl_.IsSpecifiedOnCommandLine();
  555. }
  556. std::string DefaultValue() const { return impl_.DefaultValue(); }
  557. std::string CurrentValue() const { return impl_.CurrentValue(); }
  558. private:
  559. template <typename, bool>
  560. friend class FlagRegistrar;
  561. friend class FlagImplPeer;
  562. T Get() const {
  563. // See implementation notes in CommandLineFlag::Get().
  564. union U {
  565. T value;
  566. U() {}
  567. ~U() { value.~T(); }
  568. };
  569. U u;
  570. #if !defined(NDEBUG)
  571. impl_.AssertValidType(base_internal::FastTypeId<T>(), &GenRuntimeTypeId<T>);
  572. #endif
  573. if (ABSL_PREDICT_FALSE(!value_.Get(impl_.seq_lock_, u.value))) {
  574. impl_.Read(&u.value);
  575. }
  576. return std::move(u.value);
  577. }
  578. void Set(const T& v) {
  579. impl_.AssertValidType(base_internal::FastTypeId<T>(), &GenRuntimeTypeId<T>);
  580. impl_.Write(&v);
  581. }
  582. // Access to the reflection.
  583. const CommandLineFlag& Reflect() const { return impl_; }
  584. // Flag's data
  585. // The implementation depends on value_ field to be placed exactly after the
  586. // impl_ field, so that impl_ can figure out the offset to the value and
  587. // access it.
  588. FlagImpl impl_;
  589. FlagValue<T> value_;
  590. };
  591. ///////////////////////////////////////////////////////////////////////////////
  592. // Trampoline for friend access
  593. class FlagImplPeer {
  594. public:
  595. template <typename T, typename FlagType>
  596. static T InvokeGet(const FlagType& flag) {
  597. return flag.Get();
  598. }
  599. template <typename FlagType, typename T>
  600. static void InvokeSet(FlagType& flag, const T& v) {
  601. flag.Set(v);
  602. }
  603. template <typename FlagType>
  604. static const CommandLineFlag& InvokeReflect(const FlagType& f) {
  605. return f.Reflect();
  606. }
  607. };
  608. ///////////////////////////////////////////////////////////////////////////////
  609. // Implementation of Flag value specific operations routine.
  610. template <typename T>
  611. void* FlagOps(FlagOp op, const void* v1, void* v2, void* v3) {
  612. switch (op) {
  613. case FlagOp::kAlloc: {
  614. std::allocator<T> alloc;
  615. return std::allocator_traits<std::allocator<T>>::allocate(alloc, 1);
  616. }
  617. case FlagOp::kDelete: {
  618. T* p = static_cast<T*>(v2);
  619. p->~T();
  620. std::allocator<T> alloc;
  621. std::allocator_traits<std::allocator<T>>::deallocate(alloc, p, 1);
  622. return nullptr;
  623. }
  624. case FlagOp::kCopy:
  625. *static_cast<T*>(v2) = *static_cast<const T*>(v1);
  626. return nullptr;
  627. case FlagOp::kCopyConstruct:
  628. new (v2) T(*static_cast<const T*>(v1));
  629. return nullptr;
  630. case FlagOp::kSizeof:
  631. return reinterpret_cast<void*>(static_cast<uintptr_t>(sizeof(T)));
  632. case FlagOp::kFastTypeId:
  633. return const_cast<void*>(base_internal::FastTypeId<T>());
  634. case FlagOp::kRuntimeTypeId:
  635. return const_cast<std::type_info*>(GenRuntimeTypeId<T>());
  636. case FlagOp::kParse: {
  637. // Initialize the temporary instance of type T based on current value in
  638. // destination (which is going to be flag's default value).
  639. T temp(*static_cast<T*>(v2));
  640. if (!absl::ParseFlag<T>(*static_cast<const absl::string_view*>(v1), &temp,
  641. static_cast<std::string*>(v3))) {
  642. return nullptr;
  643. }
  644. *static_cast<T*>(v2) = std::move(temp);
  645. return v2;
  646. }
  647. case FlagOp::kUnparse:
  648. *static_cast<std::string*>(v2) =
  649. absl::UnparseFlag<T>(*static_cast<const T*>(v1));
  650. return nullptr;
  651. case FlagOp::kValueOffset: {
  652. // Round sizeof(FlagImp) to a multiple of alignof(FlagValue<T>) to get the
  653. // offset of the data.
  654. size_t round_to = alignof(FlagValue<T>);
  655. size_t offset =
  656. (sizeof(FlagImpl) + round_to - 1) / round_to * round_to;
  657. return reinterpret_cast<void*>(offset);
  658. }
  659. }
  660. return nullptr;
  661. }
  662. ///////////////////////////////////////////////////////////////////////////////
  663. // This class facilitates Flag object registration and tail expression-based
  664. // flag definition, for example:
  665. // ABSL_FLAG(int, foo, 42, "Foo help").OnUpdate(NotifyFooWatcher);
  666. struct FlagRegistrarEmpty {};
  667. template <typename T, bool do_register>
  668. class FlagRegistrar {
  669. public:
  670. explicit FlagRegistrar(Flag<T>& flag, const char* filename) : flag_(flag) {
  671. if (do_register)
  672. flags_internal::RegisterCommandLineFlag(flag_.impl_, filename);
  673. }
  674. FlagRegistrar OnUpdate(FlagCallbackFunc cb) && {
  675. flag_.impl_.SetCallback(cb);
  676. return *this;
  677. }
  678. // Make the registrar "die" gracefully as an empty struct on a line where
  679. // registration happens. Registrar objects are intended to live only as
  680. // temporary.
  681. operator FlagRegistrarEmpty() const { return {}; } // NOLINT
  682. private:
  683. Flag<T>& flag_; // Flag being registered (not owned).
  684. };
  685. } // namespace flags_internal
  686. ABSL_NAMESPACE_END
  687. } // namespace absl
  688. #endif // ABSL_FLAGS_INTERNAL_FLAG_H_