xref: /llvm-project/libc/test/src/signal/sigaction_test.cpp (revision b6bc9d72f65a5086f310f321e969d96e9a559e75)
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 
18 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
19 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
20 
21 TEST(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.
27 TEST(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 
34 static int sigusr1Count;
35 static bool correctSignal;
36 
37 TEST(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 
60 TEST(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