blob: 8ff21dd35449c94186bb4b4b148883606f1e8b0d [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.
Louis Dionneed4a85e2021-06-18 13:33:14 -040011// REQUIRES: linux && (target={{aarch64-.+}} || target={{x86_64-.+}})
Daniel Kiss163101b2020-09-16 23:03:19 +020012
13#include <assert.h>
14#include <dlfcn.h>
15#include <signal.h>
16#include <stdio.h>
17#include <stdlib.h>
18#include <string.h>
19#include <sys/types.h>
20#include <unistd.h>
21#include <unwind.h>
22
23_Unwind_Reason_Code frame_handler(struct _Unwind_Context* ctx, void* arg) {
24 (void)arg;
25 Dl_info info = { 0, 0, 0, 0 };
Daniel Kiss163101b2020-09-16 23:03:19 +020026
27 // Unwind util the main is reached, above frames deeped on the platfrom and architecture.
Ryan Pricharda684bed2021-01-13 16:38:36 -080028 if (dladdr(reinterpret_cast<void *>(_Unwind_GetIP(ctx)), &info) &&
29 info.dli_sname && !strcmp("main", info.dli_sname)) {
Daniel Kiss163101b2020-09-16 23:03:19 +020030 _Exit(0);
31 }
32 return _URC_NO_REASON;
33}
34
35void signal_handler(int signum) {
36 (void)signum;
37 _Unwind_Backtrace(frame_handler, NULL);
38 _Exit(-1);
39}
40
Daniel Kiss163101b2020-09-16 23:03:19 +020041__attribute__((noinline)) void crashing_leaf_func(void) {
Leonard Chan74c6eec2021-12-03 11:20:06 -080042 // libunwind searches for the address before the return address which points
43 // to the trap instruction. NOP guarantees the trap instruction is not the
44 // first instruction of the function.
45 // We should keep this here for other unwinders that also decrement pc.
46 __asm__ __volatile__("nop");
47 __builtin_trap();
Daniel Kiss163101b2020-09-16 23:03:19 +020048}
49
Louis Dionnecbfe0172020-10-08 13:36:33 -040050int main(int, char**) {
Leonard Chan74c6eec2021-12-03 11:20:06 -080051 signal(SIGTRAP, signal_handler);
52 signal(SIGILL, signal_handler);
Daniel Kiss163101b2020-09-16 23:03:19 +020053 crashing_leaf_func();
54 return -2;
Louis Dionnef51a1542021-11-22 14:51:09 -050055}