1 // Copyright 2019 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 "base/immediate_crash.h"
6
7 #include <stdint.h>
8
9 #include <optional>
10
11 #include "base/base_paths.h"
12 #include "base/clang_profiling_buildflags.h"
13 #include "base/containers/span.h"
14 #include "base/files/file_path.h"
15 #include "base/path_service.h"
16 #include "base/ranges/algorithm.h"
17 #include "base/scoped_native_library.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "build/build_config.h"
20 #include "build/buildflag.h"
21 #include "testing/gtest/include/gtest/gtest.h"
22
23 namespace base {
24
25 namespace {
26
27 // If ImmediateCrash() is not treated as noreturn by the compiler, the compiler
28 // will complain that not all paths through this function return a value.
TestImmediateCrashTreatedAsNoReturn()29 [[maybe_unused]] int TestImmediateCrashTreatedAsNoReturn() {
30 ImmediateCrash();
31 }
32
33 #if defined(ARCH_CPU_X86_FAMILY)
34 // This is tricksy and false, since x86 instructions are not all one byte long,
35 // but there is no better alternative short of implementing an x86 instruction
36 // decoder.
37 using Instruction = uint8_t;
38
39 // https://software.intel.com/en-us/download/intel-64-and-ia-32-architectures-sdm-combined-volumes-1-2a-2b-2c-2d-3a-3b-3c-3d-and-4
40 // Look for RET opcode (0xc3). Note that 0xC3 is a substring of several
41 // other opcodes (VMRESUME, MOVNTI), and can also be encoded as part of an
42 // argument to another opcode. None of these other cases are expected to be
43 // present, so a simple byte scan should be Good Enough™.
44 constexpr Instruction kRet = 0xc3;
45 // INT3 ; UD2
46 constexpr Instruction kRequiredBody[] = {0xcc, 0x0f, 0x0b};
47 constexpr Instruction kOptionalFooter[] = {};
48
49 #elif defined(ARCH_CPU_ARMEL)
50 using Instruction = uint16_t;
51
52 // T32 opcode reference: https://developer.arm.com/docs/ddi0487/latest
53 // Actually BX LR, canonical encoding:
54 constexpr Instruction kRet = 0x4770;
55 // BKPT #0; UDF #0
56 constexpr Instruction kRequiredBody[] = {0xbe00, 0xde00};
57 constexpr Instruction kOptionalFooter[] = {};
58
59 #elif defined(ARCH_CPU_ARM64)
60 using Instruction = uint32_t;
61
62 // A64 opcode reference: https://developer.arm.com/docs/ddi0487/latest
63 // Use an enum here rather than separate constexpr vars because otherwise some
64 // of the vars will end up unused on each platform, upsetting
65 // -Wunused-const-variable.
66 enum : Instruction {
67 // There are multiple valid encodings of return (which is really a special
68 // form of branch). This is the one clang seems to use:
69 kRet = 0xd65f03c0,
70 kBrk0 = 0xd4200000,
71 kBrk1 = 0xd4200020,
72 kBrkF000 = 0xd43e0000,
73 kHlt0 = 0xd4400000,
74 };
75
76 #if BUILDFLAG(IS_WIN)
77
78 constexpr Instruction kRequiredBody[] = {kBrkF000, kBrk1};
79 constexpr Instruction kOptionalFooter[] = {};
80
81 #elif BUILDFLAG(IS_MAC)
82
83 constexpr Instruction kRequiredBody[] = {kBrk0, kHlt0};
84 // Some clangs emit a BRK #1 for __builtin_unreachable(), but some do not, so
85 // it is allowed but not required to occur.
86 constexpr Instruction kOptionalFooter[] = {kBrk1};
87
88 #else
89
90 constexpr Instruction kRequiredBody[] = {kBrk0, kHlt0};
91 constexpr Instruction kOptionalFooter[] = {};
92
93 #endif
94
95 #endif
96
97 // This function loads a shared library that defines two functions,
98 // TestFunction1 and TestFunction2. It then returns the bytes of the body of
99 // whichever of those functions happens to come first in the library.
GetTestFunctionInstructions(std::vector<Instruction> * body)100 void GetTestFunctionInstructions(std::vector<Instruction>* body) {
101 FilePath helper_library_path;
102 #if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA)
103 // On Android M, DIR_EXE == /system/bin when running base_unittests.
104 // On Fuchsia, NativeLibrary understands the native convention that libraries
105 // are not colocated with the binary.
106 ASSERT_TRUE(PathService::Get(DIR_EXE, &helper_library_path));
107 #endif
108 helper_library_path = helper_library_path.AppendASCII(
109 GetNativeLibraryName("immediate_crash_test_helper"));
110 ScopedNativeLibrary helper_library(helper_library_path);
111 ASSERT_TRUE(helper_library.is_valid())
112 << "shared library load failed: "
113 << helper_library.GetError()->ToString();
114
115 void* a = helper_library.GetFunctionPointer("TestFunction1");
116 ASSERT_TRUE(a);
117 void* b = helper_library.GetFunctionPointer("TestFunction2");
118 ASSERT_TRUE(b);
119
120 #if defined(ARCH_CPU_ARMEL)
121 // Routines loaded from a shared library will have the LSB in the pointer set
122 // if encoded as T32 instructions. The rest of this test assumes T32.
123 ASSERT_TRUE(reinterpret_cast<uintptr_t>(a) & 0x1)
124 << "Expected T32 opcodes but found A32 opcodes instead.";
125 ASSERT_TRUE(reinterpret_cast<uintptr_t>(b) & 0x1)
126 << "Expected T32 opcodes but found A32 opcodes instead.";
127
128 // Mask off the lowest bit.
129 a = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(a) & ~uintptr_t{0x1});
130 b = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(b) & ~uintptr_t{0x1});
131 #endif
132
133 // There are two identical test functions starting at a and b, which may
134 // occur in the library in either order. Grab whichever one comes first,
135 // and use the address of the other to figure out where it ends.
136 const Instruction* const start = static_cast<Instruction*>(std::min(a, b));
137 const Instruction* const end = static_cast<Instruction*>(std::max(a, b));
138
139 for (const Instruction& instruction : make_span(start, end))
140 body->push_back(instruction);
141 }
142
ExpectImmediateCrashInvocation(std::vector<Instruction> instructions)143 std::optional<std::vector<Instruction>> ExpectImmediateCrashInvocation(
144 std::vector<Instruction> instructions) {
145 auto iter = instructions.begin();
146 for (const auto inst : kRequiredBody) {
147 if (iter == instructions.end())
148 return std::nullopt;
149 EXPECT_EQ(inst, *iter);
150 iter++;
151 }
152 return std::make_optional(std::vector<Instruction>(iter, instructions.end()));
153 }
154
MaybeSkipOptionalFooter(std::vector<Instruction> instructions)155 std::vector<Instruction> MaybeSkipOptionalFooter(
156 std::vector<Instruction> instructions) {
157 auto iter = instructions.begin();
158 for (const auto inst : kOptionalFooter) {
159 if (iter == instructions.end() || *iter != inst)
160 break;
161 iter++;
162 }
163 return std::vector<Instruction>(iter, instructions.end());
164 }
165
166 #if BUILDFLAG(USE_CLANG_COVERAGE) || BUILDFLAG(CLANG_PROFILING)
MatchPrefix(const std::vector<Instruction> & haystack,const base::span<const Instruction> & needle)167 bool MatchPrefix(const std::vector<Instruction>& haystack,
168 const base::span<const Instruction>& needle) {
169 for (size_t i = 0; i < needle.size(); i++) {
170 if (i >= haystack.size() || needle[i] != haystack[i])
171 return false;
172 }
173 return true;
174 }
175
DropUntilMatch(std::vector<Instruction> haystack,const base::span<const Instruction> & needle)176 std::vector<Instruction> DropUntilMatch(
177 std::vector<Instruction> haystack,
178 const base::span<const Instruction>& needle) {
179 while (!haystack.empty() && !MatchPrefix(haystack, needle))
180 haystack.erase(haystack.begin());
181 return haystack;
182 }
183 #endif // USE_CLANG_COVERAGE || BUILDFLAG(CLANG_PROFILING)
184
MaybeSkipCoverageHook(std::vector<Instruction> instructions)185 std::vector<Instruction> MaybeSkipCoverageHook(
186 std::vector<Instruction> instructions) {
187 #if BUILDFLAG(USE_CLANG_COVERAGE) || BUILDFLAG(CLANG_PROFILING)
188 // Warning: it is not illegal for the entirety of the expected crash sequence
189 // to appear as a subsequence of the coverage hook code. If that happens, this
190 // code will falsely exit early, having not found the real expected crash
191 // sequence, so this may not adequately ensure that the immediate crash
192 // sequence is present. We do check when not under coverage, at least.
193 return DropUntilMatch(instructions, base::make_span(kRequiredBody));
194 #else
195 return instructions;
196 #endif // USE_CLANG_COVERAGE || BUILDFLAG(CLANG_PROFILING)
197 }
198
199 } // namespace
200
201 // Attempts to verify the actual instructions emitted by ImmediateCrash().
202 // While the test results are highly implementation-specific, this allows macro
203 // changes (e.g. CLs like https://crrev.com/671123) to be verified using the
204 // trybots/waterfall, without having to build and disassemble Chrome on
205 // multiple platforms. This makes it easier to evaluate changes to
206 // ImmediateCrash() against its requirements (e.g. size of emitted sequence,
207 // whether or not multiple ImmediateCrash sequences can be folded together, et
208 // cetera). Please see immediate_crash.h for more details about the
209 // requirements.
210 //
211 // Note that C++ provides no way to get the size of a function. Instead, the
212 // test relies on a shared library which defines only two functions and assumes
213 // the two functions will be laid out contiguously as a heuristic for finding
214 // the size of the function.
TEST(ImmediateCrashTest,ExpectedOpcodeSequence)215 TEST(ImmediateCrashTest, ExpectedOpcodeSequence) {
216 std::vector<Instruction> body;
217 ASSERT_NO_FATAL_FAILURE(GetTestFunctionInstructions(&body));
218 SCOPED_TRACE(HexEncode(body.data(), body.size() * sizeof(Instruction)));
219
220 auto it = ranges::find(body, kRet);
221 ASSERT_NE(body.end(), it) << "Failed to find return opcode";
222 it++;
223
224 body = std::vector<Instruction>(it, body.end());
225 std::optional<std::vector<Instruction>> result = MaybeSkipCoverageHook(body);
226 result = ExpectImmediateCrashInvocation(result.value());
227 result = MaybeSkipOptionalFooter(result.value());
228 result = MaybeSkipCoverageHook(result.value());
229 result = ExpectImmediateCrashInvocation(result.value());
230 ASSERT_TRUE(result);
231 }
232
233 } // namespace base
234