Coverage Report

Created: 2026-08-14 07:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/abseil-cpp/absl/status/internal/status_internal.cc
Line
Count
Source
1
// Copyright 2023 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
15
#include "absl/status/internal/status_internal.h"
16
17
#include <atomic>
18
#include <cassert>
19
#include <cstddef>
20
#include <cstdint>
21
#include <cstdio>
22
#include <cstring>
23
#include <memory>
24
#include <optional>
25
#include <string>
26
#include <utility>
27
28
#include "absl/base/attributes.h"
29
#include "absl/base/config.h"
30
#include "absl/base/macros.h"
31
#include "absl/base/nullability.h"
32
#include "absl/debugging/leak_check.h"
33
#include "absl/debugging/stacktrace.h"
34
#include "absl/debugging/symbolize.h"
35
#include "absl/hash/hash.h"
36
#include "absl/memory/memory.h"
37
#include "absl/status/status.h"
38
#include "absl/status/status_payload_printer.h"
39
#include "absl/strings/cord.h"
40
#include "absl/strings/escaping.h"
41
#include "absl/strings/str_cat.h"
42
#include "absl/strings/str_format.h"
43
#include "absl/strings/str_split.h"
44
#include "absl/strings/string_view.h"
45
#include "absl/types/optional_ref.h"
46
#include "absl/types/source_location.h"
47
#include "absl/types/span.h"
48
49
namespace absl {
50
ABSL_NAMESPACE_BEGIN
51
namespace status_internal {
52
53
3.15k
void StatusRep::Unref() const {
54
  // Fast path: if ref==1, there is no need for a RefCountDec (since
55
  // this is the only reference and therefore no other thread is
56
  // allowed to be mucking with r).
57
3.15k
  if (ref_.load(std::memory_order_acquire) == 1 ||
58
3.15k
      ref_.fetch_sub(1, std::memory_order_acq_rel) - 1 == 0) {
59
3.15k
    delete this;
60
3.15k
  }
61
3.15k
}
62
63
static std::optional<size_t> FindPayloadIndexByUrl(const Payloads* payloads,
64
0
                                                   absl::string_view type_url) {
65
0
  if (payloads == nullptr) return std::nullopt;
66
67
0
  for (size_t i = 0; i < payloads->size(); ++i) {
68
0
    if ((*payloads)[i].type_url == type_url) return i;
69
0
  }
70
71
0
  return std::nullopt;
72
0
}
73
74
std::optional<absl::Cord> StatusRep::GetPayload(
75
0
    absl::string_view type_url) const {
76
0
  std::optional<size_t> index =
77
0
      status_internal::FindPayloadIndexByUrl(payloads_.get(), type_url);
78
0
  if (index.has_value()) return (*payloads_)[index.value()].payload;
79
80
0
  return std::nullopt;
81
0
}
82
83
0
void StatusRep::SetPayload(absl::string_view type_url, absl::Cord payload) {
84
0
  if (payloads_ == nullptr) {
85
0
    payloads_ = std::make_unique<status_internal::Payloads>();
86
0
  }
87
88
0
  std::optional<size_t> index =
89
0
      status_internal::FindPayloadIndexByUrl(payloads_.get(), type_url);
90
0
  if (index.has_value()) {
91
0
    (*payloads_)[index.value()].payload = std::move(payload);
92
0
    return;
93
0
  }
94
95
0
  payloads_->push_back({std::string(type_url), std::move(payload)});
96
0
}
97
98
0
StatusRep::EraseResult StatusRep::ErasePayload(absl::string_view type_url) {
99
0
  std::optional<size_t> index =
100
0
      status_internal::FindPayloadIndexByUrl(payloads_.get(), type_url);
101
0
  if (!index.has_value()) return {false, Status::PointerToRep(this)};
102
0
  payloads_->erase(payloads_->begin() + index.value());
103
0
  if (payloads_->empty() && message_.empty()) {
104
    // Special case: If this can be represented inlined, it MUST be inlined
105
    // (== depends on this behavior).
106
0
    EraseResult result = {true, Status::CodeToInlinedRep(code_)};
107
0
    Unref();
108
0
    return result;
109
0
  }
110
0
  return {true, Status::PointerToRep(this)};
111
0
}
112
113
void StatusRep::ForEachPayload(
114
    absl::FunctionRef<void(absl::string_view, const absl::Cord&)> visitor)
115
0
    const {
116
0
  if (auto* payloads = payloads_.get()) {
117
0
    bool in_reverse =
118
0
        payloads->size() > 1 && reinterpret_cast<uintptr_t>(payloads) % 13 > 6;
119
120
0
    for (size_t index = 0; index < payloads->size(); ++index) {
121
0
      const auto& elem =
122
0
          (*payloads)[in_reverse ? payloads->size() - 1 - index : index];
123
124
#ifdef NDEBUG
125
      visitor(elem.type_url, elem.payload);
126
#else
127
      // In debug mode invalidate the type url to prevent users from relying on
128
      // this string lifetime.
129
130
      // NOLINTNEXTLINE intentional extra conversion to force temporary.
131
0
      visitor(std::string(elem.type_url), elem.payload);
132
0
#endif  // NDEBUG
133
0
    }
134
0
  }
135
0
}
136
137
0
absl::Span<const SourceLocation> StatusRep::GetSourceLocations() const {
138
0
  return absl::MakeSpan(source_locations_);
139
0
}
140
141
3.15k
void StatusRep::AddSourceLocation(absl::SourceLocation loc) {
142
3.15k
  source_locations_.push_back(loc);
143
3.15k
}
144
145
0
std::string StatusRep::ToString(StatusToStringMode mode) const {
146
0
  std::string text;
147
0
  absl::StrAppend(&text, absl::StatusCodeToString(code()), ": ", message());
148
149
0
  const bool with_payload = (mode & StatusToStringMode::kWithPayload) ==
150
0
                            StatusToStringMode::kWithPayload;
151
152
0
  if (with_payload) {
153
0
    status_internal::StatusPayloadPrinter printer =
154
0
        status_internal::GetStatusPayloadPrinter();
155
0
    this->ForEachPayload([&](absl::string_view type_url,
156
0
                             const absl::Cord& payload) {
157
0
      std::optional<std::string> result;
158
0
      if (printer) result = printer(type_url, payload);
159
0
      absl::StrAppend(
160
0
          &text, " [", type_url, "='",
161
0
          result.has_value() ? *result : absl::CHexEscape(std::string(payload)),
162
0
          "']");
163
0
    });
164
0
  }
165
0
  const bool with_source_location =
166
0
      (mode & StatusToStringMode::kWithSourceLocation) ==
167
0
      StatusToStringMode::kWithSourceLocation;
168
0
  if (with_source_location && !source_locations_.empty()) {
169
0
    absl::string_view whitespace = (absl::Hash<int>{}(42) % 2 == 0) ? "" : " ";
170
0
    absl::StrAppend(&text, "\n=== Source Location Trace: ===", whitespace,
171
0
                    "\n");
172
0
    for (const absl::SourceLocation loc : GetSourceLocations()) {
173
0
      absl::StrAppend(&text, loc.file_name(), ":", loc.line(), "\n");
174
0
    }
175
0
  }
176
177
0
  return text;
178
0
}
179
180
0
bool StatusRep::operator==(const StatusRep& other) const {
181
0
  assert(this != &other);
182
0
  if (code_ != other.code_) return false;
183
0
  if (message_ != other.message_) return false;
184
0
  const status_internal::Payloads* this_payloads = payloads_.get();
185
0
  const status_internal::Payloads* other_payloads = other.payloads_.get();
186
187
0
  const status_internal::Payloads no_payloads;
188
0
  const status_internal::Payloads* larger_payloads =
189
0
      this_payloads ? this_payloads : &no_payloads;
190
0
  const status_internal::Payloads* smaller_payloads =
191
0
      other_payloads ? other_payloads : &no_payloads;
192
0
  if (larger_payloads->size() < smaller_payloads->size()) {
193
0
    std::swap(larger_payloads, smaller_payloads);
194
0
  }
195
0
  if ((larger_payloads->size() - smaller_payloads->size()) > 1) return false;
196
  // Payloads can be ordered differently, so we can't just compare payload
197
  // vectors.
198
0
  for (const auto& payload : *larger_payloads) {
199
200
0
    bool found = false;
201
0
    for (const auto& other_payload : *smaller_payloads) {
202
0
      if (payload.type_url == other_payload.type_url) {
203
0
        if (payload.payload != other_payload.payload) {
204
0
          return false;
205
0
        }
206
0
        found = true;
207
0
        break;
208
0
      }
209
0
    }
210
0
    if (!found) return false;
211
0
  }
212
0
  return true;
213
0
}
214
215
StatusRep* absl_nonnull StatusRep::Clone(
216
    absl::optional_ref<absl::string_view> new_message, bool include_payloads,
217
0
    bool include_source_locations) const {
218
  // Optimization: no need to create a clone if we already have a refcount of 1.
219
0
  if (ref_.load(std::memory_order_acquire) == 1 && !new_message.has_value() &&
220
0
      include_payloads && include_source_locations) {
221
    // All StatusRep instances are heap allocated and mutable, therefore this
222
    // const_cast will never cast away const from a stack instance.
223
    //
224
    // CloneAndUnref is the only method that doesn't involve an external cast to
225
    // get a mutable StatusRep* from the uintptr_t rep stored in Status.
226
0
    return const_cast<StatusRep*>(this);
227
0
  }
228
0
  std::unique_ptr<status_internal::Payloads> payloads;
229
0
  if (include_payloads && payloads_) {
230
0
    payloads = std::make_unique<status_internal::Payloads>(*payloads_);
231
0
  }
232
0
  auto* new_rep =
233
0
      new StatusRep(code_, new_message.value_or(message_), std::move(payloads));
234
0
  if (include_source_locations) {
235
0
    new_rep->source_locations_ = source_locations_;
236
0
  }
237
0
  return new_rep;
238
0
}
239
240
0
StatusRep* absl_nonnull StatusRep::CloneAndUnref() const {
241
0
  return CloneAndUnref(std::nullopt, true, true);
242
0
}
243
244
StatusRep* absl_nonnull StatusRep::CloneAndUnref(
245
    absl::optional_ref<absl::string_view> new_message, bool include_payloads,
246
0
    bool include_source_locations) const {
247
0
  StatusRep* new_rep =
248
0
      Clone(new_message, /*include_payloads=*/include_payloads,
249
0
            /*include_source_locations=*/include_source_locations);
250
0
  if (new_rep != this) {
251
0
    Unref();
252
0
  }
253
0
  return new_rep;
254
0
}
255
256
// Convert canonical code to a value known to this binary.
257
0
absl::StatusCode MapToLocalCode(int value) {
258
0
  absl::StatusCode code = static_cast<absl::StatusCode>(value);
259
0
  switch (code) {
260
0
    case absl::StatusCode::kOk:
261
0
    case absl::StatusCode::kCancelled:
262
0
    case absl::StatusCode::kUnknown:
263
0
    case absl::StatusCode::kInvalidArgument:
264
0
    case absl::StatusCode::kDeadlineExceeded:
265
0
    case absl::StatusCode::kNotFound:
266
0
    case absl::StatusCode::kAlreadyExists:
267
0
    case absl::StatusCode::kPermissionDenied:
268
0
    case absl::StatusCode::kResourceExhausted:
269
0
    case absl::StatusCode::kFailedPrecondition:
270
0
    case absl::StatusCode::kAborted:
271
0
    case absl::StatusCode::kOutOfRange:
272
0
    case absl::StatusCode::kUnimplemented:
273
0
    case absl::StatusCode::kInternal:
274
0
    case absl::StatusCode::kUnavailable:
275
0
    case absl::StatusCode::kDataLoss:
276
0
    case absl::StatusCode::kUnauthenticated:
277
0
      return code;
278
0
    default:
279
0
      return absl::StatusCode::kUnknown;
280
0
  }
281
0
}
282
283
const char* absl_nonnull MakeCheckFailString(
284
0
    const absl::Status* absl_nonnull status, const char* absl_nonnull prefix) {
285
  // There's no need to free this string since the process is crashing.
286
0
  return absl::IgnoreLeak(
287
0
             new std::string(absl::StrCat(
288
0
                 prefix, " (",
289
0
                 status->ToString(StatusToStringMode::kWithEverything), ")")))
290
0
      ->c_str();
291
0
}
292
293
}  // namespace status_internal
294
295
ABSL_NAMESPACE_END
296
}  // namespace absl