blob: bdeb44ab62ae8575289b233bff40c5d33ab0f080 [file] [log] [blame]
Daniel Kiss163101b2020-09-16 23:03:19 +02001// -*- C++ -*-
2//===----------------------------------------------------------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10// Ensure that leaf function can be unwund.
Ulrich Weigandf1108b62022-05-04 10:43:11 +020011// REQUIRES: linux && (target={{aarch64-.+}} || target={{s390x-.+}} || target={{x86_64-.+}})
Daniel Kiss163101b2020-09-16 23:03:19 +020012
Louis Dionne31359e02022-03-02 17:49:13 -050013// TODO: Figure out why this fails with Memory Sanitizer.
14// XFAIL: msan
15
Florian Mayer47974e92022-08-04 15:02:52 -070016#undef NDEBUG
Daniel Kiss163101b2020-09-16 23:03:19 +020017#include <assert.h>
18#include <dlfcn.h>
19#include <signal.h>
20#include <stdio.h>
21#include <stdlib.h>
22#include <string.h>
23#include <sys/types.h>
24#include <unistd.h>
25#include <unwind.h>
26
27_Unwind_Reason_Code frame_handler(struct _Unwind_Context* ctx, void* arg) {
28 (void)arg;
29 Dl_info info = { 0, 0, 0, 0 };
Daniel Kiss163101b2020-09-16 23:03:19 +020030
Gabriel Ravier42aa6de2022-08-20 18:09:03 -070031 // Unwind until the main is reached, above frames deeped on the platform and
32 // architecture.
Ryan Pricharda684bed2021-01-13 16:38:36 -080033 if (dladdr(reinterpret_cast<void *>(_Unwind_GetIP(ctx)), &info) &&
34 info.dli_sname && !strcmp("main", info.dli_sname)) {
Daniel Kiss163101b2020-09-16 23:03:19 +020035 _Exit(0);
36 }
37 return _URC_NO_REASON;
38}
39
40void signal_handler(int signum) {
41 (void)signum;
42 _Unwind_Backtrace(frame_handler, NULL);
43 _Exit(-1);
44}
45
Daniel Kiss163101b2020-09-16 23:03:19 +020046__attribute__((noinline)) void crashing_leaf_func(void) {
Leonard Chan74c6eec2021-12-03 11:20:06 -080047 // libunwind searches for the address before the return address which points
48 // to the trap instruction. NOP guarantees the trap instruction is not the
49 // first instruction of the function.
50 // We should keep this here for other unwinders that also decrement pc.
51 __asm__ __volatile__("nop");
52 __builtin_trap();
Daniel Kiss163101b2020-09-16 23:03:19 +020053}
54
Louis Dionnecbfe0172020-10-08 13:36:33 -040055int main(int, char**) {
Leonard Chan74c6eec2021-12-03 11:20:06 -080056 signal(SIGTRAP, signal_handler);
57 signal(SIGILL, signal_handler);
Daniel Kiss163101b2020-09-16 23:03:19 +020058 crashing_leaf_func();
59 return -2;
Louis Dionnef51a1542021-11-22 14:51:09 -050060}