reflection.cc 12 KB

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