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 "third_party/abseil-cpp/absl/types/optional.h"
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 ::testing::InSequence dummy;
673 ::testing::StrictMock<MockLogAssertHandler> handler_a, handler_b;
674
675 EXPECT_CALL(
676 handler_a,
677 HandleLogAssert(
678 _, _, base::StringPiece("First assert must be caught by handler_a"),
679 _));
680 EXPECT_CALL(
681 handler_b,
682 HandleLogAssert(
683 _, _, base::StringPiece("Second assert must be caught by handler_b"),
684 _));
685 EXPECT_CALL(
686 handler_a,
687 HandleLogAssert(
688 _, _,
689 base::StringPiece("Last assert must be caught by handler_a again"),
690 _));
691
692 logging::ScopedLogAssertHandler scoped_handler_a(base::BindRepeating(
693 &MockLogAssertHandler::HandleLogAssert, base::Unretained(&handler_a)));
694
695 // Using LOG(FATAL) rather than CHECK(false) here since log messages aren't
696 // preserved for CHECKs in official builds.
697 LOG(FATAL) << "First assert must be caught by handler_a";
698
699 {
700 logging::ScopedLogAssertHandler scoped_handler_b(base::BindRepeating(
701 &MockLogAssertHandler::HandleLogAssert, base::Unretained(&handler_b)));
702 LOG(FATAL) << "Second assert must be caught by handler_b";
703 }
704
705 LOG(FATAL) << "Last assert must be caught by handler_a again";
706 }
707
708 // Test that defining an operator<< for a type in a namespace doesn't prevent
709 // other code in that namespace from calling the operator<<(ostream, wstring)
710 // defined by logging.h. This can fail if operator<<(ostream, wstring) can't be
711 // found by ADL, since defining another operator<< prevents name lookup from
712 // looking in the global namespace.
713 namespace nested_test {
714 class Streamable {};
operator <<(std::ostream & out,const Streamable &)715 [[maybe_unused]] std::ostream& operator<<(std::ostream& out,
716 const Streamable&) {
717 return out << "Streamable";
718 }
TEST_F(LoggingTest,StreamingWstringFindsCorrectOperator)719 TEST_F(LoggingTest, StreamingWstringFindsCorrectOperator) {
720 std::wstring wstr = L"Hello World";
721 std::ostringstream ostr;
722 ostr << wstr;
723 EXPECT_EQ("Hello World", ostr.str());
724 }
725 } // namespace nested_test
726
TEST_F(LoggingTest,LogPrefix)727 TEST_F(LoggingTest, LogPrefix) {
728 // Use a static because only captureless lambdas can be converted to a
729 // function pointer for SetLogMessageHandler().
730 static base::NoDestructor<std::string> log_string;
731 SetLogMessageHandler([](int severity, const char* file, int line,
732 size_t start, const std::string& str) -> bool {
733 *log_string = str;
734 return true;
735 });
736
737 // Logging with a prefix includes the prefix string.
738 const char kPrefix[] = "prefix";
739 SetLogPrefix(kPrefix);
740 LOG(ERROR) << "test"; // Writes into |log_string|.
741 EXPECT_NE(std::string::npos, log_string->find(kPrefix));
742 // Logging without a prefix does not include the prefix string.
743 SetLogPrefix(nullptr);
744 LOG(ERROR) << "test"; // Writes into |log_string|.
745 EXPECT_EQ(std::string::npos, log_string->find(kPrefix));
746 }
747
748 #if BUILDFLAG(IS_CHROMEOS_ASH)
TEST_F(LoggingTest,LogCrosSyslogFormat)749 TEST_F(LoggingTest, LogCrosSyslogFormat) {
750 // Set log format to syslog format.
751 scoped_logging_settings().SetLogFormat(LogFormat::LOG_FORMAT_SYSLOG);
752
753 const char* kTimestampPattern = R"(\d\d\d\d\-\d\d\-\d\d)" // date
754 R"(T\d\d\:\d\d\:\d\d\.\d\d\d\d\d\d)" // time
755 R"(Z.+\n)"; // timezone
756
757 // Use a static because only captureless lambdas can be converted to a
758 // function pointer for SetLogMessageHandler().
759 static base::NoDestructor<std::string> log_string;
760 SetLogMessageHandler([](int severity, const char* file, int line,
761 size_t start, const std::string& str) -> bool {
762 *log_string = str;
763 return true;
764 });
765
766 {
767 // All flags are true.
768 SetLogItems(true, true, true, true);
769 const char* kExpected =
770 R"(\S+ \d+ ERROR \S+\[\d+:\d+\]\: \[\S+\] message\n)";
771
772 LOG(ERROR) << "message";
773
774 EXPECT_THAT(*log_string, ::testing::MatchesRegex(kTimestampPattern));
775 EXPECT_THAT(*log_string, ::testing::MatchesRegex(kExpected));
776 }
777
778 {
779 // Timestamp is true.
780 SetLogItems(false, false, true, false);
781 const char* kExpected = R"(\S+ ERROR \S+\: \[\S+\] message\n)";
782
783 LOG(ERROR) << "message";
784
785 EXPECT_THAT(*log_string, ::testing::MatchesRegex(kTimestampPattern));
786 EXPECT_THAT(*log_string, ::testing::MatchesRegex(kExpected));
787 }
788
789 {
790 // PID and timestamp are true.
791 SetLogItems(true, false, true, false);
792 const char* kExpected = R"(\S+ ERROR \S+\[\d+\]: \[\S+\] message\n)";
793
794 LOG(ERROR) << "message";
795
796 EXPECT_THAT(*log_string, ::testing::MatchesRegex(kTimestampPattern));
797 EXPECT_THAT(*log_string, ::testing::MatchesRegex(kExpected));
798 }
799
800 {
801 // ThreadID and timestamp are true.
802 SetLogItems(false, true, true, false);
803 const char* kExpected = R"(\S+ ERROR \S+\[:\d+\]: \[\S+\] message\n)";
804
805 LOG(ERROR) << "message";
806
807 EXPECT_THAT(*log_string, ::testing::MatchesRegex(kTimestampPattern));
808 EXPECT_THAT(*log_string, ::testing::MatchesRegex(kExpected));
809 }
810
811 {
812 // All flags are false.
813 SetLogItems(false, false, false, false);
814 const char* kExpected = R"(ERROR \S+: \[\S+\] message\n)";
815
816 LOG(ERROR) << "message";
817
818 EXPECT_THAT(*log_string, ::testing::MatchesRegex(kExpected));
819 }
820 }
821 #endif // BUILDFLAG(IS_CHROMEOS_ASH)
822
823 // We define a custom operator<< for std::u16string so we can use it with
824 // logging. This tests that conversion.
TEST_F(LoggingTest,String16)825 TEST_F(LoggingTest, String16) {
826 // Basic stream test.
827 {
828 std::ostringstream stream;
829 stream << "Empty '" << std::u16string() << "' standard '"
830 << std::u16string(u"Hello, world") << "'";
831 EXPECT_STREQ("Empty '' standard 'Hello, world'", stream.str().c_str());
832 }
833
834 // Interesting edge cases.
835 {
836 // These should each get converted to the invalid character: EF BF BD.
837 std::u16string initial_surrogate;
838 initial_surrogate.push_back(0xd800);
839 std::u16string final_surrogate;
840 final_surrogate.push_back(0xdc00);
841
842 // Old italic A = U+10300, will get converted to: F0 90 8C 80 'z'.
843 std::u16string surrogate_pair;
844 surrogate_pair.push_back(0xd800);
845 surrogate_pair.push_back(0xdf00);
846 surrogate_pair.push_back('z');
847
848 // Will get converted to the invalid char + 's': EF BF BD 's'.
849 std::u16string unterminated_surrogate;
850 unterminated_surrogate.push_back(0xd800);
851 unterminated_surrogate.push_back('s');
852
853 std::ostringstream stream;
854 stream << initial_surrogate << "," << final_surrogate << ","
855 << surrogate_pair << "," << unterminated_surrogate;
856
857 EXPECT_STREQ("\xef\xbf\xbd,\xef\xbf\xbd,\xf0\x90\x8c\x80z,\xef\xbf\xbds",
858 stream.str().c_str());
859 }
860 }
861
862 // Tests that we don't VLOG from logging_unittest except when in the scope
863 // of the ScopedVmoduleSwitches.
TEST_F(LoggingTest,ScopedVmoduleSwitches)864 TEST_F(LoggingTest, ScopedVmoduleSwitches) {
865 EXPECT_TRUE(VLOG_IS_ON(0));
866
867 // To avoid unreachable-code warnings when VLOG is disabled at compile-time.
868 int expected_logs = 0;
869 if (VLOG_IS_ON(0))
870 expected_logs += 1;
871
872 SetMinLogLevel(LOGGING_FATAL);
873
874 {
875 MockLogSource mock_log_source;
876 EXPECT_CALL(mock_log_source, Log()).Times(0);
877
878 VLOG(1) << mock_log_source.Log();
879 }
880
881 {
882 ScopedVmoduleSwitches scoped_vmodule_switches;
883 scoped_vmodule_switches.InitWithSwitches(__FILE__ "=1");
884 MockLogSource mock_log_source;
885 EXPECT_CALL(mock_log_source, Log())
886 .Times(expected_logs)
887 .WillRepeatedly(Return("log message"));
888
889 VLOG(1) << mock_log_source.Log();
890 }
891
892 {
893 MockLogSource mock_log_source;
894 EXPECT_CALL(mock_log_source, Log()).Times(0);
895
896 VLOG(1) << mock_log_source.Log();
897 }
898 }
899
TEST_F(LoggingTest,BuildCrashString)900 TEST_F(LoggingTest, BuildCrashString) {
901 EXPECT_EQ("file.cc:42: ",
902 LogMessage("file.cc", 42, LOGGING_ERROR).BuildCrashString());
903
904 // BuildCrashString() should strip path/to/file prefix.
905 LogMessage msg(
906 #if BUILDFLAG(IS_WIN)
907 "..\\foo\\bar\\file.cc",
908 #else
909 "../foo/bar/file.cc",
910 #endif // BUILDFLAG(IS_WIN)
911 42, LOGGING_ERROR);
912 msg.stream() << "Hello";
913 EXPECT_EQ("file.cc:42: Hello", msg.BuildCrashString());
914 }
915
TEST_F(LoggingTest,BuildTimeVLOG)916 TEST_F(LoggingTest, BuildTimeVLOG) {
917 // Use a static because only captureless lambdas can be converted to a
918 // function pointer for SetLogMessageHandler().
919 static base::NoDestructor<std::string> log_string;
920 SetLogMessageHandler([](int severity, const char* file, int line,
921 size_t start, const std::string& str) -> bool {
922 *log_string = str;
923 return true;
924 });
925
926 // No VLOG by default.
927 EXPECT_FALSE(VLOG_IS_ON(1));
928 VLOG(1) << "Expect not logged";
929 EXPECT_TRUE(log_string->empty());
930
931 // Re-define ENABLED_VLOG_LEVEL to enable VLOG(1).
932 // Note that ENABLED_VLOG_LEVEL has impact on all the code after it so please
933 // keep this test case the last one in this file.
934 #undef ENABLED_VLOG_LEVEL
935 #define ENABLED_VLOG_LEVEL 1
936
937 EXPECT_TRUE(VLOG_IS_ON(1));
938 EXPECT_FALSE(VLOG_IS_ON(2));
939
940 VLOG(1) << "Expect logged";
941 EXPECT_THAT(*log_string, ::testing::MatchesRegex(".* Expect logged\n"));
942
943 log_string->clear();
944 VLOG(2) << "Expect not logged";
945 EXPECT_TRUE(log_string->empty());
946 }
947
948 // NO NEW TESTS HERE
949 // The test above redefines ENABLED_VLOG_LEVEL, so new tests should be added
950 // before it.
951
952 } // namespace
953
954 } // namespace logging
955