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