1 // Copyright 2018 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "absl/debugging/symbolize.h"
16
17 #ifdef __EMSCRIPTEN__
18 #include <emscripten.h>
19 #endif
20
21 #ifndef _WIN32
22 #include <fcntl.h>
23 #include <sys/mman.h>
24 #endif
25
26 #include <cstring>
27 #include <iostream>
28 #include <memory>
29
30 #include "gmock/gmock.h"
31 #include "gtest/gtest.h"
32 #include "absl/base/attributes.h"
33 #include "absl/base/casts.h"
34 #include "absl/base/config.h"
35 #include "absl/base/internal/per_thread_tls.h"
36 #include "absl/base/optimization.h"
37 #include "absl/debugging/internal/stack_consumption.h"
38 #include "absl/log/check.h"
39 #include "absl/log/log.h"
40 #include "absl/memory/memory.h"
41 #include "absl/strings/string_view.h"
42
43 #if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
44 #define MAP_ANONYMOUS MAP_ANON
45 #endif
46
47 using testing::Contains;
48
49 #ifdef _WIN32
50 #define ABSL_SYMBOLIZE_TEST_NOINLINE __declspec(noinline)
51 #else
52 #define ABSL_SYMBOLIZE_TEST_NOINLINE ABSL_ATTRIBUTE_NOINLINE
53 #endif
54
55 // Functions to symbolize. Use C linkage to avoid mangled names.
56 extern "C" {
nonstatic_func()57 ABSL_SYMBOLIZE_TEST_NOINLINE void nonstatic_func() {
58 // The next line makes this a unique function to prevent the compiler from
59 // folding identical functions together.
60 volatile int x = __LINE__;
61 static_cast<void>(x);
62 ABSL_BLOCK_TAIL_CALL_OPTIMIZATION();
63 }
64
static_func()65 ABSL_SYMBOLIZE_TEST_NOINLINE static void static_func() {
66 // The next line makes this a unique function to prevent the compiler from
67 // folding identical functions together.
68 volatile int x = __LINE__;
69 static_cast<void>(x);
70 ABSL_BLOCK_TAIL_CALL_OPTIMIZATION();
71 }
72 } // extern "C"
73
74 struct Foo {
75 static void func(int x);
76 };
77
78 // A C++ method that should have a mangled name.
func(int)79 ABSL_SYMBOLIZE_TEST_NOINLINE void Foo::func(int) {
80 // The next line makes this a unique function to prevent the compiler from
81 // folding identical functions together.
82 volatile int x = __LINE__;
83 static_cast<void>(x);
84 ABSL_BLOCK_TAIL_CALL_OPTIMIZATION();
85 }
86
87 // Create functions that will remain in different text sections in the
88 // final binary when linker option "-z,keep-text-section-prefix" is used.
unlikely_func()89 int ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.unlikely) unlikely_func() {
90 return 0;
91 }
92
hot_func()93 int ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.hot) hot_func() { return 0; }
94
startup_func()95 int ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.startup) startup_func() { return 0; }
96
exit_func()97 int ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.exit) exit_func() { return 0; }
98
regular_func()99 int /*ABSL_ATTRIBUTE_SECTION_VARIABLE(.text)*/ regular_func() { return 0; }
100
101 // Thread-local data may confuse the symbolizer, ensure that it does not.
102 // Variable sizes and order are important.
103 #if ABSL_PER_THREAD_TLS
104 static ABSL_PER_THREAD_TLS_KEYWORD char symbolize_test_thread_small[1];
105 static ABSL_PER_THREAD_TLS_KEYWORD char
106 symbolize_test_thread_big[2 * 1024 * 1024];
107 #endif
108
109 #if !defined(__EMSCRIPTEN__)
GetPCFromFnPtr(void * ptr)110 static void *GetPCFromFnPtr(void *ptr) { return ptr; }
111
112 // Used below to hopefully inhibit some compiler/linker optimizations
113 // that may remove kHpageTextPadding, kPadding0, and kPadding1 from
114 // the binary.
115 static volatile bool volatile_bool = false;
116
117 // Force the binary to be large enough that a THP .text remap will succeed.
118 static constexpr size_t kHpageSize = 1 << 21;
119 const char kHpageTextPadding[kHpageSize * 4] ABSL_ATTRIBUTE_SECTION_VARIABLE(
120 .text) = "";
121
122 #else
GetPCFromFnPtr(void * ptr)123 static void *GetPCFromFnPtr(void *ptr) {
124 return EM_ASM_PTR(
125 { return wasmOffsetConverter.convert(wasmTable.get($0).name, 0); }, ptr);
126 }
127
128 #endif // !defined(__EMSCRIPTEN__)
129
130 static char try_symbolize_buffer[4096];
131
132 // A wrapper function for absl::Symbolize() to make the unit test simple. The
133 // limit must be < sizeof(try_symbolize_buffer). Returns null if
134 // absl::Symbolize() returns false, otherwise returns try_symbolize_buffer with
135 // the result of absl::Symbolize().
TrySymbolizeWithLimit(void * pc,int limit)136 static const char *TrySymbolizeWithLimit(void *pc, int limit) {
137 CHECK_LE(limit, sizeof(try_symbolize_buffer))
138 << "try_symbolize_buffer is too small";
139
140 // Use the heap to facilitate heap and buffer sanitizer tools.
141 auto heap_buffer = absl::make_unique<char[]>(sizeof(try_symbolize_buffer));
142 bool found = absl::Symbolize(pc, heap_buffer.get(), limit);
143 if (found) {
144 CHECK_LT(static_cast<int>(
145 strnlen(heap_buffer.get(), static_cast<size_t>(limit))),
146 limit)
147 << "absl::Symbolize() did not properly terminate the string";
148 strncpy(try_symbolize_buffer, heap_buffer.get(),
149 sizeof(try_symbolize_buffer) - 1);
150 try_symbolize_buffer[sizeof(try_symbolize_buffer) - 1] = '\0';
151 }
152
153 return found ? try_symbolize_buffer : nullptr;
154 }
155
156 // A wrapper for TrySymbolizeWithLimit(), with a large limit.
TrySymbolize(void * pc)157 static const char *TrySymbolize(void *pc) {
158 return TrySymbolizeWithLimit(pc, sizeof(try_symbolize_buffer));
159 }
160
161 #if defined(ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE) || \
162 defined(ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE) || \
163 defined(ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE)
164
165 // Test with a return address.
TestWithReturnAddress()166 void ABSL_ATTRIBUTE_NOINLINE TestWithReturnAddress() {
167 #if defined(ABSL_HAVE_ATTRIBUTE_NOINLINE)
168 void *return_address = __builtin_return_address(0);
169 const char *symbol = TrySymbolize(return_address);
170 CHECK_NE(symbol, nullptr) << "TestWithReturnAddress failed";
171 CHECK_STREQ(symbol, "main") << "TestWithReturnAddress failed";
172 std::cout << "TestWithReturnAddress passed" << std::endl;
173 #endif
174 }
175
TEST(Symbolize,Cached)176 TEST(Symbolize, Cached) {
177 // Compilers should give us pointers to them.
178 EXPECT_STREQ("nonstatic_func",
179 TrySymbolize(GetPCFromFnPtr((void *)(&nonstatic_func))));
180 // The name of an internal linkage symbol is not specified; allow either a
181 // mangled or an unmangled name here.
182 const char *static_func_symbol =
183 TrySymbolize(GetPCFromFnPtr((void *)(&static_func)));
184 EXPECT_TRUE(strcmp("static_func", static_func_symbol) == 0 ||
185 strcmp("static_func()", static_func_symbol) == 0);
186
187 EXPECT_TRUE(nullptr == TrySymbolize(nullptr));
188 }
189
TEST(Symbolize,Truncation)190 TEST(Symbolize, Truncation) {
191 constexpr char kNonStaticFunc[] = "nonstatic_func";
192 EXPECT_STREQ("nonstatic_func",
193 TrySymbolizeWithLimit(GetPCFromFnPtr((void *)(&nonstatic_func)),
194 strlen(kNonStaticFunc) + 1));
195 EXPECT_STREQ("nonstatic_...",
196 TrySymbolizeWithLimit(GetPCFromFnPtr((void *)(&nonstatic_func)),
197 strlen(kNonStaticFunc) + 0));
198 EXPECT_STREQ("nonstatic...",
199 TrySymbolizeWithLimit(GetPCFromFnPtr((void *)(&nonstatic_func)),
200 strlen(kNonStaticFunc) - 1));
201 EXPECT_STREQ("n...", TrySymbolizeWithLimit(
202 GetPCFromFnPtr((void *)(&nonstatic_func)), 5));
203 EXPECT_STREQ("...", TrySymbolizeWithLimit(
204 GetPCFromFnPtr((void *)(&nonstatic_func)), 4));
205 EXPECT_STREQ("..", TrySymbolizeWithLimit(
206 GetPCFromFnPtr((void *)(&nonstatic_func)), 3));
207 EXPECT_STREQ(
208 ".", TrySymbolizeWithLimit(GetPCFromFnPtr((void *)(&nonstatic_func)), 2));
209 EXPECT_STREQ(
210 "", TrySymbolizeWithLimit(GetPCFromFnPtr((void *)(&nonstatic_func)), 1));
211 EXPECT_EQ(nullptr, TrySymbolizeWithLimit(
212 GetPCFromFnPtr((void *)(&nonstatic_func)), 0));
213 }
214
TEST(Symbolize,SymbolizeWithDemangling)215 TEST(Symbolize, SymbolizeWithDemangling) {
216 Foo::func(100);
217 #ifdef __EMSCRIPTEN__
218 // Emscripten's online symbolizer is more precise with arguments.
219 EXPECT_STREQ("Foo::func(int)",
220 TrySymbolize(GetPCFromFnPtr((void *)(&Foo::func))));
221 #else
222 EXPECT_STREQ("Foo::func()",
223 TrySymbolize(GetPCFromFnPtr((void *)(&Foo::func))));
224 #endif
225 }
226
TEST(Symbolize,SymbolizeSplitTextSections)227 TEST(Symbolize, SymbolizeSplitTextSections) {
228 EXPECT_STREQ("unlikely_func()",
229 TrySymbolize(GetPCFromFnPtr((void *)(&unlikely_func))));
230 EXPECT_STREQ("hot_func()", TrySymbolize(GetPCFromFnPtr((void *)(&hot_func))));
231 EXPECT_STREQ("startup_func()",
232 TrySymbolize(GetPCFromFnPtr((void *)(&startup_func))));
233 EXPECT_STREQ("exit_func()",
234 TrySymbolize(GetPCFromFnPtr((void *)(&exit_func))));
235 EXPECT_STREQ("regular_func()",
236 TrySymbolize(GetPCFromFnPtr((void *)(®ular_func))));
237 }
238
239 // Tests that verify that Symbolize stack footprint is within some limit.
240 #ifdef ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION
241
242 static void *g_pc_to_symbolize;
243 static char g_symbolize_buffer[4096];
244 static char *g_symbolize_result;
245
SymbolizeSignalHandler(int signo)246 static void SymbolizeSignalHandler(int signo) {
247 if (absl::Symbolize(g_pc_to_symbolize, g_symbolize_buffer,
248 sizeof(g_symbolize_buffer))) {
249 g_symbolize_result = g_symbolize_buffer;
250 } else {
251 g_symbolize_result = nullptr;
252 }
253 }
254
255 // Call Symbolize and figure out the stack footprint of this call.
SymbolizeStackConsumption(void * pc,int * stack_consumed)256 static const char *SymbolizeStackConsumption(void *pc, int *stack_consumed) {
257 g_pc_to_symbolize = pc;
258 *stack_consumed = absl::debugging_internal::GetSignalHandlerStackConsumption(
259 SymbolizeSignalHandler);
260 return g_symbolize_result;
261 }
262
GetStackConsumptionUpperLimit()263 static int GetStackConsumptionUpperLimit() {
264 // Symbolize stack consumption should be within 2kB.
265 int stack_consumption_upper_limit = 2048;
266 #if defined(ABSL_HAVE_ADDRESS_SANITIZER) || \
267 defined(ABSL_HAVE_MEMORY_SANITIZER) || defined(ABSL_HAVE_THREAD_SANITIZER)
268 // Account for sanitizer instrumentation requiring additional stack space.
269 stack_consumption_upper_limit *= 5;
270 #endif
271 return stack_consumption_upper_limit;
272 }
273
TEST(Symbolize,SymbolizeStackConsumption)274 TEST(Symbolize, SymbolizeStackConsumption) {
275 int stack_consumed = 0;
276
277 const char *symbol =
278 SymbolizeStackConsumption((void *)(&nonstatic_func), &stack_consumed);
279 EXPECT_STREQ("nonstatic_func", symbol);
280 EXPECT_GT(stack_consumed, 0);
281 EXPECT_LT(stack_consumed, GetStackConsumptionUpperLimit());
282
283 // The name of an internal linkage symbol is not specified; allow either a
284 // mangled or an unmangled name here.
285 symbol = SymbolizeStackConsumption((void *)(&static_func), &stack_consumed);
286 EXPECT_TRUE(strcmp("static_func", symbol) == 0 ||
287 strcmp("static_func()", symbol) == 0);
288 EXPECT_GT(stack_consumed, 0);
289 EXPECT_LT(stack_consumed, GetStackConsumptionUpperLimit());
290 }
291
TEST(Symbolize,SymbolizeWithDemanglingStackConsumption)292 TEST(Symbolize, SymbolizeWithDemanglingStackConsumption) {
293 Foo::func(100);
294 int stack_consumed = 0;
295
296 const char *symbol =
297 SymbolizeStackConsumption((void *)(&Foo::func), &stack_consumed);
298
299 EXPECT_STREQ("Foo::func()", symbol);
300 EXPECT_GT(stack_consumed, 0);
301 EXPECT_LT(stack_consumed, GetStackConsumptionUpperLimit());
302 }
303
304 #endif // ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION
305
306 #if !defined(ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE) && \
307 !defined(ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE)
308 // Use a 64K page size for PPC.
309 const size_t kPageSize = 64 << 10;
310 // We place a read-only symbols into the .text section and verify that we can
311 // symbolize them and other symbols after remapping them.
312 const char kPadding0[kPageSize * 4] ABSL_ATTRIBUTE_SECTION_VARIABLE(.text) = "";
313 const char kPadding1[kPageSize * 4] ABSL_ATTRIBUTE_SECTION_VARIABLE(.text) = "";
314
FilterElfHeader(struct dl_phdr_info * info,size_t size,void * data)315 static int FilterElfHeader(struct dl_phdr_info *info, size_t size, void *data) {
316 for (int i = 0; i < info->dlpi_phnum; i++) {
317 if (info->dlpi_phdr[i].p_type == PT_LOAD &&
318 info->dlpi_phdr[i].p_flags == (PF_R | PF_X)) {
319 const void *const vaddr =
320 absl::bit_cast<void *>(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
321 const auto segsize = info->dlpi_phdr[i].p_memsz;
322
323 const char *self_exe;
324 if (info->dlpi_name != nullptr && info->dlpi_name[0] != '\0') {
325 self_exe = info->dlpi_name;
326 } else {
327 self_exe = "/proc/self/exe";
328 }
329
330 absl::debugging_internal::RegisterFileMappingHint(
331 vaddr, reinterpret_cast<const char *>(vaddr) + segsize,
332 info->dlpi_phdr[i].p_offset, self_exe);
333
334 return 1;
335 }
336 }
337
338 return 1;
339 }
340
TEST(Symbolize,SymbolizeWithMultipleMaps)341 TEST(Symbolize, SymbolizeWithMultipleMaps) {
342 // Force kPadding0 and kPadding1 to be linked in.
343 if (volatile_bool) {
344 LOG(INFO) << kPadding0;
345 LOG(INFO) << kPadding1;
346 }
347
348 // Verify we can symbolize everything.
349 char buf[512];
350 memset(buf, 0, sizeof(buf));
351 absl::Symbolize(kPadding0, buf, sizeof(buf));
352 EXPECT_STREQ("kPadding0", buf);
353
354 memset(buf, 0, sizeof(buf));
355 absl::Symbolize(kPadding1, buf, sizeof(buf));
356 EXPECT_STREQ("kPadding1", buf);
357
358 // Specify a hint for the executable segment.
359 dl_iterate_phdr(FilterElfHeader, nullptr);
360
361 // Reload at least one page out of kPadding0, kPadding1
362 const char *ptrs[] = {kPadding0, kPadding1};
363
364 for (const char *ptr : ptrs) {
365 const int kMapFlags = MAP_ANONYMOUS | MAP_PRIVATE;
366 void *addr = mmap(nullptr, kPageSize, PROT_READ, kMapFlags, 0, 0);
367 ASSERT_NE(addr, MAP_FAILED);
368
369 // kPadding[0-1] is full of zeroes, so we can remap anywhere within it, but
370 // we ensure there is at least a full page of padding.
371 void *remapped = reinterpret_cast<void *>(
372 reinterpret_cast<uintptr_t>(ptr + kPageSize) & ~(kPageSize - 1ULL));
373
374 const int kMremapFlags = (MREMAP_MAYMOVE | MREMAP_FIXED);
375 void *ret = mremap(addr, kPageSize, kPageSize, kMremapFlags, remapped);
376 ASSERT_NE(ret, MAP_FAILED);
377 }
378
379 // Invalidate the symbolization cache so we are forced to rely on the hint.
380 absl::Symbolize(nullptr, buf, sizeof(buf));
381
382 // Verify we can still symbolize.
383 const char *expected[] = {"kPadding0", "kPadding1"};
384 const size_t offsets[] = {0, kPageSize, 2 * kPageSize, 3 * kPageSize};
385
386 for (int i = 0; i < 2; i++) {
387 for (size_t offset : offsets) {
388 memset(buf, 0, sizeof(buf));
389 absl::Symbolize(ptrs[i] + offset, buf, sizeof(buf));
390 EXPECT_STREQ(expected[i], buf);
391 }
392 }
393 }
394
395 // Appends string(*args->arg) to args->symbol_buf.
DummySymbolDecorator(const absl::debugging_internal::SymbolDecoratorArgs * args)396 static void DummySymbolDecorator(
397 const absl::debugging_internal::SymbolDecoratorArgs *args) {
398 std::string *message = static_cast<std::string *>(args->arg);
399 strncat(args->symbol_buf, message->c_str(),
400 args->symbol_buf_size - strlen(args->symbol_buf) - 1);
401 }
402
TEST(Symbolize,InstallAndRemoveSymbolDecorators)403 TEST(Symbolize, InstallAndRemoveSymbolDecorators) {
404 int ticket_a;
405 std::string a_message("a");
406 EXPECT_GE(ticket_a = absl::debugging_internal::InstallSymbolDecorator(
407 DummySymbolDecorator, &a_message),
408 0);
409
410 int ticket_b;
411 std::string b_message("b");
412 EXPECT_GE(ticket_b = absl::debugging_internal::InstallSymbolDecorator(
413 DummySymbolDecorator, &b_message),
414 0);
415
416 int ticket_c;
417 std::string c_message("c");
418 EXPECT_GE(ticket_c = absl::debugging_internal::InstallSymbolDecorator(
419 DummySymbolDecorator, &c_message),
420 0);
421
422 // Use addresses 4 and 8 here to ensure that we always use valid addresses
423 // even on systems that require instructions to be 32-bit aligned.
424 char *address = reinterpret_cast<char *>(4);
425 EXPECT_STREQ("abc", TrySymbolize(address));
426
427 EXPECT_TRUE(absl::debugging_internal::RemoveSymbolDecorator(ticket_b));
428
429 EXPECT_STREQ("ac", TrySymbolize(address + 4));
430
431 // Cleanup: remove all remaining decorators so other stack traces don't
432 // get mystery "ac" decoration.
433 EXPECT_TRUE(absl::debugging_internal::RemoveSymbolDecorator(ticket_a));
434 EXPECT_TRUE(absl::debugging_internal::RemoveSymbolDecorator(ticket_c));
435 }
436
437 // Some versions of Clang with optimizations enabled seem to be able
438 // to optimize away the .data section if no variables live in the
439 // section. This variable should get placed in the .data section, and
440 // the test below checks for the existence of a .data section.
441 static int in_data_section = 1;
442
TEST(Symbolize,ForEachSection)443 TEST(Symbolize, ForEachSection) {
444 int fd = TEMP_FAILURE_RETRY(open("/proc/self/exe", O_RDONLY));
445 ASSERT_NE(fd, -1);
446
447 std::vector<std::string> sections;
448 ASSERT_TRUE(absl::debugging_internal::ForEachSection(
449 fd, [§ions](const absl::string_view name, const ElfW(Shdr) &) {
450 sections.emplace_back(name);
451 return true;
452 }));
453
454 // Check for the presence of common section names.
455 EXPECT_THAT(sections, Contains(".text"));
456 EXPECT_THAT(sections, Contains(".rodata"));
457 EXPECT_THAT(sections, Contains(".bss"));
458 ++in_data_section;
459 EXPECT_THAT(sections, Contains(".data"));
460
461 close(fd);
462 }
463 #endif // !ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE &&
464 // !ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE
465
466 // x86 specific tests. Uses some inline assembler.
467 extern "C" {
inline_func()468 inline void *ABSL_ATTRIBUTE_ALWAYS_INLINE inline_func() {
469 void *pc = nullptr;
470 #if defined(__i386__)
471 __asm__ __volatile__("call 1f;\n 1: pop %[PC]" : [PC] "=r"(pc));
472 #elif defined(__x86_64__)
473 __asm__ __volatile__("leaq 0(%%rip),%[PC];\n" : [PC] "=r"(pc));
474 #endif
475 return pc;
476 }
477
non_inline_func()478 void *ABSL_ATTRIBUTE_NOINLINE non_inline_func() {
479 void *pc = nullptr;
480 #if defined(__i386__)
481 __asm__ __volatile__("call 1f;\n 1: pop %[PC]" : [PC] "=r"(pc));
482 #elif defined(__x86_64__)
483 __asm__ __volatile__("leaq 0(%%rip),%[PC];\n" : [PC] "=r"(pc));
484 #endif
485 return pc;
486 }
487
TestWithPCInsideNonInlineFunction()488 void ABSL_ATTRIBUTE_NOINLINE TestWithPCInsideNonInlineFunction() {
489 #if defined(ABSL_HAVE_ATTRIBUTE_NOINLINE) && \
490 (defined(__i386__) || defined(__x86_64__))
491 void *pc = non_inline_func();
492 const char *symbol = TrySymbolize(pc);
493 CHECK_NE(symbol, nullptr) << "TestWithPCInsideNonInlineFunction failed";
494 CHECK_STREQ(symbol, "non_inline_func")
495 << "TestWithPCInsideNonInlineFunction failed";
496 std::cout << "TestWithPCInsideNonInlineFunction passed" << std::endl;
497 #endif
498 }
499
TestWithPCInsideInlineFunction()500 void ABSL_ATTRIBUTE_NOINLINE TestWithPCInsideInlineFunction() {
501 #if defined(ABSL_HAVE_ATTRIBUTE_ALWAYS_INLINE) && \
502 (defined(__i386__) || defined(__x86_64__))
503 void *pc = inline_func(); // Must be inlined.
504 const char *symbol = TrySymbolize(pc);
505 CHECK_NE(symbol, nullptr) << "TestWithPCInsideInlineFunction failed";
506 CHECK_STREQ(symbol, __FUNCTION__) << "TestWithPCInsideInlineFunction failed";
507 std::cout << "TestWithPCInsideInlineFunction passed" << std::endl;
508 #endif
509 }
510 }
511
512 #if defined(__arm__) && ABSL_HAVE_ATTRIBUTE(target) && \
513 ((__ARM_ARCH >= 7) || !defined(__ARM_PCS_VFP))
514 // Test that we correctly identify bounds of Thumb functions on ARM.
515 //
516 // Thumb functions have the lowest-order bit set in their addresses in the ELF
517 // symbol table. This requires some extra logic to properly compute function
518 // bounds. To test this logic, nudge a Thumb function right up against an ARM
519 // function and try to symbolize the ARM function.
520 //
521 // A naive implementation will simply use the Thumb function's entry point as
522 // written in the symbol table and will therefore treat the Thumb function as
523 // extending one byte further in the instruction stream than it actually does.
524 // When asked to symbolize the start of the ARM function, it will identify an
525 // overlap between the Thumb and ARM functions, and it will return the name of
526 // the Thumb function.
527 //
528 // A correct implementation, on the other hand, will null out the lowest-order
529 // bit in the Thumb function's entry point. It will correctly compute the end of
530 // the Thumb function, it will find no overlap between the Thumb and ARM
531 // functions, and it will return the name of the ARM function.
532 //
533 // Unfortunately we cannot perform this test on armv6 or lower systems that use
534 // the hard float ABI because gcc refuses to compile thumb functions on such
535 // systems with a "sorry, unimplemented: Thumb-1 hard-float VFP ABI" error.
536
ArmThumbOverlapThumb(int x)537 __attribute__((target("thumb"))) int ArmThumbOverlapThumb(int x) {
538 return x * x * x;
539 }
540
ArmThumbOverlapArm(int x)541 __attribute__((target("arm"))) int ArmThumbOverlapArm(int x) {
542 return x * x * x;
543 }
544
TestArmThumbOverlap()545 void ABSL_ATTRIBUTE_NOINLINE TestArmThumbOverlap() {
546 #if defined(ABSL_HAVE_ATTRIBUTE_NOINLINE)
547 const char *symbol = TrySymbolize((void *)&ArmThumbOverlapArm);
548 CHECK_NE(symbol, nullptr) << "TestArmThumbOverlap failed";
549 CHECK_STREQ("ArmThumbOverlapArm()", symbol) << "TestArmThumbOverlap failed";
550 std::cout << "TestArmThumbOverlap passed" << std::endl;
551 #endif
552 }
553
554 #endif // defined(__arm__) && ABSL_HAVE_ATTRIBUTE(target) && ((__ARM_ARCH >= 7)
555 // || !defined(__ARM_PCS_VFP))
556
557 #elif defined(_WIN32)
558 #if !defined(ABSL_CONSUME_DLL)
559
TEST(Symbolize,Basics)560 TEST(Symbolize, Basics) {
561 EXPECT_STREQ("nonstatic_func", TrySymbolize((void *)(&nonstatic_func)));
562
563 // The name of an internal linkage symbol is not specified; allow either a
564 // mangled or an unmangled name here.
565 const char *static_func_symbol = TrySymbolize((void *)(&static_func));
566 ASSERT_TRUE(static_func_symbol != nullptr);
567 EXPECT_TRUE(strstr(static_func_symbol, "static_func") != nullptr);
568
569 EXPECT_TRUE(nullptr == TrySymbolize(nullptr));
570 }
571
TEST(Symbolize,Truncation)572 TEST(Symbolize, Truncation) {
573 constexpr char kNonStaticFunc[] = "nonstatic_func";
574 EXPECT_STREQ("nonstatic_func",
575 TrySymbolizeWithLimit((void *)(&nonstatic_func),
576 strlen(kNonStaticFunc) + 1));
577 EXPECT_STREQ("nonstatic_...",
578 TrySymbolizeWithLimit((void *)(&nonstatic_func),
579 strlen(kNonStaticFunc) + 0));
580 EXPECT_STREQ("nonstatic...",
581 TrySymbolizeWithLimit((void *)(&nonstatic_func),
582 strlen(kNonStaticFunc) - 1));
583 EXPECT_STREQ("n...", TrySymbolizeWithLimit((void *)(&nonstatic_func), 5));
584 EXPECT_STREQ("...", TrySymbolizeWithLimit((void *)(&nonstatic_func), 4));
585 EXPECT_STREQ("..", TrySymbolizeWithLimit((void *)(&nonstatic_func), 3));
586 EXPECT_STREQ(".", TrySymbolizeWithLimit((void *)(&nonstatic_func), 2));
587 EXPECT_STREQ("", TrySymbolizeWithLimit((void *)(&nonstatic_func), 1));
588 EXPECT_EQ(nullptr, TrySymbolizeWithLimit((void *)(&nonstatic_func), 0));
589 }
590
TEST(Symbolize,SymbolizeWithDemangling)591 TEST(Symbolize, SymbolizeWithDemangling) {
592 const char *result = TrySymbolize((void *)(&Foo::func));
593 ASSERT_TRUE(result != nullptr);
594 EXPECT_TRUE(strstr(result, "Foo::func") != nullptr) << result;
595 }
596
597 #endif // !defined(ABSL_CONSUME_DLL)
598 #else // Symbolizer unimplemented
TEST(Symbolize,Unimplemented)599 TEST(Symbolize, Unimplemented) {
600 char buf[64];
601 EXPECT_FALSE(absl::Symbolize((void *)(&nonstatic_func), buf, sizeof(buf)));
602 EXPECT_FALSE(absl::Symbolize((void *)(&static_func), buf, sizeof(buf)));
603 EXPECT_FALSE(absl::Symbolize((void *)(&Foo::func), buf, sizeof(buf)));
604 }
605
606 #endif
607
main(int argc,char ** argv)608 int main(int argc, char **argv) {
609 #if !defined(__EMSCRIPTEN__)
610 // Make sure kHpageTextPadding is linked into the binary.
611 if (volatile_bool) {
612 LOG(INFO) << kHpageTextPadding;
613 }
614 #endif // !defined(__EMSCRIPTEN__)
615
616 #if ABSL_PER_THREAD_TLS
617 // Touch the per-thread variables.
618 symbolize_test_thread_small[0] = 0;
619 symbolize_test_thread_big[0] = 0;
620 #endif
621
622 absl::InitializeSymbolizer(argv[0]);
623 testing::InitGoogleTest(&argc, argv);
624
625 #if defined(ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE) || \
626 defined(ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE) || \
627 defined(ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE)
628 TestWithPCInsideInlineFunction();
629 TestWithPCInsideNonInlineFunction();
630 TestWithReturnAddress();
631 #if defined(__arm__) && ABSL_HAVE_ATTRIBUTE(target) && \
632 ((__ARM_ARCH >= 7) || !defined(__ARM_PCS_VFP))
633 TestArmThumbOverlap();
634 #endif
635 #endif
636
637 return RUN_ALL_TESTS();
638 }
639