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