1 // Copyright 2019 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/status.h"
15
16 #include <cassert>
17
18 #include "absl/base/internal/raw_logging.h"
19 #include "absl/debugging/stacktrace.h"
20 #include "absl/debugging/symbolize.h"
21 #include "absl/status/status_payload_printer.h"
22 #include "absl/strings/escaping.h"
23 #include "absl/strings/str_cat.h"
24 #include "absl/strings/str_format.h"
25 #include "absl/strings/str_split.h"
26
27 namespace absl {
28 ABSL_NAMESPACE_BEGIN
29
StatusCodeToString(StatusCode code)30 std::string StatusCodeToString(StatusCode code) {
31 switch (code) {
32 case StatusCode::kOk:
33 return "OK";
34 case StatusCode::kCancelled:
35 return "CANCELLED";
36 case StatusCode::kUnknown:
37 return "UNKNOWN";
38 case StatusCode::kInvalidArgument:
39 return "INVALID_ARGUMENT";
40 case StatusCode::kDeadlineExceeded:
41 return "DEADLINE_EXCEEDED";
42 case StatusCode::kNotFound:
43 return "NOT_FOUND";
44 case StatusCode::kAlreadyExists:
45 return "ALREADY_EXISTS";
46 case StatusCode::kPermissionDenied:
47 return "PERMISSION_DENIED";
48 case StatusCode::kUnauthenticated:
49 return "UNAUTHENTICATED";
50 case StatusCode::kResourceExhausted:
51 return "RESOURCE_EXHAUSTED";
52 case StatusCode::kFailedPrecondition:
53 return "FAILED_PRECONDITION";
54 case StatusCode::kAborted:
55 return "ABORTED";
56 case StatusCode::kOutOfRange:
57 return "OUT_OF_RANGE";
58 case StatusCode::kUnimplemented:
59 return "UNIMPLEMENTED";
60 case StatusCode::kInternal:
61 return "INTERNAL";
62 case StatusCode::kUnavailable:
63 return "UNAVAILABLE";
64 case StatusCode::kDataLoss:
65 return "DATA_LOSS";
66 default:
67 return "";
68 }
69 }
70
operator <<(std::ostream & os,StatusCode code)71 std::ostream& operator<<(std::ostream& os, StatusCode code) {
72 return os << StatusCodeToString(code);
73 }
74
75 namespace status_internal {
76
FindPayloadIndexByUrl(const Payloads * payloads,absl::string_view type_url)77 static int FindPayloadIndexByUrl(const Payloads* payloads,
78 absl::string_view type_url) {
79 if (payloads == nullptr) return -1;
80
81 for (size_t i = 0; i < payloads->size(); ++i) {
82 if ((*payloads)[i].type_url == type_url) return i;
83 }
84
85 return -1;
86 }
87
88 // Convert canonical code to a value known to this binary.
MapToLocalCode(int value)89 absl::StatusCode MapToLocalCode(int value) {
90 absl::StatusCode code = static_cast<absl::StatusCode>(value);
91 switch (code) {
92 case absl::StatusCode::kOk:
93 case absl::StatusCode::kCancelled:
94 case absl::StatusCode::kUnknown:
95 case absl::StatusCode::kInvalidArgument:
96 case absl::StatusCode::kDeadlineExceeded:
97 case absl::StatusCode::kNotFound:
98 case absl::StatusCode::kAlreadyExists:
99 case absl::StatusCode::kPermissionDenied:
100 case absl::StatusCode::kResourceExhausted:
101 case absl::StatusCode::kFailedPrecondition:
102 case absl::StatusCode::kAborted:
103 case absl::StatusCode::kOutOfRange:
104 case absl::StatusCode::kUnimplemented:
105 case absl::StatusCode::kInternal:
106 case absl::StatusCode::kUnavailable:
107 case absl::StatusCode::kDataLoss:
108 case absl::StatusCode::kUnauthenticated:
109 return code;
110 default:
111 return absl::StatusCode::kUnknown;
112 }
113 }
114 } // namespace status_internal
115
GetPayload(absl::string_view type_url) const116 absl::optional<absl::Cord> Status::GetPayload(
117 absl::string_view type_url) const {
118 const auto* payloads = GetPayloads();
119 int index = status_internal::FindPayloadIndexByUrl(payloads, type_url);
120 if (index != -1) return (*payloads)[index].payload;
121
122 return absl::nullopt;
123 }
124
SetPayload(absl::string_view type_url,absl::Cord payload)125 void Status::SetPayload(absl::string_view type_url, absl::Cord payload) {
126 if (ok()) return;
127
128 PrepareToModify();
129
130 status_internal::StatusRep* rep = RepToPointer(rep_);
131 if (!rep->payloads) {
132 rep->payloads = absl::make_unique<status_internal::Payloads>();
133 }
134
135 int index =
136 status_internal::FindPayloadIndexByUrl(rep->payloads.get(), type_url);
137 if (index != -1) {
138 (*rep->payloads)[index].payload = std::move(payload);
139 return;
140 }
141
142 rep->payloads->push_back({std::string(type_url), std::move(payload)});
143 }
144
ErasePayload(absl::string_view type_url)145 bool Status::ErasePayload(absl::string_view type_url) {
146 int index = status_internal::FindPayloadIndexByUrl(GetPayloads(), type_url);
147 if (index != -1) {
148 PrepareToModify();
149 GetPayloads()->erase(GetPayloads()->begin() + index);
150 if (GetPayloads()->empty() && message().empty()) {
151 // Special case: If this can be represented inlined, it MUST be
152 // inlined (EqualsSlow depends on this behavior).
153 StatusCode c = static_cast<StatusCode>(raw_code());
154 Unref(rep_);
155 rep_ = CodeToInlinedRep(c);
156 }
157 return true;
158 }
159
160 return false;
161 }
162
ForEachPayload(const std::function<void (absl::string_view,const absl::Cord &)> & visitor) const163 void Status::ForEachPayload(
164 const std::function<void(absl::string_view, const absl::Cord&)>& visitor)
165 const {
166 if (auto* payloads = GetPayloads()) {
167 bool in_reverse =
168 payloads->size() > 1 && reinterpret_cast<uintptr_t>(payloads) % 13 > 6;
169
170 for (size_t index = 0; index < payloads->size(); ++index) {
171 const auto& elem =
172 (*payloads)[in_reverse ? payloads->size() - 1 - index : index];
173
174 #ifdef NDEBUG
175 visitor(elem.type_url, elem.payload);
176 #else
177 // In debug mode invalidate the type url to prevent users from relying on
178 // this string lifetime.
179
180 // NOLINTNEXTLINE intentional extra conversion to force temporary.
181 visitor(std::string(elem.type_url), elem.payload);
182 #endif // NDEBUG
183 }
184 }
185 }
186
EmptyString()187 const std::string* Status::EmptyString() {
188 static std::string* empty_string = new std::string();
189 return empty_string;
190 }
191
192 constexpr const char Status::kMovedFromString[];
193
MovedFromString()194 const std::string* Status::MovedFromString() {
195 static std::string* moved_from_string = new std::string(kMovedFromString);
196 return moved_from_string;
197 }
198
UnrefNonInlined(uintptr_t rep)199 void Status::UnrefNonInlined(uintptr_t rep) {
200 status_internal::StatusRep* r = RepToPointer(rep);
201 // Fast path: if ref==1, there is no need for a RefCountDec (since
202 // this is the only reference and therefore no other thread is
203 // allowed to be mucking with r).
204 if (r->ref.load(std::memory_order_acquire) == 1 ||
205 r->ref.fetch_sub(1, std::memory_order_acq_rel) - 1 == 0) {
206 delete r;
207 }
208 }
209
Status(absl::StatusCode code,absl::string_view msg)210 Status::Status(absl::StatusCode code, absl::string_view msg)
211 : rep_(CodeToInlinedRep(code)) {
212 if (code != absl::StatusCode::kOk && !msg.empty()) {
213 rep_ = PointerToRep(new status_internal::StatusRep(code, msg, nullptr));
214 }
215 }
216
raw_code() const217 int Status::raw_code() const {
218 if (IsInlined(rep_)) {
219 return static_cast<int>(InlinedRepToCode(rep_));
220 }
221 status_internal::StatusRep* rep = RepToPointer(rep_);
222 return static_cast<int>(rep->code);
223 }
224
code() const225 absl::StatusCode Status::code() const {
226 return status_internal::MapToLocalCode(raw_code());
227 }
228
PrepareToModify()229 void Status::PrepareToModify() {
230 ABSL_RAW_CHECK(!ok(), "PrepareToModify shouldn't be called on OK status.");
231 if (IsInlined(rep_)) {
232 rep_ = PointerToRep(new status_internal::StatusRep(
233 static_cast<absl::StatusCode>(raw_code()), absl::string_view(),
234 nullptr));
235 return;
236 }
237
238 uintptr_t rep_i = rep_;
239 status_internal::StatusRep* rep = RepToPointer(rep_);
240 if (rep->ref.load(std::memory_order_acquire) != 1) {
241 std::unique_ptr<status_internal::Payloads> payloads;
242 if (rep->payloads) {
243 payloads = absl::make_unique<status_internal::Payloads>(*rep->payloads);
244 }
245 status_internal::StatusRep* const new_rep = new status_internal::StatusRep(
246 rep->code, message(), std::move(payloads));
247 rep_ = PointerToRep(new_rep);
248 UnrefNonInlined(rep_i);
249 }
250 }
251
EqualsSlow(const absl::Status & a,const absl::Status & b)252 bool Status::EqualsSlow(const absl::Status& a, const absl::Status& b) {
253 if (IsInlined(a.rep_) != IsInlined(b.rep_)) return false;
254 if (a.message() != b.message()) return false;
255 if (a.raw_code() != b.raw_code()) return false;
256 if (a.GetPayloads() == b.GetPayloads()) return true;
257
258 const status_internal::Payloads no_payloads;
259 const status_internal::Payloads* larger_payloads =
260 a.GetPayloads() ? a.GetPayloads() : &no_payloads;
261 const status_internal::Payloads* smaller_payloads =
262 b.GetPayloads() ? b.GetPayloads() : &no_payloads;
263 if (larger_payloads->size() < smaller_payloads->size()) {
264 std::swap(larger_payloads, smaller_payloads);
265 }
266 if ((larger_payloads->size() - smaller_payloads->size()) > 1) return false;
267 // Payloads can be ordered differently, so we can't just compare payload
268 // vectors.
269 for (const auto& payload : *larger_payloads) {
270
271 bool found = false;
272 for (const auto& other_payload : *smaller_payloads) {
273 if (payload.type_url == other_payload.type_url) {
274 if (payload.payload != other_payload.payload) {
275 return false;
276 }
277 found = true;
278 break;
279 }
280 }
281 if (!found) return false;
282 }
283 return true;
284 }
285
ToStringSlow(StatusToStringMode mode) const286 std::string Status::ToStringSlow(StatusToStringMode mode) const {
287 std::string text;
288 absl::StrAppend(&text, absl::StatusCodeToString(code()), ": ", message());
289
290 const bool with_payload = (mode & StatusToStringMode::kWithPayload) ==
291 StatusToStringMode::kWithPayload;
292
293 if (with_payload) {
294 status_internal::StatusPayloadPrinter printer =
295 status_internal::GetStatusPayloadPrinter();
296 this->ForEachPayload([&](absl::string_view type_url,
297 const absl::Cord& payload) {
298 absl::optional<std::string> result;
299 if (printer) result = printer(type_url, payload);
300 absl::StrAppend(
301 &text, " [", type_url, "='",
302 result.has_value() ? *result : absl::CHexEscape(std::string(payload)),
303 "']");
304 });
305 }
306
307 return text;
308 }
309
operator <<(std::ostream & os,const Status & x)310 std::ostream& operator<<(std::ostream& os, const Status& x) {
311 os << x.ToString(StatusToStringMode::kWithEverything);
312 return os;
313 }
314
AbortedError(absl::string_view message)315 Status AbortedError(absl::string_view message) {
316 return Status(absl::StatusCode::kAborted, message);
317 }
318
AlreadyExistsError(absl::string_view message)319 Status AlreadyExistsError(absl::string_view message) {
320 return Status(absl::StatusCode::kAlreadyExists, message);
321 }
322
CancelledError(absl::string_view message)323 Status CancelledError(absl::string_view message) {
324 return Status(absl::StatusCode::kCancelled, message);
325 }
326
DataLossError(absl::string_view message)327 Status DataLossError(absl::string_view message) {
328 return Status(absl::StatusCode::kDataLoss, message);
329 }
330
DeadlineExceededError(absl::string_view message)331 Status DeadlineExceededError(absl::string_view message) {
332 return Status(absl::StatusCode::kDeadlineExceeded, message);
333 }
334
FailedPreconditionError(absl::string_view message)335 Status FailedPreconditionError(absl::string_view message) {
336 return Status(absl::StatusCode::kFailedPrecondition, message);
337 }
338
InternalError(absl::string_view message)339 Status InternalError(absl::string_view message) {
340 return Status(absl::StatusCode::kInternal, message);
341 }
342
InvalidArgumentError(absl::string_view message)343 Status InvalidArgumentError(absl::string_view message) {
344 return Status(absl::StatusCode::kInvalidArgument, message);
345 }
346
NotFoundError(absl::string_view message)347 Status NotFoundError(absl::string_view message) {
348 return Status(absl::StatusCode::kNotFound, message);
349 }
350
OutOfRangeError(absl::string_view message)351 Status OutOfRangeError(absl::string_view message) {
352 return Status(absl::StatusCode::kOutOfRange, message);
353 }
354
PermissionDeniedError(absl::string_view message)355 Status PermissionDeniedError(absl::string_view message) {
356 return Status(absl::StatusCode::kPermissionDenied, message);
357 }
358
ResourceExhaustedError(absl::string_view message)359 Status ResourceExhaustedError(absl::string_view message) {
360 return Status(absl::StatusCode::kResourceExhausted, message);
361 }
362
UnauthenticatedError(absl::string_view message)363 Status UnauthenticatedError(absl::string_view message) {
364 return Status(absl::StatusCode::kUnauthenticated, message);
365 }
366
UnavailableError(absl::string_view message)367 Status UnavailableError(absl::string_view message) {
368 return Status(absl::StatusCode::kUnavailable, message);
369 }
370
UnimplementedError(absl::string_view message)371 Status UnimplementedError(absl::string_view message) {
372 return Status(absl::StatusCode::kUnimplemented, message);
373 }
374
UnknownError(absl::string_view message)375 Status UnknownError(absl::string_view message) {
376 return Status(absl::StatusCode::kUnknown, message);
377 }
378
IsAborted(const Status & status)379 bool IsAborted(const Status& status) {
380 return status.code() == absl::StatusCode::kAborted;
381 }
382
IsAlreadyExists(const Status & status)383 bool IsAlreadyExists(const Status& status) {
384 return status.code() == absl::StatusCode::kAlreadyExists;
385 }
386
IsCancelled(const Status & status)387 bool IsCancelled(const Status& status) {
388 return status.code() == absl::StatusCode::kCancelled;
389 }
390
IsDataLoss(const Status & status)391 bool IsDataLoss(const Status& status) {
392 return status.code() == absl::StatusCode::kDataLoss;
393 }
394
IsDeadlineExceeded(const Status & status)395 bool IsDeadlineExceeded(const Status& status) {
396 return status.code() == absl::StatusCode::kDeadlineExceeded;
397 }
398
IsFailedPrecondition(const Status & status)399 bool IsFailedPrecondition(const Status& status) {
400 return status.code() == absl::StatusCode::kFailedPrecondition;
401 }
402
IsInternal(const Status & status)403 bool IsInternal(const Status& status) {
404 return status.code() == absl::StatusCode::kInternal;
405 }
406
IsInvalidArgument(const Status & status)407 bool IsInvalidArgument(const Status& status) {
408 return status.code() == absl::StatusCode::kInvalidArgument;
409 }
410
IsNotFound(const Status & status)411 bool IsNotFound(const Status& status) {
412 return status.code() == absl::StatusCode::kNotFound;
413 }
414
IsOutOfRange(const Status & status)415 bool IsOutOfRange(const Status& status) {
416 return status.code() == absl::StatusCode::kOutOfRange;
417 }
418
IsPermissionDenied(const Status & status)419 bool IsPermissionDenied(const Status& status) {
420 return status.code() == absl::StatusCode::kPermissionDenied;
421 }
422
IsResourceExhausted(const Status & status)423 bool IsResourceExhausted(const Status& status) {
424 return status.code() == absl::StatusCode::kResourceExhausted;
425 }
426
IsUnauthenticated(const Status & status)427 bool IsUnauthenticated(const Status& status) {
428 return status.code() == absl::StatusCode::kUnauthenticated;
429 }
430
IsUnavailable(const Status & status)431 bool IsUnavailable(const Status& status) {
432 return status.code() == absl::StatusCode::kUnavailable;
433 }
434
IsUnimplemented(const Status & status)435 bool IsUnimplemented(const Status& status) {
436 return status.code() == absl::StatusCode::kUnimplemented;
437 }
438
IsUnknown(const Status & status)439 bool IsUnknown(const Status& status) {
440 return status.code() == absl::StatusCode::kUnknown;
441 }
442
443 ABSL_NAMESPACE_END
444 } // namespace absl
445