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