blob: dfe319712e6dd0dd74e18d68b570971815e0e547 [file] [log] [blame]
Dave Allisonf4b80bc2014-05-14 15:41:25 -07001/*
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 <unistd.h>
20
21#include "jni.h"
22
23#ifdef __arm__
24#include <sys/ucontext.h>
25#endif
26
27static void signalhandler(int sig, siginfo_t* info, void* context) {
28 printf("signal caught\n");
29#ifdef __arm__
30 // On ARM we do a more exhaustive test to make sure the signal
31 // context is OK.
32 // We can do this because we know that the instruction causing
33 // the signal is 2 bytes long (thumb mov instruction). On
34 // other architectures this is more difficult.
35 // TODO: we could do this on other architectures too if necessary, it's just harder.
36 struct ucontext *uc = reinterpret_cast<struct ucontext*>(context);
37 struct sigcontext *sc = reinterpret_cast<struct sigcontext*>(&uc->uc_mcontext);
38 sc->arm_pc += 2; // Skip instruction causing segv.
39#endif
40}
41
42static struct sigaction oldaction;
43
44extern "C" JNIEXPORT void JNICALL Java_SignalTest_initSignalTest(JNIEnv*, jclass) {
45 struct sigaction action;
46 action.sa_sigaction = signalhandler;
47 sigemptyset(&action.sa_mask);
48 action.sa_flags = SA_SIGINFO | SA_ONSTACK;
Ian Rogersc5f17732014-06-05 20:48:42 -070049#if !defined(__APPLE__) && !defined(__mips__)
Dave Allisonf4b80bc2014-05-14 15:41:25 -070050 action.sa_restorer = nullptr;
51#endif
52
53 sigaction(SIGSEGV, &action, &oldaction);
54}
55
56extern "C" JNIEXPORT void JNICALL Java_SignalTest_terminateSignalTest(JNIEnv*, jclass) {
57 sigaction(SIGSEGV, &oldaction, nullptr);
58}
59
60// Prevent the compiler being a smart-alec and optimizing out the assignment
61// to nullptr.
62char *p = nullptr;
63
64extern "C" JNIEXPORT jint JNICALL Java_SignalTest_testSignal(JNIEnv*, jclass) {
65#ifdef __arm__
66 // On ARM we cause a real SEGV.
67 *p = 'a';
68#else
69 // On other architectures we simulate SEGV.
70 kill(getpid(), SIGSEGV);
71#endif
72 return 1234;
73}
74