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
NewRep(absl::StatusCode code,absl::string_view msg,std::unique_ptr<status_internal::Payloads> payloads)210 uintptr_t Status::NewRep(absl::StatusCode code, absl::string_view msg,
211 std::unique_ptr<status_internal::Payloads> payloads) {
212 status_internal::StatusRep* rep = new status_internal::StatusRep;
213 rep->ref.store(1, std::memory_order_relaxed);
214 rep->code = code;
215 rep->message.assign(msg.data(), msg.size());
216 rep->payloads = std::move(payloads);
217 return PointerToRep(rep);
218 }
219
Status(absl::StatusCode code,absl::string_view msg)220 Status::Status(absl::StatusCode code, absl::string_view msg)
221 : rep_(CodeToInlinedRep(code)) {
222 if (code != absl::StatusCode::kOk && !msg.empty()) {
223 rep_ = NewRep(code, msg, nullptr);
224 }
225 }
226
raw_code() const227 int Status::raw_code() const {
228 if (IsInlined(rep_)) {
229 return static_cast<int>(InlinedRepToCode(rep_));
230 }
231 status_internal::StatusRep* rep = RepToPointer(rep_);
232 return static_cast<int>(rep->code);
233 }
234
code() const235 absl::StatusCode Status::code() const {
236 return status_internal::MapToLocalCode(raw_code());
237 }
238
PrepareToModify()239 void Status::PrepareToModify() {
240 ABSL_RAW_CHECK(!ok(), "PrepareToModify shouldn't be called on OK status.");
241 if (IsInlined(rep_)) {
242 rep_ = NewRep(static_cast<absl::StatusCode>(raw_code()),
243 absl::string_view(), nullptr);
244 return;
245 }
246
247 uintptr_t rep_i = rep_;
248 status_internal::StatusRep* rep = RepToPointer(rep_);
249 if (rep->ref.load(std::memory_order_acquire) != 1) {
250 std::unique_ptr<status_internal::Payloads> payloads;
251 if (rep->payloads) {
252 payloads = absl::make_unique<status_internal::Payloads>(*rep->payloads);
253 }
254 rep_ = NewRep(rep->code, message(), std::move(payloads));
255 UnrefNonInlined(rep_i);
256 }
257 }
258
EqualsSlow(const absl::Status & a,const absl::Status & b)259 bool Status::EqualsSlow(const absl::Status& a, const absl::Status& b) {
260 if (IsInlined(a.rep_) != IsInlined(b.rep_)) return false;
261 if (a.message() != b.message()) return false;
262 if (a.raw_code() != b.raw_code()) return false;
263 if (a.GetPayloads() == b.GetPayloads()) return true;
264
265 const status_internal::Payloads no_payloads;
266 const status_internal::Payloads* larger_payloads =
267 a.GetPayloads() ? a.GetPayloads() : &no_payloads;
268 const status_internal::Payloads* smaller_payloads =
269 b.GetPayloads() ? b.GetPayloads() : &no_payloads;
270 if (larger_payloads->size() < smaller_payloads->size()) {
271 std::swap(larger_payloads, smaller_payloads);
272 }
273 if ((larger_payloads->size() - smaller_payloads->size()) > 1) return false;
274 // Payloads can be ordered differently, so we can't just compare payload
275 // vectors.
276 for (const auto& payload : *larger_payloads) {
277
278 bool found = false;
279 for (const auto& other_payload : *smaller_payloads) {
280 if (payload.type_url == other_payload.type_url) {
281 if (payload.payload != other_payload.payload) {
282 return false;
283 }
284 found = true;
285 break;
286 }
287 }
288 if (!found) return false;
289 }
290 return true;
291 }
292
ToStringSlow() const293 std::string Status::ToStringSlow() const {
294 std::string text;
295 absl::StrAppend(&text, absl::StatusCodeToString(code()), ": ", message());
296 status_internal::StatusPayloadPrinter printer =
297 status_internal::GetStatusPayloadPrinter();
298 this->ForEachPayload([&](absl::string_view type_url,
299 const absl::Cord& payload) {
300 absl::optional<std::string> result;
301 if (printer) result = printer(type_url, payload);
302 absl::StrAppend(
303 &text, " [", type_url, "='",
304 result.has_value() ? *result : absl::CHexEscape(std::string(payload)),
305 "']");
306 });
307
308 return text;
309 }
310
operator <<(std::ostream & os,const Status & x)311 std::ostream& operator<<(std::ostream& os, const Status& x) {
312 os << x.ToString();
313 return os;
314 }
315
AbortedError(absl::string_view message)316 Status AbortedError(absl::string_view message) {
317 return Status(absl::StatusCode::kAborted, message);
318 }
319
AlreadyExistsError(absl::string_view message)320 Status AlreadyExistsError(absl::string_view message) {
321 return Status(absl::StatusCode::kAlreadyExists, message);
322 }
323
CancelledError(absl::string_view message)324 Status CancelledError(absl::string_view message) {
325 return Status(absl::StatusCode::kCancelled, message);
326 }
327
DataLossError(absl::string_view message)328 Status DataLossError(absl::string_view message) {
329 return Status(absl::StatusCode::kDataLoss, message);
330 }
331
DeadlineExceededError(absl::string_view message)332 Status DeadlineExceededError(absl::string_view message) {
333 return Status(absl::StatusCode::kDeadlineExceeded, message);
334 }
335
FailedPreconditionError(absl::string_view message)336 Status FailedPreconditionError(absl::string_view message) {
337 return Status(absl::StatusCode::kFailedPrecondition, message);
338 }
339
InternalError(absl::string_view message)340 Status InternalError(absl::string_view message) {
341 return Status(absl::StatusCode::kInternal, message);
342 }
343
InvalidArgumentError(absl::string_view message)344 Status InvalidArgumentError(absl::string_view message) {
345 return Status(absl::StatusCode::kInvalidArgument, message);
346 }
347
NotFoundError(absl::string_view message)348 Status NotFoundError(absl::string_view message) {
349 return Status(absl::StatusCode::kNotFound, message);
350 }
351
OutOfRangeError(absl::string_view message)352 Status OutOfRangeError(absl::string_view message) {
353 return Status(absl::StatusCode::kOutOfRange, message);
354 }
355
PermissionDeniedError(absl::string_view message)356 Status PermissionDeniedError(absl::string_view message) {
357 return Status(absl::StatusCode::kPermissionDenied, message);
358 }
359
ResourceExhaustedError(absl::string_view message)360 Status ResourceExhaustedError(absl::string_view message) {
361 return Status(absl::StatusCode::kResourceExhausted, message);
362 }
363
UnauthenticatedError(absl::string_view message)364 Status UnauthenticatedError(absl::string_view message) {
365 return Status(absl::StatusCode::kUnauthenticated, message);
366 }
367
UnavailableError(absl::string_view message)368 Status UnavailableError(absl::string_view message) {
369 return Status(absl::StatusCode::kUnavailable, message);
370 }
371
UnimplementedError(absl::string_view message)372 Status UnimplementedError(absl::string_view message) {
373 return Status(absl::StatusCode::kUnimplemented, message);
374 }
375
UnknownError(absl::string_view message)376 Status UnknownError(absl::string_view message) {
377 return Status(absl::StatusCode::kUnknown, message);
378 }
379
IsAborted(const Status & status)380 bool IsAborted(const Status& status) {
381 return status.code() == absl::StatusCode::kAborted;
382 }
383
IsAlreadyExists(const Status & status)384 bool IsAlreadyExists(const Status& status) {
385 return status.code() == absl::StatusCode::kAlreadyExists;
386 }
387
IsCancelled(const Status & status)388 bool IsCancelled(const Status& status) {
389 return status.code() == absl::StatusCode::kCancelled;
390 }
391
IsDataLoss(const Status & status)392 bool IsDataLoss(const Status& status) {
393 return status.code() == absl::StatusCode::kDataLoss;
394 }
395
IsDeadlineExceeded(const Status & status)396 bool IsDeadlineExceeded(const Status& status) {
397 return status.code() == absl::StatusCode::kDeadlineExceeded;
398 }
399
IsFailedPrecondition(const Status & status)400 bool IsFailedPrecondition(const Status& status) {
401 return status.code() == absl::StatusCode::kFailedPrecondition;
402 }
403
IsInternal(const Status & status)404 bool IsInternal(const Status& status) {
405 return status.code() == absl::StatusCode::kInternal;
406 }
407
IsInvalidArgument(const Status & status)408 bool IsInvalidArgument(const Status& status) {
409 return status.code() == absl::StatusCode::kInvalidArgument;
410 }
411
IsNotFound(const Status & status)412 bool IsNotFound(const Status& status) {
413 return status.code() == absl::StatusCode::kNotFound;
414 }
415
IsOutOfRange(const Status & status)416 bool IsOutOfRange(const Status& status) {
417 return status.code() == absl::StatusCode::kOutOfRange;
418 }
419
IsPermissionDenied(const Status & status)420 bool IsPermissionDenied(const Status& status) {
421 return status.code() == absl::StatusCode::kPermissionDenied;
422 }
423
IsResourceExhausted(const Status & status)424 bool IsResourceExhausted(const Status& status) {
425 return status.code() == absl::StatusCode::kResourceExhausted;
426 }
427
IsUnauthenticated(const Status & status)428 bool IsUnauthenticated(const Status& status) {
429 return status.code() == absl::StatusCode::kUnauthenticated;
430 }
431
IsUnavailable(const Status & status)432 bool IsUnavailable(const Status& status) {
433 return status.code() == absl::StatusCode::kUnavailable;
434 }
435
IsUnimplemented(const Status & status)436 bool IsUnimplemented(const Status& status) {
437 return status.code() == absl::StatusCode::kUnimplemented;
438 }
439
IsUnknown(const Status & status)440 bool IsUnknown(const Status& status) {
441 return status.code() == absl::StatusCode::kUnknown;
442 }
443
444 ABSL_NAMESPACE_END
445 } // namespace absl
446