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 <errno.h>
17
18 #include <cassert>
19 #include <utility>
20
21 #include "absl/base/internal/raw_logging.h"
22 #include "absl/base/internal/strerror.h"
23 #include "absl/debugging/stacktrace.h"
24 #include "absl/debugging/symbolize.h"
25 #include "absl/status/status_payload_printer.h"
26 #include "absl/strings/escaping.h"
27 #include "absl/strings/str_cat.h"
28 #include "absl/strings/str_format.h"
29 #include "absl/strings/str_split.h"
30
31 namespace absl {
32 ABSL_NAMESPACE_BEGIN
33
StatusCodeToString(StatusCode code)34 std::string StatusCodeToString(StatusCode code) {
35 switch (code) {
36 case StatusCode::kOk:
37 return "OK";
38 case StatusCode::kCancelled:
39 return "CANCELLED";
40 case StatusCode::kUnknown:
41 return "UNKNOWN";
42 case StatusCode::kInvalidArgument:
43 return "INVALID_ARGUMENT";
44 case StatusCode::kDeadlineExceeded:
45 return "DEADLINE_EXCEEDED";
46 case StatusCode::kNotFound:
47 return "NOT_FOUND";
48 case StatusCode::kAlreadyExists:
49 return "ALREADY_EXISTS";
50 case StatusCode::kPermissionDenied:
51 return "PERMISSION_DENIED";
52 case StatusCode::kUnauthenticated:
53 return "UNAUTHENTICATED";
54 case StatusCode::kResourceExhausted:
55 return "RESOURCE_EXHAUSTED";
56 case StatusCode::kFailedPrecondition:
57 return "FAILED_PRECONDITION";
58 case StatusCode::kAborted:
59 return "ABORTED";
60 case StatusCode::kOutOfRange:
61 return "OUT_OF_RANGE";
62 case StatusCode::kUnimplemented:
63 return "UNIMPLEMENTED";
64 case StatusCode::kInternal:
65 return "INTERNAL";
66 case StatusCode::kUnavailable:
67 return "UNAVAILABLE";
68 case StatusCode::kDataLoss:
69 return "DATA_LOSS";
70 default:
71 return "";
72 }
73 }
74
operator <<(std::ostream & os,StatusCode code)75 std::ostream& operator<<(std::ostream& os, StatusCode code) {
76 return os << StatusCodeToString(code);
77 }
78
79 namespace status_internal {
80
FindPayloadIndexByUrl(const Payloads * payloads,absl::string_view type_url)81 static absl::optional<size_t> FindPayloadIndexByUrl(
82 const Payloads* payloads,
83 absl::string_view type_url) {
84 if (payloads == nullptr)
85 return absl::nullopt;
86
87 for (size_t i = 0; i < payloads->size(); ++i) {
88 if ((*payloads)[i].type_url == type_url) return i;
89 }
90
91 return absl::nullopt;
92 }
93
94 // Convert canonical code to a value known to this binary.
MapToLocalCode(int value)95 absl::StatusCode MapToLocalCode(int value) {
96 absl::StatusCode code = static_cast<absl::StatusCode>(value);
97 switch (code) {
98 case absl::StatusCode::kOk:
99 case absl::StatusCode::kCancelled:
100 case absl::StatusCode::kUnknown:
101 case absl::StatusCode::kInvalidArgument:
102 case absl::StatusCode::kDeadlineExceeded:
103 case absl::StatusCode::kNotFound:
104 case absl::StatusCode::kAlreadyExists:
105 case absl::StatusCode::kPermissionDenied:
106 case absl::StatusCode::kResourceExhausted:
107 case absl::StatusCode::kFailedPrecondition:
108 case absl::StatusCode::kAborted:
109 case absl::StatusCode::kOutOfRange:
110 case absl::StatusCode::kUnimplemented:
111 case absl::StatusCode::kInternal:
112 case absl::StatusCode::kUnavailable:
113 case absl::StatusCode::kDataLoss:
114 case absl::StatusCode::kUnauthenticated:
115 return code;
116 default:
117 return absl::StatusCode::kUnknown;
118 }
119 }
120 } // namespace status_internal
121
GetPayload(absl::string_view type_url) const122 absl::optional<absl::Cord> Status::GetPayload(
123 absl::string_view type_url) const {
124 const auto* payloads = GetPayloads();
125 absl::optional<size_t> index =
126 status_internal::FindPayloadIndexByUrl(payloads, type_url);
127 if (index.has_value())
128 return (*payloads)[index.value()].payload;
129
130 return absl::nullopt;
131 }
132
SetPayload(absl::string_view type_url,absl::Cord payload)133 void Status::SetPayload(absl::string_view type_url, absl::Cord payload) {
134 if (ok()) return;
135
136 PrepareToModify();
137
138 status_internal::StatusRep* rep = RepToPointer(rep_);
139 if (!rep->payloads) {
140 rep->payloads = absl::make_unique<status_internal::Payloads>();
141 }
142
143 absl::optional<size_t> index =
144 status_internal::FindPayloadIndexByUrl(rep->payloads.get(), type_url);
145 if (index.has_value()) {
146 (*rep->payloads)[index.value()].payload = std::move(payload);
147 return;
148 }
149
150 rep->payloads->push_back({std::string(type_url), std::move(payload)});
151 }
152
ErasePayload(absl::string_view type_url)153 bool Status::ErasePayload(absl::string_view type_url) {
154 absl::optional<size_t> index =
155 status_internal::FindPayloadIndexByUrl(GetPayloads(), type_url);
156 if (index.has_value()) {
157 PrepareToModify();
158 GetPayloads()->erase(GetPayloads()->begin() + index.value());
159 if (GetPayloads()->empty() && message().empty()) {
160 // Special case: If this can be represented inlined, it MUST be
161 // inlined (EqualsSlow depends on this behavior).
162 StatusCode c = static_cast<StatusCode>(raw_code());
163 Unref(rep_);
164 rep_ = CodeToInlinedRep(c);
165 }
166 return true;
167 }
168
169 return false;
170 }
171
ForEachPayload(absl::FunctionRef<void (absl::string_view,const absl::Cord &)> visitor) const172 void Status::ForEachPayload(
173 absl::FunctionRef<void(absl::string_view, const absl::Cord&)> visitor)
174 const {
175 if (auto* payloads = GetPayloads()) {
176 bool in_reverse =
177 payloads->size() > 1 && reinterpret_cast<uintptr_t>(payloads) % 13 > 6;
178
179 for (size_t index = 0; index < payloads->size(); ++index) {
180 const auto& elem =
181 (*payloads)[in_reverse ? payloads->size() - 1 - index : index];
182
183 #ifdef NDEBUG
184 visitor(elem.type_url, elem.payload);
185 #else
186 // In debug mode invalidate the type url to prevent users from relying on
187 // this string lifetime.
188
189 // NOLINTNEXTLINE intentional extra conversion to force temporary.
190 visitor(std::string(elem.type_url), elem.payload);
191 #endif // NDEBUG
192 }
193 }
194 }
195
EmptyString()196 const std::string* Status::EmptyString() {
197 static union EmptyString {
198 std::string str;
199 ~EmptyString() {}
200 } empty = {{}};
201 return &empty.str;
202 }
203
204 #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
205 constexpr const char Status::kMovedFromString[];
206 #endif
207
MovedFromString()208 const std::string* Status::MovedFromString() {
209 static std::string* moved_from_string = new std::string(kMovedFromString);
210 return moved_from_string;
211 }
212
UnrefNonInlined(uintptr_t rep)213 void Status::UnrefNonInlined(uintptr_t rep) {
214 status_internal::StatusRep* r = RepToPointer(rep);
215 // Fast path: if ref==1, there is no need for a RefCountDec (since
216 // this is the only reference and therefore no other thread is
217 // allowed to be mucking with r).
218 if (r->ref.load(std::memory_order_acquire) == 1 ||
219 r->ref.fetch_sub(1, std::memory_order_acq_rel) - 1 == 0) {
220 delete r;
221 }
222 }
223
Status(absl::StatusCode code,absl::string_view msg)224 Status::Status(absl::StatusCode code, absl::string_view msg)
225 : rep_(CodeToInlinedRep(code)) {
226 if (code != absl::StatusCode::kOk && !msg.empty()) {
227 rep_ = PointerToRep(new status_internal::StatusRep(code, msg, nullptr));
228 }
229 }
230
raw_code() const231 int Status::raw_code() const {
232 if (IsInlined(rep_)) {
233 return static_cast<int>(InlinedRepToCode(rep_));
234 }
235 status_internal::StatusRep* rep = RepToPointer(rep_);
236 return static_cast<int>(rep->code);
237 }
238
code() const239 absl::StatusCode Status::code() const {
240 return status_internal::MapToLocalCode(raw_code());
241 }
242
PrepareToModify()243 void Status::PrepareToModify() {
244 ABSL_RAW_CHECK(!ok(), "PrepareToModify shouldn't be called on OK status.");
245 if (IsInlined(rep_)) {
246 rep_ = PointerToRep(new status_internal::StatusRep(
247 static_cast<absl::StatusCode>(raw_code()), absl::string_view(),
248 nullptr));
249 return;
250 }
251
252 uintptr_t rep_i = rep_;
253 status_internal::StatusRep* rep = RepToPointer(rep_);
254 if (rep->ref.load(std::memory_order_acquire) != 1) {
255 std::unique_ptr<status_internal::Payloads> payloads;
256 if (rep->payloads) {
257 payloads = absl::make_unique<status_internal::Payloads>(*rep->payloads);
258 }
259 status_internal::StatusRep* const new_rep = new status_internal::StatusRep(
260 rep->code, message(), std::move(payloads));
261 rep_ = PointerToRep(new_rep);
262 UnrefNonInlined(rep_i);
263 }
264 }
265
EqualsSlow(const absl::Status & a,const absl::Status & b)266 bool Status::EqualsSlow(const absl::Status& a, const absl::Status& b) {
267 if (IsInlined(a.rep_) != IsInlined(b.rep_)) return false;
268 if (a.message() != b.message()) return false;
269 if (a.raw_code() != b.raw_code()) return false;
270 if (a.GetPayloads() == b.GetPayloads()) return true;
271
272 const status_internal::Payloads no_payloads;
273 const status_internal::Payloads* larger_payloads =
274 a.GetPayloads() ? a.GetPayloads() : &no_payloads;
275 const status_internal::Payloads* smaller_payloads =
276 b.GetPayloads() ? b.GetPayloads() : &no_payloads;
277 if (larger_payloads->size() < smaller_payloads->size()) {
278 std::swap(larger_payloads, smaller_payloads);
279 }
280 if ((larger_payloads->size() - smaller_payloads->size()) > 1) return false;
281 // Payloads can be ordered differently, so we can't just compare payload
282 // vectors.
283 for (const auto& payload : *larger_payloads) {
284
285 bool found = false;
286 for (const auto& other_payload : *smaller_payloads) {
287 if (payload.type_url == other_payload.type_url) {
288 if (payload.payload != other_payload.payload) {
289 return false;
290 }
291 found = true;
292 break;
293 }
294 }
295 if (!found) return false;
296 }
297 return true;
298 }
299
ToStringSlow(StatusToStringMode mode) const300 std::string Status::ToStringSlow(StatusToStringMode mode) const {
301 std::string text;
302 absl::StrAppend(&text, absl::StatusCodeToString(code()), ": ", message());
303
304 const bool with_payload = (mode & StatusToStringMode::kWithPayload) ==
305 StatusToStringMode::kWithPayload;
306
307 if (with_payload) {
308 status_internal::StatusPayloadPrinter printer =
309 status_internal::GetStatusPayloadPrinter();
310 this->ForEachPayload([&](absl::string_view type_url,
311 const absl::Cord& payload) {
312 absl::optional<std::string> result;
313 if (printer) result = printer(type_url, payload);
314 absl::StrAppend(
315 &text, " [", type_url, "='",
316 result.has_value() ? *result : absl::CHexEscape(std::string(payload)),
317 "']");
318 });
319 }
320
321 return text;
322 }
323
operator <<(std::ostream & os,const Status & x)324 std::ostream& operator<<(std::ostream& os, const Status& x) {
325 os << x.ToString(StatusToStringMode::kWithEverything);
326 return os;
327 }
328
AbortedError(absl::string_view message)329 Status AbortedError(absl::string_view message) {
330 return Status(absl::StatusCode::kAborted, message);
331 }
332
AlreadyExistsError(absl::string_view message)333 Status AlreadyExistsError(absl::string_view message) {
334 return Status(absl::StatusCode::kAlreadyExists, message);
335 }
336
CancelledError(absl::string_view message)337 Status CancelledError(absl::string_view message) {
338 return Status(absl::StatusCode::kCancelled, message);
339 }
340
DataLossError(absl::string_view message)341 Status DataLossError(absl::string_view message) {
342 return Status(absl::StatusCode::kDataLoss, message);
343 }
344
DeadlineExceededError(absl::string_view message)345 Status DeadlineExceededError(absl::string_view message) {
346 return Status(absl::StatusCode::kDeadlineExceeded, message);
347 }
348
FailedPreconditionError(absl::string_view message)349 Status FailedPreconditionError(absl::string_view message) {
350 return Status(absl::StatusCode::kFailedPrecondition, message);
351 }
352
InternalError(absl::string_view message)353 Status InternalError(absl::string_view message) {
354 return Status(absl::StatusCode::kInternal, message);
355 }
356
InvalidArgumentError(absl::string_view message)357 Status InvalidArgumentError(absl::string_view message) {
358 return Status(absl::StatusCode::kInvalidArgument, message);
359 }
360
NotFoundError(absl::string_view message)361 Status NotFoundError(absl::string_view message) {
362 return Status(absl::StatusCode::kNotFound, message);
363 }
364
OutOfRangeError(absl::string_view message)365 Status OutOfRangeError(absl::string_view message) {
366 return Status(absl::StatusCode::kOutOfRange, message);
367 }
368
PermissionDeniedError(absl::string_view message)369 Status PermissionDeniedError(absl::string_view message) {
370 return Status(absl::StatusCode::kPermissionDenied, message);
371 }
372
ResourceExhaustedError(absl::string_view message)373 Status ResourceExhaustedError(absl::string_view message) {
374 return Status(absl::StatusCode::kResourceExhausted, message);
375 }
376
UnauthenticatedError(absl::string_view message)377 Status UnauthenticatedError(absl::string_view message) {
378 return Status(absl::StatusCode::kUnauthenticated, message);
379 }
380
UnavailableError(absl::string_view message)381 Status UnavailableError(absl::string_view message) {
382 return Status(absl::StatusCode::kUnavailable, message);
383 }
384
UnimplementedError(absl::string_view message)385 Status UnimplementedError(absl::string_view message) {
386 return Status(absl::StatusCode::kUnimplemented, message);
387 }
388
UnknownError(absl::string_view message)389 Status UnknownError(absl::string_view message) {
390 return Status(absl::StatusCode::kUnknown, message);
391 }
392
IsAborted(const Status & status)393 bool IsAborted(const Status& status) {
394 return status.code() == absl::StatusCode::kAborted;
395 }
396
IsAlreadyExists(const Status & status)397 bool IsAlreadyExists(const Status& status) {
398 return status.code() == absl::StatusCode::kAlreadyExists;
399 }
400
IsCancelled(const Status & status)401 bool IsCancelled(const Status& status) {
402 return status.code() == absl::StatusCode::kCancelled;
403 }
404
IsDataLoss(const Status & status)405 bool IsDataLoss(const Status& status) {
406 return status.code() == absl::StatusCode::kDataLoss;
407 }
408
IsDeadlineExceeded(const Status & status)409 bool IsDeadlineExceeded(const Status& status) {
410 return status.code() == absl::StatusCode::kDeadlineExceeded;
411 }
412
IsFailedPrecondition(const Status & status)413 bool IsFailedPrecondition(const Status& status) {
414 return status.code() == absl::StatusCode::kFailedPrecondition;
415 }
416
IsInternal(const Status & status)417 bool IsInternal(const Status& status) {
418 return status.code() == absl::StatusCode::kInternal;
419 }
420
IsInvalidArgument(const Status & status)421 bool IsInvalidArgument(const Status& status) {
422 return status.code() == absl::StatusCode::kInvalidArgument;
423 }
424
IsNotFound(const Status & status)425 bool IsNotFound(const Status& status) {
426 return status.code() == absl::StatusCode::kNotFound;
427 }
428
IsOutOfRange(const Status & status)429 bool IsOutOfRange(const Status& status) {
430 return status.code() == absl::StatusCode::kOutOfRange;
431 }
432
IsPermissionDenied(const Status & status)433 bool IsPermissionDenied(const Status& status) {
434 return status.code() == absl::StatusCode::kPermissionDenied;
435 }
436
IsResourceExhausted(const Status & status)437 bool IsResourceExhausted(const Status& status) {
438 return status.code() == absl::StatusCode::kResourceExhausted;
439 }
440
IsUnauthenticated(const Status & status)441 bool IsUnauthenticated(const Status& status) {
442 return status.code() == absl::StatusCode::kUnauthenticated;
443 }
444
IsUnavailable(const Status & status)445 bool IsUnavailable(const Status& status) {
446 return status.code() == absl::StatusCode::kUnavailable;
447 }
448
IsUnimplemented(const Status & status)449 bool IsUnimplemented(const Status& status) {
450 return status.code() == absl::StatusCode::kUnimplemented;
451 }
452
IsUnknown(const Status & status)453 bool IsUnknown(const Status& status) {
454 return status.code() == absl::StatusCode::kUnknown;
455 }
456
ErrnoToStatusCode(int error_number)457 StatusCode ErrnoToStatusCode(int error_number) {
458 switch (error_number) {
459 case 0:
460 return StatusCode::kOk;
461 case EINVAL: // Invalid argument
462 case ENAMETOOLONG: // Filename too long
463 case E2BIG: // Argument list too long
464 case EDESTADDRREQ: // Destination address required
465 case EDOM: // Mathematics argument out of domain of function
466 case EFAULT: // Bad address
467 case EILSEQ: // Illegal byte sequence
468 case ENOPROTOOPT: // Protocol not available
469 case ENOSTR: // Not a STREAM
470 case ENOTSOCK: // Not a socket
471 case ENOTTY: // Inappropriate I/O control operation
472 case EPROTOTYPE: // Protocol wrong type for socket
473 case ESPIPE: // Invalid seek
474 return StatusCode::kInvalidArgument;
475 case ETIMEDOUT: // Connection timed out
476 case ETIME: // Timer expired
477 return StatusCode::kDeadlineExceeded;
478 case ENODEV: // No such device
479 case ENOENT: // No such file or directory
480 #ifdef ENOMEDIUM
481 case ENOMEDIUM: // No medium found
482 #endif
483 case ENXIO: // No such device or address
484 case ESRCH: // No such process
485 return StatusCode::kNotFound;
486 case EEXIST: // File exists
487 case EADDRNOTAVAIL: // Address not available
488 case EALREADY: // Connection already in progress
489 #ifdef ENOTUNIQ
490 case ENOTUNIQ: // Name not unique on network
491 #endif
492 return StatusCode::kAlreadyExists;
493 case EPERM: // Operation not permitted
494 case EACCES: // Permission denied
495 #ifdef ENOKEY
496 case ENOKEY: // Required key not available
497 #endif
498 case EROFS: // Read only file system
499 return StatusCode::kPermissionDenied;
500 case ENOTEMPTY: // Directory not empty
501 case EISDIR: // Is a directory
502 case ENOTDIR: // Not a directory
503 case EADDRINUSE: // Address already in use
504 case EBADF: // Invalid file descriptor
505 #ifdef EBADFD
506 case EBADFD: // File descriptor in bad state
507 #endif
508 case EBUSY: // Device or resource busy
509 case ECHILD: // No child processes
510 case EISCONN: // Socket is connected
511 #ifdef EISNAM
512 case EISNAM: // Is a named type file
513 #endif
514 #ifdef ENOTBLK
515 case ENOTBLK: // Block device required
516 #endif
517 case ENOTCONN: // The socket is not connected
518 case EPIPE: // Broken pipe
519 #ifdef ESHUTDOWN
520 case ESHUTDOWN: // Cannot send after transport endpoint shutdown
521 #endif
522 case ETXTBSY: // Text file busy
523 #ifdef EUNATCH
524 case EUNATCH: // Protocol driver not attached
525 #endif
526 return StatusCode::kFailedPrecondition;
527 case ENOSPC: // No space left on device
528 #ifdef EDQUOT
529 case EDQUOT: // Disk quota exceeded
530 #endif
531 case EMFILE: // Too many open files
532 case EMLINK: // Too many links
533 case ENFILE: // Too many open files in system
534 case ENOBUFS: // No buffer space available
535 case ENODATA: // No message is available on the STREAM read queue
536 case ENOMEM: // Not enough space
537 case ENOSR: // No STREAM resources
538 #ifdef EUSERS
539 case EUSERS: // Too many users
540 #endif
541 return StatusCode::kResourceExhausted;
542 #ifdef ECHRNG
543 case ECHRNG: // Channel number out of range
544 #endif
545 case EFBIG: // File too large
546 case EOVERFLOW: // Value too large to be stored in data type
547 case ERANGE: // Result too large
548 return StatusCode::kOutOfRange;
549 #ifdef ENOPKG
550 case ENOPKG: // Package not installed
551 #endif
552 case ENOSYS: // Function not implemented
553 case ENOTSUP: // Operation not supported
554 case EAFNOSUPPORT: // Address family not supported
555 #ifdef EPFNOSUPPORT
556 case EPFNOSUPPORT: // Protocol family not supported
557 #endif
558 case EPROTONOSUPPORT: // Protocol not supported
559 #ifdef ESOCKTNOSUPPORT
560 case ESOCKTNOSUPPORT: // Socket type not supported
561 #endif
562 case EXDEV: // Improper link
563 return StatusCode::kUnimplemented;
564 case EAGAIN: // Resource temporarily unavailable
565 #ifdef ECOMM
566 case ECOMM: // Communication error on send
567 #endif
568 case ECONNREFUSED: // Connection refused
569 case ECONNABORTED: // Connection aborted
570 case ECONNRESET: // Connection reset
571 case EINTR: // Interrupted function call
572 #ifdef EHOSTDOWN
573 case EHOSTDOWN: // Host is down
574 #endif
575 case EHOSTUNREACH: // Host is unreachable
576 case ENETDOWN: // Network is down
577 case ENETRESET: // Connection aborted by network
578 case ENETUNREACH: // Network unreachable
579 case ENOLCK: // No locks available
580 case ENOLINK: // Link has been severed
581 #ifdef ENONET
582 case ENONET: // Machine is not on the network
583 #endif
584 return StatusCode::kUnavailable;
585 case EDEADLK: // Resource deadlock avoided
586 #ifdef ESTALE
587 case ESTALE: // Stale file handle
588 #endif
589 return StatusCode::kAborted;
590 case ECANCELED: // Operation cancelled
591 return StatusCode::kCancelled;
592 default:
593 return StatusCode::kUnknown;
594 }
595 }
596
597 namespace {
MessageForErrnoToStatus(int error_number,absl::string_view message)598 std::string MessageForErrnoToStatus(int error_number,
599 absl::string_view message) {
600 return absl::StrCat(message, ": ",
601 absl::base_internal::StrError(error_number));
602 }
603 } // namespace
604
ErrnoToStatus(int error_number,absl::string_view message)605 Status ErrnoToStatus(int error_number, absl::string_view message) {
606 return Status(ErrnoToStatusCode(error_number),
607 MessageForErrnoToStatus(error_number, message));
608 }
609
610 namespace status_internal {
611
MakeCheckFailString(const absl::Status * status,const char * prefix)612 std::string* MakeCheckFailString(const absl::Status* status,
613 const char* prefix) {
614 return new std::string(
615 absl::StrCat(prefix, " (",
616 status->ToString(StatusToStringMode::kWithEverything), ")"));
617 }
618
619 } // namespace status_internal
620
621 ABSL_NAMESPACE_END
622 } // namespace absl
623