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