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 "asm_support_x86_64.h"
20 #include "base/macros.h"
21 #include "thread-current-inl.h"
22 #include "thread_list.h"
23 
24 #if defined(__linux__)
25 #include <asm/prctl.h>
26 #include <sys/prctl.h>
27 #include <sys/syscall.h>
28 #elif defined(__Fuchsia__)
29 #include <zircon/process.h>
30 #include <zircon/syscalls.h>
31 #include <zircon/syscalls/object.h>
32 #endif
33 
34 namespace art {
35 
36 #if defined(__linux__)
arch_prctl(int code,void * val)37 static void arch_prctl(int code, void* val) {
38   syscall(__NR_arch_prctl, code, val);
39 }
40 #endif
41 
InitCpu()42 void Thread::InitCpu() {
43   MutexLock mu(nullptr, *Locks::modify_ldt_lock_);
44 
45 #if defined(__linux__)
46   arch_prctl(ARCH_SET_GS, this);
47 #elif defined(__Fuchsia__)
48   Thread* thread_ptr = this;
49   zx_status_t status = zx_object_set_property(zx_thread_self(),
50                                               ZX_PROP_REGISTER_GS,
51                                               &thread_ptr,
52                                               sizeof(thread_ptr));
53   CHECK_EQ(status, ZX_OK) << "failed to set GS register";
54 #else
55   UNIMPLEMENTED(FATAL) << "Need to set GS";
56 #endif
57 
58   // Allow easy indirection back to Thread*.
59   tlsPtr_.self = this;
60 
61   // Check that the reads from %gs point to this Thread*.
62   Thread* self_check;
63   __asm__ __volatile__("movq %%gs:(%1), %0"
64       : "=r"(self_check)  // output
65       : "r"(THREAD_SELF_OFFSET)  // input
66       :);  // clobber
67   CHECK_EQ(self_check, this);
68 }
69 
CleanupCpu()70 void Thread::CleanupCpu() {
71   // Check that the reads from %gs point to this Thread*.
72   Thread* self_check;
73   __asm__ __volatile__("movq %%gs:(%1), %0"
74       : "=r"(self_check)  // output
75       : "r"(THREAD_SELF_OFFSET)  // input
76       :);  // clobber
77   CHECK_EQ(self_check, this);
78 
79   // Do nothing.
80 }
81 
82 }  // namespace art
83