1//===-- Unittests for sigaction -------------------------------------------===//
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/signal/raise.h"
10#include "src/signal/sigaction.h"
11
12#include "test/UnitTest/ErrnoSetterMatcher.h"
13#include "test/UnitTest/Test.h"
14
15#include <errno.h>
16#include <signal.h>
17
18using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
19using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
20
21TEST(LlvmLibcSigaction, Invalid) {
22 // -1 is a much larger signal that NSIG, so this should fail.
23 EXPECT_THAT(LIBC_NAMESPACE::sigaction(-1, nullptr, nullptr), Fails(EINVAL));
24}
25
26// SIGKILL cannot have its action changed, but it can be examined.
27TEST(LlvmLibcSigaction, Sigkill) {
28 struct sigaction action;
29 EXPECT_THAT(LIBC_NAMESPACE::sigaction(SIGKILL, nullptr, &action), Succeeds());
30 EXPECT_THAT(LIBC_NAMESPACE::sigaction(SIGKILL, &action, nullptr),
31 Fails(EINVAL));
32}
33
34static int sigusr1Count;
35static bool correctSignal;
36
37TEST(LlvmLibcSigaction, CustomAction) {
38 // Zero this incase tests get run multiple times in the future.
39 sigusr1Count = 0;
40
41 struct sigaction action;
42 EXPECT_THAT(LIBC_NAMESPACE::sigaction(SIGUSR1, nullptr, &action), Succeeds());
43
44 action.sa_handler = +[](int signal) {
45 correctSignal = signal == SIGUSR1;
46 sigusr1Count++;
47 };
48 EXPECT_THAT(LIBC_NAMESPACE::sigaction(SIGUSR1, &action, nullptr), Succeeds());
49
50 LIBC_NAMESPACE::raise(SIGUSR1);
51 EXPECT_EQ(sigusr1Count, 1);
52 EXPECT_TRUE(correctSignal);
53
54 action.sa_handler = SIG_DFL;
55 EXPECT_THAT(LIBC_NAMESPACE::sigaction(SIGUSR1, &action, nullptr), Succeeds());
56
57 EXPECT_DEATH([] { LIBC_NAMESPACE::raise(SIGUSR1); }, WITH_SIGNAL(SIGUSR1));
58}
59
60TEST(LlvmLibcSigaction, Ignore) {
61 struct sigaction action;
62 EXPECT_THAT(LIBC_NAMESPACE::sigaction(SIGUSR1, nullptr, &action), Succeeds());
63 action.sa_handler = SIG_IGN;
64 EXPECT_THAT(LIBC_NAMESPACE::sigaction(SIGUSR1, &action, nullptr), Succeeds());
65
66 EXPECT_EXITS([] { LIBC_NAMESPACE::raise(SIGUSR1); }, 0);
67}
68

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