flag.h 28 KB

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