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