SignalTestUtils.cpp 10.3 KB
Newer Older
M
mamingshuai 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <fcntl.h>
#include "log.h"
#include "utils.h"
#include "SignalTest.h"

using namespace testing::ext;

// static member must init before use.
int IpcSignalTest::mReceivedSignal = 0;
int IpcSignalTest::mShmid = 0;
siginfo_t IpcSignalTest::mSiginfo;

// special signal hander for function 'abort'
void IpcSignalTest::SigAbortHandler(int signum)
{
    LOG("hander: recv a signal: %d", signum);
    int *shared = static_cast<int*>(shmat(mShmid, nullptr, 0));
    if (shared == reinterpret_cast<int*>(-1)) {
        LOG("SigAbortHandler: shmat fail, errno = %d", errno);
    } else {
        LOG("shared: %p", shared);
        *shared = signum;
        if (shmdt(shared) == -1) {
            LOG("SigAbortHandler: shmdt errno = %d", errno);
        }
    }
}

// special signal handler for function 'sigaction'
void IpcSignalTest::SigactionHandler(int signum, siginfo_t* si, void* ucontext)
{
    LOG("hander recv a signal: %s(%d)", ALL_SIGNALS[signum].signame, signum);
    mReceivedSignal = signum;
    // siginfo_t para is not supported yet
}

// general signal hander. note: not thread-safe
void IpcSignalTest::SignalHandler(int signum)
{
    LOG("hander recv a signal: %s(%d)", ALL_SIGNALS[signum].signame, signum);
    mReceivedSignal = signum;
}

SignalNameAction const ALL_SIGNALS[MAX_SIGNAL] = {
    {"NA",      "Unknown signal",           TERMINATE},
    {"SIGHUP",  "Hangup",                   TERMINATE}, //  1
    {"SIGINT",  "Interrupt",                TERMINATE},
    {"SIGQUIT", "Quit",                     COREDUMP},
    {"SIGILL",  "Illegal instruction",      COREDUMP},
    {"SIGTRAP", "Trace/breakpoint trap",    COREDUMP},
    {"SIGABRT", "Aborted",                  COREDUMP},  //  alias:  SIGIOT
    {"SIGBUS",  "Bus error",                COREDUMP},
    {"SIGFPE",  "Arithmetic exception",     COREDUMP},
    {"SIGKILL", "Killed",                   TERMINATE},
    {"SIGUSR1", "User defined signal 1",    TERMINATE}, //  10
    {"SIGSEGV", "Segmentation fault",       COREDUMP},
    {"SIGUSR2", "User defined signal 2",    TERMINATE},
    {"SIGPIPE", "Broken pipe",              TERMINATE},
    {"SIGALRM", "Alarm clock",              TERMINATE},
    {"SIGTERM", "Terminated",               TERMINATE},
    {"SIGSTKFLT", "Stack fault",            TERMINATE},
    {"SIGCHLD", "Child process status",     IGNORE},    //  alias:  SIGCLD
    {"SIGCONT", "Continued",                CONTINUE},
    {"SIGSTOP", "Stopped (signal)",         STOP},
    {"SIGTSTP", "Stopped",                  STOP},      //  20
    {"SIGTTIN", "Stopped (tty input)",      STOP},
    {"SIGTTOU", "Stopped (tty output)",     STOP},
    {"SIGURG",  "Urgent I/O condition",     IGNORE},
    {"SIGXCPU", "CPU time limit exceeded",  COREDUMP},
    {"SIGXFSZ", "File size limit exceeded", COREDUMP},
    {"SIGVTALRM", "Virtual timer expired",  TERMINATE},
    {"SIGPROF", "Profiling timer expired",  TERMINATE},
    {"SIGWINCH",  "Window changed",         IGNORE},
    {"SIGIO",   "I/O possible",             TERMINATE}, //  alias:  SIGPOLL
    {"SIGPWR",  "Power failure",            TERMINATE}, //  alias:  SIGINFO,    30
};

void IpcSignalTest::DefaultActionTest(const int signum, const bool expectStop, const bool coredump)
{
    pid_t pid = fork();
    ASSERT_TRUE(pid >= 0) << "======== Fork Error! =========";
    if (pid > 0) { // parent
        Msleep(20);
        LOGD("befor kill");
        kill(pid, signum);
        if (!expectStop) {
            Msleep(20);
            AssertProcAlive(pid);
            Msleep(20);
            WaitProcExitedOK(pid);
        } else {
            WaitProcKilled(pid, signum);
            if (coredump) {
                // check codedump, liteos not support yet
            }
        }
    } else { // child
        LOGD("child start");
        KeepRun(100);
        if (expectStop) {
            LOG("Child should has been Terminated, but still alive.");
            exit(1);
        }
        exit(0);
    }
}

void IpcSignalTest::SendAndRecvTest(const int signum)
{
    pid_t pid1, pid2;
    bool useBrother = GetRandom(100) % 2; // if use brother to send the signal
    pid1 = fork();
    ASSERT_TRUE(pid1 >= 0) << "======== Fork1 Error! =========";
    if (pid1 > 0) { // parent
        LOGD("in parent...");
        if (useBrother) {
            pid2 = fork();
            ASSERT_TRUE(pid2 >= 0) << "======== Fork2 Error! =========";
            if (pid2 == 0) { // child 2
                Msleep(50);
                kill(pid1, signum);
                exit(0);
            }
            // parent
            Msleep(20);
            LOG("check if child2 exited OK");
            WaitProcExitedOK(pid2);
        } else {
            Msleep(100);
            kill(pid1, signum);
        }
        AssertProcAlive(pid1);

        Msleep(20); // child should exited now
        LOG("check if child exited OK");
        WaitProcExitedOK(pid1);
    } else { // child 1, the receiver
        LOGD("in child, pid=%d", getpid());
        handler_type rt = signal(signum, SignalHandler);
        if (rt == SIG_ERR) {
            LOG("set %d signal handler failed, errno=%d", signum, errno);
            exit(1);
        }
        Msleep(150);
        if (mReceivedSignal != signum) {
            LOG("SignalHandler check fail, expected=%d, received=%d", signum, mReceivedSignal);
            exit(1);
        }
        LOGD("child sleeping....");
        Msleep(20);
        LOGD("child exit 0....");
        exit(0);
    }
}

int IpcSignalTest::CheckSigString(const char* outfile, const char* expectStr)
{
    const int bufLen = 64;
    char buffer[bufLen];

    FILE *fp = fopen(outfile, "rb");
    size_t bytes = fread(buffer, 1, bufLen, fp);
    buffer[bytes] = 0;
    LOGD("%d bytes read from logfile:%s", bytes, buffer);
    fclose(fp);
    size_t expectLen = strlen(expectStr);
    LOGD("expect string len = %d", expectLen);
    if (bytes != (expectLen + 1)) {
        LOG("bytes number read from stderr file error, expect:%d, actual:%d",
            expectLen + 1, bytes);
        return 1;
    }
    return strncmp(expectStr, buffer, expectLen);
}

void IpcSignalTest::SignalFailTest(int signum, handler_type h, int expectErrno)
{
    errno = 0;
    handler_type rt = signal(signum, h);
    ASSERT_EQ(rt, SIG_ERR) << "signal error for " << signum;
    ASSERT_EQ(errno, expectErrno) << "signal error for " << signum;
}
void IpcSignalTest::SigpendingFailTest(sigset_t* pset)
{
    errno = 0;
    int rt = sigpending(pset);
    ASSERT_EQ(rt, -1);
    ASSERT_EQ(errno, EFAULT);
}
void IpcSignalTest::SigtimedwaitFailTest(const sigset_t *set, siginfo_t* info, const timespec* timeout, int expectErrno)
{
    errno = 0;
    int rt = sigtimedwait(set, info, timeout);
    ASSERT_EQ(rt, -1);
    ASSERT_EQ(errno, expectErrno);
}

// thread function for testcase: 'testPthreadkill'
void* IpcSignalTest::ThreadFunc1(void* arg)
{
    int sigNo = (int)((uintptr_t)arg);
    signal(sigNo, SignalHandler);
    Msleep(60);
    return nullptr;
}

// thread function for testcase: 'testPthreadkillMain'
void* IpcSignalTest::ThreadFunc2(void* arg)
{
    pthread_t* tid = (pthread_t*)arg;
    int ret = pthread_kill(*tid, SIGINT);
    if (ret != 0) {
        LOG("pthread_kill failed, errno=%d", ret);
        return (void*)1;
    }
    LOG("pthread_kill send signal(%d) ok", SIGINT);
    return nullptr;
}

// thread function for testcase: 'testPthreadSigmask'
void* IpcSignalTest::ThreadFuncForSigmask1(void* arg)
{
    int rt;
    int type = (int)((uintptr_t)arg);
    if (type == 1) {
        signal(SIGINT, SignalHandler);
    }

    LOG("block SIGINT");
    sigset_t sigmask, oldmask;
    sigemptyset(&sigmask);
    sigemptyset(&oldmask);
    sigaddset(&sigmask, SIGINT);
    sigaddset(&sigmask, SIGUSR1);
    rt = pthread_sigmask(SIG_BLOCK, &sigmask, &oldmask);
    EXPECT_EQ(rt, 0);
    raise(SIGINT);
    EXPECT_EQ(mReceivedSignal, 0) << "SignalHandler check fail, SIGINT should has blocked!";

    LOG("unblock SIGINT");
    sigemptyset(&sigmask);
    sigaddset(&sigmask, SIGINT);
    rt = pthread_sigmask(SIG_UNBLOCK, &sigmask, nullptr);
    EXPECT_EQ(rt, 0);

    LOG("check the new block set");
    sigemptyset(&oldmask);
    pthread_sigmask(SIG_UNBLOCK, nullptr, &oldmask);
    EXPECT_EQ(sigismember(&oldmask, SIGINT), 0) << "SIGINT should has deleted from block set!";
    EXPECT_EQ(sigismember(&oldmask, SIGUSR1), 1) << "SIGUSR1 should still in block set!";

    EXPECT_EQ(mReceivedSignal, SIGINT) << "SignalHandler check fail, SIGINT should deliver after unblock!";
    return nullptr;
}

// thread function for testcase: 'testPthreadSigmaskInherit'
void* IpcSignalTest::ThreadFuncForSigmask2(void* arg)
{
    sigset_t sigmask, oldmask;
    sigemptyset(&sigmask);
    sigemptyset(&oldmask);

    LOG("SubThread: check the block set is inherited");
    pthread_sigmask(SIG_BLOCK, nullptr, &oldmask);
    if (!sigismember(&oldmask, SIGUSR1)) {
        LOG("initial block set should include SIGUSR1!");
        return (void*)1;
    }

    LOG("SubThread: add SIGINT to block set");
    sigaddset(&sigmask, SIGINT);
    int rt = pthread_sigmask(SIG_BLOCK, &sigmask, &oldmask);
    EXPECT_EQ(rt, 0);

    LOG("SubThread: check the new block set");
    sigemptyset(&oldmask);
    pthread_sigmask(SIG_UNBLOCK, nullptr, &oldmask);
    if (!sigismember(&oldmask, SIGINT)) {
        LOG("failed to add SIGINT to block set!");
        return (void*)1;
    }
    if (!sigismember(&oldmask, SIGUSR1)) {
        LOG("SIGUSR1 should still in block set!");
        return (void*)1;
    }
    return nullptr;
}