1 /*
2 * Copyright (C) 2011 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 "thread.h"
18
19 #include <signal.h>
20
21 #include "base/logging.h" // For VLOG.
22 #include "base/utils.h"
23
24 namespace art {
25
SigAltStack(stack_t * new_stack,stack_t * old_stack)26 static void SigAltStack(stack_t* new_stack, stack_t* old_stack) {
27 if (sigaltstack(new_stack, old_stack) == -1) {
28 PLOG(FATAL) << "sigaltstack failed";
29 }
30 }
31
32 // The default SIGSTKSZ on linux is 8K. If we do any logging in a signal
33 // handler or do a stack unwind, this is too small. We allocate 32K
34 // instead of the minimum signal stack size.
35 // TODO: We shouldn't do logging (with locks) in signal handlers.
36 static constexpr int kHostAltSigStackSize =
37 32 * KB < MINSIGSTKSZ ? MINSIGSTKSZ : 32 * KB;
38
SetUpAlternateSignalStack()39 void Thread::SetUpAlternateSignalStack() {
40 // Create and set an alternate signal stack.
41 #ifdef ART_TARGET_ANDROID
42 LOG(FATAL) << "Invalid use of alternate signal stack on Android";
43 #endif
44 stack_t ss;
45 ss.ss_sp = new uint8_t[kHostAltSigStackSize];
46 ss.ss_size = kHostAltSigStackSize;
47 ss.ss_flags = 0;
48 CHECK(ss.ss_sp != nullptr);
49 SigAltStack(&ss, nullptr);
50
51 // Double-check that it worked.
52 ss.ss_sp = nullptr;
53 SigAltStack(nullptr, &ss);
54 VLOG(threads) << "Alternate signal stack is " << PrettySize(ss.ss_size) << " at " << ss.ss_sp;
55 }
56
TearDownAlternateSignalStack()57 void Thread::TearDownAlternateSignalStack() {
58 // Get the pointer so we can free the memory.
59 stack_t ss;
60 SigAltStack(nullptr, &ss);
61 uint8_t* allocated_signal_stack = reinterpret_cast<uint8_t*>(ss.ss_sp);
62
63 // Tell the kernel to stop using it.
64 ss.ss_sp = nullptr;
65 ss.ss_flags = SS_DISABLE;
66 ss.ss_size = kHostAltSigStackSize; // Avoid ENOMEM failure with Mac OS' buggy libc.
67 SigAltStack(&ss, nullptr);
68
69 // Free it.
70 delete[] allocated_signal_stack;
71 }
72
73 } // namespace art
74