| 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 | |
| 16 | #include "absl/flags/internal/flag.h" |
| 17 | |
| 18 | #include <assert.h> |
| 19 | #include <stddef.h> |
| 20 | #include <stdint.h> |
| 21 | #include <string.h> |
| 22 | |
| 23 | #include <array> |
| 24 | #include <atomic> |
| 25 | #include <memory> |
| 26 | #include <new> |
| 27 | #include <string> |
| 28 | #include <typeinfo> |
| 29 | |
| 30 | #include "absl/base/call_once.h" |
| 31 | #include "absl/base/casts.h" |
| 32 | #include "absl/base/config.h" |
| 33 | #include "absl/base/dynamic_annotations.h" |
| 34 | #include "absl/base/optimization.h" |
| 35 | #include "absl/flags/config.h" |
| 36 | #include "absl/flags/internal/commandlineflag.h" |
| 37 | #include "absl/flags/usage_config.h" |
| 38 | #include "absl/memory/memory.h" |
| 39 | #include "absl/strings/str_cat.h" |
| 40 | #include "absl/strings/string_view.h" |
| 41 | #include "absl/synchronization/mutex.h" |
| 42 | |
| 43 | namespace absl { |
| 44 | ABSL_NAMESPACE_BEGIN |
| 45 | namespace flags_internal { |
| 46 | |
| 47 | // The help message indicating that the commandline flag has been |
| 48 | // 'stripped'. It will not show up when doing "-help" and its |
| 49 | // variants. The flag is stripped if ABSL_FLAGS_STRIP_HELP is set to 1 |
| 50 | // before including absl/flags/flag.h |
| 51 | const char kStrippedFlagHelp[] = "\001\002\003\004 (unknown) \004\003\002\001"; |
| 52 | |
| 53 | namespace { |
| 54 | |
| 55 | // Currently we only validate flag values for user-defined flag types. |
| 56 | bool ShouldValidateFlagValue(FlagFastTypeId flag_type_id) { |
| 57 | #define DONT_VALIDATE(T, _) \ |
| 58 | if (flag_type_id == base_internal::FastTypeId<T>()) return false; |
| 59 | ABSL_FLAGS_INTERNAL_SUPPORTED_TYPES(DONT_VALIDATE) |
| 60 | #undef DONT_VALIDATE |
| 61 | |
| 62 | return true; |
| 63 | } |
| 64 | |
| 65 | // RAII helper used to temporarily unlock and relock `absl::Mutex`. |
| 66 | // This is used when we need to ensure that locks are released while |
| 67 | // invoking user supplied callbacks and then reacquired, since callbacks may |
| 68 | // need to acquire these locks themselves. |
| 69 | class MutexRelock { |
| 70 | public: |
| 71 | explicit MutexRelock(absl::Mutex& mu) : mu_(mu) { mu_.Unlock(); } |
| 72 | ~MutexRelock() { mu_.Lock(); } |
| 73 | |
| 74 | MutexRelock(const MutexRelock&) = delete; |
| 75 | MutexRelock& operator=(const MutexRelock&) = delete; |
| 76 | |
| 77 | private: |
| 78 | absl::Mutex& mu_; |
| 79 | }; |
| 80 | |
| 81 | } // namespace |
| 82 | |
| 83 | /////////////////////////////////////////////////////////////////////////////// |
| 84 | // Persistent state of the flag data. |
| 85 | |
| 86 | class FlagImpl; |
| 87 | |
| 88 | class FlagState : public flags_internal::FlagStateInterface { |
| 89 | public: |
| 90 | template <typename V> |
| 91 | FlagState(FlagImpl& flag_impl, const V& v, bool modified, |
| 92 | bool on_command_line, int64_t counter) |
| 93 | : flag_impl_(flag_impl), |
| 94 | value_(v), |
| 95 | modified_(modified), |
| 96 | on_command_line_(on_command_line), |
| 97 | counter_(counter) {} |
| 98 | |
| 99 | ~FlagState() override { |
| 100 | if (flag_impl_.ValueStorageKind() != FlagValueStorageKind::kAlignedBuffer && |
| 101 | flag_impl_.ValueStorageKind() != FlagValueStorageKind::kSequenceLocked) |
| 102 | return; |
| 103 | flags_internal::Delete(flag_impl_.op_, value_.heap_allocated); |
| 104 | } |
| 105 | |
| 106 | private: |
| 107 | friend class FlagImpl; |
| 108 | |
| 109 | // Restores the flag to the saved state. |
| 110 | void Restore() const override { |
| 111 | if (!flag_impl_.RestoreState(*this)) return; |
| 112 | |
| 113 | ABSL_INTERNAL_LOG(INFO, |
| 114 | absl::StrCat("Restore saved value of ", flag_impl_.Name(), |
| 115 | " to: ", flag_impl_.CurrentValue())); |
| 116 | } |
| 117 | |
| 118 | // Flag and saved flag data. |
| 119 | FlagImpl& flag_impl_; |
| 120 | union SavedValue { |
| 121 | explicit SavedValue(void* v) : heap_allocated(v) {} |
| 122 | explicit SavedValue(int64_t v) : one_word(v) {} |
| 123 | |
| 124 | void* heap_allocated; |
| 125 | int64_t one_word; |
| 126 | } value_; |
| 127 | bool modified_; |
| 128 | bool on_command_line_; |
| 129 | int64_t counter_; |
| 130 | }; |
| 131 | |
| 132 | /////////////////////////////////////////////////////////////////////////////// |
| 133 | // Flag implementation, which does not depend on flag value type. |
| 134 | |
| 135 | DynValueDeleter::DynValueDeleter(FlagOpFn op_arg) : op(op_arg) {} |
| 136 | |
| 137 | void DynValueDeleter::operator()(void* ptr) const { |
| 138 | if (op == nullptr) return; |
| 139 | |
| 140 | Delete(op, ptr); |
| 141 | } |
| 142 | |
| 143 | void FlagImpl::Init() { |
| 144 | new (&data_guard_) absl::Mutex; |
| 145 | |
| 146 | auto def_kind = static_cast<FlagDefaultKind>(def_kind_); |
| 147 | |
| 148 | switch (ValueStorageKind()) { |
| 149 | case FlagValueStorageKind::kValueAndInitBit: |
| 150 | case FlagValueStorageKind::kOneWordAtomic: { |
| 151 | alignas(int64_t) std::array<char, sizeof(int64_t)> buf{}; |
| 152 | if (def_kind == FlagDefaultKind::kGenFunc) { |
| 153 | (*default_value_.gen_func)(buf.data()); |
| 154 | } else { |
| 155 | assert(def_kind != FlagDefaultKind::kDynamicValue); |
| 156 | std::memcpy(buf.data(), &default_value_, Sizeof(op_)); |
| 157 | } |
| 158 | if (ValueStorageKind() == FlagValueStorageKind::kValueAndInitBit) { |
| 159 | // We presume here the memory layout of FlagValueAndInitBit struct. |
| 160 | uint8_t initialized = 1; |
| 161 | std::memcpy(buf.data() + Sizeof(op_), &initialized, |
| 162 | sizeof(initialized)); |
| 163 | } |
| 164 | // Type can contain valid uninitialized bits, e.g. padding. |
| 165 | ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(buf.data(), buf.size()); |
| 166 | OneWordValue().store(absl::bit_cast<int64_t>(buf), |
| 167 | std::memory_order_release); |
| 168 | break; |
| 169 | } |
| 170 | case FlagValueStorageKind::kSequenceLocked: { |
| 171 | // For this storage kind the default_value_ always points to gen_func |
| 172 | // during initialization. |
| 173 | assert(def_kind == FlagDefaultKind::kGenFunc); |
| 174 | (*default_value_.gen_func)(AtomicBufferValue()); |
| 175 | break; |
| 176 | } |
| 177 | case FlagValueStorageKind::kAlignedBuffer: |
| 178 | // For this storage kind the default_value_ always points to gen_func |
| 179 | // during initialization. |
| 180 | assert(def_kind == FlagDefaultKind::kGenFunc); |
| 181 | (*default_value_.gen_func)(AlignedBufferValue()); |
| 182 | break; |
| 183 | } |
| 184 | seq_lock_.MarkInitialized(); |
| 185 | } |
| 186 | |
| 187 | absl::Mutex* FlagImpl::DataGuard() const { |
| 188 | absl::call_once(const_cast<FlagImpl*>(this)->init_control_, &FlagImpl::Init, |
| 189 | const_cast<FlagImpl*>(this)); |
| 190 | |
| 191 | // data_guard_ is initialized inside Init. |
| 192 | return reinterpret_cast<absl::Mutex*>(&data_guard_); |
| 193 | } |
| 194 | |
| 195 | void FlagImpl::AssertValidType(FlagFastTypeId rhs_type_id, |
| 196 | const std::type_info* (*gen_rtti)()) const { |
| 197 | FlagFastTypeId lhs_type_id = flags_internal::FastTypeId(op_); |
| 198 | |
| 199 | // `rhs_type_id` is the fast type id corresponding to the declaration |
| 200 | // visibile at the call site. `lhs_type_id` is the fast type id |
| 201 | // corresponding to the type specified in flag definition. They must match |
| 202 | // for this operation to be well-defined. |
| 203 | if (ABSL_PREDICT_TRUE(lhs_type_id == rhs_type_id)) return; |
| 204 | |
| 205 | const std::type_info* lhs_runtime_type_id = |
| 206 | flags_internal::RuntimeTypeId(op_); |
| 207 | const std::type_info* rhs_runtime_type_id = (*gen_rtti)(); |
| 208 | |
| 209 | if (lhs_runtime_type_id == rhs_runtime_type_id) return; |
| 210 | |
| 211 | #ifdef ABSL_INTERNAL_HAS_RTTI |
| 212 | if (*lhs_runtime_type_id == *rhs_runtime_type_id) return; |
| 213 | #endif |
| 214 | |
| 215 | ABSL_INTERNAL_LOG( |
| 216 | FATAL, absl::StrCat("Flag '", Name(), |
| 217 | "' is defined as one type and declared as another")); |
| 218 | } |
| 219 | |
| 220 | std::unique_ptr<void, DynValueDeleter> FlagImpl::MakeInitValue() const { |
| 221 | void* res = nullptr; |
| 222 | switch (DefaultKind()) { |
| 223 | case FlagDefaultKind::kDynamicValue: |
| 224 | res = flags_internal::Clone(op_, default_value_.dynamic_value); |
| 225 | break; |
| 226 | case FlagDefaultKind::kGenFunc: |
| 227 | res = flags_internal::Alloc(op_); |
| 228 | (*default_value_.gen_func)(res); |
| 229 | break; |
| 230 | default: |
| 231 | res = flags_internal::Clone(op_, &default_value_); |
| 232 | break; |
| 233 | } |
| 234 | return {res, DynValueDeleter{op_}}; |
| 235 | } |
| 236 | |
| 237 | void FlagImpl::StoreValue(const void* src) { |
| 238 | switch (ValueStorageKind()) { |
| 239 | case FlagValueStorageKind::kValueAndInitBit: |
| 240 | case FlagValueStorageKind::kOneWordAtomic: { |
| 241 | // Load the current value to avoid setting 'init' bit manualy. |
| 242 | int64_t one_word_val = OneWordValue().load(std::memory_order_acquire); |
| 243 | std::memcpy(&one_word_val, src, Sizeof(op_)); |
| 244 | OneWordValue().store(one_word_val, std::memory_order_release); |
| 245 | seq_lock_.IncrementModificationCount(); |
| 246 | break; |
| 247 | } |
| 248 | case FlagValueStorageKind::kSequenceLocked: { |
| 249 | seq_lock_.Write(AtomicBufferValue(), src, Sizeof(op_)); |
| 250 | break; |
| 251 | } |
| 252 | case FlagValueStorageKind::kAlignedBuffer: |
| 253 | Copy(op_, src, AlignedBufferValue()); |
| 254 | seq_lock_.IncrementModificationCount(); |
| 255 | break; |
| 256 | } |
| 257 | modified_ = true; |
| 258 | InvokeCallback(); |
| 259 | } |
| 260 | |
| 261 | absl::string_view FlagImpl::Name() const { return name_; } |
| 262 | |
| 263 | std::string FlagImpl::Filename() const { |
| 264 | return flags_internal::GetUsageConfig().normalize_filename(filename_); |
| 265 | } |
| 266 | |
| 267 | std::string FlagImpl::Help() const { |
| 268 | return HelpSourceKind() == FlagHelpKind::kLiteral ? help_.literal |
| 269 | : help_.gen_func(); |
| 270 | } |
| 271 | |
| 272 | FlagFastTypeId FlagImpl::TypeId() const { |
| 273 | return flags_internal::FastTypeId(op_); |
| 274 | } |
| 275 | |
| 276 | int64_t FlagImpl::ModificationCount() const { |
| 277 | return seq_lock_.ModificationCount(); |
| 278 | } |
| 279 | |
| 280 | bool FlagImpl::IsSpecifiedOnCommandLine() const { |
| 281 | absl::MutexLock l(DataGuard()); |
| 282 | return on_command_line_; |
| 283 | } |
| 284 | |
| 285 | std::string FlagImpl::DefaultValue() const { |
| 286 | absl::MutexLock l(DataGuard()); |
| 287 | |
| 288 | auto obj = MakeInitValue(); |
| 289 | return flags_internal::Unparse(op_, obj.get()); |
| 290 | } |
| 291 | |
| 292 | std::string FlagImpl::CurrentValue() const { |
| 293 | auto* guard = DataGuard(); // Make sure flag initialized |
| 294 | switch (ValueStorageKind()) { |
| 295 | case FlagValueStorageKind::kValueAndInitBit: |
| 296 | case FlagValueStorageKind::kOneWordAtomic: { |
| 297 | const auto one_word_val = |
| 298 | absl::bit_cast<std::array<char, sizeof(int64_t)>>( |
| 299 | OneWordValue().load(std::memory_order_acquire)); |
| 300 | return flags_internal::Unparse(op_, one_word_val.data()); |
| 301 | } |
| 302 | case FlagValueStorageKind::kSequenceLocked: { |
| 303 | std::unique_ptr<void, DynValueDeleter> cloned(flags_internal::Alloc(op_), |
| 304 | DynValueDeleter{op_}); |
| 305 | ReadSequenceLockedData(cloned.get()); |
| 306 | return flags_internal::Unparse(op_, cloned.get()); |
| 307 | } |
| 308 | case FlagValueStorageKind::kAlignedBuffer: { |
| 309 | absl::MutexLock l(guard); |
| 310 | return flags_internal::Unparse(op_, AlignedBufferValue()); |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | return ""; |
| 315 | } |
| 316 | |
| 317 | void FlagImpl::SetCallback(const FlagCallbackFunc mutation_callback) { |
| 318 | absl::MutexLock l(DataGuard()); |
| 319 | |
| 320 | if (callback_ == nullptr) { |
| 321 | callback_ = new FlagCallback; |
| 322 | } |
| 323 | callback_->func = mutation_callback; |
| 324 | |
| 325 | InvokeCallback(); |
| 326 | } |
| 327 | |
| 328 | void FlagImpl::InvokeCallback() const { |
| 329 | if (!callback_) return; |
| 330 | |
| 331 | // Make a copy of the C-style function pointer that we are about to invoke |
| 332 | // before we release the lock guarding it. |
| 333 | FlagCallbackFunc cb = callback_->func; |
| 334 | |
| 335 | // If the flag has a mutation callback this function invokes it. While the |
| 336 | // callback is being invoked the primary flag's mutex is unlocked and it is |
| 337 | // re-locked back after call to callback is completed. Callback invocation is |
| 338 | // guarded by flag's secondary mutex instead which prevents concurrent |
| 339 | // callback invocation. Note that it is possible for other thread to grab the |
| 340 | // primary lock and update flag's value at any time during the callback |
| 341 | // invocation. This is by design. Callback can get a value of the flag if |
| 342 | // necessary, but it might be different from the value initiated the callback |
| 343 | // and it also can be different by the time the callback invocation is |
| 344 | // completed. Requires that *primary_lock be held in exclusive mode; it may be |
| 345 | // released and reacquired by the implementation. |
| 346 | MutexRelock relock(*DataGuard()); |
| 347 | absl::MutexLock lock(&callback_->guard); |
| 348 | cb(); |
| 349 | } |
| 350 | |
| 351 | std::unique_ptr<FlagStateInterface> FlagImpl::SaveState() { |
| 352 | absl::MutexLock l(DataGuard()); |
| 353 | |
| 354 | bool modified = modified_; |
| 355 | bool on_command_line = on_command_line_; |
| 356 | switch (ValueStorageKind()) { |
| 357 | case FlagValueStorageKind::kValueAndInitBit: |
| 358 | case FlagValueStorageKind::kOneWordAtomic: { |
| 359 | return absl::make_unique<FlagState>( |
| 360 | *this, OneWordValue().load(std::memory_order_acquire), modified, |
| 361 | on_command_line, ModificationCount()); |
| 362 | } |
| 363 | case FlagValueStorageKind::kSequenceLocked: { |
| 364 | void* cloned = flags_internal::Alloc(op_); |
| 365 | // Read is guaranteed to be successful because we hold the lock. |
| 366 | bool success = |
| 367 | seq_lock_.TryRead(cloned, AtomicBufferValue(), Sizeof(op_)); |
| 368 | assert(success); |
| 369 | static_cast<void>(success); |
| 370 | return absl::make_unique<FlagState>(*this, cloned, modified, |
| 371 | on_command_line, ModificationCount()); |
| 372 | } |
| 373 | case FlagValueStorageKind::kAlignedBuffer: { |
| 374 | return absl::make_unique<FlagState>( |
| 375 | *this, flags_internal::Clone(op_, AlignedBufferValue()), modified, |
| 376 | on_command_line, ModificationCount()); |
| 377 | } |
| 378 | } |
| 379 | return nullptr; |
| 380 | } |
| 381 | |
| 382 | bool FlagImpl::RestoreState(const FlagState& flag_state) { |
| 383 | absl::MutexLock l(DataGuard()); |
| 384 | if (flag_state.counter_ == ModificationCount()) { |
| 385 | return false; |
| 386 | } |
| 387 | |
| 388 | switch (ValueStorageKind()) { |
| 389 | case FlagValueStorageKind::kValueAndInitBit: |
| 390 | case FlagValueStorageKind::kOneWordAtomic: |
| 391 | StoreValue(&flag_state.value_.one_word); |
| 392 | break; |
| 393 | case FlagValueStorageKind::kSequenceLocked: |
| 394 | case FlagValueStorageKind::kAlignedBuffer: |
| 395 | StoreValue(flag_state.value_.heap_allocated); |
| 396 | break; |
| 397 | } |
| 398 | |
| 399 | modified_ = flag_state.modified_; |
| 400 | on_command_line_ = flag_state.on_command_line_; |
| 401 | |
| 402 | return true; |
| 403 | } |
| 404 | |
| 405 | template <typename StorageT> |
| 406 | StorageT* FlagImpl::OffsetValue() const { |
| 407 | char* p = reinterpret_cast<char*>(const_cast<FlagImpl*>(this)); |
| 408 | // The offset is deduced via Flag value type specific op_. |
| 409 | ptrdiff_t offset = flags_internal::ValueOffset(op_); |
| 410 | |
| 411 | return reinterpret_cast<StorageT*>(p + offset); |
| 412 | } |
| 413 | |
| 414 | void* FlagImpl::AlignedBufferValue() const { |
| 415 | assert(ValueStorageKind() == FlagValueStorageKind::kAlignedBuffer); |
| 416 | return OffsetValue<void>(); |
| 417 | } |
| 418 | |
| 419 | std::atomic<uint64_t>* FlagImpl::AtomicBufferValue() const { |
| 420 | assert(ValueStorageKind() == FlagValueStorageKind::kSequenceLocked); |
| 421 | return OffsetValue<std::atomic<uint64_t>>(); |
| 422 | } |
| 423 | |
| 424 | std::atomic<int64_t>& FlagImpl::OneWordValue() const { |
| 425 | assert(ValueStorageKind() == FlagValueStorageKind::kOneWordAtomic || |
| 426 | ValueStorageKind() == FlagValueStorageKind::kValueAndInitBit); |
| 427 | return OffsetValue<FlagOneWordValue>()->value; |
| 428 | } |
| 429 | |
| 430 | // Attempts to parse supplied `value` string using parsing routine in the `flag` |
| 431 | // argument. If parsing successful, this function replaces the dst with newly |
| 432 | // parsed value. In case if any error is encountered in either step, the error |
| 433 | // message is stored in 'err' |
| 434 | std::unique_ptr<void, DynValueDeleter> FlagImpl::TryParse( |
| 435 | absl::string_view value, std::string& err) const { |
| 436 | std::unique_ptr<void, DynValueDeleter> tentative_value = MakeInitValue(); |
| 437 | |
| 438 | std::string parse_err; |
| 439 | if (!flags_internal::Parse(op_, value, tentative_value.get(), &parse_err)) { |
| 440 | absl::string_view err_sep = parse_err.empty() ? "" : "; "; |
| 441 | err = absl::StrCat("Illegal value '", value, "' specified for flag '", |
| 442 | Name(), "'", err_sep, parse_err); |
| 443 | return nullptr; |
| 444 | } |
| 445 | |
| 446 | return tentative_value; |
| 447 | } |
| 448 | |
| 449 | void FlagImpl::Read(void* dst) const { |
| 450 | auto* guard = DataGuard(); // Make sure flag initialized |
| 451 | switch (ValueStorageKind()) { |
| 452 | case FlagValueStorageKind::kValueAndInitBit: |
| 453 | case FlagValueStorageKind::kOneWordAtomic: { |
| 454 | const int64_t one_word_val = |
| 455 | OneWordValue().load(std::memory_order_acquire); |
| 456 | std::memcpy(dst, &one_word_val, Sizeof(op_)); |
| 457 | break; |
| 458 | } |
| 459 | case FlagValueStorageKind::kSequenceLocked: { |
| 460 | ReadSequenceLockedData(dst); |
| 461 | break; |
| 462 | } |
| 463 | case FlagValueStorageKind::kAlignedBuffer: { |
| 464 | absl::MutexLock l(guard); |
| 465 | flags_internal::CopyConstruct(op_, AlignedBufferValue(), dst); |
| 466 | break; |
| 467 | } |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | int64_t FlagImpl::ReadOneWord() const { |
| 472 | assert(ValueStorageKind() == FlagValueStorageKind::kOneWordAtomic || |
| 473 | ValueStorageKind() == FlagValueStorageKind::kValueAndInitBit); |
| 474 | auto* guard = DataGuard(); // Make sure flag initialized |
| 475 | (void)guard; |
| 476 | return OneWordValue().load(std::memory_order_acquire); |
| 477 | } |
| 478 | |
| 479 | bool FlagImpl::ReadOneBool() const { |
| 480 | assert(ValueStorageKind() == FlagValueStorageKind::kValueAndInitBit); |
| 481 | auto* guard = DataGuard(); // Make sure flag initialized |
| 482 | (void)guard; |
| 483 | return absl::bit_cast<FlagValueAndInitBit<bool>>( |
| 484 | OneWordValue().load(std::memory_order_acquire)) |
| 485 | .value; |
| 486 | } |
| 487 | |
| 488 | void FlagImpl::ReadSequenceLockedData(void* dst) const { |
| 489 | size_t size = Sizeof(op_); |
| 490 | // Attempt to read using the sequence lock. |
| 491 | if (ABSL_PREDICT_TRUE(seq_lock_.TryRead(dst, AtomicBufferValue(), size))) { |
| 492 | return; |
| 493 | } |
| 494 | // We failed due to contention. Acquire the lock to prevent contention |
| 495 | // and try again. |
| 496 | absl::ReaderMutexLock l(DataGuard()); |
| 497 | bool success = seq_lock_.TryRead(dst, AtomicBufferValue(), size); |
| 498 | assert(success); |
| 499 | static_cast<void>(success); |
| 500 | } |
| 501 | |
| 502 | void FlagImpl::Write(const void* src) { |
| 503 | absl::MutexLock l(DataGuard()); |
| 504 | |
| 505 | if (ShouldValidateFlagValue(flags_internal::FastTypeId(op_))) { |
| 506 | std::unique_ptr<void, DynValueDeleter> obj{flags_internal::Clone(op_, src), |
| 507 | DynValueDeleter{op_}}; |
| 508 | std::string ignored_error; |
| 509 | std::string src_as_str = flags_internal::Unparse(op_, src); |
| 510 | if (!flags_internal::Parse(op_, src_as_str, obj.get(), &ignored_error)) { |
| 511 | ABSL_INTERNAL_LOG(ERROR, absl::StrCat("Attempt to set flag '", Name(), |
| 512 | "' to invalid value ", src_as_str)); |
| 513 | } |
| 514 | } |
| 515 | |
| 516 | StoreValue(src); |
| 517 | } |
| 518 | |
| 519 | // Sets the value of the flag based on specified string `value`. If the flag |
| 520 | // was successfully set to new value, it returns true. Otherwise, sets `err` |
| 521 | // to indicate the error, leaves the flag unchanged, and returns false. There |
| 522 | // are three ways to set the flag's value: |
| 523 | // * Update the current flag value |
| 524 | // * Update the flag's default value |
| 525 | // * Update the current flag value if it was never set before |
| 526 | // The mode is selected based on 'set_mode' parameter. |
| 527 | bool FlagImpl::ParseFrom(absl::string_view value, FlagSettingMode set_mode, |
| 528 | ValueSource source, std::string& err) { |
| 529 | absl::MutexLock l(DataGuard()); |
| 530 | |
| 531 | switch (set_mode) { |
| 532 | case SET_FLAGS_VALUE: { |
| 533 | // set or modify the flag's value |
| 534 | auto tentative_value = TryParse(value, err); |
| 535 | if (!tentative_value) return false; |
| 536 | |
| 537 | StoreValue(tentative_value.get()); |
| 538 | |
| 539 | if (source == kCommandLine) { |
| 540 | on_command_line_ = true; |
| 541 | } |
| 542 | break; |
| 543 | } |
| 544 | case SET_FLAG_IF_DEFAULT: { |
| 545 | // set the flag's value, but only if it hasn't been set by someone else |
| 546 | if (modified_) { |
| 547 | // TODO(rogeeff): review and fix this semantic. Currently we do not fail |
| 548 | // in this case if flag is modified. This is misleading since the flag's |
| 549 | // value is not updated even though we return true. |
| 550 | // *err = absl::StrCat(Name(), " is already set to ", |
| 551 | // CurrentValue(), "\n"); |
| 552 | // return false; |
| 553 | return true; |
| 554 | } |
| 555 | auto tentative_value = TryParse(value, err); |
| 556 | if (!tentative_value) return false; |
| 557 | |
| 558 | StoreValue(tentative_value.get()); |
| 559 | break; |
| 560 | } |
| 561 | case SET_FLAGS_DEFAULT: { |
| 562 | auto tentative_value = TryParse(value, err); |
| 563 | if (!tentative_value) return false; |
| 564 | |
| 565 | if (DefaultKind() == FlagDefaultKind::kDynamicValue) { |
| 566 | void* old_value = default_value_.dynamic_value; |
| 567 | default_value_.dynamic_value = tentative_value.release(); |
| 568 | tentative_value.reset(old_value); |
| 569 | } else { |
| 570 | default_value_.dynamic_value = tentative_value.release(); |
| 571 | def_kind_ = static_cast<uint8_t>(FlagDefaultKind::kDynamicValue); |
| 572 | } |
| 573 | |
| 574 | if (!modified_) { |
| 575 | // Need to set both default value *and* current, in this case. |
| 576 | StoreValue(default_value_.dynamic_value); |
| 577 | modified_ = false; |
| 578 | } |
| 579 | break; |
| 580 | } |
| 581 | } |
| 582 | |
| 583 | return true; |
| 584 | } |
| 585 | |
| 586 | void FlagImpl::CheckDefaultValueParsingRoundtrip() const { |
| 587 | std::string v = DefaultValue(); |
| 588 | |
| 589 | absl::MutexLock lock(DataGuard()); |
| 590 | |
| 591 | auto dst = MakeInitValue(); |
| 592 | std::string error; |
| 593 | if (!flags_internal::Parse(op_, v, dst.get(), &error)) { |
| 594 | ABSL_INTERNAL_LOG( |
| 595 | FATAL, |
| 596 | absl::StrCat("Flag ", Name(), " (from ", Filename(), |
| 597 | "): string form of default value '", v, |
| 598 | "' could not be parsed; error=", error)); |
| 599 | } |
| 600 | |
| 601 | // We do not compare dst to def since parsing/unparsing may make |
| 602 | // small changes, e.g., precision loss for floating point types. |
| 603 | } |
| 604 | |
| 605 | bool FlagImpl::ValidateInputValue(absl::string_view value) const { |
| 606 | absl::MutexLock l(DataGuard()); |
| 607 | |
| 608 | auto obj = MakeInitValue(); |
| 609 | std::string ignored_error; |
| 610 | return flags_internal::Parse(op_, value, obj.get(), &ignored_error); |
| 611 | } |
| 612 | |
| 613 | } // namespace flags_internal |
| 614 | ABSL_NAMESPACE_END |
| 615 | } // namespace absl |
| 616 | |