Coverage Report

Created: 2026-07-16 06:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/abseil-cpp/absl/log/internal/log_message.cc
Line
Count
Source
1
//
2
// Copyright 2022 The Abseil Authors.
3
//
4
// Licensed under the Apache License, Version 2.0 (the "License");
5
// you may not use this file except in compliance with the License.
6
// You may obtain a copy of the License at
7
//
8
//      https://www.apache.org/licenses/LICENSE-2.0
9
//
10
// Unless required by applicable law or agreed to in writing, software
11
// distributed under the License is distributed on an "AS IS" BASIS,
12
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
// See the License for the specific language governing permissions and
14
// limitations under the License.
15
16
#include "absl/log/internal/log_message.h"
17
18
#include <stddef.h>
19
#include <stdint.h>
20
#include <stdlib.h>
21
#include <string.h>
22
23
#ifndef _WIN32
24
#include <unistd.h>
25
#endif
26
27
#include <algorithm>
28
#include <array>
29
#include <atomic>
30
#include <ios>
31
#include <memory>
32
#include <ostream>
33
#include <string>
34
#include <string_view>
35
36
#include "absl/base/attributes.h"
37
#include "absl/base/config.h"
38
#include "absl/base/internal/raw_logging.h"
39
#include "absl/base/internal/strerror.h"
40
#include "absl/base/internal/sysinfo.h"
41
#include "absl/base/log_severity.h"
42
#include "absl/base/nullability.h"
43
#include "absl/container/inlined_vector.h"
44
#include "absl/debugging/internal/examine_stack.h"
45
#include "absl/log/globals.h"
46
#include "absl/log/internal/append_truncated.h"
47
#include "absl/log/internal/globals.h"
48
#include "absl/log/internal/log_format.h"
49
#include "absl/log/internal/log_sink_set.h"
50
#include "absl/log/internal/nullguard.h"
51
#include "absl/log/internal/proto.h"
52
#include "absl/log/internal/structured_proto.h"
53
#include "absl/log/log_entry.h"
54
#include "absl/log/log_sink.h"
55
#include "absl/log/log_sink_registry.h"
56
#include "absl/strings/internal/utf8.h"
57
#include "absl/strings/string_view.h"
58
#include "absl/time/clock.h"
59
#include "absl/time/time.h"
60
#include "absl/types/span.h"
61
62
extern "C" ABSL_ATTRIBUTE_WEAK void ABSL_INTERNAL_C_SYMBOL(
63
0
    AbslInternalOnFatalLogMessage)(const absl::LogEntry&) {
64
  // Default - Do nothing
65
0
}
66
67
namespace absl {
68
ABSL_NAMESPACE_BEGIN
69
namespace log_internal {
70
71
namespace {
72
// message `logging.proto.Event`
73
enum EventTag : uint8_t {
74
  kFileName = 2,
75
  kFileLine = 3,
76
  kTimeNsecs = 4,
77
  kSeverity = 5,
78
  kThreadId = 6,
79
  kValue = 7,
80
  kSequenceNumber = 9,
81
  kThreadName = 10,
82
};
83
84
// message `logging.proto.Value`
85
enum ValueTag : uint8_t {
86
  kString = 1,
87
  kStringLiteral = 6,
88
};
89
90
// Decodes a `logging.proto.Value` from `buf` and writes a string representation
91
// into `dst`.  The string representation will be truncated if `dst` is not
92
// large enough to hold it.  Returns false if `dst` has size zero or one (i.e.
93
// sufficient only for a nul-terminator) and no decoded data could be written.
94
// This function may or may not write a nul-terminator into `dst`, and it may or
95
// may not truncate the data it writes in order to do make space for that nul
96
// terminator.  In any case, `dst` will be advanced to point at the byte where
97
// subsequent writes should begin.
98
0
bool PrintValue(absl::Span<char>& dst, absl::Span<const char> buf) {
99
0
  if (dst.size() <= 1) return false;
100
0
  ProtoField field;
101
0
  while (field.DecodeFrom(&buf)) {
102
0
    switch (field.tag()) {
103
0
      case ValueTag::kString:
104
0
      case ValueTag::kStringLiteral:
105
0
        if (field.type() == WireType::kLengthDelimited)
106
0
          if (log_internal::AppendTruncated(field.string_value(), dst) <
107
0
              field.string_value().size())
108
0
            return false;
109
0
    }
110
0
  }
111
0
  return true;
112
0
}
113
114
// See `logging.proto.Severity`
115
0
int32_t ProtoSeverity(absl::LogSeverity severity, int verbose_level) {
116
0
  switch (severity) {
117
0
    case absl::LogSeverity::kInfo:
118
0
      if (verbose_level == absl::LogEntry::kNoVerbosityLevel) return 800;
119
0
      return 600 - verbose_level;
120
0
    case absl::LogSeverity::kWarning:
121
0
      return 900;
122
0
    case absl::LogSeverity::kError:
123
0
      return 950;
124
0
    case absl::LogSeverity::kFatal:
125
0
      return 1100;
126
0
    default:
127
0
      return 800;
128
0
  }
129
0
}
130
131
0
absl::string_view Basename(absl::string_view filepath) {
132
#ifdef _WIN32
133
  size_t path = filepath.find_last_of("/\\");
134
#else
135
0
  size_t path = filepath.find_last_of('/');
136
0
#endif
137
0
  if (path != filepath.npos) filepath.remove_prefix(path + 1);
138
0
  return filepath;
139
0
}
140
141
0
void WriteToString(const char* data, void* str) {
142
0
  reinterpret_cast<std::string*>(str)->append(data);
143
0
}
144
0
void WriteToStream(const char* data, void* os) {
145
0
  auto* cast_os = static_cast<std::ostream*>(os);
146
0
  *cast_os << data;
147
0
}
148
}  // namespace
149
150
struct LogMessage::LogMessageData final {
151
  LogMessageData(absl::string_view file, int line,
152
                 absl::LogSeverity severity, absl::Time timestamp);
153
  LogMessageData(const LogMessageData&) = delete;
154
  LogMessageData& operator=(const LogMessageData&) = delete;
155
156
  // `LogEntry` sent to `LogSink`s; contains metadata.
157
  absl::LogEntry entry;
158
159
  // true => this was first fatal msg
160
  bool first_fatal;
161
  // true => all failures should be quiet
162
  bool fail_quietly;
163
  // true => PLOG was requested
164
  bool is_perror;
165
166
  // Extra `LogSink`s to log to, in addition to `global_sinks`.
167
  absl::InlinedVector<absl::LogSink* absl_nonnull, 16> extra_sinks;
168
  // If true, log to `extra_sinks` but not to `global_sinks` or hardcoded
169
  // non-sink targets (e.g. stderr, log files).
170
  bool extra_sinks_only;
171
172
  std::ostream manipulated;  // ostream with IO manipulators applied
173
174
  // A `logging.proto.Event` proto message is built into `encoded_buf`.
175
  std::array<char, kLogMessageBufferSize> encoded_buf;
176
  // `encoded_remaining()` is the suffix of `encoded_buf` that has not been
177
  // filled yet.  If a datum to be encoded does not fit into
178
  // `encoded_remaining()` and cannot be truncated to fit, the size of
179
  // `encoded_remaining()` will be zeroed to prevent encoding of any further
180
  // data.  Note that in this case its `data()` pointer will not point past the
181
  // end of `encoded_buf`.
182
  // The first use of `encoded_remaining()` is our chance to record metadata
183
  // after any modifications (e.g. by `AtLocation()`) but before any data have
184
  // been recorded.  We want to record metadata before data so that data are
185
  // preferentially truncated if we run out of buffer.
186
0
  absl::Span<char>& encoded_remaining() {
187
0
    if (encoded_remaining_actual_do_not_use_directly.data() == nullptr) {
188
0
      encoded_remaining_actual_do_not_use_directly =
189
0
          absl::MakeSpan(encoded_buf);
190
0
      InitializeEncodingAndFormat();
191
0
    }
192
0
    return encoded_remaining_actual_do_not_use_directly;
193
0
  }
194
  absl::Span<char> encoded_remaining_actual_do_not_use_directly;
195
196
  // A formatted string message is built in `string_buf`.
197
  std::array<char, kLogMessageBufferSize> string_buf;
198
199
  void InitializeEncodingAndFormat();
200
  void FinalizeEncodingAndFormat();
201
};
202
203
LogMessage::LogMessageData::LogMessageData(absl::string_view file,
204
                                           int line, absl::LogSeverity severity,
205
                                           absl::Time timestamp)
206
0
    : extra_sinks_only(false), manipulated(nullptr) {
207
  // Legacy defaults for LOG's ostream:
208
0
  manipulated.setf(std::ios_base::showbase | std::ios_base::boolalpha);
209
0
  entry.full_filename_ = file;
210
0
  entry.base_filename_ = Basename(file);
211
0
  entry.line_ = line;
212
0
  entry.prefix_ = absl::ShouldPrependLogPrefix();
213
0
  entry.severity_ = absl::NormalizeLogSeverity(severity);
214
0
  entry.verbose_level_ = absl::LogEntry::kNoVerbosityLevel;
215
0
  entry.timestamp_ = timestamp;
216
0
  entry.tid_ = absl::base_internal::GetCachedTID();
217
0
}
218
219
0
void LogMessage::LogMessageData::InitializeEncodingAndFormat() {
220
0
  EncodeStringTruncate(EventTag::kFileName, entry.source_filename(),
221
0
                       &encoded_remaining());
222
0
  EncodeVarint(EventTag::kFileLine, entry.source_line(), &encoded_remaining());
223
0
  EncodeVarint(EventTag::kTimeNsecs, absl::ToUnixNanos(entry.timestamp()),
224
0
               &encoded_remaining());
225
0
  EncodeVarint(EventTag::kSeverity,
226
0
               ProtoSeverity(entry.log_severity(), entry.verbosity()),
227
0
               &encoded_remaining());
228
0
  EncodeVarint(EventTag::kThreadId, static_cast<uint64_t>(entry.tid()),
229
0
               &encoded_remaining());
230
0
}
231
232
0
void LogMessage::LogMessageData::FinalizeEncodingAndFormat() {
233
  // Note that `encoded_remaining()` may have zero size without pointing past
234
  // the end of `encoded_buf`, so the difference between `data()` pointers is
235
  // used to compute the size of `encoded_data`.
236
0
  absl::Span<const char> encoded_data(
237
0
      encoded_buf.data(),
238
0
      static_cast<size_t>(encoded_remaining().data() - encoded_buf.data()));
239
  // `string_remaining` is the suffix of `string_buf` that has not been filled
240
  // yet.
241
0
  absl::Span<char> string_remaining(string_buf);
242
  // We may need to write a newline and nul-terminator at the end of the decoded
243
  // string data.  Rather than worry about whether those should overwrite the
244
  // end of the string (if the buffer is full) or be appended, we avoid writing
245
  // into the last two bytes so we always have space to append.
246
0
  string_remaining.remove_suffix(2);
247
0
  entry.prefix_len_ =
248
0
      entry.prefix() ? log_internal::FormatLogPrefix(
249
0
                           entry.log_severity(), entry.timestamp(), entry.tid(),
250
0
                           entry.source_basename(), entry.source_line(),
251
0
                           log_internal::ThreadIsLoggingToLogSink()
252
0
                               ? PrefixFormat::kRaw
253
0
                               : PrefixFormat::kNotRaw,
254
0
                           string_remaining)
255
0
                     : 0;
256
  // Decode data from `encoded_buf` until we run out of data or we run out of
257
  // `string_remaining`.
258
0
  ProtoField field;
259
0
  while (field.DecodeFrom(&encoded_data)) {
260
0
    switch (field.tag()) {
261
0
      case EventTag::kValue:
262
0
        if (field.type() != WireType::kLengthDelimited) continue;
263
0
        if (PrintValue(string_remaining, field.bytes_value())) continue;
264
0
        break;
265
0
    }
266
0
  }
267
0
  auto chars_written =
268
0
      static_cast<size_t>(string_remaining.data() - string_buf.data());
269
0
    string_buf[chars_written++] = '\n';
270
0
  string_buf[chars_written++] = '\0';
271
0
  entry.text_message_with_prefix_and_newline_and_nul_ =
272
0
      absl::MakeSpan(string_buf).subspan(0, chars_written);
273
0
}
274
275
LogMessage::LogMessage(const char* absl_nonnull file, int line,
276
                       absl::LogSeverity severity)
277
0
  : LogMessage(absl::string_view(file), line, severity) {}
278
LogMessage::LogMessage(absl::string_view file, int line,
279
                       absl::LogSeverity severity)
280
    : data_(
281
0
          std::make_unique<LogMessageData>(file, line, severity, absl::Now())) {
282
0
  data_->first_fatal = false;
283
0
  data_->is_perror = false;
284
0
  data_->fail_quietly = false;
285
286
  // This logs a backtrace even if the location is subsequently changed using
287
  // AtLocation.  This quirk, and the behavior when AtLocation is called twice,
288
  // are fixable but probably not worth fixing.
289
0
  LogBacktraceIfNeeded();
290
0
}
291
292
LogMessage::LogMessage(const char* absl_nonnull file, int line, InfoTag)
293
0
    : LogMessage(file, line, absl::LogSeverity::kInfo) {}
294
LogMessage::LogMessage(const char* absl_nonnull file, int line, WarningTag)
295
0
    : LogMessage(file, line, absl::LogSeverity::kWarning) {}
296
LogMessage::LogMessage(const char* absl_nonnull file, int line, ErrorTag)
297
0
    : LogMessage(file, line, absl::LogSeverity::kError) {}
298
299
// This cannot go in the header since LogMessageData is defined in this file.
300
0
LogMessage::~LogMessage() = default;
301
302
0
LogMessage& LogMessage::AtLocation(absl::string_view file, int line) {
303
0
  data_->entry.full_filename_ = file;
304
0
  data_->entry.base_filename_ = Basename(file);
305
0
  data_->entry.line_ = line;
306
0
  LogBacktraceIfNeeded();
307
0
  return *this;
308
0
}
309
310
0
LogMessage& LogMessage::NoPrefix() {
311
0
  data_->entry.prefix_ = false;
312
0
  return *this;
313
0
}
314
315
0
LogMessage& LogMessage::WithVerbosity(int verbose_level) {
316
0
  if (verbose_level == absl::LogEntry::kNoVerbosityLevel) {
317
0
    data_->entry.verbose_level_ = absl::LogEntry::kNoVerbosityLevel;
318
0
  } else {
319
0
    data_->entry.verbose_level_ = std::max(0, verbose_level);
320
0
  }
321
0
  return *this;
322
0
}
323
324
0
LogMessage& LogMessage::WithTimestamp(absl::Time timestamp) {
325
0
  data_->entry.timestamp_ = timestamp;
326
0
  return *this;
327
0
}
328
329
0
LogMessage& LogMessage::WithThreadID(absl::LogEntry::tid_t tid) {
330
0
  data_->entry.tid_ = tid;
331
0
  return *this;
332
0
}
333
334
0
LogMessage& LogMessage::WithMetadataFrom(const absl::LogEntry& entry) {
335
0
  data_->entry.full_filename_ = entry.full_filename_;
336
0
  data_->entry.base_filename_ = entry.base_filename_;
337
0
  data_->entry.line_ = entry.line_;
338
0
  data_->entry.prefix_ = entry.prefix_;
339
0
  data_->entry.severity_ = entry.severity_;
340
0
  data_->entry.verbose_level_ = entry.verbose_level_;
341
0
  data_->entry.timestamp_ = entry.timestamp_;
342
0
  data_->entry.tid_ = entry.tid_;
343
0
  return *this;
344
0
}
345
346
0
LogMessage& LogMessage::WithPerror() {
347
0
  data_->is_perror = true;
348
0
  return *this;
349
0
}
350
351
0
LogMessage& LogMessage::ToSinkAlso(absl::LogSink* absl_nonnull sink) {
352
0
  ABSL_INTERNAL_CHECK(sink, "null LogSink*");
353
0
  data_->extra_sinks.push_back(sink);
354
0
  return *this;
355
0
}
356
357
0
LogMessage& LogMessage::ToSinkOnly(absl::LogSink* absl_nonnull sink) {
358
0
  ABSL_INTERNAL_CHECK(sink, "null LogSink*");
359
0
  data_->extra_sinks.clear();
360
0
  data_->extra_sinks.push_back(sink);
361
0
  data_->extra_sinks_only = true;
362
0
  return *this;
363
0
}
364
365
#ifdef __ELF__
366
extern "C" void __gcov_dump() ABSL_ATTRIBUTE_WEAK;
367
extern "C" void __gcov_flush() ABSL_ATTRIBUTE_WEAK;
368
#endif
369
370
0
void LogMessage::FailWithoutStackTrace() {
371
  // Now suppress repeated trace logging:
372
0
  log_internal::SetSuppressSigabortTrace(true);
373
#if defined _DEBUG && defined COMPILER_MSVC
374
  // When debugging on windows, avoid the obnoxious dialog.
375
  __debugbreak();
376
#endif
377
378
0
#ifdef __ELF__
379
  // For b/8737634, flush coverage if we are in coverage mode.
380
0
  if (&__gcov_dump != nullptr) {
381
0
    __gcov_dump();
382
0
  } else if (&__gcov_flush != nullptr) {
383
0
    __gcov_flush();
384
0
  }
385
0
#endif
386
387
0
  abort();
388
0
}
389
390
0
void LogMessage::FailQuietly() {
391
  // _exit. Calling abort() would trigger all sorts of death signal handlers
392
  // and a detailed stack trace. Calling exit() would trigger the onexit
393
  // handlers, including the heap-leak checker, which is guaranteed to fail in
394
  // this case: we probably just new'ed the std::string that we logged.
395
  // Anyway, if you're calling Fail or FailQuietly, you're trying to bail out
396
  // of the program quickly, and it doesn't make much sense for FailQuietly to
397
  // offer different guarantees about exit behavior than Fail does. (And as a
398
  // consequence for QCHECK and CHECK to offer different exit behaviors)
399
0
  _exit(1);
400
0
}
401
402
0
LogMessage& LogMessage::operator<<(const std::string& v) {
403
0
  CopyToEncodedBuffer<StringType::kNotLiteral>(v);
404
0
  return *this;
405
0
}
406
407
0
LogMessage& LogMessage::operator<<(absl::string_view v) {
408
0
  CopyToEncodedBuffer<StringType::kNotLiteral>(v);
409
0
  return *this;
410
0
}
411
412
0
LogMessage& LogMessage::operator<<(const std::wstring& v) {
413
0
  CopyToEncodedBuffer<StringType::kNotLiteral>(v);
414
0
  return *this;
415
0
}
416
417
0
LogMessage& LogMessage::operator<<(std::wstring_view v) {
418
0
  CopyToEncodedBuffer<StringType::kNotLiteral>(v);
419
0
  return *this;
420
0
}
421
422
template <>
423
LogMessage& LogMessage::operator<< <const wchar_t*>(
424
0
    const wchar_t* absl_nullable const& v) {
425
0
  if (v == nullptr) {
426
0
    CopyToEncodedBuffer<StringType::kNotLiteral>(
427
0
        absl::string_view(kCharNull.data(), kCharNull.size() - 1));
428
0
  } else {
429
0
    CopyToEncodedBuffer<StringType::kNotLiteral>(v);
430
0
  }
431
0
  return *this;
432
0
}
433
434
0
LogMessage& LogMessage::operator<<(wchar_t v) {
435
0
  CopyToEncodedBuffer<StringType::kNotLiteral>(std::wstring_view(&v, 1));
436
0
  return *this;
437
0
}
438
439
0
LogMessage& LogMessage::operator<<(std::ostream& (*m)(std::ostream& os)) {
440
0
  OstreamView view(*data_);
441
0
  data_->manipulated << m;
442
0
  return *this;
443
0
}
444
0
LogMessage& LogMessage::operator<<(std::ios_base& (*m)(std::ios_base& os)) {
445
0
  OstreamView view(*data_);
446
0
  data_->manipulated << m;
447
0
  return *this;
448
0
}
449
// NOLINTBEGIN(runtime/int)
450
// NOLINTBEGIN(google-runtime-int)
451
template LogMessage& LogMessage::operator<<(const char& v);
452
template LogMessage& LogMessage::operator<<(const signed char& v);
453
template LogMessage& LogMessage::operator<<(const unsigned char& v);
454
template LogMessage& LogMessage::operator<<(const short& v);
455
template LogMessage& LogMessage::operator<<(const unsigned short& v);
456
template LogMessage& LogMessage::operator<<(const int& v);
457
template LogMessage& LogMessage::operator<<(const unsigned int& v);
458
template LogMessage& LogMessage::operator<<(const long& v);
459
template LogMessage& LogMessage::operator<<(const unsigned long& v);
460
template LogMessage& LogMessage::operator<<(const long long& v);
461
template LogMessage& LogMessage::operator<<(const unsigned long long& v);
462
template LogMessage& LogMessage::operator<<(void* const& v);
463
template LogMessage& LogMessage::operator<<(const void* const& v);
464
template LogMessage& LogMessage::operator<<(const float& v);
465
template LogMessage& LogMessage::operator<<(const double& v);
466
template LogMessage& LogMessage::operator<<(const bool& v);
467
// NOLINTEND(google-runtime-int)
468
// NOLINTEND(runtime/int)
469
470
0
void LogMessage::Flush() {
471
0
  if (data_->entry.log_severity() < absl::MinLogLevel()) return;
472
473
0
  if (data_->is_perror) {
474
0
    InternalStream() << ": " << absl::base_internal::StrError(errno_saver_())
475
0
                     << " [" << errno_saver_() << "]";
476
0
  }
477
478
  // Have we already seen a fatal message?
479
0
  ABSL_CONST_INIT static std::atomic<bool> seen_fatal(false);
480
0
  if (data_->entry.log_severity() == absl::LogSeverity::kFatal &&
481
0
      absl::log_internal::ExitOnDFatal()) {
482
    // Exactly one LOG(FATAL) message is responsible for aborting the process,
483
    // even if multiple threads LOG(FATAL) concurrently.
484
0
    bool expected_seen_fatal = false;
485
0
    if (seen_fatal.compare_exchange_strong(expected_seen_fatal, true,
486
0
                                           std::memory_order_relaxed)) {
487
0
      data_->first_fatal = true;
488
0
    }
489
0
  }
490
491
0
  data_->FinalizeEncodingAndFormat();
492
0
  data_->entry.encoding_ =
493
0
      absl::string_view(data_->encoded_buf.data(),
494
0
                        static_cast<size_t>(data_->encoded_remaining().data() -
495
0
                                            data_->encoded_buf.data()));
496
0
  SendToLog();
497
0
}
498
499
0
void LogMessage::SetFailQuietly() { data_->fail_quietly = true; }
500
501
LogMessage::OstreamView::OstreamView(LogMessageData& message_data)
502
0
    : data_(message_data), encoded_remaining_copy_(data_.encoded_remaining()) {
503
  // This constructor sets the `streambuf` up so that streaming into an attached
504
  // ostream encodes string data in-place.  To do that, we write appropriate
505
  // headers into the buffer using a copy of the buffer view so that we can
506
  // decide not to keep them later if nothing is ever streamed in.  We don't
507
  // know how much data we'll get, but we can use the size of the remaining
508
  // buffer as an upper bound and fill in the right size once we know it.
509
0
  message_start_ =
510
0
      EncodeMessageStart(EventTag::kValue, encoded_remaining_copy_.size(),
511
0
                         &encoded_remaining_copy_);
512
0
  string_start_ =
513
0
      EncodeMessageStart(ValueTag::kString, encoded_remaining_copy_.size(),
514
0
                         &encoded_remaining_copy_);
515
0
  setp(encoded_remaining_copy_.data(),
516
0
       encoded_remaining_copy_.data() + encoded_remaining_copy_.size());
517
0
  data_.manipulated.rdbuf(this);
518
0
}
519
520
0
LogMessage::OstreamView::~OstreamView() {
521
0
  data_.manipulated.rdbuf(nullptr);
522
0
  if (!string_start_.data()) {
523
    // The second field header didn't fit.  Whether the first one did or not, we
524
    // shouldn't commit `encoded_remaining_copy_`, and we also need to zero the
525
    // size of `data_->encoded_remaining()` so that no more data are encoded.
526
0
    data_.encoded_remaining().remove_suffix(data_.encoded_remaining().size());
527
0
    return;
528
0
  }
529
0
  const absl::Span<const char> contents(pbase(),
530
0
                                        static_cast<size_t>(pptr() - pbase()));
531
0
  if (contents.empty()) return;
532
0
  encoded_remaining_copy_.remove_prefix(contents.size());
533
0
  EncodeMessageLength(string_start_, &encoded_remaining_copy_);
534
0
  EncodeMessageLength(message_start_, &encoded_remaining_copy_);
535
0
  data_.encoded_remaining() = encoded_remaining_copy_;
536
0
}
537
538
0
std::ostream& LogMessage::OstreamView::stream() { return data_.manipulated; }
539
540
0
bool LogMessage::IsFatal() const {
541
0
  return data_->entry.log_severity() == absl::LogSeverity::kFatal &&
542
0
         absl::log_internal::ExitOnDFatal();
543
0
}
544
545
0
void LogMessage::PrepareToDie() {
546
  // If we log a FATAL message, flush all the log destinations, then toss
547
  // a signal for others to catch. We leave the logs in a state that
548
  // someone else can use them (as long as they flush afterwards)
549
0
  if (data_->first_fatal) {
550
    // Notify observers about the upcoming fatal error.
551
0
    ABSL_INTERNAL_C_SYMBOL(AbslInternalOnFatalLogMessage)(data_->entry);
552
0
  }
553
554
0
  if (!data_->fail_quietly) {
555
    // Log the message first before we start collecting stack trace.
556
0
    log_internal::LogToSinks(data_->entry, absl::MakeSpan(data_->extra_sinks),
557
0
                             data_->extra_sinks_only);
558
559
    // `DumpStackTrace` generates an empty string under MSVC.
560
    // Adding the constant prefix here simplifies testing.
561
0
    data_->entry.stacktrace_ = "*** Check failure stack trace: ***\n";
562
0
    debugging_internal::DumpStackTrace(
563
0
        0, log_internal::MaxFramesInLogStackTrace(),
564
0
        log_internal::ShouldSymbolizeLogStackTrace(), WriteToString,
565
0
        &data_->entry.stacktrace_);
566
0
  }
567
0
}
568
569
0
void LogMessage::Die() {
570
0
  absl::FlushLogSinks();
571
572
0
  if (data_->fail_quietly) {
573
0
    FailQuietly();
574
0
  } else {
575
0
    FailWithoutStackTrace();
576
0
  }
577
0
}
578
579
0
void LogMessage::SendToLog() {
580
0
  if (IsFatal()) PrepareToDie();
581
  // Also log to all registered sinks, even if OnlyLogToStderr() is set.
582
0
  log_internal::LogToSinks(data_->entry, absl::MakeSpan(data_->extra_sinks),
583
0
                           data_->extra_sinks_only);
584
0
  if (IsFatal()) Die();
585
0
}
586
587
0
void LogMessage::LogBacktraceIfNeeded() {
588
0
  if (!absl::log_internal::IsInitialized()) return;
589
590
0
  if (!absl::log_internal::ShouldLogBacktraceAt(data_->entry.source_basename(),
591
0
                                                data_->entry.source_line()))
592
0
    return;
593
0
  OstreamView view(*data_);
594
0
  view.stream() << " (stacktrace:\n";
595
0
  debugging_internal::DumpStackTrace(
596
0
      1, log_internal::MaxFramesInLogStackTrace(),
597
0
      log_internal::ShouldSymbolizeLogStackTrace(), WriteToStream,
598
0
      &view.stream());
599
0
  view.stream() << ") ";
600
0
}
601
602
// Encodes into `data_->encoded_remaining()` a partial `logging.proto.Event`
603
// containing the specified string data using a `Value` field appropriate to
604
// `str_type`.  Truncates `str` if necessary, but emits nothing and marks the
605
// buffer full if  even the field headers do not fit.
606
template <LogMessage::StringType str_type>
607
0
void LogMessage::CopyToEncodedBuffer(absl::string_view str) {
608
0
  auto encoded_remaining_copy = data_->encoded_remaining();
609
0
  constexpr uint8_t tag_value = str_type == StringType::kLiteral
610
0
                                    ? ValueTag::kStringLiteral
611
0
                                    : ValueTag::kString;
612
0
  auto start = EncodeMessageStart(
613
0
      EventTag::kValue,
614
0
      BufferSizeFor(tag_value, WireType::kLengthDelimited) + str.size(),
615
0
      &encoded_remaining_copy);
616
  // If the `logging.proto.Event.value` field header did not fit,
617
  // `EncodeMessageStart` will have zeroed `encoded_remaining_copy`'s size and
618
  // `EncodeStringTruncate` will fail too.
619
0
  if (EncodeStringTruncate(tag_value, str, &encoded_remaining_copy)) {
620
    // The string may have been truncated, but the field header fit.
621
0
    EncodeMessageLength(start, &encoded_remaining_copy);
622
0
    data_->encoded_remaining() = encoded_remaining_copy;
623
0
  } else {
624
    // The field header(s) did not fit; zero `encoded_remaining()` so we don't
625
    // write anything else later.
626
0
    data_->encoded_remaining().remove_suffix(data_->encoded_remaining().size());
627
0
  }
628
0
}
Unexecuted instantiation: void absl::log_internal::LogMessage::CopyToEncodedBuffer<(absl::log_internal::LogMessage::StringType)0>(std::__1::basic_string_view<char, std::__1::char_traits<char> >)
Unexecuted instantiation: void absl::log_internal::LogMessage::CopyToEncodedBuffer<(absl::log_internal::LogMessage::StringType)1>(std::__1::basic_string_view<char, std::__1::char_traits<char> >)
629
template void LogMessage::CopyToEncodedBuffer<LogMessage::StringType::kLiteral>(
630
    absl::string_view str);
631
template void LogMessage::CopyToEncodedBuffer<
632
    LogMessage::StringType::kNotLiteral>(absl::string_view str);
633
template <LogMessage::StringType str_type>
634
0
void LogMessage::CopyToEncodedBuffer(char ch, size_t num) {
635
0
  auto encoded_remaining_copy = data_->encoded_remaining();
636
0
  constexpr uint8_t tag_value = str_type == StringType::kLiteral
637
0
                                    ? ValueTag::kStringLiteral
638
0
                                    : ValueTag::kString;
639
0
  auto value_start = EncodeMessageStart(
640
0
      EventTag::kValue,
641
0
      BufferSizeFor(tag_value, WireType::kLengthDelimited) + num,
642
0
      &encoded_remaining_copy);
643
0
  auto str_start = EncodeMessageStart(tag_value, num, &encoded_remaining_copy);
644
0
  if (str_start.data()) {
645
    // The field headers fit.
646
0
    log_internal::AppendTruncated(ch, num, encoded_remaining_copy);
647
0
    EncodeMessageLength(str_start, &encoded_remaining_copy);
648
0
    EncodeMessageLength(value_start, &encoded_remaining_copy);
649
0
    data_->encoded_remaining() = encoded_remaining_copy;
650
0
  } else {
651
    // The field header(s) did not fit; zero `encoded_remaining()` so we don't
652
    // write anything else later.
653
0
    data_->encoded_remaining().remove_suffix(data_->encoded_remaining().size());
654
0
  }
655
0
}
Unexecuted instantiation: void absl::log_internal::LogMessage::CopyToEncodedBuffer<(absl::log_internal::LogMessage::StringType)0>(char, unsigned long)
Unexecuted instantiation: void absl::log_internal::LogMessage::CopyToEncodedBuffer<(absl::log_internal::LogMessage::StringType)1>(char, unsigned long)
656
template void LogMessage::CopyToEncodedBuffer<LogMessage::StringType::kLiteral>(
657
    char ch, size_t num);
658
template void LogMessage::CopyToEncodedBuffer<
659
    LogMessage::StringType::kNotLiteral>(char ch, size_t num);
660
661
template <LogMessage::StringType str_type>
662
0
void LogMessage::CopyToEncodedBuffer(std::wstring_view str) {
663
0
  auto encoded_remaining_copy = data_->encoded_remaining();
664
0
  constexpr uint8_t tag_value = str_type == StringType::kLiteral
665
0
                                    ? ValueTag::kStringLiteral
666
0
                                    : ValueTag::kString;
667
0
  size_t max_str_byte_length =
668
0
      absl::strings_internal::kMaxEncodedUTF8Size * str.length();
669
0
  auto value_start =
670
0
      EncodeMessageStart(EventTag::kValue,
671
0
                         BufferSizeFor(tag_value, WireType::kLengthDelimited) +
672
0
                             max_str_byte_length,
673
0
                         &encoded_remaining_copy);
674
0
  auto str_start = EncodeMessageStart(tag_value, max_str_byte_length,
675
0
                                      &encoded_remaining_copy);
676
0
  if (str_start.data()) {
677
0
    log_internal::AppendTruncated(str, encoded_remaining_copy);
678
0
    EncodeMessageLength(str_start, &encoded_remaining_copy);
679
0
    EncodeMessageLength(value_start, &encoded_remaining_copy);
680
0
    data_->encoded_remaining() = encoded_remaining_copy;
681
0
  } else {
682
    // The field header(s) did not fit; zero `encoded_remaining()` so we don't
683
    // write anything else later.
684
0
    data_->encoded_remaining().remove_suffix(data_->encoded_remaining().size());
685
0
  }
686
0
}
Unexecuted instantiation: void absl::log_internal::LogMessage::CopyToEncodedBuffer<(absl::log_internal::LogMessage::StringType)0>(std::__1::basic_string_view<wchar_t, std::__1::char_traits<wchar_t> >)
Unexecuted instantiation: void absl::log_internal::LogMessage::CopyToEncodedBuffer<(absl::log_internal::LogMessage::StringType)1>(std::__1::basic_string_view<wchar_t, std::__1::char_traits<wchar_t> >)
687
template void LogMessage::CopyToEncodedBuffer<LogMessage::StringType::kLiteral>(
688
    std::wstring_view str);
689
template void LogMessage::CopyToEncodedBuffer<
690
    LogMessage::StringType::kNotLiteral>(std::wstring_view str);
691
692
template void LogMessage::CopyToEncodedBufferWithStructuredProtoField<
693
    LogMessage::StringType::kLiteral>(StructuredProtoField field,
694
                                      absl::string_view str);
695
template void LogMessage::CopyToEncodedBufferWithStructuredProtoField<
696
    LogMessage::StringType::kNotLiteral>(StructuredProtoField field,
697
                                         absl::string_view str);
698
699
template <LogMessage::StringType str_type>
700
void LogMessage::CopyToEncodedBufferWithStructuredProtoField(
701
0
    StructuredProtoField field, absl::string_view str) {
702
0
  auto encoded_remaining_copy = data_->encoded_remaining();
703
0
  size_t encoded_field_size = BufferSizeForStructuredProtoField(field);
704
0
  constexpr uint8_t tag_value = str_type == StringType::kLiteral
705
0
                                    ? ValueTag::kStringLiteral
706
0
                                    : ValueTag::kString;
707
0
  auto start = EncodeMessageStart(
708
0
      EventTag::kValue,
709
0
      encoded_field_size +
710
0
          BufferSizeFor(tag_value, WireType::kLengthDelimited) + str.size(),
711
0
      &encoded_remaining_copy);
712
713
  // Write the encoded proto field.
714
0
  if (!EncodeStructuredProtoField(field, encoded_remaining_copy)) {
715
    // The header / field will not fit; zero `encoded_remaining()` so we
716
    // don't write anything else later.
717
0
    data_->encoded_remaining().remove_suffix(data_->encoded_remaining().size());
718
0
    return;
719
0
  }
720
721
  // Write the string, truncating if necessary.
722
0
  if (!EncodeStringTruncate(tag_value, str, &encoded_remaining_copy)) {
723
    // The length of the string itself did not fit; zero `encoded_remaining()`
724
    // so the value is not encoded at all.
725
0
    data_->encoded_remaining().remove_suffix(data_->encoded_remaining().size());
726
0
    return;
727
0
  }
728
729
0
  EncodeMessageLength(start, &encoded_remaining_copy);
730
0
  data_->encoded_remaining() = encoded_remaining_copy;
731
0
}
Unexecuted instantiation: void absl::log_internal::LogMessage::CopyToEncodedBufferWithStructuredProtoField<(absl::log_internal::LogMessage::StringType)0>(absl::log_internal::StructuredProtoField, std::__1::basic_string_view<char, std::__1::char_traits<char> >)
Unexecuted instantiation: void absl::log_internal::LogMessage::CopyToEncodedBufferWithStructuredProtoField<(absl::log_internal::LogMessage::StringType)1>(absl::log_internal::StructuredProtoField, std::__1::basic_string_view<char, std::__1::char_traits<char> >)
732
733
// We intentionally don't return from these destructors. Disable MSVC's warning
734
// about the destructor never returning as we do so intentionally here.
735
#if defined(_MSC_VER) && !defined(__clang__)
736
#pragma warning(push)
737
#pragma warning(disable : 4722)
738
#endif
739
740
LogMessageFatal::LogMessageFatal(const char* absl_nonnull file, int line)
741
0
    : LogMessage(file, line, absl::LogSeverity::kFatal) {}
742
743
LogMessageFatal::LogMessageFatal(const char* absl_nonnull file, int line,
744
                                 const char* absl_nonnull failure_msg)
745
0
    : LogMessage(file, line, absl::LogSeverity::kFatal) {
746
0
  *this << "Check failed: " << failure_msg << " ";
747
0
}
748
749
0
LogMessageFatal::~LogMessageFatal() { FailWithoutStackTrace(); }
750
751
LogMessageDebugFatal::LogMessageDebugFatal(const char* absl_nonnull file,
752
                                           int line)
753
0
    : LogMessage(file, line, absl::LogSeverity::kFatal) {}
754
755
0
LogMessageDebugFatal::~LogMessageDebugFatal() { FailWithoutStackTrace(); }
756
757
LogMessageQuietlyDebugFatal::LogMessageQuietlyDebugFatal(
758
    const char* absl_nonnull file, int line)
759
0
    : LogMessage(file, line, absl::LogSeverity::kFatal) {
760
0
  SetFailQuietly();
761
0
}
762
763
0
LogMessageQuietlyDebugFatal::~LogMessageQuietlyDebugFatal() { FailQuietly(); }
764
765
LogMessageQuietlyFatal::LogMessageQuietlyFatal(const char* absl_nonnull file,
766
                                               int line)
767
0
    : LogMessage(file, line, absl::LogSeverity::kFatal) {
768
0
  SetFailQuietly();
769
0
}
770
771
LogMessageQuietlyFatal::LogMessageQuietlyFatal(
772
    const char* absl_nonnull file, int line,
773
    const char* absl_nonnull failure_msg)
774
0
    : LogMessageQuietlyFatal(file, line) {
775
0
  *this << "Check failed: " << failure_msg << " ";
776
0
}
777
778
0
LogMessageQuietlyFatal::~LogMessageQuietlyFatal() { FailQuietly(); }
779
#if defined(_MSC_VER) && !defined(__clang__)
780
#pragma warning(pop)
781
#endif
782
783
}  // namespace log_internal
784
785
ABSL_NAMESPACE_END
786
}  // namespace absl