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