reflection.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. //
  2. // Copyright 2020 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. #include "absl/flags/reflection.h"
  16. #include <assert.h>
  17. #include <atomic>
  18. #include <string>
  19. #include "absl/base/config.h"
  20. #include "absl/base/thread_annotations.h"
  21. #include "absl/container/flat_hash_map.h"
  22. #include "absl/flags/commandlineflag.h"
  23. #include "absl/flags/internal/private_handle_accessor.h"
  24. #include "absl/flags/internal/registry.h"
  25. #include "absl/flags/usage_config.h"
  26. #include "absl/strings/str_cat.h"
  27. #include "absl/strings/string_view.h"
  28. #include "absl/synchronization/mutex.h"
  29. namespace absl {
  30. ABSL_NAMESPACE_BEGIN
  31. namespace flags_internal {
  32. // --------------------------------------------------------------------
  33. // FlagRegistry
  34. // A FlagRegistry singleton object holds all flag objects indexed by their
  35. // names so that if you know a flag's name, you can access or set it. If the
  36. // function is named FooLocked(), you must own the registry lock before
  37. // calling the function; otherwise, you should *not* hold the lock, and the
  38. // function will acquire it itself if needed.
  39. // --------------------------------------------------------------------
  40. class FlagRegistry {
  41. public:
  42. FlagRegistry() = default;
  43. ~FlagRegistry() = default;
  44. // Store a flag in this registry. Takes ownership of *flag.
  45. void RegisterFlag(CommandLineFlag& flag, const char* filename);
  46. void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION(lock_) { lock_.Lock(); }
  47. void Unlock() ABSL_UNLOCK_FUNCTION(lock_) { lock_.Unlock(); }
  48. // Returns the flag object for the specified name, or nullptr if not found.
  49. // Will emit a warning if a 'retired' flag is specified.
  50. CommandLineFlag* FindFlag(absl::string_view name);
  51. static FlagRegistry& GlobalRegistry(); // returns a singleton registry
  52. private:
  53. friend class flags_internal::FlagSaverImpl; // reads all the flags in order
  54. // to copy them
  55. friend void ForEachFlag(std::function<void(CommandLineFlag&)> visitor);
  56. friend void FinalizeRegistry();
  57. // The map from name to flag, for FindFlag().
  58. using FlagMap = absl::flat_hash_map<absl::string_view, CommandLineFlag*>;
  59. using FlagIterator = FlagMap::iterator;
  60. using FlagConstIterator = FlagMap::const_iterator;
  61. FlagMap flags_;
  62. std::vector<CommandLineFlag*> flat_flags_;
  63. std::atomic<bool> finalized_flags_{false};
  64. absl::Mutex lock_;
  65. // Disallow
  66. FlagRegistry(const FlagRegistry&);
  67. FlagRegistry& operator=(const FlagRegistry&);
  68. };
  69. namespace {
  70. class FlagRegistryLock {
  71. public:
  72. explicit FlagRegistryLock(FlagRegistry& fr) : fr_(fr) { fr_.Lock(); }
  73. ~FlagRegistryLock() { fr_.Unlock(); }
  74. private:
  75. FlagRegistry& fr_;
  76. };
  77. } // namespace
  78. CommandLineFlag* FlagRegistry::FindFlag(absl::string_view name) {
  79. if (finalized_flags_.load(std::memory_order_acquire)) {
  80. // We could save some gcus here if we make `Name()` be non-virtual.
  81. // We could move the `const char*` name to the base class.
  82. auto it = std::partition_point(
  83. flat_flags_.begin(), flat_flags_.end(),
  84. [=](CommandLineFlag* f) { return f->Name() < name; });
  85. if (it != flat_flags_.end() && (*it)->Name() == name) return *it;
  86. }
  87. FlagRegistryLock frl(*this);
  88. auto it = flags_.find(name);
  89. return it != flags_.end() ? it->second : nullptr;
  90. }
  91. void FlagRegistry::RegisterFlag(CommandLineFlag& flag, const char* filename) {
  92. if (filename != nullptr &&
  93. flag.Filename() != GetUsageConfig().normalize_filename(filename)) {
  94. flags_internal::ReportUsageError(
  95. absl::StrCat(
  96. "Inconsistency between flag object and registration for flag '",
  97. flag.Name(),
  98. "', likely due to duplicate flags or an ODR violation. Relevant "
  99. "files: ",
  100. flag.Filename(), " and ", filename),
  101. true);
  102. std::exit(1);
  103. }
  104. FlagRegistryLock registry_lock(*this);
  105. std::pair<FlagIterator, bool> ins =
  106. flags_.insert(FlagMap::value_type(flag.Name(), &flag));
  107. if (ins.second == false) { // means the name was already in the map
  108. CommandLineFlag& old_flag = *ins.first->second;
  109. if (flag.IsRetired() != old_flag.IsRetired()) {
  110. // All registrations must agree on the 'retired' flag.
  111. flags_internal::ReportUsageError(
  112. absl::StrCat(
  113. "Retired flag '", flag.Name(), "' was defined normally in file '",
  114. (flag.IsRetired() ? old_flag.Filename() : flag.Filename()), "'."),
  115. true);
  116. } else if (flags_internal::PrivateHandleAccessor::TypeId(flag) !=
  117. flags_internal::PrivateHandleAccessor::TypeId(old_flag)) {
  118. flags_internal::ReportUsageError(
  119. absl::StrCat("Flag '", flag.Name(),
  120. "' was defined more than once but with "
  121. "differing types. Defined in files '",
  122. old_flag.Filename(), "' and '", flag.Filename(), "'."),
  123. true);
  124. } else if (old_flag.IsRetired()) {
  125. return;
  126. } else if (old_flag.Filename() != flag.Filename()) {
  127. flags_internal::ReportUsageError(
  128. absl::StrCat("Flag '", flag.Name(),
  129. "' was defined more than once (in files '",
  130. old_flag.Filename(), "' and '", flag.Filename(), "')."),
  131. true);
  132. } else {
  133. flags_internal::ReportUsageError(
  134. absl::StrCat(
  135. "Something is wrong with flag '", flag.Name(), "' in file '",
  136. flag.Filename(), "'. One possibility: file '", flag.Filename(),
  137. "' is being linked both statically and dynamically into this "
  138. "executable. e.g. some files listed as srcs to a test and also "
  139. "listed as srcs of some shared lib deps of the same test."),
  140. true);
  141. }
  142. // All cases above are fatal, except for the retired flags.
  143. std::exit(1);
  144. }
  145. }
  146. FlagRegistry& FlagRegistry::GlobalRegistry() {
  147. static FlagRegistry* global_registry = new FlagRegistry;
  148. return *global_registry;
  149. }
  150. // --------------------------------------------------------------------
  151. void ForEachFlag(std::function<void(CommandLineFlag&)> visitor) {
  152. FlagRegistry& registry = FlagRegistry::GlobalRegistry();
  153. if (registry.finalized_flags_.load(std::memory_order_acquire)) {
  154. for (const auto& i : registry.flat_flags_) visitor(*i);
  155. }
  156. FlagRegistryLock frl(registry);
  157. for (const auto& i : registry.flags_) visitor(*i.second);
  158. }
  159. // --------------------------------------------------------------------
  160. bool RegisterCommandLineFlag(CommandLineFlag& flag, const char* filename) {
  161. FlagRegistry::GlobalRegistry().RegisterFlag(flag, filename);
  162. return true;
  163. }
  164. void FinalizeRegistry() {
  165. auto& registry = FlagRegistry::GlobalRegistry();
  166. FlagRegistryLock frl(registry);
  167. if (registry.finalized_flags_.load(std::memory_order_relaxed)) {
  168. // Was already finalized. Ignore the second time.
  169. return;
  170. }
  171. registry.flat_flags_.reserve(registry.flags_.size());
  172. for (const auto& f : registry.flags_) {
  173. registry.flat_flags_.push_back(f.second);
  174. }
  175. std::sort(std::begin(registry.flat_flags_), std::end(registry.flat_flags_),
  176. [](const CommandLineFlag* lhs, const CommandLineFlag* rhs) {
  177. return lhs->Name() < rhs->Name();
  178. });
  179. registry.flags_.clear();
  180. registry.finalized_flags_.store(true, std::memory_order_release);
  181. }
  182. // --------------------------------------------------------------------
  183. namespace {
  184. class RetiredFlagObj final : public CommandLineFlag {
  185. public:
  186. constexpr RetiredFlagObj(const char* name, FlagFastTypeId type_id)
  187. : name_(name), type_id_(type_id) {}
  188. private:
  189. absl::string_view Name() const override { return name_; }
  190. std::string Filename() const override {
  191. OnAccess();
  192. return "RETIRED";
  193. }
  194. FlagFastTypeId TypeId() const override { return type_id_; }
  195. std::string Help() const override {
  196. OnAccess();
  197. return "";
  198. }
  199. bool IsRetired() const override { return true; }
  200. bool IsSpecifiedOnCommandLine() const override {
  201. OnAccess();
  202. return false;
  203. }
  204. std::string DefaultValue() const override {
  205. OnAccess();
  206. return "";
  207. }
  208. std::string CurrentValue() const override {
  209. OnAccess();
  210. return "";
  211. }
  212. // Any input is valid
  213. bool ValidateInputValue(absl::string_view) const override {
  214. OnAccess();
  215. return true;
  216. }
  217. std::unique_ptr<flags_internal::FlagStateInterface> SaveState() override {
  218. return nullptr;
  219. }
  220. bool ParseFrom(absl::string_view, flags_internal::FlagSettingMode,
  221. flags_internal::ValueSource, std::string&) override {
  222. OnAccess();
  223. return false;
  224. }
  225. void CheckDefaultValueParsingRoundtrip() const override { OnAccess(); }
  226. void Read(void*) const override { OnAccess(); }
  227. void OnAccess() const {
  228. flags_internal::ReportUsageError(
  229. absl::StrCat("Accessing retired flag '", name_, "'"), false);
  230. }
  231. // Data members
  232. const char* const name_;
  233. const FlagFastTypeId type_id_;
  234. };
  235. } // namespace
  236. void Retire(const char* name, FlagFastTypeId type_id, char* buf) {
  237. static_assert(sizeof(RetiredFlagObj) == kRetiredFlagObjSize, "");
  238. static_assert(alignof(RetiredFlagObj) == kRetiredFlagObjAlignment, "");
  239. auto* flag = ::new (static_cast<void*>(buf))
  240. flags_internal::RetiredFlagObj(name, type_id);
  241. FlagRegistry::GlobalRegistry().RegisterFlag(*flag, nullptr);
  242. }
  243. // --------------------------------------------------------------------
  244. class FlagSaverImpl {
  245. public:
  246. FlagSaverImpl() = default;
  247. FlagSaverImpl(const FlagSaverImpl&) = delete;
  248. void operator=(const FlagSaverImpl&) = delete;
  249. // Saves the flag states from the flag registry into this object.
  250. // It's an error to call this more than once.
  251. void SaveFromRegistry() {
  252. assert(backup_registry_.empty()); // call only once!
  253. flags_internal::ForEachFlag([&](CommandLineFlag& flag) {
  254. if (auto flag_state =
  255. flags_internal::PrivateHandleAccessor::SaveState(flag)) {
  256. backup_registry_.emplace_back(std::move(flag_state));
  257. }
  258. });
  259. }
  260. // Restores the saved flag states into the flag registry.
  261. void RestoreToRegistry() {
  262. for (const auto& flag_state : backup_registry_) {
  263. flag_state->Restore();
  264. }
  265. }
  266. private:
  267. std::vector<std::unique_ptr<flags_internal::FlagStateInterface>>
  268. backup_registry_;
  269. };
  270. } // namespace flags_internal
  271. FlagSaver::FlagSaver() : impl_(new flags_internal::FlagSaverImpl) {
  272. impl_->SaveFromRegistry();
  273. }
  274. FlagSaver::~FlagSaver() {
  275. if (!impl_) return;
  276. impl_->RestoreToRegistry();
  277. delete impl_;
  278. }
  279. // --------------------------------------------------------------------
  280. CommandLineFlag* FindCommandLineFlag(absl::string_view name) {
  281. if (name.empty()) return nullptr;
  282. flags_internal::FlagRegistry& registry =
  283. flags_internal::FlagRegistry::GlobalRegistry();
  284. return registry.FindFlag(name);
  285. }
  286. // --------------------------------------------------------------------
  287. absl::flat_hash_map<absl::string_view, absl::CommandLineFlag*> GetAllFlags() {
  288. absl::flat_hash_map<absl::string_view, absl::CommandLineFlag*> res;
  289. flags_internal::ForEachFlag([&](CommandLineFlag& flag) {
  290. if (!flag.IsRetired()) res.insert({flag.Name(), &flag});
  291. });
  292. return res;
  293. }
  294. ABSL_NAMESPACE_END
  295. } // namespace absl