status_internal.cc 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. // Copyright 2023 The Abseil Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "absl/status/internal/status_internal.h"
  15. #include <atomic>
  16. #include <cassert>
  17. #include <cstddef>
  18. #include <cstdint>
  19. #include <cstdio>
  20. #include <cstring>
  21. #include <memory>
  22. #include <string>
  23. #include <utility>
  24. #include "absl/base/attributes.h"
  25. #include "absl/base/config.h"
  26. #include "absl/base/macros.h"
  27. #include "absl/base/nullability.h"
  28. #include "absl/debugging/stacktrace.h"
  29. #include "absl/debugging/symbolize.h"
  30. #include "absl/memory/memory.h"
  31. #include "absl/status/status.h"
  32. #include "absl/status/status_payload_printer.h"
  33. #include "absl/strings/cord.h"
  34. #include "absl/strings/escaping.h"
  35. #include "absl/strings/str_cat.h"
  36. #include "absl/strings/str_format.h"
  37. #include "absl/strings/str_split.h"
  38. #include "absl/strings/string_view.h"
  39. #include "absl/types/optional.h"
  40. namespace absl {
  41. ABSL_NAMESPACE_BEGIN
  42. namespace status_internal {
  43. void StatusRep::Unref() const {
  44. // Fast path: if ref==1, there is no need for a RefCountDec (since
  45. // this is the only reference and therefore no other thread is
  46. // allowed to be mucking with r).
  47. if (ref_.load(std::memory_order_acquire) == 1 ||
  48. ref_.fetch_sub(1, std::memory_order_acq_rel) - 1 == 0) {
  49. delete this;
  50. }
  51. }
  52. static absl::optional<size_t> FindPayloadIndexByUrl(
  53. const Payloads* payloads, absl::string_view type_url) {
  54. if (payloads == nullptr) return absl::nullopt;
  55. for (size_t i = 0; i < payloads->size(); ++i) {
  56. if ((*payloads)[i].type_url == type_url) return i;
  57. }
  58. return absl::nullopt;
  59. }
  60. absl::optional<absl::Cord> StatusRep::GetPayload(
  61. absl::string_view type_url) const {
  62. absl::optional<size_t> index =
  63. status_internal::FindPayloadIndexByUrl(payloads_.get(), type_url);
  64. if (index.has_value()) return (*payloads_)[index.value()].payload;
  65. return absl::nullopt;
  66. }
  67. void StatusRep::SetPayload(absl::string_view type_url, absl::Cord payload) {
  68. if (payloads_ == nullptr) {
  69. payloads_ = absl::make_unique<status_internal::Payloads>();
  70. }
  71. absl::optional<size_t> index =
  72. status_internal::FindPayloadIndexByUrl(payloads_.get(), type_url);
  73. if (index.has_value()) {
  74. (*payloads_)[index.value()].payload = std::move(payload);
  75. return;
  76. }
  77. payloads_->push_back({std::string(type_url), std::move(payload)});
  78. }
  79. StatusRep::EraseResult StatusRep::ErasePayload(absl::string_view type_url) {
  80. absl::optional<size_t> index =
  81. status_internal::FindPayloadIndexByUrl(payloads_.get(), type_url);
  82. if (!index.has_value()) return {false, Status::PointerToRep(this)};
  83. payloads_->erase(payloads_->begin() + index.value());
  84. if (payloads_->empty() && message_.empty()) {
  85. // Special case: If this can be represented inlined, it MUST be inlined
  86. // (== depends on this behavior).
  87. EraseResult result = {true, Status::CodeToInlinedRep(code_)};
  88. Unref();
  89. return result;
  90. }
  91. return {true, Status::PointerToRep(this)};
  92. }
  93. void StatusRep::ForEachPayload(
  94. absl::FunctionRef<void(absl::string_view, const absl::Cord&)> visitor)
  95. const {
  96. if (auto* payloads = payloads_.get()) {
  97. bool in_reverse =
  98. payloads->size() > 1 && reinterpret_cast<uintptr_t>(payloads) % 13 > 6;
  99. for (size_t index = 0; index < payloads->size(); ++index) {
  100. const auto& elem =
  101. (*payloads)[in_reverse ? payloads->size() - 1 - index : index];
  102. #ifdef NDEBUG
  103. visitor(elem.type_url, elem.payload);
  104. #else
  105. // In debug mode invalidate the type url to prevent users from relying on
  106. // this string lifetime.
  107. // NOLINTNEXTLINE intentional extra conversion to force temporary.
  108. visitor(std::string(elem.type_url), elem.payload);
  109. #endif // NDEBUG
  110. }
  111. }
  112. }
  113. std::string StatusRep::ToString(StatusToStringMode mode) const {
  114. std::string text;
  115. absl::StrAppend(&text, absl::StatusCodeToString(code()), ": ", message());
  116. const bool with_payload = (mode & StatusToStringMode::kWithPayload) ==
  117. StatusToStringMode::kWithPayload;
  118. if (with_payload) {
  119. status_internal::StatusPayloadPrinter printer =
  120. status_internal::GetStatusPayloadPrinter();
  121. this->ForEachPayload([&](absl::string_view type_url,
  122. const absl::Cord& payload) {
  123. absl::optional<std::string> result;
  124. if (printer) result = printer(type_url, payload);
  125. absl::StrAppend(
  126. &text, " [", type_url, "='",
  127. result.has_value() ? *result : absl::CHexEscape(std::string(payload)),
  128. "']");
  129. });
  130. }
  131. return text;
  132. }
  133. bool StatusRep::operator==(const StatusRep& other) const {
  134. assert(this != &other);
  135. if (code_ != other.code_) return false;
  136. if (message_ != other.message_) return false;
  137. const status_internal::Payloads* this_payloads = payloads_.get();
  138. const status_internal::Payloads* other_payloads = other.payloads_.get();
  139. const status_internal::Payloads no_payloads;
  140. const status_internal::Payloads* larger_payloads =
  141. this_payloads ? this_payloads : &no_payloads;
  142. const status_internal::Payloads* smaller_payloads =
  143. other_payloads ? other_payloads : &no_payloads;
  144. if (larger_payloads->size() < smaller_payloads->size()) {
  145. std::swap(larger_payloads, smaller_payloads);
  146. }
  147. if ((larger_payloads->size() - smaller_payloads->size()) > 1) return false;
  148. // Payloads can be ordered differently, so we can't just compare payload
  149. // vectors.
  150. for (const auto& payload : *larger_payloads) {
  151. bool found = false;
  152. for (const auto& other_payload : *smaller_payloads) {
  153. if (payload.type_url == other_payload.type_url) {
  154. if (payload.payload != other_payload.payload) {
  155. return false;
  156. }
  157. found = true;
  158. break;
  159. }
  160. }
  161. if (!found) return false;
  162. }
  163. return true;
  164. }
  165. absl::Nonnull<StatusRep*> StatusRep::CloneAndUnref() const {
  166. // Optimization: no need to create a clone if we already have a refcount of 1.
  167. if (ref_.load(std::memory_order_acquire) == 1) {
  168. // All StatusRep instances are heap allocated and mutable, therefore this
  169. // const_cast will never cast away const from a stack instance.
  170. //
  171. // CloneAndUnref is the only method that doesn't involve an external cast to
  172. // get a mutable StatusRep* from the uintptr_t rep stored in Status.
  173. return const_cast<StatusRep*>(this);
  174. }
  175. std::unique_ptr<status_internal::Payloads> payloads;
  176. if (payloads_) {
  177. payloads = absl::make_unique<status_internal::Payloads>(*payloads_);
  178. }
  179. auto* new_rep = new StatusRep(code_, message_, std::move(payloads));
  180. Unref();
  181. return new_rep;
  182. }
  183. // Convert canonical code to a value known to this binary.
  184. absl::StatusCode MapToLocalCode(int value) {
  185. absl::StatusCode code = static_cast<absl::StatusCode>(value);
  186. switch (code) {
  187. case absl::StatusCode::kOk:
  188. case absl::StatusCode::kCancelled:
  189. case absl::StatusCode::kUnknown:
  190. case absl::StatusCode::kInvalidArgument:
  191. case absl::StatusCode::kDeadlineExceeded:
  192. case absl::StatusCode::kNotFound:
  193. case absl::StatusCode::kAlreadyExists:
  194. case absl::StatusCode::kPermissionDenied:
  195. case absl::StatusCode::kResourceExhausted:
  196. case absl::StatusCode::kFailedPrecondition:
  197. case absl::StatusCode::kAborted:
  198. case absl::StatusCode::kOutOfRange:
  199. case absl::StatusCode::kUnimplemented:
  200. case absl::StatusCode::kInternal:
  201. case absl::StatusCode::kUnavailable:
  202. case absl::StatusCode::kDataLoss:
  203. case absl::StatusCode::kUnauthenticated:
  204. return code;
  205. default:
  206. return absl::StatusCode::kUnknown;
  207. }
  208. }
  209. absl::Nonnull<std::string*> MakeCheckFailString(
  210. absl::Nonnull<const absl::Status*> status,
  211. absl::Nonnull<const char*> prefix) {
  212. return new std::string(
  213. absl::StrCat(prefix, " (",
  214. status->ToString(StatusToStringMode::kWithEverything), ")"));
  215. }
  216. } // namespace status_internal
  217. ABSL_NAMESPACE_END
  218. } // namespace absl