signaltest.cc revision 03c9785a8a6d712775cf406c4371d0227c44148f
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <signal.h>
18#include <stdio.h>
19#include <stdlib.h>
20#include <unistd.h>
21
22#include "jni.h"
23
24#ifdef __arm__
25#include <sys/ucontext.h>
26#endif
27
28static int signal_count;
29static const int kMaxSignal = 2;
30
31static void signalhandler(int sig, siginfo_t* info, void* context) {
32  printf("signal caught\n");
33  ++signal_count;
34  if (signal_count > kMaxSignal) {
35     abort();
36  }
37#ifdef __arm__
38  // On ARM we do a more exhaustive test to make sure the signal
39  // context is OK.
40  // We can do this because we know that the instruction causing
41  // the signal is 2 bytes long (thumb mov instruction).  On
42  // other architectures this is more difficult.
43  // TODO: we could do this on other architectures too if necessary, it's just harder.
44  struct ucontext *uc = reinterpret_cast<struct ucontext*>(context);
45  struct sigcontext *sc = reinterpret_cast<struct sigcontext*>(&uc->uc_mcontext);
46  sc->arm_pc += 2;          // Skip instruction causing segv.
47#endif
48}
49
50static struct sigaction oldaction;
51
52extern "C" JNIEXPORT void JNICALL Java_Main_initSignalTest(JNIEnv*, jclass) {
53  struct sigaction action;
54  action.sa_sigaction = signalhandler;
55  sigemptyset(&action.sa_mask);
56  action.sa_flags = SA_SIGINFO | SA_ONSTACK;
57#if !defined(__APPLE__) && !defined(__mips__)
58  action.sa_restorer = nullptr;
59#endif
60
61  sigaction(SIGSEGV, &action, &oldaction);
62}
63
64extern "C" JNIEXPORT void JNICALL Java_Main_terminateSignalTest(JNIEnv*, jclass) {
65  sigaction(SIGSEGV, &oldaction, nullptr);
66}
67
68// Prevent the compiler being a smart-alec and optimizing out the assignment
69// to nullptr.
70char *p = nullptr;
71
72extern "C" JNIEXPORT jint JNICALL Java_Main_testSignal(JNIEnv*, jclass) {
73#ifdef __arm__
74  // On ARM we cause a real SEGV.
75  *p = 'a';
76#else
77  // On other architectures we simulate SEGV.
78  kill(getpid(), SIGSEGV);
79#endif
80  return 1234;
81}
82
83