1 //
2 // Copyright 2018 The Abseil Authors.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      https://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #include "absl/debugging/failure_signal_handler.h"
18 
19 #include <csignal>
20 #include <cstdio>
21 #include <cstdlib>
22 #include <cstring>
23 #include <fstream>
24 
25 #include "gtest/gtest.h"
26 #include "gmock/gmock.h"
27 #include "absl/base/internal/raw_logging.h"
28 #include "absl/debugging/stacktrace.h"
29 #include "absl/debugging/symbolize.h"
30 #include "absl/strings/match.h"
31 #include "absl/strings/str_cat.h"
32 
33 namespace {
34 
35 using testing::StartsWith;
36 
37 #if GTEST_HAS_DEATH_TEST
38 
39 // For the parameterized death tests. GetParam() returns the signal number.
40 using FailureSignalHandlerDeathTest = ::testing::TestWithParam<int>;
41 
42 // This function runs in a fork()ed process on most systems.
InstallHandlerAndRaise(int signo)43 void InstallHandlerAndRaise(int signo) {
44   absl::InstallFailureSignalHandler(absl::FailureSignalHandlerOptions());
45   raise(signo);
46 }
47 
TEST_P(FailureSignalHandlerDeathTest,AbslFailureSignal)48 TEST_P(FailureSignalHandlerDeathTest, AbslFailureSignal) {
49   const int signo = GetParam();
50   std::string exit_regex = absl::StrCat(
51       "\\*\\*\\* ", absl::debugging_internal::FailureSignalToString(signo),
52       " received at time=");
53 #ifndef _WIN32
54   EXPECT_EXIT(InstallHandlerAndRaise(signo), testing::KilledBySignal(signo),
55               exit_regex);
56 #else
57   // Windows doesn't have testing::KilledBySignal().
58   EXPECT_DEATH_IF_SUPPORTED(InstallHandlerAndRaise(signo), exit_regex);
59 #endif
60 }
61 
62 ABSL_CONST_INIT FILE* error_file = nullptr;
63 
WriteToErrorFile(const char * msg)64 void WriteToErrorFile(const char* msg) {
65   if (msg != nullptr) {
66     ABSL_RAW_CHECK(fwrite(msg, strlen(msg), 1, error_file) == 1,
67                    "fwrite() failed");
68   }
69   ABSL_RAW_CHECK(fflush(error_file) == 0, "fflush() failed");
70 }
71 
GetTmpDir()72 std::string GetTmpDir() {
73   // TEST_TMPDIR is set by Bazel. Try the others when not running under Bazel.
74   static const char* const kTmpEnvVars[] = {"TEST_TMPDIR", "TMPDIR", "TEMP",
75                                             "TEMPDIR", "TMP"};
76   for (const char* const var : kTmpEnvVars) {
77     const char* tmp_dir = std::getenv(var);
78     if (tmp_dir != nullptr) {
79       return tmp_dir;
80     }
81   }
82 
83   // Try something reasonable.
84   return "/tmp";
85 }
86 
87 // This function runs in a fork()ed process on most systems.
InstallHandlerWithWriteToFileAndRaise(const char * file,int signo)88 void InstallHandlerWithWriteToFileAndRaise(const char* file, int signo) {
89   error_file = fopen(file, "w");
90   ABSL_RAW_CHECK(error_file != nullptr, "Failed create error_file");
91   absl::FailureSignalHandlerOptions options;
92   options.writerfn = WriteToErrorFile;
93   absl::InstallFailureSignalHandler(options);
94   raise(signo);
95 }
96 
TEST_P(FailureSignalHandlerDeathTest,AbslFatalSignalsWithWriterFn)97 TEST_P(FailureSignalHandlerDeathTest, AbslFatalSignalsWithWriterFn) {
98   const int signo = GetParam();
99   std::string tmp_dir = GetTmpDir();
100   std::string file = absl::StrCat(tmp_dir, "/signo_", signo);
101 
102   std::string exit_regex = absl::StrCat(
103       "\\*\\*\\* ", absl::debugging_internal::FailureSignalToString(signo),
104       " received at time=");
105 #ifndef _WIN32
106   EXPECT_EXIT(InstallHandlerWithWriteToFileAndRaise(file.c_str(), signo),
107               testing::KilledBySignal(signo), exit_regex);
108 #else
109   // Windows doesn't have testing::KilledBySignal().
110   EXPECT_DEATH_IF_SUPPORTED(
111       InstallHandlerWithWriteToFileAndRaise(file.c_str(), signo), exit_regex);
112 #endif
113 
114   // Open the file in this process and check its contents.
115   std::fstream error_output(file);
116   ASSERT_TRUE(error_output.is_open()) << file;
117   std::string error_line;
118   std::getline(error_output, error_line);
119   EXPECT_THAT(
120       error_line,
121       StartsWith(absl::StrCat(
122           "*** ", absl::debugging_internal::FailureSignalToString(signo),
123           " received at ")));
124 
125   // On platforms where it is possible to get the current CPU, the
126   // CPU number is also logged. Check that it is present in output.
127 #if defined(__linux__)
128   EXPECT_THAT(error_line, testing::HasSubstr(" on cpu "));
129 #endif
130 
131   if (absl::debugging_internal::StackTraceWorksForTest()) {
132     std::getline(error_output, error_line);
133     EXPECT_THAT(error_line, StartsWith("PC: "));
134   }
135 }
136 
137 constexpr int kFailureSignals[] = {
138     SIGSEGV, SIGILL,  SIGFPE, SIGABRT, SIGTERM,
139 #ifndef _WIN32
140     SIGBUS,  SIGTRAP,
141 #endif
142 };
143 
SignalParamToString(const::testing::TestParamInfo<int> & info)144 std::string SignalParamToString(const ::testing::TestParamInfo<int>& info) {
145   std::string result =
146       absl::debugging_internal::FailureSignalToString(info.param);
147   if (result.empty()) {
148     result = absl::StrCat(info.param);
149   }
150   return result;
151 }
152 
153 INSTANTIATE_TEST_SUITE_P(AbslDeathTest, FailureSignalHandlerDeathTest,
154                          ::testing::ValuesIn(kFailureSignals),
155                          SignalParamToString);
156 
157 #endif  // GTEST_HAS_DEATH_TEST
158 
159 }  // namespace
160 
main(int argc,char ** argv)161 int main(int argc, char** argv) {
162   absl::InitializeSymbolizer(argv[0]);
163   testing::InitGoogleTest(&argc, argv);
164   return RUN_ALL_TESTS();
165 }
166