Austin Schuh | 36244a1 | 2019-09-21 17:52:38 -0700 | [diff] [blame^] | 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/commandlineflag.h" |
| 17 | |
| 18 | #include <cassert> |
| 19 | |
| 20 | #include "absl/base/internal/raw_logging.h" |
| 21 | #include "absl/base/optimization.h" |
| 22 | #include "absl/flags/config.h" |
| 23 | #include "absl/flags/usage_config.h" |
| 24 | #include "absl/strings/str_cat.h" |
| 25 | #include "absl/synchronization/mutex.h" |
| 26 | |
| 27 | namespace absl { |
| 28 | namespace flags_internal { |
| 29 | |
| 30 | // The help message indicating that the commandline flag has been |
| 31 | // 'stripped'. It will not show up when doing "-help" and its |
| 32 | // variants. The flag is stripped if ABSL_FLAGS_STRIP_HELP is set to 1 |
| 33 | // before including absl/flags/flag.h |
| 34 | |
| 35 | // This is used by this file, and also in commandlineflags_reporting.cc |
| 36 | const char kStrippedFlagHelp[] = "\001\002\003\004 (unknown) \004\003\002\001"; |
| 37 | |
| 38 | namespace { |
| 39 | |
| 40 | // Currently we only validate flag values for user-defined flag types. |
| 41 | bool ShouldValidateFlagValue(const CommandLineFlag& flag) { |
| 42 | #define DONT_VALIDATE(T) \ |
| 43 | if (flag.IsOfType<T>()) return false; |
| 44 | ABSL_FLAGS_INTERNAL_FOR_EACH_LOCK_FREE(DONT_VALIDATE) |
| 45 | DONT_VALIDATE(std::string) |
| 46 | DONT_VALIDATE(std::vector<std::string>) |
| 47 | #undef DONT_VALIDATE |
| 48 | |
| 49 | return true; |
| 50 | } |
| 51 | |
| 52 | } // namespace |
| 53 | |
| 54 | absl::Mutex* InitFlag(CommandLineFlag* flag) { |
| 55 | ABSL_CONST_INIT static absl::Mutex init_lock(absl::kConstInit); |
| 56 | absl::Mutex* mu; |
| 57 | |
| 58 | { |
| 59 | absl::MutexLock lock(&init_lock); |
| 60 | |
| 61 | if (flag->locks_ == nullptr) { // Must initialize Mutexes for this flag. |
| 62 | flag->locks_ = new flags_internal::CommandLineFlagLocks; |
| 63 | } |
| 64 | |
| 65 | mu = &flag->locks_->primary_mu; |
| 66 | } |
| 67 | |
| 68 | { |
| 69 | absl::MutexLock lock(mu); |
| 70 | |
| 71 | if (!flag->IsRetired() && flag->def_ == nullptr) { |
| 72 | // Need to initialize def and cur fields. |
| 73 | flag->def_ = (*flag->make_init_value_)(); |
| 74 | flag->cur_ = Clone(flag->op_, flag->def_); |
| 75 | UpdateCopy(flag); |
| 76 | flag->inited_.store(true, std::memory_order_release); |
| 77 | flag->InvokeCallback(); |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | flag->inited_.store(true, std::memory_order_release); |
| 82 | return mu; |
| 83 | } |
| 84 | |
| 85 | // Ensure that the lazily initialized fields of *flag have been initialized, |
| 86 | // and return &flag->locks_->primary_mu. |
| 87 | absl::Mutex* CommandLineFlag::InitFlagIfNecessary() const |
| 88 | ABSL_LOCK_RETURNED(locks_->primary_mu) { |
| 89 | if (!inited_.load(std::memory_order_acquire)) { |
| 90 | return InitFlag(const_cast<CommandLineFlag*>(this)); |
| 91 | } |
| 92 | |
| 93 | // All fields initialized; locks_ is therefore safe to read. |
| 94 | return &locks_->primary_mu; |
| 95 | } |
| 96 | |
| 97 | bool CommandLineFlag::IsModified() const { |
| 98 | absl::MutexLock l(InitFlagIfNecessary()); |
| 99 | return modified_; |
| 100 | } |
| 101 | |
| 102 | void CommandLineFlag::SetModified(bool is_modified) { |
| 103 | absl::MutexLock l(InitFlagIfNecessary()); |
| 104 | modified_ = is_modified; |
| 105 | } |
| 106 | |
| 107 | bool CommandLineFlag::IsSpecifiedOnCommandLine() const { |
| 108 | absl::MutexLock l(InitFlagIfNecessary()); |
| 109 | return on_command_line_; |
| 110 | } |
| 111 | |
| 112 | absl::string_view CommandLineFlag::Typename() const { |
| 113 | // We do not store/report type in Abseil Flags, so that user do not rely on in |
| 114 | // at runtime |
| 115 | if (IsAbseilFlag() || IsRetired()) return ""; |
| 116 | |
| 117 | #define HANDLE_V1_BUILTIN_TYPE(t) \ |
| 118 | if (IsOfType<t>()) { \ |
| 119 | return #t; \ |
| 120 | } |
| 121 | |
| 122 | HANDLE_V1_BUILTIN_TYPE(bool); |
| 123 | HANDLE_V1_BUILTIN_TYPE(int32_t); |
| 124 | HANDLE_V1_BUILTIN_TYPE(int64_t); |
| 125 | HANDLE_V1_BUILTIN_TYPE(uint64_t); |
| 126 | HANDLE_V1_BUILTIN_TYPE(double); |
| 127 | #undef HANDLE_V1_BUILTIN_TYPE |
| 128 | |
| 129 | if (IsOfType<std::string>()) { |
| 130 | return "string"; |
| 131 | } |
| 132 | |
| 133 | return ""; |
| 134 | } |
| 135 | |
| 136 | std::string CommandLineFlag::Filename() const { |
| 137 | return flags_internal::GetUsageConfig().normalize_filename(filename_); |
| 138 | } |
| 139 | |
| 140 | std::string CommandLineFlag::DefaultValue() const { |
| 141 | absl::MutexLock l(InitFlagIfNecessary()); |
| 142 | |
| 143 | return Unparse(marshalling_op_, def_); |
| 144 | } |
| 145 | |
| 146 | std::string CommandLineFlag::CurrentValue() const { |
| 147 | absl::MutexLock l(InitFlagIfNecessary()); |
| 148 | |
| 149 | return Unparse(marshalling_op_, cur_); |
| 150 | } |
| 151 | |
| 152 | // Attempts to parse supplied `value` string using parsing routine in the `flag` |
| 153 | // argument. If parsing is successful, it will try to validate that the parsed |
| 154 | // value is valid for the specified 'flag'. Finally this function stores the |
| 155 | // parsed value in 'dst' assuming it is a pointer to the flag's value type. In |
| 156 | // case if any error is encountered in either step, the error message is stored |
| 157 | // in 'err' |
| 158 | bool TryParseLocked(CommandLineFlag* flag, void* dst, absl::string_view value, |
| 159 | std::string* err) |
| 160 | ABSL_EXCLUSIVE_LOCKS_REQUIRED(flag->locks_->primary_mu) { |
| 161 | void* tentative_value = Clone(flag->op_, flag->def_); |
| 162 | std::string parse_err; |
| 163 | if (!Parse(flag->marshalling_op_, value, tentative_value, &parse_err)) { |
| 164 | auto type_name = flag->Typename(); |
| 165 | absl::string_view err_sep = parse_err.empty() ? "" : "; "; |
| 166 | absl::string_view typename_sep = type_name.empty() ? "" : " "; |
| 167 | *err = absl::StrCat("Illegal value '", value, "' specified for", |
| 168 | typename_sep, type_name, " flag '", flag->Name(), "'", |
| 169 | err_sep, parse_err); |
| 170 | Delete(flag->op_, tentative_value); |
| 171 | return false; |
| 172 | } |
| 173 | |
| 174 | if (!flag->InvokeValidator(tentative_value)) { |
| 175 | *err = absl::StrCat("Failed validation of new value '", |
| 176 | Unparse(flag->marshalling_op_, tentative_value), |
| 177 | "' for flag '", flag->Name(), "'"); |
| 178 | Delete(flag->op_, tentative_value); |
| 179 | return false; |
| 180 | } |
| 181 | |
| 182 | flag->counter_++; |
| 183 | Copy(flag->op_, tentative_value, dst); |
| 184 | Delete(flag->op_, tentative_value); |
| 185 | return true; |
| 186 | } |
| 187 | |
| 188 | // Sets the value of the flag based on specified string `value`. If the flag |
| 189 | // was successfully set to new value, it returns true. Otherwise, sets `err` |
| 190 | // to indicate the error, leaves the flag unchanged, and returns false. There |
| 191 | // are three ways to set the flag's value: |
| 192 | // * Update the current flag value |
| 193 | // * Update the flag's default value |
| 194 | // * Update the current flag value if it was never set before |
| 195 | // The mode is selected based on 'set_mode' parameter. |
| 196 | bool CommandLineFlag::SetFromString(absl::string_view value, |
| 197 | FlagSettingMode set_mode, |
| 198 | ValueSource source, std::string* err) { |
| 199 | if (IsRetired()) return false; |
| 200 | |
| 201 | absl::MutexLock l(InitFlagIfNecessary()); |
| 202 | |
| 203 | // Direct-access flags can be modified without going through the |
| 204 | // flag API. Detect such changes and update the flag->modified_ bit. |
| 205 | if (!IsAbseilFlag()) { |
| 206 | if (!modified_ && ChangedDirectly(this, cur_, def_)) { |
| 207 | modified_ = true; |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | switch (set_mode) { |
| 212 | case SET_FLAGS_VALUE: { |
| 213 | // set or modify the flag's value |
| 214 | if (!TryParseLocked(this, cur_, value, err)) return false; |
| 215 | modified_ = true; |
| 216 | UpdateCopy(this); |
| 217 | InvokeCallback(); |
| 218 | |
| 219 | if (source == kCommandLine) { |
| 220 | on_command_line_ = true; |
| 221 | } |
| 222 | break; |
| 223 | } |
| 224 | case SET_FLAG_IF_DEFAULT: { |
| 225 | // set the flag's value, but only if it hasn't been set by someone else |
| 226 | if (!modified_) { |
| 227 | if (!TryParseLocked(this, cur_, value, err)) return false; |
| 228 | modified_ = true; |
| 229 | UpdateCopy(this); |
| 230 | InvokeCallback(); |
| 231 | } else { |
| 232 | // TODO(rogeeff): review and fix this semantic. Currently we do not fail |
| 233 | // in this case if flag is modified. This is misleading since the flag's |
| 234 | // value is not updated even though we return true. |
| 235 | // *err = absl::StrCat(Name(), " is already set to ", |
| 236 | // CurrentValue(), "\n"); |
| 237 | // return false; |
| 238 | return true; |
| 239 | } |
| 240 | break; |
| 241 | } |
| 242 | case SET_FLAGS_DEFAULT: { |
| 243 | // modify the flag's default-value |
| 244 | if (!TryParseLocked(this, def_, value, err)) return false; |
| 245 | |
| 246 | if (!modified_) { |
| 247 | // Need to set both defvalue *and* current, in this case |
| 248 | Copy(op_, def_, cur_); |
| 249 | UpdateCopy(this); |
| 250 | InvokeCallback(); |
| 251 | } |
| 252 | break; |
| 253 | } |
| 254 | default: { |
| 255 | // unknown set_mode |
| 256 | assert(false); |
| 257 | return false; |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | return true; |
| 262 | } |
| 263 | |
| 264 | void CommandLineFlag::CheckDefaultValueParsingRoundtrip() const { |
| 265 | std::string v = DefaultValue(); |
| 266 | |
| 267 | absl::MutexLock lock(InitFlagIfNecessary()); |
| 268 | |
| 269 | void* dst = Clone(op_, def_); |
| 270 | std::string error; |
| 271 | if (!flags_internal::Parse(marshalling_op_, v, dst, &error)) { |
| 272 | ABSL_INTERNAL_LOG( |
| 273 | FATAL, |
| 274 | absl::StrCat("Flag ", Name(), " (from ", Filename(), |
| 275 | "): std::string form of default value '", v, |
| 276 | "' could not be parsed; error=", error)); |
| 277 | } |
| 278 | |
| 279 | // We do not compare dst to def since parsing/unparsing may make |
| 280 | // small changes, e.g., precision loss for floating point types. |
| 281 | Delete(op_, dst); |
| 282 | } |
| 283 | |
| 284 | bool CommandLineFlag::ValidateDefaultValue() const { |
| 285 | absl::MutexLock lock(InitFlagIfNecessary()); |
| 286 | return InvokeValidator(def_); |
| 287 | } |
| 288 | |
| 289 | bool CommandLineFlag::ValidateInputValue(absl::string_view value) const { |
| 290 | absl::MutexLock l(InitFlagIfNecessary()); // protect default value access |
| 291 | |
| 292 | void* obj = Clone(op_, def_); |
| 293 | std::string ignored_error; |
| 294 | const bool result = |
| 295 | flags_internal::Parse(marshalling_op_, value, obj, &ignored_error) && |
| 296 | InvokeValidator(obj); |
| 297 | Delete(op_, obj); |
| 298 | return result; |
| 299 | } |
| 300 | |
| 301 | void CommandLineFlag::Read(void* dst, |
| 302 | const flags_internal::FlagOpFn dst_op) const { |
| 303 | absl::ReaderMutexLock l(InitFlagIfNecessary()); |
| 304 | |
| 305 | // `dst_op` is the unmarshaling operation corresponding to the declaration |
| 306 | // visibile at the call site. `op` is the Flag's defined unmarshalling |
| 307 | // operation. They must match for this operation to be well-defined. |
| 308 | if (ABSL_PREDICT_FALSE(dst_op != op_)) { |
| 309 | ABSL_INTERNAL_LOG( |
| 310 | ERROR, |
| 311 | absl::StrCat("Flag '", Name(), |
| 312 | "' is defined as one type and declared as another")); |
| 313 | } |
| 314 | CopyConstruct(op_, cur_, dst); |
| 315 | } |
| 316 | |
| 317 | void CommandLineFlag::Write(const void* src, |
| 318 | const flags_internal::FlagOpFn src_op) { |
| 319 | absl::MutexLock l(InitFlagIfNecessary()); |
| 320 | |
| 321 | // `src_op` is the marshalling operation corresponding to the declaration |
| 322 | // visible at the call site. `op` is the Flag's defined marshalling operation. |
| 323 | // They must match for this operation to be well-defined. |
| 324 | if (ABSL_PREDICT_FALSE(src_op != op_)) { |
| 325 | ABSL_INTERNAL_LOG( |
| 326 | ERROR, |
| 327 | absl::StrCat("Flag '", Name(), |
| 328 | "' is defined as one type and declared as another")); |
| 329 | } |
| 330 | |
| 331 | if (ShouldValidateFlagValue(*this)) { |
| 332 | void* obj = Clone(op_, src); |
| 333 | std::string ignored_error; |
| 334 | std::string src_as_str = Unparse(marshalling_op_, src); |
| 335 | if (!Parse(marshalling_op_, src_as_str, obj, &ignored_error) || |
| 336 | !InvokeValidator(obj)) { |
| 337 | ABSL_INTERNAL_LOG(ERROR, absl::StrCat("Attempt to set flag '", Name(), |
| 338 | "' to invalid value ", src_as_str)); |
| 339 | } |
| 340 | Delete(op_, obj); |
| 341 | } |
| 342 | |
| 343 | modified_ = true; |
| 344 | counter_++; |
| 345 | Copy(op_, src, cur_); |
| 346 | |
| 347 | UpdateCopy(this); |
| 348 | InvokeCallback(); |
| 349 | } |
| 350 | |
| 351 | std::string HelpText::GetHelpText() const { |
| 352 | if (help_function_) return help_function_(); |
| 353 | if (help_message_) return help_message_; |
| 354 | |
| 355 | return {}; |
| 356 | } |
| 357 | |
| 358 | // Update any copy of the flag value that is stored in an atomic word. |
| 359 | // In addition if flag has a mutation callback this function invokes it. |
| 360 | void UpdateCopy(CommandLineFlag* flag) { |
| 361 | #define STORE_ATOMIC(T) \ |
| 362 | else if (flag->IsOfType<T>()) { \ |
| 363 | flag->StoreAtomic(); \ |
| 364 | } |
| 365 | |
| 366 | if (false) { |
| 367 | } |
| 368 | ABSL_FLAGS_INTERNAL_FOR_EACH_LOCK_FREE(STORE_ATOMIC) |
| 369 | #undef STORE_ATOMIC |
| 370 | } |
| 371 | |
| 372 | // Return true iff flag value was changed via direct-access. |
| 373 | bool ChangedDirectly(CommandLineFlag* flag, const void* a, const void* b) { |
| 374 | if (!flag->IsAbseilFlag()) { |
| 375 | // Need to compare values for direct-access flags. |
| 376 | #define CHANGED_FOR_TYPE(T) \ |
| 377 | if (flag->IsOfType<T>()) { \ |
| 378 | return *reinterpret_cast<const T*>(a) != *reinterpret_cast<const T*>(b); \ |
| 379 | } |
| 380 | |
| 381 | CHANGED_FOR_TYPE(bool); |
| 382 | CHANGED_FOR_TYPE(int32_t); |
| 383 | CHANGED_FOR_TYPE(int64_t); |
| 384 | CHANGED_FOR_TYPE(uint64_t); |
| 385 | CHANGED_FOR_TYPE(double); |
| 386 | CHANGED_FOR_TYPE(std::string); |
| 387 | #undef CHANGED_FOR_TYPE |
| 388 | } |
| 389 | |
| 390 | return false; |
| 391 | } |
| 392 | |
| 393 | } // namespace flags_internal |
| 394 | } // namespace absl |