1//===-- Unittests for sigaltstack -----------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "src/__support/OSUtil/syscall.h" // For internal syscall function.
10#include "src/errno/libc_errno.h"
11#include "src/signal/linux/signal_utils.h"
12#include "src/signal/raise.h"
13#include "src/signal/sigaction.h"
14#include "src/signal/sigaltstack.h"
15
16#include "test/UnitTest/ErrnoSetterMatcher.h"
17#include "test/UnitTest/Test.h"
18
19#include <signal.h>
20#include <stdint.h>
21#include <sys/syscall.h>
22
23constexpr int LOCAL_VAR_SIZE = 512;
24constexpr int ALT_STACK_SIZE = SIGSTKSZ + LOCAL_VAR_SIZE * 2;
25static uint8_t alt_stack[ALT_STACK_SIZE];
26
27using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
28using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
29
30static bool good_stack;
31static void handler(int) {
32 // Allocate a large stack variable so that it does not get optimized
33 // out or mapped to a register.
34 uint8_t var[LOCAL_VAR_SIZE];
35 for (int i = 0; i < LOCAL_VAR_SIZE; ++i)
36 var[i] = i;
37 // Verify that array is completely on the alt_stack.
38 for (int i = 0; i < LOCAL_VAR_SIZE; ++i) {
39 if (!(uintptr_t(var + i) < uintptr_t(alt_stack + ALT_STACK_SIZE) &&
40 uintptr_t(alt_stack) <= uintptr_t(var + i))) {
41 good_stack = false;
42 return;
43 }
44 }
45 good_stack = true;
46}
47
48TEST(LlvmLibcSignalTest, SigaltstackRunOnAltStack) {
49 struct sigaction action;
50 LIBC_NAMESPACE::libc_errno = 0;
51 ASSERT_THAT(LIBC_NAMESPACE::sigaction(SIGUSR1, nullptr, &action),
52 Succeeds(0));
53 action.sa_handler = handler;
54 // Indicate that the signal should be delivered on an alternate stack.
55 action.sa_flags = SA_ONSTACK;
56 ASSERT_THAT(LIBC_NAMESPACE::sigaction(SIGUSR1, &action, nullptr),
57 Succeeds(0));
58
59 stack_t ss;
60 ss.ss_sp = alt_stack;
61 ss.ss_size = ALT_STACK_SIZE;
62 ss.ss_flags = 0;
63 // Setup the alternate stack.
64 ASSERT_THAT(LIBC_NAMESPACE::sigaltstack(&ss, nullptr), Succeeds(0));
65
66 good_stack = false;
67 LIBC_NAMESPACE::raise(SIGUSR1);
68 EXPECT_TRUE(good_stack);
69}
70
71// This tests for invalid input.
72TEST(LlvmLibcSignalTest, SigaltstackInvalidStack) {
73 stack_t ss;
74 ss.ss_sp = alt_stack;
75 ss.ss_size = 0;
76 ss.ss_flags = SS_ONSTACK;
77 ASSERT_THAT(LIBC_NAMESPACE::sigaltstack(&ss, nullptr), Fails(EINVAL));
78
79 ss.ss_flags = 0;
80 ASSERT_THAT(LIBC_NAMESPACE::sigaltstack(&ss, nullptr), Fails(ENOMEM));
81}
82

source code of libc/test/src/signal/sigaltstack_test.cpp