1 // Copyright 2011 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifdef UNSAFE_BUFFERS_BUILD
6 // TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
7 #pragma allow_unsafe_buffers
8 #endif
9
10 #include "base/logging.h"
11
12 #include <sstream>
13 #include <string>
14 #include <string_view>
15
16 #include "base/command_line.h"
17 #include "base/files/file_util.h"
18 #include "base/files/scoped_temp_dir.h"
19 #include "base/functional/bind.h"
20 #include "base/functional/callback.h"
21 #include "base/no_destructor.h"
22 #include "base/process/process.h"
23 #include "base/run_loop.h"
24 #include "base/sanitizer_buildflags.h"
25 #include "base/strings/strcat.h"
26 #include "base/strings/string_number_conversions.h"
27 #include "base/strings/utf_string_conversions.h"
28 #include "base/test/bind.h"
29 #include "base/test/scoped_logging_settings.h"
30 #include "base/test/task_environment.h"
31 #include "build/build_config.h"
32 #include "build/chromeos_buildflags.h"
33 #include "testing/gmock/include/gmock/gmock.h"
34 #include "testing/gtest/include/gtest/gtest.h"
35
36 #if BUILDFLAG(IS_POSIX)
37 #include <errno.h>
38 #include <signal.h>
39 #include <unistd.h>
40
41 #include "base/posix/eintr_wrapper.h"
42 #endif // BUILDFLAG(IS_POSIX)
43
44 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
45 #include <ucontext.h>
46 #endif
47
48 #if BUILDFLAG(IS_WIN)
49 #include <windows.h>
50
51 #include <excpt.h>
52 #endif // BUILDFLAG(IS_WIN)
53
54 #if BUILDFLAG(IS_FUCHSIA)
55 #include <lib/zx/channel.h>
56 #include <lib/zx/event.h>
57 #include <lib/zx/exception.h>
58 #include <lib/zx/thread.h>
59 #include <zircon/syscalls/debug.h>
60 #include <zircon/syscalls/exception.h>
61 #include <zircon/types.h>
62 #endif // BUILDFLAG(IS_FUCHSIA)
63
64 #include <optional>
65
66 namespace logging {
67
68 namespace {
69
70 using ::testing::Return;
71 using ::testing::_;
72
73 class LoggingTest : public testing::Test {
74 protected:
scoped_logging_settings()75 const ScopedLoggingSettings& scoped_logging_settings() {
76 return scoped_logging_settings_;
77 }
78
79 private:
80 base::test::SingleThreadTaskEnvironment task_environment_{
81 base::test::SingleThreadTaskEnvironment::MainThreadType::IO};
82 ScopedLoggingSettings scoped_logging_settings_;
83 };
84
85 class MockLogSource {
86 public:
87 MOCK_METHOD0(Log, const char*());
88 };
89
90 class MockLogAssertHandler {
91 public:
92 MOCK_METHOD4(
93 HandleLogAssert,
94 void(const char*, int, const std::string_view, const std::string_view));
95 };
96
TEST_F(LoggingTest,BasicLogging)97 TEST_F(LoggingTest, BasicLogging) {
98 MockLogSource mock_log_source;
99
100 // 4 base logs: LOG, LOG_IF, PLOG, and PLOG_IF
101 int expected_logs = 4;
102
103 // 4 verbose logs: VLOG, VLOG_IF, VPLOG, VPLOG_IF.
104 if (VLOG_IS_ON(0))
105 expected_logs += 4;
106
107 // 4 debug logs: DLOG, DLOG_IF, DPLOG, DPLOG_IF.
108 if (DCHECK_IS_ON())
109 expected_logs += 4;
110
111 // 4 verbose debug logs: DVLOG, DVLOG_IF, DVPLOG, DVPLOG_IF
112 if (VLOG_IS_ON(0) && DCHECK_IS_ON())
113 expected_logs += 4;
114
115 EXPECT_CALL(mock_log_source, Log())
116 .Times(expected_logs)
117 .WillRepeatedly(Return("log message"));
118
119 SetMinLogLevel(LOGGING_INFO);
120
121 EXPECT_TRUE(LOG_IS_ON(INFO));
122 EXPECT_EQ(DCHECK_IS_ON(), DLOG_IS_ON(INFO));
123
124 EXPECT_TRUE(VLOG_IS_ON(0));
125
126 LOG(INFO) << mock_log_source.Log();
127 LOG_IF(INFO, true) << mock_log_source.Log();
128 PLOG(INFO) << mock_log_source.Log();
129 PLOG_IF(INFO, true) << mock_log_source.Log();
130 VLOG(0) << mock_log_source.Log();
131 VLOG_IF(0, true) << mock_log_source.Log();
132 VPLOG(0) << mock_log_source.Log();
133 VPLOG_IF(0, true) << mock_log_source.Log();
134
135 DLOG(INFO) << mock_log_source.Log();
136 DLOG_IF(INFO, true) << mock_log_source.Log();
137 DPLOG(INFO) << mock_log_source.Log();
138 DPLOG_IF(INFO, true) << mock_log_source.Log();
139 DVLOG(0) << mock_log_source.Log();
140 DVLOG_IF(0, true) << mock_log_source.Log();
141 DVPLOG(0) << mock_log_source.Log();
142 DVPLOG_IF(0, true) << mock_log_source.Log();
143 }
144
TEST_F(LoggingTest,LogIsOn)145 TEST_F(LoggingTest, LogIsOn) {
146 SetMinLogLevel(LOGGING_INFO);
147 EXPECT_TRUE(LOG_IS_ON(INFO));
148 EXPECT_TRUE(LOG_IS_ON(WARNING));
149 EXPECT_TRUE(LOG_IS_ON(ERROR));
150 EXPECT_TRUE(LOG_IS_ON(FATAL));
151 EXPECT_TRUE(LOG_IS_ON(DFATAL));
152
153 SetMinLogLevel(LOGGING_WARNING);
154 EXPECT_FALSE(LOG_IS_ON(INFO));
155 EXPECT_TRUE(LOG_IS_ON(WARNING));
156 EXPECT_TRUE(LOG_IS_ON(ERROR));
157 EXPECT_TRUE(LOG_IS_ON(FATAL));
158 EXPECT_TRUE(LOG_IS_ON(DFATAL));
159
160 SetMinLogLevel(LOGGING_ERROR);
161 EXPECT_FALSE(LOG_IS_ON(INFO));
162 EXPECT_FALSE(LOG_IS_ON(WARNING));
163 EXPECT_TRUE(LOG_IS_ON(ERROR));
164 EXPECT_TRUE(LOG_IS_ON(FATAL));
165 EXPECT_TRUE(LOG_IS_ON(DFATAL));
166
167 SetMinLogLevel(LOGGING_FATAL + 1);
168 EXPECT_FALSE(LOG_IS_ON(INFO));
169 EXPECT_FALSE(LOG_IS_ON(WARNING));
170 EXPECT_FALSE(LOG_IS_ON(ERROR));
171 // LOG_IS_ON(FATAL) should always be true.
172 EXPECT_TRUE(LOG_IS_ON(FATAL));
173 // If DCHECK_IS_ON() then DFATAL is FATAL.
174 EXPECT_EQ(DCHECK_IS_ON(), LOG_IS_ON(DFATAL));
175 }
176
TEST_F(LoggingTest,LoggingIsLazyBySeverity)177 TEST_F(LoggingTest, LoggingIsLazyBySeverity) {
178 MockLogSource mock_log_source;
179 EXPECT_CALL(mock_log_source, Log()).Times(0);
180
181 SetMinLogLevel(LOGGING_WARNING);
182
183 EXPECT_FALSE(LOG_IS_ON(INFO));
184 EXPECT_FALSE(DLOG_IS_ON(INFO));
185 EXPECT_FALSE(VLOG_IS_ON(1));
186
187 LOG(INFO) << mock_log_source.Log();
188 LOG_IF(INFO, false) << mock_log_source.Log();
189 PLOG(INFO) << mock_log_source.Log();
190 PLOG_IF(INFO, false) << mock_log_source.Log();
191 VLOG(1) << mock_log_source.Log();
192 VLOG_IF(1, true) << mock_log_source.Log();
193 VPLOG(1) << mock_log_source.Log();
194 VPLOG_IF(1, true) << mock_log_source.Log();
195
196 DLOG(INFO) << mock_log_source.Log();
197 DLOG_IF(INFO, true) << mock_log_source.Log();
198 DPLOG(INFO) << mock_log_source.Log();
199 DPLOG_IF(INFO, true) << mock_log_source.Log();
200 DVLOG(1) << mock_log_source.Log();
201 DVLOG_IF(1, true) << mock_log_source.Log();
202 DVPLOG(1) << mock_log_source.Log();
203 DVPLOG_IF(1, true) << mock_log_source.Log();
204 }
205
TEST_F(LoggingTest,LoggingIsLazyByDestination)206 TEST_F(LoggingTest, LoggingIsLazyByDestination) {
207 MockLogSource mock_log_source;
208 MockLogSource mock_log_source_error;
209 EXPECT_CALL(mock_log_source, Log()).Times(0);
210
211 // Severity >= ERROR is always printed to stderr.
212 EXPECT_CALL(mock_log_source_error, Log()).Times(1).
213 WillRepeatedly(Return("log message"));
214
215 LoggingSettings settings;
216 settings.logging_dest = LOG_NONE;
217 InitLogging(settings);
218
219 LOG(INFO) << mock_log_source.Log();
220 LOG(WARNING) << mock_log_source.Log();
221 LOG(ERROR) << mock_log_source_error.Log();
222 }
223
224 // Check that logging to stderr is gated on LOG_TO_STDERR.
TEST_F(LoggingTest,LogToStdErrFlag)225 TEST_F(LoggingTest, LogToStdErrFlag) {
226 LoggingSettings settings;
227 settings.logging_dest = LOG_NONE;
228 InitLogging(settings);
229 MockLogSource mock_log_source;
230 EXPECT_CALL(mock_log_source, Log()).Times(0);
231 LOG(INFO) << mock_log_source.Log();
232
233 settings.logging_dest = LOG_TO_STDERR;
234 MockLogSource mock_log_source_stderr;
235 InitLogging(settings);
236 EXPECT_CALL(mock_log_source_stderr, Log()).Times(1).WillOnce(Return("foo"));
237 LOG(INFO) << mock_log_source_stderr.Log();
238 }
239
240 // Check that messages with severity ERROR or higher are always logged to
241 // stderr if no log-destinations are set, other than LOG_TO_FILE.
242 // This test is currently only POSIX-compatible.
243 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
244 namespace {
TestForLogToStderr(int log_destinations,bool * did_log_info,bool * did_log_error)245 void TestForLogToStderr(int log_destinations,
246 bool* did_log_info,
247 bool* did_log_error) {
248 const char kInfoLogMessage[] = "This is an INFO level message";
249 const char kErrorLogMessage[] = "Here we have a message of level ERROR";
250 base::ScopedTempDir temp_dir;
251 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
252
253 // Set up logging.
254 LoggingSettings settings;
255 settings.logging_dest = log_destinations;
256 base::FilePath file_logs_path;
257 if (log_destinations & LOG_TO_FILE) {
258 file_logs_path = temp_dir.GetPath().Append("file.log");
259 settings.log_file_path = file_logs_path.value().c_str();
260 }
261 InitLogging(settings);
262
263 // Create a file and change stderr to write to that file, to easily check
264 // contents.
265 base::FilePath stderr_logs_path = temp_dir.GetPath().Append("stderr.log");
266 base::File stderr_logs = base::File(
267 stderr_logs_path,
268 base::File::FLAG_CREATE | base::File::FLAG_WRITE | base::File::FLAG_READ);
269 base::ScopedFD stderr_backup = base::ScopedFD(dup(STDERR_FILENO));
270 int dup_result = dup2(stderr_logs.GetPlatformFile(), STDERR_FILENO);
271 ASSERT_EQ(dup_result, STDERR_FILENO);
272
273 LOG(INFO) << kInfoLogMessage;
274 LOG(ERROR) << kErrorLogMessage;
275
276 // Restore the original stderr logging destination.
277 dup_result = dup2(stderr_backup.get(), STDERR_FILENO);
278 ASSERT_EQ(dup_result, STDERR_FILENO);
279
280 // Check which of the messages were written to stderr.
281 std::string written_logs;
282 ASSERT_TRUE(base::ReadFileToString(stderr_logs_path, &written_logs));
283 *did_log_info = written_logs.find(kInfoLogMessage) != std::string::npos;
284 *did_log_error = written_logs.find(kErrorLogMessage) != std::string::npos;
285 }
286 } // namespace
287
TEST_F(LoggingTest,AlwaysLogErrorsToStderr)288 TEST_F(LoggingTest, AlwaysLogErrorsToStderr) {
289 bool did_log_info = false;
290 bool did_log_error = false;
291
292 // Fuchsia only logs to stderr when explicitly specified.
293 #if !BUILDFLAG(IS_FUCHSIA)
294 // When no destinations are specified, ERRORs should still log to stderr.
295 TestForLogToStderr(LOG_NONE, &did_log_info, &did_log_error);
296 EXPECT_FALSE(did_log_info);
297 EXPECT_TRUE(did_log_error);
298
299 // Logging only to a file should also log ERRORs to stderr as well.
300 TestForLogToStderr(LOG_TO_FILE, &did_log_info, &did_log_error);
301 EXPECT_FALSE(did_log_info);
302 EXPECT_TRUE(did_log_error);
303 #endif
304
305 // ERRORs should not be logged to stderr if any destination besides FILE is
306 // set.
307 TestForLogToStderr(LOG_TO_SYSTEM_DEBUG_LOG, &did_log_info, &did_log_error);
308 EXPECT_FALSE(did_log_info);
309 EXPECT_FALSE(did_log_error);
310
311 // Both ERRORs and INFO should be logged if LOG_TO_STDERR is set.
312 TestForLogToStderr(LOG_TO_STDERR, &did_log_info, &did_log_error);
313 EXPECT_TRUE(did_log_info);
314 EXPECT_TRUE(did_log_error);
315 }
316 #endif // BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
317
318 #if BUILDFLAG(IS_CHROMEOS_ASH)
TEST_F(LoggingTest,InitWithFileDescriptor)319 TEST_F(LoggingTest, InitWithFileDescriptor) {
320 const char kErrorLogMessage[] = "something bad happened";
321
322 // Open a file to pass to the InitLogging.
323 base::ScopedTempDir temp_dir;
324 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
325 base::FilePath file_log_path = temp_dir.GetPath().Append("file.log");
326 FILE* log_file = fopen(file_log_path.value().c_str(), "w");
327 CHECK(log_file);
328
329 // Set up logging.
330 LoggingSettings settings;
331 settings.logging_dest = LOG_TO_FILE;
332 settings.log_file = log_file;
333 InitLogging(settings);
334
335 LOG(ERROR) << kErrorLogMessage;
336
337 // Check the message was written to the log file.
338 std::string written_logs;
339 ASSERT_TRUE(base::ReadFileToString(file_log_path, &written_logs));
340 ASSERT_NE(written_logs.find(kErrorLogMessage), std::string::npos);
341 }
342
TEST_F(LoggingTest,DuplicateLogFile)343 TEST_F(LoggingTest, DuplicateLogFile) {
344 const char kErrorLogMessage1[] = "something really bad happened";
345 const char kErrorLogMessage2[] = "some other bad thing happened";
346
347 base::ScopedTempDir temp_dir;
348 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
349 base::FilePath file_log_path = temp_dir.GetPath().Append("file.log");
350
351 // Set up logging.
352 LoggingSettings settings;
353 settings.logging_dest = LOG_TO_FILE;
354 settings.log_file_path = file_log_path.value().c_str();
355 InitLogging(settings);
356
357 LOG(ERROR) << kErrorLogMessage1;
358
359 // Duplicate the log FILE, close the original (to make sure we actually
360 // duplicated it), and write to the duplicate.
361 FILE* log_file_dup = DuplicateLogFILE();
362 CHECK(log_file_dup);
363 CloseLogFile();
364 fprintf(log_file_dup, "%s\n", kErrorLogMessage2);
365 fflush(log_file_dup);
366
367 // Check the messages were written to the log file.
368 std::string written_logs;
369 ASSERT_TRUE(base::ReadFileToString(file_log_path, &written_logs));
370 ASSERT_NE(written_logs.find(kErrorLogMessage1), std::string::npos);
371 ASSERT_NE(written_logs.find(kErrorLogMessage2), std::string::npos);
372 fclose(log_file_dup);
373 }
374 #endif // BUILDFLAG(IS_CHROMEOS_ASH)
375
376 #if !CHECK_WILL_STREAM() && BUILDFLAG(IS_WIN)
377 // Tell clang to not optimize this function or else it will remove the CHECKs.
CheckContainingFunc(int death_location)378 [[clang::optnone]] NOINLINE void CheckContainingFunc(int death_location) {
379 CHECK(death_location != 1);
380 CHECK(death_location != 2);
381 CHECK(death_location != 3);
382 }
383
GetCheckExceptionData(EXCEPTION_POINTERS * p,DWORD * code,void ** addr)384 int GetCheckExceptionData(EXCEPTION_POINTERS* p, DWORD* code, void** addr) {
385 *code = p->ExceptionRecord->ExceptionCode;
386 *addr = p->ExceptionRecord->ExceptionAddress;
387 return EXCEPTION_EXECUTE_HANDLER;
388 }
389
TEST_F(LoggingTest,CheckCausesDistinctBreakpoints)390 TEST_F(LoggingTest, CheckCausesDistinctBreakpoints) {
391 DWORD code1 = 0;
392 DWORD code2 = 0;
393 DWORD code3 = 0;
394 void* addr1 = nullptr;
395 void* addr2 = nullptr;
396 void* addr3 = nullptr;
397
398 // Record the exception code and addresses.
399 __try {
400 CheckContainingFunc(1);
401 } __except (
402 GetCheckExceptionData(GetExceptionInformation(), &code1, &addr1)) {
403 }
404
405 __try {
406 CheckContainingFunc(2);
407 } __except (
408 GetCheckExceptionData(GetExceptionInformation(), &code2, &addr2)) {
409 }
410
411 __try {
412 CheckContainingFunc(3);
413 } __except (
414 GetCheckExceptionData(GetExceptionInformation(), &code3, &addr3)) {
415 }
416
417 // Ensure that the exception codes are correct (in particular, breakpoints,
418 // not access violations).
419 EXPECT_EQ(STATUS_BREAKPOINT, code1);
420 EXPECT_EQ(STATUS_BREAKPOINT, code2);
421 EXPECT_EQ(STATUS_BREAKPOINT, code3);
422
423 // Ensure that none of the CHECKs are colocated.
424 EXPECT_NE(addr1, addr2);
425 EXPECT_NE(addr1, addr3);
426 EXPECT_NE(addr2, addr3);
427 }
428 #elif BUILDFLAG(IS_FUCHSIA)
429
430 // CHECK causes a direct crash (without jumping to another function) only in
431 // official builds. Unfortunately, continuous test coverage on official builds
432 // is lower. Furthermore, since the Fuchsia implementation uses threads, it is
433 // not possible to rely on an implementation of CHECK that calls abort(), which
434 // takes down the whole process, preventing the thread exception handler from
435 // handling the exception. DO_CHECK here falls back on base::ImmediateCrash() in
436 // non-official builds, to catch regressions earlier in the CQ.
437 #if !CHECK_WILL_STREAM()
438 #define DO_CHECK CHECK
439 #else
440 #define DO_CHECK(cond) \
441 if (!(cond)) { \
442 base::ImmediateCrash(); \
443 }
444 #endif
445
446 struct thread_data_t {
447 // For signaling the thread ended properly.
448 zx::event event;
449 // For catching thread exceptions. Created by the crashing thread.
450 zx::channel channel;
451 // Location where the thread is expected to crash.
452 int death_location;
453 };
454
455 // Indicates the exception channel has been created successfully.
456 constexpr zx_signals_t kChannelReadySignal = ZX_USER_SIGNAL_0;
457
458 // Indicates an error setting up the crash thread.
459 constexpr zx_signals_t kCrashThreadErrorSignal = ZX_USER_SIGNAL_1;
460
CrashThread(void * arg)461 void* CrashThread(void* arg) {
462 thread_data_t* data = (thread_data_t*)arg;
463 int death_location = data->death_location;
464
465 // Register the exception handler.
466 zx_status_t status =
467 zx::thread::self()->create_exception_channel(0, &data->channel);
468 if (status != ZX_OK) {
469 data->event.signal(0, kCrashThreadErrorSignal);
470 return nullptr;
471 }
472 data->event.signal(0, kChannelReadySignal);
473
474 DO_CHECK(death_location != 1);
475 DO_CHECK(death_location != 2);
476 DO_CHECK(death_location != 3);
477
478 // We should never reach this point, signal the thread incorrectly ended
479 // properly.
480 data->event.signal(0, kCrashThreadErrorSignal);
481 return nullptr;
482 }
483
484 // Helper function to call pthread_exit(nullptr).
exception_pthread_exit()485 _Noreturn __NO_SAFESTACK void exception_pthread_exit() {
486 pthread_exit(nullptr);
487 }
488
489 // Runs the CrashThread function in a separate thread.
SpawnCrashThread(int death_location,uintptr_t * child_crash_addr)490 void SpawnCrashThread(int death_location, uintptr_t* child_crash_addr) {
491 zx::event event;
492 zx_status_t status = zx::event::create(0, &event);
493 ASSERT_EQ(status, ZX_OK);
494
495 // Run the thread.
496 thread_data_t thread_data = {std::move(event), zx::channel(), death_location};
497 pthread_t thread;
498 int ret = pthread_create(&thread, nullptr, CrashThread, &thread_data);
499 ASSERT_EQ(ret, 0);
500
501 // Wait for the thread to set up its exception channel.
502 zx_signals_t signals = 0;
503 status =
504 thread_data.event.wait_one(kChannelReadySignal | kCrashThreadErrorSignal,
505 zx::time::infinite(), &signals);
506 ASSERT_EQ(status, ZX_OK);
507 ASSERT_EQ(signals, kChannelReadySignal);
508
509 // Wait for the exception and read it out of the channel.
510 status =
511 thread_data.channel.wait_one(ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED,
512 zx::time::infinite(), &signals);
513 ASSERT_EQ(status, ZX_OK);
514 // Check the thread did crash and not terminate.
515 ASSERT_FALSE(signals & ZX_CHANNEL_PEER_CLOSED);
516
517 zx_exception_info_t exception_info;
518 zx::exception exception;
519 status = thread_data.channel.read(
520 0, &exception_info, exception.reset_and_get_address(),
521 sizeof(exception_info), 1, nullptr, nullptr);
522 ASSERT_EQ(status, ZX_OK);
523
524 // Get the crash address and point the thread towards exiting.
525 zx::thread zircon_thread;
526 status = exception.get_thread(&zircon_thread);
527 ASSERT_EQ(status, ZX_OK);
528 zx_thread_state_general_regs_t buffer;
529 status = zircon_thread.read_state(ZX_THREAD_STATE_GENERAL_REGS, &buffer,
530 sizeof(buffer));
531 ASSERT_EQ(status, ZX_OK);
532 #if defined(ARCH_CPU_X86_64)
533 *child_crash_addr = static_cast<uintptr_t>(buffer.rip);
534 buffer.rip = reinterpret_cast<uintptr_t>(exception_pthread_exit);
535 #elif defined(ARCH_CPU_ARM64)
536 *child_crash_addr = static_cast<uintptr_t>(buffer.pc);
537 buffer.pc = reinterpret_cast<uintptr_t>(exception_pthread_exit);
538 #else
539 #error Unsupported architecture
540 #endif
541 ASSERT_EQ(zircon_thread.write_state(ZX_THREAD_STATE_GENERAL_REGS, &buffer,
542 sizeof(buffer)),
543 ZX_OK);
544
545 // Clear the exception so the thread continues.
546 uint32_t state = ZX_EXCEPTION_STATE_HANDLED;
547 ASSERT_EQ(
548 exception.set_property(ZX_PROP_EXCEPTION_STATE, &state, sizeof(state)),
549 ZX_OK);
550 exception.reset();
551
552 // Join the exiting pthread.
553 ASSERT_EQ(pthread_join(thread, nullptr), 0);
554 }
555
TEST_F(LoggingTest,CheckCausesDistinctBreakpoints)556 TEST_F(LoggingTest, CheckCausesDistinctBreakpoints) {
557 uintptr_t child_crash_addr_1 = 0;
558 uintptr_t child_crash_addr_2 = 0;
559 uintptr_t child_crash_addr_3 = 0;
560
561 SpawnCrashThread(1, &child_crash_addr_1);
562 SpawnCrashThread(2, &child_crash_addr_2);
563 SpawnCrashThread(3, &child_crash_addr_3);
564
565 ASSERT_NE(0u, child_crash_addr_1);
566 ASSERT_NE(0u, child_crash_addr_2);
567 ASSERT_NE(0u, child_crash_addr_3);
568 #if defined(OFFICIAL_BUILD)
569 // In unofficial builds, we'll end up in std::abort
570 // for each crash. In official builds, we should get a different
571 // crash address for each location.
572 ASSERT_NE(child_crash_addr_1, child_crash_addr_2);
573 ASSERT_NE(child_crash_addr_1, child_crash_addr_3);
574 ASSERT_NE(child_crash_addr_2, child_crash_addr_3);
575 #endif // defined(OFFICIAL_BUILD)
576 }
577 #elif BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_NACL) && !BUILDFLAG(IS_IOS) && \
578 (defined(ARCH_CPU_X86_FAMILY) || defined(ARCH_CPU_ARM_FAMILY))
579
580 int g_child_crash_pipe;
581
CheckCrashTestSighandler(int,siginfo_t * info,void * context_ptr)582 void CheckCrashTestSighandler(int, siginfo_t* info, void* context_ptr) {
583 // Conversely to what clearly stated in "man 2 sigaction", some Linux kernels
584 // do NOT populate the |info->si_addr| in the case of a SIGTRAP. Hence we
585 // need the arch-specific boilerplate below, which is inspired by breakpad.
586 // At the same time, on OSX, ucontext.h is deprecated but si_addr works fine.
587 uintptr_t crash_addr = 0;
588 #if BUILDFLAG(IS_MAC)
589 crash_addr = reinterpret_cast<uintptr_t>(info->si_addr);
590 #else // OS_*
591 ucontext_t* context = reinterpret_cast<ucontext_t*>(context_ptr);
592 #if defined(ARCH_CPU_X86)
593 crash_addr = static_cast<uintptr_t>(context->uc_mcontext.gregs[REG_EIP]);
594 #elif defined(ARCH_CPU_X86_64)
595 crash_addr = static_cast<uintptr_t>(context->uc_mcontext.gregs[REG_RIP]);
596 #elif defined(ARCH_CPU_ARMEL)
597 crash_addr = static_cast<uintptr_t>(context->uc_mcontext.arm_pc);
598 #elif defined(ARCH_CPU_ARM64)
599 crash_addr = static_cast<uintptr_t>(context->uc_mcontext.pc);
600 #endif // ARCH_*
601 #endif // OS_*
602 HANDLE_EINTR(write(g_child_crash_pipe, &crash_addr, sizeof(uintptr_t)));
603 _exit(0);
604 }
605
606 // CHECK causes a direct crash (without jumping to another function) only in
607 // official builds. Unfortunately, continuous test coverage on official builds
608 // is lower. DO_CHECK here falls back on a home-brewed implementation in
609 // non-official builds, to catch regressions earlier in the CQ.
610 #if !CHECK_WILL_STREAM()
611 #define DO_CHECK CHECK
612 #else
613 #define DO_CHECK(cond) \
614 if (!(cond)) { \
615 base::ImmediateCrash(); \
616 }
617 #endif
618
CrashChildMain(int death_location)619 void CrashChildMain(int death_location) {
620 struct sigaction act = {};
621 act.sa_sigaction = CheckCrashTestSighandler;
622 act.sa_flags = SA_SIGINFO;
623 ASSERT_EQ(0, sigaction(SIGTRAP, &act, nullptr));
624 ASSERT_EQ(0, sigaction(SIGBUS, &act, nullptr));
625 ASSERT_EQ(0, sigaction(SIGILL, &act, nullptr));
626 ASSERT_EQ(0, sigaction(SIGABRT, &act, nullptr));
627 DO_CHECK(death_location != 1);
628 DO_CHECK(death_location != 2);
629 printf("\n");
630 DO_CHECK(death_location != 3);
631
632 // Should never reach this point.
633 const uintptr_t failed = 0;
634 HANDLE_EINTR(write(g_child_crash_pipe, &failed, sizeof(uintptr_t)));
635 }
636
SpawnChildAndCrash(int death_location,uintptr_t * child_crash_addr)637 void SpawnChildAndCrash(int death_location, uintptr_t* child_crash_addr) {
638 int pipefd[2];
639 ASSERT_EQ(0, pipe(pipefd));
640
641 int pid = fork();
642 ASSERT_GE(pid, 0);
643
644 if (pid == 0) { // child process.
645 close(pipefd[0]); // Close reader (parent) end.
646 g_child_crash_pipe = pipefd[1];
647 CrashChildMain(death_location);
648 FAIL() << "The child process was supposed to crash. It didn't.";
649 }
650
651 close(pipefd[1]); // Close writer (child) end.
652 DCHECK(child_crash_addr);
653 int res = HANDLE_EINTR(read(pipefd[0], child_crash_addr, sizeof(uintptr_t)));
654 ASSERT_EQ(static_cast<int>(sizeof(uintptr_t)), res);
655 }
656
TEST_F(LoggingTest,CheckCausesDistinctBreakpoints)657 TEST_F(LoggingTest, CheckCausesDistinctBreakpoints) {
658 uintptr_t child_crash_addr_1 = 0;
659 uintptr_t child_crash_addr_2 = 0;
660 uintptr_t child_crash_addr_3 = 0;
661
662 SpawnChildAndCrash(1, &child_crash_addr_1);
663 SpawnChildAndCrash(2, &child_crash_addr_2);
664 SpawnChildAndCrash(3, &child_crash_addr_3);
665
666 ASSERT_NE(0u, child_crash_addr_1);
667 ASSERT_NE(0u, child_crash_addr_2);
668 ASSERT_NE(0u, child_crash_addr_3);
669
670 #if defined(OFFICIAL_BUILD)
671 // In unofficial builds, we'll end up in std::abort
672 // for each crash. In official builds, we should get a different
673 // crash address for each location.
674 ASSERT_NE(child_crash_addr_1, child_crash_addr_2);
675 ASSERT_NE(child_crash_addr_1, child_crash_addr_3);
676 ASSERT_NE(child_crash_addr_2, child_crash_addr_3);
677 #endif
678 }
679 #endif // BUILDFLAG(IS_POSIX)
680
TEST_F(LoggingTest,DebugLoggingReleaseBehavior)681 TEST_F(LoggingTest, DebugLoggingReleaseBehavior) {
682 #if DCHECK_IS_ON()
683 int debug_only_variable = 1;
684 #endif
685 // These should avoid emitting references to |debug_only_variable|
686 // in release mode.
687 DLOG_IF(INFO, debug_only_variable) << "test";
688 DLOG_ASSERT(debug_only_variable) << "test";
689 DPLOG_IF(INFO, debug_only_variable) << "test";
690 DVLOG_IF(1, debug_only_variable) << "test";
691 }
692
TEST_F(LoggingTest,NestedLogAssertHandlers)693 TEST_F(LoggingTest, NestedLogAssertHandlers) {
694 if (LOGGING_DFATAL != LOGGING_FATAL) {
695 GTEST_SKIP() << "Test relies on DFATAL being FATAL for "
696 "NestedLogAssertHandlers to fire.";
697 }
698
699 ::testing::InSequence dummy;
700 ::testing::StrictMock<MockLogAssertHandler> handler_a, handler_b;
701
702 EXPECT_CALL(
703 handler_a,
704 HandleLogAssert(
705 _, _, std::string_view("First assert must be caught by handler_a"),
706 _));
707 EXPECT_CALL(
708 handler_b,
709 HandleLogAssert(
710 _, _, std::string_view("Second assert must be caught by handler_b"),
711 _));
712 EXPECT_CALL(
713 handler_a,
714 HandleLogAssert(
715 _, _,
716 std::string_view("Last assert must be caught by handler_a again"),
717 _));
718
719 logging::ScopedLogAssertHandler scoped_handler_a(base::BindRepeating(
720 &MockLogAssertHandler::HandleLogAssert, base::Unretained(&handler_a)));
721
722 // Using LOG(DFATAL) rather than LOG(FATAL) as the latter is not cancellable.
723 LOG(DFATAL) << "First assert must be caught by handler_a";
724
725 {
726 logging::ScopedLogAssertHandler scoped_handler_b(base::BindRepeating(
727 &MockLogAssertHandler::HandleLogAssert, base::Unretained(&handler_b)));
728 LOG(DFATAL) << "Second assert must be caught by handler_b";
729 }
730
731 LOG(DFATAL) << "Last assert must be caught by handler_a again";
732 }
733
734 // Test that defining an operator<< for a type in a namespace doesn't prevent
735 // other code in that namespace from calling the operator<<(ostream, wstring)
736 // defined by logging.h. This can fail if operator<<(ostream, wstring) can't be
737 // found by ADL, since defining another operator<< prevents name lookup from
738 // looking in the global namespace.
739 namespace nested_test {
740 class Streamable {};
operator <<(std::ostream & out,const Streamable &)741 [[maybe_unused]] std::ostream& operator<<(std::ostream& out,
742 const Streamable&) {
743 return out << "Streamable";
744 }
TEST_F(LoggingTest,StreamingWstringFindsCorrectOperator)745 TEST_F(LoggingTest, StreamingWstringFindsCorrectOperator) {
746 std::wstring wstr = L"Hello World";
747 std::ostringstream ostr;
748 ostr << wstr;
749 EXPECT_EQ("Hello World", ostr.str());
750 }
751 } // namespace nested_test
752
TEST_F(LoggingTest,LogPrefix)753 TEST_F(LoggingTest, LogPrefix) {
754 // Use a static because only captureless lambdas can be converted to a
755 // function pointer for SetLogMessageHandler().
756 static base::NoDestructor<std::string> log_string;
757 SetLogMessageHandler([](int severity, const char* file, int line,
758 size_t start, const std::string& str) -> bool {
759 *log_string = str;
760 return true;
761 });
762
763 // Logging with a prefix includes the prefix string.
764 const char kPrefix[] = "prefix";
765 SetLogPrefix(kPrefix);
766 LOG(ERROR) << "test"; // Writes into |log_string|.
767 EXPECT_NE(std::string::npos, log_string->find(kPrefix));
768 // Logging without a prefix does not include the prefix string.
769 SetLogPrefix(nullptr);
770 LOG(ERROR) << "test"; // Writes into |log_string|.
771 EXPECT_EQ(std::string::npos, log_string->find(kPrefix));
772 }
773
774 #if BUILDFLAG(IS_CHROMEOS_ASH)
TEST_F(LoggingTest,LogCrosSyslogFormat)775 TEST_F(LoggingTest, LogCrosSyslogFormat) {
776 // Set log format to syslog format.
777 scoped_logging_settings().SetLogFormat(LogFormat::LOG_FORMAT_SYSLOG);
778
779 const char* kTimestampPattern = R"(\d\d\d\d\-\d\d\-\d\d)" // date
780 R"(T\d\d\:\d\d\:\d\d\.\d\d\d\d\d\d)" // time
781 R"(Z.+\n)"; // timezone
782
783 // Use a static because only captureless lambdas can be converted to a
784 // function pointer for SetLogMessageHandler().
785 static base::NoDestructor<std::string> log_string;
786 SetLogMessageHandler([](int severity, const char* file, int line,
787 size_t start, const std::string& str) -> bool {
788 *log_string = str;
789 return true;
790 });
791
792 {
793 // All flags are true.
794 SetLogItems(true, true, true, true);
795 const char* kExpected =
796 R"(\S+ \d+ ERROR \S+\[\d+:\d+\]\: \[\S+\] message\n)";
797
798 LOG(ERROR) << "message";
799
800 EXPECT_THAT(*log_string, ::testing::MatchesRegex(kTimestampPattern));
801 EXPECT_THAT(*log_string, ::testing::MatchesRegex(kExpected));
802 }
803
804 {
805 // Timestamp is true.
806 SetLogItems(false, false, true, false);
807 const char* kExpected = R"(\S+ ERROR \S+\: \[\S+\] message\n)";
808
809 LOG(ERROR) << "message";
810
811 EXPECT_THAT(*log_string, ::testing::MatchesRegex(kTimestampPattern));
812 EXPECT_THAT(*log_string, ::testing::MatchesRegex(kExpected));
813 }
814
815 {
816 // PID and timestamp are true.
817 SetLogItems(true, false, true, false);
818 const char* kExpected = R"(\S+ ERROR \S+\[\d+\]: \[\S+\] message\n)";
819
820 LOG(ERROR) << "message";
821
822 EXPECT_THAT(*log_string, ::testing::MatchesRegex(kTimestampPattern));
823 EXPECT_THAT(*log_string, ::testing::MatchesRegex(kExpected));
824 }
825
826 {
827 // ThreadID and timestamp are true.
828 SetLogItems(false, true, true, false);
829 const char* kExpected = R"(\S+ ERROR \S+\[:\d+\]: \[\S+\] message\n)";
830
831 LOG(ERROR) << "message";
832
833 EXPECT_THAT(*log_string, ::testing::MatchesRegex(kTimestampPattern));
834 EXPECT_THAT(*log_string, ::testing::MatchesRegex(kExpected));
835 }
836
837 {
838 // All flags are false.
839 SetLogItems(false, false, false, false);
840 const char* kExpected = R"(ERROR \S+: \[\S+\] message\n)";
841
842 LOG(ERROR) << "message";
843
844 EXPECT_THAT(*log_string, ::testing::MatchesRegex(kExpected));
845 }
846 }
847 #endif // BUILDFLAG(IS_CHROMEOS_ASH)
848
849 // We define a custom operator<< for std::u16string so we can use it with
850 // logging. This tests that conversion.
TEST_F(LoggingTest,String16)851 TEST_F(LoggingTest, String16) {
852 // Basic stream test.
853 {
854 std::ostringstream stream;
855 stream << "Empty '" << std::u16string() << "' standard '"
856 << std::u16string(u"Hello, world") << "'";
857 EXPECT_STREQ("Empty '' standard 'Hello, world'", stream.str().c_str());
858 }
859
860 // Interesting edge cases.
861 {
862 // These should each get converted to the invalid character: EF BF BD.
863 std::u16string initial_surrogate;
864 initial_surrogate.push_back(0xd800);
865 std::u16string final_surrogate;
866 final_surrogate.push_back(0xdc00);
867
868 // Old italic A = U+10300, will get converted to: F0 90 8C 80 'z'.
869 std::u16string surrogate_pair;
870 surrogate_pair.push_back(0xd800);
871 surrogate_pair.push_back(0xdf00);
872 surrogate_pair.push_back('z');
873
874 // Will get converted to the invalid char + 's': EF BF BD 's'.
875 std::u16string unterminated_surrogate;
876 unterminated_surrogate.push_back(0xd800);
877 unterminated_surrogate.push_back('s');
878
879 std::ostringstream stream;
880 stream << initial_surrogate << "," << final_surrogate << ","
881 << surrogate_pair << "," << unterminated_surrogate;
882
883 EXPECT_STREQ("\xef\xbf\xbd,\xef\xbf\xbd,\xf0\x90\x8c\x80z,\xef\xbf\xbds",
884 stream.str().c_str());
885 }
886 }
887
888 // Tests that we don't VLOG from logging_unittest except when in the scope
889 // of the ScopedVmoduleSwitches.
TEST_F(LoggingTest,ScopedVmoduleSwitches)890 TEST_F(LoggingTest, ScopedVmoduleSwitches) {
891 EXPECT_TRUE(VLOG_IS_ON(0));
892
893 // To avoid unreachable-code warnings when VLOG is disabled at compile-time.
894 int expected_logs = 0;
895 if (VLOG_IS_ON(0))
896 expected_logs += 1;
897
898 SetMinLogLevel(LOGGING_FATAL);
899
900 {
901 MockLogSource mock_log_source;
902 EXPECT_CALL(mock_log_source, Log()).Times(0);
903
904 VLOG(1) << mock_log_source.Log();
905 }
906
907 {
908 ScopedVmoduleSwitches scoped_vmodule_switches;
909 scoped_vmodule_switches.InitWithSwitches(__FILE__ "=1");
910 MockLogSource mock_log_source;
911 EXPECT_CALL(mock_log_source, Log())
912 .Times(expected_logs)
913 .WillRepeatedly(Return("log message"));
914
915 VLOG(1) << mock_log_source.Log();
916 }
917
918 {
919 MockLogSource mock_log_source;
920 EXPECT_CALL(mock_log_source, Log()).Times(0);
921
922 VLOG(1) << mock_log_source.Log();
923 }
924 }
925
TEST_F(LoggingTest,BuildCrashString)926 TEST_F(LoggingTest, BuildCrashString) {
927 EXPECT_EQ("file.cc:42: ",
928 LogMessage("file.cc", 42, LOGGING_ERROR).BuildCrashString());
929
930 // BuildCrashString() should strip path/to/file prefix.
931 LogMessage msg(
932 #if BUILDFLAG(IS_WIN)
933 "..\\foo\\bar\\file.cc",
934 #else
935 "../foo/bar/file.cc",
936 #endif // BUILDFLAG(IS_WIN)
937 42, LOGGING_ERROR);
938 msg.stream() << "Hello";
939 EXPECT_EQ("file.cc:42: Hello", msg.BuildCrashString());
940 }
941
TEST_F(LoggingTest,SystemErrorNotChanged)942 TEST_F(LoggingTest, SystemErrorNotChanged) {
943 auto set_last_error = [](logging::SystemErrorCode error) {
944 #if BUILDFLAG(IS_WIN)
945 ::SetLastError(error);
946 #else
947 errno = error;
948 #endif
949 };
950
951 SystemErrorCode during_streaming = 0;
952 SystemErrorCode set_during_streaming = 0;
953
954 set_last_error(SystemErrorCode(123));
955 LOG(WARNING) << (during_streaming = GetLastSystemErrorCode())
956 << (set_last_error(SystemErrorCode(42)),
957 set_during_streaming = GetLastSystemErrorCode());
958
959 // Initializing the LogMessage shouldn't change the observable error code.
960 EXPECT_EQ(SystemErrorCode(123), during_streaming);
961 // Verify that we can set and get the error code during streaming.
962 EXPECT_EQ(SystemErrorCode(42), set_during_streaming);
963 // Verify that the last set error code (during streaming) is preserved after
964 // logging as well.
965 EXPECT_EQ(SystemErrorCode(42), GetLastSystemErrorCode());
966
967 // Repeat the test above but using PLOG.
968 during_streaming = 0;
969 set_during_streaming = 0;
970 set_last_error(SystemErrorCode(123));
971 PLOG(ERROR) << (during_streaming = GetLastSystemErrorCode())
972 << (set_last_error(SystemErrorCode(42)),
973 set_during_streaming = GetLastSystemErrorCode());
974
975 EXPECT_EQ(SystemErrorCode(123), during_streaming);
976 EXPECT_EQ(SystemErrorCode(42), set_during_streaming);
977 EXPECT_EQ(SystemErrorCode(42), GetLastSystemErrorCode());
978 }
979
TEST_F(LoggingTest,CorrectSystemErrorUsed)980 TEST_F(LoggingTest, CorrectSystemErrorUsed) {
981 auto set_last_error = [](logging::SystemErrorCode error) {
982 #if BUILDFLAG(IS_WIN)
983 ::SetLastError(error);
984 #else
985 errno = error;
986 #endif
987 };
988
989 // Use a static because only captureless lambdas can be converted to a
990 // function pointer for SetLogMessageHandler().
991 static base::NoDestructor<std::string> log_string;
992 SetLogMessageHandler([](int severity, const char* file, int line,
993 size_t start, const std::string& str) -> bool {
994 *log_string = str;
995 return true;
996 });
997
998 const SystemErrorCode kTestError = 28;
999 const std::string kExpectedSystemErrorMsg =
1000 SystemErrorCodeToString(kTestError);
1001
1002 set_last_error(kTestError);
1003 PLOG(ERROR);
1004
1005 // Test that the last system error code got printed as expected.
1006 EXPECT_NE(std::string::npos, log_string->find(kExpectedSystemErrorMsg));
1007
1008 if (DCHECK_IS_ON()) {
1009 *log_string = "";
1010 set_last_error(kTestError);
1011 DPLOG(ERROR);
1012
1013 EXPECT_NE(std::string::npos, log_string->find(kExpectedSystemErrorMsg));
1014 }
1015 }
1016
TEST_F(LoggingTest,BuildTimeVLOG)1017 TEST_F(LoggingTest, BuildTimeVLOG) {
1018 // Use a static because only captureless lambdas can be converted to a
1019 // function pointer for SetLogMessageHandler().
1020 static base::NoDestructor<std::string> log_string;
1021 SetLogMessageHandler([](int severity, const char* file, int line,
1022 size_t start, const std::string& str) -> bool {
1023 *log_string = str;
1024 return true;
1025 });
1026
1027 // No VLOG by default.
1028 EXPECT_FALSE(VLOG_IS_ON(1));
1029 VLOG(1) << "Expect not logged";
1030 EXPECT_TRUE(log_string->empty());
1031
1032 // Re-define ENABLED_VLOG_LEVEL to enable VLOG(1).
1033 // Note that ENABLED_VLOG_LEVEL has impact on all the code after it so please
1034 // keep this test case the last one in this file.
1035 #undef ENABLED_VLOG_LEVEL
1036 #define ENABLED_VLOG_LEVEL 1
1037
1038 EXPECT_TRUE(VLOG_IS_ON(1));
1039 EXPECT_FALSE(VLOG_IS_ON(2));
1040
1041 VLOG(1) << "Expect logged";
1042 EXPECT_THAT(*log_string, ::testing::MatchesRegex(".* Expect logged\n"));
1043
1044 log_string->clear();
1045 VLOG(2) << "Expect not logged";
1046 EXPECT_TRUE(log_string->empty());
1047 }
1048
1049 // NO NEW TESTS HERE
1050 // The test above redefines ENABLED_VLOG_LEVEL, so new tests should be added
1051 // before it.
1052
1053 } // namespace
1054
1055 } // namespace logging
1056