1 /*
2  * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  *
23  */
24 
25 // no precompiled headers
26 #include "asm/macroAssembler.hpp"
27 #include "classfile/classLoader.hpp"
28 #include "classfile/systemDictionary.hpp"
29 #include "classfile/vmSymbols.hpp"
30 #include "code/icBuffer.hpp"
31 #include "code/vtableStubs.hpp"
32 #include "interpreter/interpreter.hpp"
33 #include "jvm_bsd.h"
34 #include "memory/allocation.inline.hpp"
35 #include "mutex_bsd.inline.hpp"
36 #include "os_share_bsd.hpp"
37 #include "prims/jniFastGetField.hpp"
38 #include "prims/jvm.h"
39 #include "prims/jvm_misc.hpp"
40 #include "runtime/arguments.hpp"
41 #include "runtime/extendedPC.hpp"
42 #include "runtime/frame.inline.hpp"
43 #include "runtime/interfaceSupport.hpp"
44 #include "runtime/java.hpp"
45 #include "runtime/javaCalls.hpp"
46 #include "runtime/mutexLocker.hpp"
47 #include "runtime/osThread.hpp"
48 #include "runtime/sharedRuntime.hpp"
49 #include "runtime/stubRoutines.hpp"
50 #include "runtime/thread.inline.hpp"
51 #include "runtime/timer.hpp"
52 #include "utilities/events.hpp"
53 #include "utilities/vmError.hpp"
54 
55 // put OS-includes here
56 # include <sys/types.h>
57 # include <sys/mman.h>
58 # include <pthread.h>
59 # include <signal.h>
60 # include <errno.h>
61 # include <dlfcn.h>
62 # include <stdlib.h>
63 # include <stdio.h>
64 # include <unistd.h>
65 # include <sys/resource.h>
66 # include <pthread.h>
67 # include <sys/stat.h>
68 # include <sys/time.h>
69 # include <sys/utsname.h>
70 # include <sys/socket.h>
71 # include <sys/wait.h>
72 # include <pwd.h>
73 # include <poll.h>
74 #ifndef __OpenBSD__
75 # include <ucontext.h>
76 #endif
77 #ifdef __FreeBSD__
78 # include <sys/sysctl.h>
79 # include <sys/procctl.h>
80 #ifndef PROC_STACKGAP_STATUS
81 #define PROC_STACKGAP_STATUS	18
82 #endif
83 #ifndef PROC_STACKGAP_DISABLE
84 #define PROC_STACKGAP_DISABLE	0x0002
85 #endif
86 #endif /* __FreeBSD__ */
87 
88 #if !defined(__APPLE__) && !defined(__NetBSD__)
89 # include <pthread_np.h>
90 #endif
91 
92 // needed by current_stack_region() workaround for Mavericks
93 #if defined(__APPLE__)
94 # include <errno.h>
95 # include <sys/types.h>
96 # include <sys/sysctl.h>
97 # define DEFAULT_MAIN_THREAD_STACK_PAGES 2048
98 # define OS_X_10_9_0_KERNEL_MAJOR_VERSION 13
99 #endif
100 
101 #ifdef AMD64
102 #define SPELL_REG_SP "rsp"
103 #define SPELL_REG_FP "rbp"
104 #else
105 #define SPELL_REG_SP "esp"
106 #define SPELL_REG_FP "ebp"
107 #endif // AMD64
108 
109 #if defined(__FreeBSD__) || defined(__DragonFly__)
110 # define context_trapno uc_mcontext.mc_trapno
111 # ifdef AMD64
112 #  define context_pc uc_mcontext.mc_rip
113 #  define context_sp uc_mcontext.mc_rsp
114 #  define context_fp uc_mcontext.mc_rbp
115 #  define context_rip uc_mcontext.mc_rip
116 #  define context_rsp uc_mcontext.mc_rsp
117 #  define context_rbp uc_mcontext.mc_rbp
118 #  define context_rax uc_mcontext.mc_rax
119 #  define context_rbx uc_mcontext.mc_rbx
120 #  define context_rcx uc_mcontext.mc_rcx
121 #  define context_rdx uc_mcontext.mc_rdx
122 #  define context_rsi uc_mcontext.mc_rsi
123 #  define context_rdi uc_mcontext.mc_rdi
124 #  define context_r8  uc_mcontext.mc_r8
125 #  define context_r9  uc_mcontext.mc_r9
126 #  define context_r10 uc_mcontext.mc_r10
127 #  define context_r11 uc_mcontext.mc_r11
128 #  define context_r12 uc_mcontext.mc_r12
129 #  define context_r13 uc_mcontext.mc_r13
130 #  define context_r14 uc_mcontext.mc_r14
131 #  define context_r15 uc_mcontext.mc_r15
132 #  define context_flags uc_mcontext.mc_flags
133 #  define context_err uc_mcontext.mc_err
134 # else
135 #  define context_pc uc_mcontext.mc_eip
136 #  define context_sp uc_mcontext.mc_esp
137 #  define context_fp uc_mcontext.mc_ebp
138 #  define context_eip uc_mcontext.mc_eip
139 #  define context_esp uc_mcontext.mc_esp
140 #  define context_eax uc_mcontext.mc_eax
141 #  define context_ebx uc_mcontext.mc_ebx
142 #  define context_ecx uc_mcontext.mc_ecx
143 #  define context_edx uc_mcontext.mc_edx
144 #  define context_ebp uc_mcontext.mc_ebp
145 #  define context_esi uc_mcontext.mc_esi
146 #  define context_edi uc_mcontext.mc_edi
147 #  define context_eflags uc_mcontext.mc_eflags
148 #  define context_trapno uc_mcontext.mc_trapno
149 # endif
150 #endif
151 
152 #ifdef __APPLE__
153 # if __DARWIN_UNIX03 && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
154   // 10.5 UNIX03 member name prefixes
155   #define DU3_PREFIX(s, m) __ ## s.__ ## m
156 # else
157   #define DU3_PREFIX(s, m) s ## . ## m
158 # endif
159 
160 # ifdef AMD64
161 #  define context_pc context_rip
162 #  define context_sp context_rsp
163 #  define context_fp context_rbp
164 #  define context_rip uc_mcontext->DU3_PREFIX(ss,rip)
165 #  define context_rsp uc_mcontext->DU3_PREFIX(ss,rsp)
166 #  define context_rax uc_mcontext->DU3_PREFIX(ss,rax)
167 #  define context_rbx uc_mcontext->DU3_PREFIX(ss,rbx)
168 #  define context_rcx uc_mcontext->DU3_PREFIX(ss,rcx)
169 #  define context_rdx uc_mcontext->DU3_PREFIX(ss,rdx)
170 #  define context_rbp uc_mcontext->DU3_PREFIX(ss,rbp)
171 #  define context_rsi uc_mcontext->DU3_PREFIX(ss,rsi)
172 #  define context_rdi uc_mcontext->DU3_PREFIX(ss,rdi)
173 #  define context_r8  uc_mcontext->DU3_PREFIX(ss,r8)
174 #  define context_r9  uc_mcontext->DU3_PREFIX(ss,r9)
175 #  define context_r10 uc_mcontext->DU3_PREFIX(ss,r10)
176 #  define context_r11 uc_mcontext->DU3_PREFIX(ss,r11)
177 #  define context_r12 uc_mcontext->DU3_PREFIX(ss,r12)
178 #  define context_r13 uc_mcontext->DU3_PREFIX(ss,r13)
179 #  define context_r14 uc_mcontext->DU3_PREFIX(ss,r14)
180 #  define context_r15 uc_mcontext->DU3_PREFIX(ss,r15)
181 #  define context_flags uc_mcontext->DU3_PREFIX(ss,rflags)
182 #  define context_trapno uc_mcontext->DU3_PREFIX(es,trapno)
183 #  define context_err uc_mcontext->DU3_PREFIX(es,err)
184 # else
185 #  define context_pc context_eip
186 #  define context_sp context_esp
187 #  define context_fp context_ebp
188 #  define context_eip uc_mcontext->DU3_PREFIX(ss,eip)
189 #  define context_esp uc_mcontext->DU3_PREFIX(ss,esp)
190 #  define context_eax uc_mcontext->DU3_PREFIX(ss,eax)
191 #  define context_ebx uc_mcontext->DU3_PREFIX(ss,ebx)
192 #  define context_ecx uc_mcontext->DU3_PREFIX(ss,ecx)
193 #  define context_edx uc_mcontext->DU3_PREFIX(ss,edx)
194 #  define context_ebp uc_mcontext->DU3_PREFIX(ss,ebp)
195 #  define context_esi uc_mcontext->DU3_PREFIX(ss,esi)
196 #  define context_edi uc_mcontext->DU3_PREFIX(ss,edi)
197 #  define context_eflags uc_mcontext->DU3_PREFIX(ss,eflags)
198 #  define context_trapno uc_mcontext->DU3_PREFIX(es,trapno)
199 # endif
200 #endif
201 
202 #ifdef __OpenBSD__
203 # define context_trapno sc_trapno
204 # ifdef AMD64
205 #  define context_pc sc_rip
206 #  define context_sp sc_rsp
207 #  define context_fp sc_rbp
208 #  define context_rip sc_rip
209 #  define context_rsp sc_rsp
210 #  define context_rbp sc_rbp
211 #  define context_rax sc_rax
212 #  define context_rbx sc_rbx
213 #  define context_rcx sc_rcx
214 #  define context_rdx sc_rdx
215 #  define context_rsi sc_rsi
216 #  define context_rdi sc_rdi
217 #  define context_r8  sc_r8
218 #  define context_r9  sc_r9
219 #  define context_r10 sc_r10
220 #  define context_r11 sc_r11
221 #  define context_r12 sc_r12
222 #  define context_r13 sc_r13
223 #  define context_r14 sc_r14
224 #  define context_r15 sc_r15
225 #  define context_flags sc_rflags
226 #  define context_err sc_err
227 # else
228 #  define context_pc sc_eip
229 #  define context_sp sc_esp
230 #  define context_fp sc_ebp
231 #  define context_eip sc_eip
232 #  define context_esp sc_esp
233 #  define context_eax sc_eax
234 #  define context_ebx sc_ebx
235 #  define context_ecx sc_ecx
236 #  define context_edx sc_edx
237 #  define context_ebp sc_ebp
238 #  define context_esi sc_esi
239 #  define context_edi sc_edi
240 #  define context_eflags sc_eflags
241 #  define context_trapno sc_trapno
242 # endif
243 #endif
244 
245 #ifdef __NetBSD__
246 # define context_trapno uc_mcontext.__gregs[_REG_TRAPNO]
247 # ifdef AMD64
248 #  define __register_t __greg_t
249 #  define context_pc uc_mcontext.__gregs[_REG_RIP]
250 #  define context_sp uc_mcontext.__gregs[_REG_URSP]
251 #  define context_fp uc_mcontext.__gregs[_REG_RBP]
252 #  define context_rip uc_mcontext.__gregs[_REG_RIP]
253 #  define context_rsp uc_mcontext.__gregs[_REG_URSP]
254 #  define context_rax uc_mcontext.__gregs[_REG_RAX]
255 #  define context_rbx uc_mcontext.__gregs[_REG_RBX]
256 #  define context_rcx uc_mcontext.__gregs[_REG_RCX]
257 #  define context_rdx uc_mcontext.__gregs[_REG_RDX]
258 #  define context_rbp uc_mcontext.__gregs[_REG_RBP]
259 #  define context_rsi uc_mcontext.__gregs[_REG_RSI]
260 #  define context_rdi uc_mcontext.__gregs[_REG_RDI]
261 #  define context_r8  uc_mcontext.__gregs[_REG_R8]
262 #  define context_r9  uc_mcontext.__gregs[_REG_R9]
263 #  define context_r10 uc_mcontext.__gregs[_REG_R10]
264 #  define context_r11 uc_mcontext.__gregs[_REG_R11]
265 #  define context_r12 uc_mcontext.__gregs[_REG_R12]
266 #  define context_r13 uc_mcontext.__gregs[_REG_R13]
267 #  define context_r14 uc_mcontext.__gregs[_REG_R14]
268 #  define context_r15 uc_mcontext.__gregs[_REG_R15]
269 #  define context_flags uc_mcontext.__gregs[_REG_RFL]
270 #  define context_err uc_mcontext.__gregs[_REG_ERR]
271 # else
272 #  define context_pc uc_mcontext.__gregs[_REG_EIP]
273 #  define context_sp uc_mcontext.__gregs[_REG_UESP]
274 #  define context_fp uc_mcontext.__gregs[_REG_EBP]
275 #  define context_eip uc_mcontext.__gregs[_REG_EIP]
276 #  define context_esp uc_mcontext.__gregs[_REG_UESP]
277 #  define context_eax uc_mcontext.__gregs[_REG_EAX]
278 #  define context_ebx uc_mcontext.__gregs[_REG_EBX]
279 #  define context_ecx uc_mcontext.__gregs[_REG_ECX]
280 #  define context_edx uc_mcontext.__gregs[_REG_EDX]
281 #  define context_ebp uc_mcontext.__gregs[_REG_EBP]
282 #  define context_esi uc_mcontext.__gregs[_REG_ESI]
283 #  define context_edi uc_mcontext.__gregs[_REG_EDI]
284 #  define context_eflags uc_mcontext.__gregs[_REG_EFL]
285 #  define context_trapno uc_mcontext.__gregs[_REG_TRAPNO]
286 # endif
287 #endif
288 
289 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
290 
current_stack_pointer()291 address os::current_stack_pointer() {
292 #if defined(__clang__) || defined(__llvm__)
293   register void *esp;
294   __asm__("mov %%" SPELL_REG_SP ", %0" : "=r" (esp));
295   return (address) esp;
296 #elif defined(SPARC_WORKS)
297   register void *esp;
298   __asm__("mov %%" SPELL_REG_SP ", %0" : "=r" (esp));
299   return (address) ((char*)esp + sizeof(long)*2);
300 #else
301   register void *esp __asm__ (SPELL_REG_SP);
302   return (address) esp;
303 #endif
304 }
305 
non_memory_address_word()306 char* os::non_memory_address_word() {
307   // Must never look like an address returned by reserve_memory,
308   // even in its subfields (as defined by the CPU immediate fields,
309   // if the CPU splits constants across multiple instructions).
310 
311   return (char*) -1;
312 }
313 
initialize_thread(Thread * thr)314 void os::initialize_thread(Thread* thr) {
315 // Nothing to do.
316 }
317 
ucontext_get_pc(ucontext_t * uc)318 address os::Bsd::ucontext_get_pc(ucontext_t * uc) {
319   return (address)uc->context_pc;
320 }
321 
ucontext_get_sp(ucontext_t * uc)322 intptr_t* os::Bsd::ucontext_get_sp(ucontext_t * uc) {
323   return (intptr_t*)uc->context_sp;
324 }
325 
ucontext_get_fp(ucontext_t * uc)326 intptr_t* os::Bsd::ucontext_get_fp(ucontext_t * uc) {
327   return (intptr_t*)uc->context_fp;
328 }
329 
330 // For Forte Analyzer AsyncGetCallTrace profiling support - thread
331 // is currently interrupted by SIGPROF.
332 // os::Solaris::fetch_frame_from_ucontext() tries to skip nested signal
333 // frames. Currently we don't do that on Bsd, so it's the same as
334 // os::fetch_frame_from_context().
fetch_frame_from_ucontext(Thread * thread,ucontext_t * uc,intptr_t ** ret_sp,intptr_t ** ret_fp)335 ExtendedPC os::Bsd::fetch_frame_from_ucontext(Thread* thread,
336   ucontext_t* uc, intptr_t** ret_sp, intptr_t** ret_fp) {
337 
338   assert(thread != NULL, "just checking");
339   assert(ret_sp != NULL, "just checking");
340   assert(ret_fp != NULL, "just checking");
341 
342   return os::fetch_frame_from_context(uc, ret_sp, ret_fp);
343 }
344 
fetch_frame_from_context(void * ucVoid,intptr_t ** ret_sp,intptr_t ** ret_fp)345 ExtendedPC os::fetch_frame_from_context(void* ucVoid,
346                     intptr_t** ret_sp, intptr_t** ret_fp) {
347 
348   ExtendedPC  epc;
349   ucontext_t* uc = (ucontext_t*)ucVoid;
350 
351   if (uc != NULL) {
352     epc = ExtendedPC(os::Bsd::ucontext_get_pc(uc));
353     if (ret_sp) *ret_sp = os::Bsd::ucontext_get_sp(uc);
354     if (ret_fp) *ret_fp = os::Bsd::ucontext_get_fp(uc);
355   } else {
356     // construct empty ExtendedPC for return value checking
357     epc = ExtendedPC(NULL);
358     if (ret_sp) *ret_sp = (intptr_t *)NULL;
359     if (ret_fp) *ret_fp = (intptr_t *)NULL;
360   }
361 
362   return epc;
363 }
364 
fetch_frame_from_context(void * ucVoid)365 frame os::fetch_frame_from_context(void* ucVoid) {
366   intptr_t* sp;
367   intptr_t* fp;
368   ExtendedPC epc = fetch_frame_from_context(ucVoid, &sp, &fp);
369   return frame(sp, fp, epc.pc());
370 }
371 
372 // By default, gcc always save frame pointer (%ebp/%rbp) on stack. It may get
373 // turned off by -fomit-frame-pointer,
get_sender_for_C_frame(frame * fr)374 frame os::get_sender_for_C_frame(frame* fr) {
375   return frame(fr->sender_sp(), fr->link(), fr->sender_pc());
376 }
377 
_get_previous_fp()378 intptr_t* _get_previous_fp() {
379 #if defined(SPARC_WORKS) || defined(__clang__) || defined(__llvm__)
380   register intptr_t **ebp;
381   __asm__("mov %%" SPELL_REG_FP ", %0" : "=r" (ebp));
382 #else
383   register intptr_t **ebp __asm__ (SPELL_REG_FP);
384 #endif
385   return (intptr_t*) *ebp;   // we want what it points to.
386 }
387 
388 
current_frame()389 frame os::current_frame() {
390   intptr_t* fp = _get_previous_fp();
391   frame myframe((intptr_t*)os::current_stack_pointer(),
392                 (intptr_t*)fp,
393                 CAST_FROM_FN_PTR(address, os::current_frame));
394   if (os::is_first_C_frame(&myframe)) {
395     // stack is not walkable
396     return frame();
397   } else {
398     return os::get_sender_for_C_frame(&myframe);
399   }
400 }
401 
402 // Utility functions
403 
404 // From IA32 System Programming Guide
405 enum {
406   trap_page_fault = 0xE
407 };
408 
409 extern "C" JNIEXPORT int
JVM_handle_bsd_signal(int sig,siginfo_t * info,void * ucVoid,int abort_if_unrecognized)410 JVM_handle_bsd_signal(int sig,
411                         siginfo_t* info,
412                         void* ucVoid,
413                         int abort_if_unrecognized) {
414   ucontext_t* uc = (ucontext_t*) ucVoid;
415 
416   Thread* t = ThreadLocalStorage::get_thread_slow();
417 
418   // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away
419   // (no destructors can be run)
420   os::ThreadCrashProtection::check_crash_protection(sig, t);
421 
422   SignalHandlerMark shm(t);
423 
424   // Note: it's not uncommon that JNI code uses signal/sigset to install
425   // then restore certain signal handler (e.g. to temporarily block SIGPIPE,
426   // or have a SIGILL handler when detecting CPU type). When that happens,
427   // JVM_handle_bsd_signal() might be invoked with junk info/ucVoid. To
428   // avoid unnecessary crash when libjsig is not preloaded, try handle signals
429   // that do not require siginfo/ucontext first.
430 
431   if (sig == SIGPIPE || sig == SIGXFSZ) {
432     // allow chained handler to go first
433     if (os::Bsd::chained_handler(sig, info, ucVoid)) {
434       return true;
435     } else {
436       if (PrintMiscellaneous && (WizardMode || Verbose)) {
437         char buf[64];
438         warning("Ignoring %s - see bugs 4229104 or 646499219",
439                 os::exception_name(sig, buf, sizeof(buf)));
440       }
441       return true;
442     }
443   }
444 
445   JavaThread* thread = NULL;
446   VMThread* vmthread = NULL;
447   if (os::Bsd::signal_handlers_are_installed) {
448     if (t != NULL ){
449       if(t->is_Java_thread()) {
450         thread = (JavaThread*)t;
451       }
452       else if(t->is_VM_thread()){
453         vmthread = (VMThread *)t;
454       }
455     }
456   }
457 /*
458   NOTE: does not seem to work on bsd.
459   if (info == NULL || info->si_code <= 0 || info->si_code == SI_NOINFO) {
460     // can't decode this kind of signal
461     info = NULL;
462   } else {
463     assert(sig == info->si_signo, "bad siginfo");
464   }
465 */
466   // decide if this trap can be handled by a stub
467   address stub = NULL;
468 
469   address pc          = NULL;
470 
471   //%note os_trap_1
472   if (info != NULL && uc != NULL && thread != NULL) {
473     pc = (address) os::Bsd::ucontext_get_pc(uc);
474 
475     if (StubRoutines::is_safefetch_fault(pc)) {
476       uc->context_pc = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc));
477       return 1;
478     }
479 
480     // Handle ALL stack overflow variations here
481     if (sig == SIGSEGV || sig == SIGBUS) {
482       address addr = (address) info->si_addr;
483 #ifdef __FreeBSD__
484       /*
485        * Determine whether the kernel stack guard pages have been disabled
486        */
487       int status = 0;
488       int ret = procctl(P_PID, getpid(), PROC_STACKGAP_STATUS, &status);
489 
490       /*
491        * Check if the call to procctl(2) failed or the stack guard is not
492        * disabled.  Either way, we'll then attempt a workaround.
493        */
494       if (ret == -1 || !(status & PROC_STACKGAP_DISABLE)) {
495           /*
496            * Try to work around the problems caused on FreeBSD where the kernel
497            * may place guard pages above JVM guard pages and prevent the Java
498            * thread stacks growing into the JVM guard pages.  The work around
499            * is to determine how many such pages there may be and round down the
500            * fault address so that tests of whether it is in the JVM guard zone
501            * succeed.
502            *
503            * Note that this is a partial workaround at best since the normally
504            * the JVM could then unprotect the reserved area to allow a critical
505            * section to complete.  This is not possible if the kernel has
506            * placed guard pages below the reserved area.
507            *
508            * This also suffers from the problem that the
509            * security.bsd.stack_guard_page sysctl is dynamic and may have
510            * changed since the stack was allocated.  This is likely to be rare
511            * in practice though.
512            *
513            * What this does do is prevent the JVM crashing on FreeBSD and
514            * instead throwing a StackOverflowError when infinite recursion
515            * is attempted, which is the expected behaviour.  Due to it's
516            * limitations though, objects may be in unexpected states when
517            * this occurs.
518            *
519            * A better way to avoid these problems is either to be on a new
520            * enough version of FreeBSD (one that has PROC_STACKGAP_CTL) or set
521            * security.bsd.stack_guard_page to zero.
522            */
523           int guard_pages = 0;
524           size_t size = sizeof(guard_pages);
525           if (sysctlbyname("security.bsd.stack_guard_page",
526                            &guard_pages, &size, NULL, 0) == 0 &&
527               guard_pages > 0) {
528             addr -= guard_pages * os::vm_page_size();
529           }
530       }
531 #endif
532 
533       // check if fault address is within thread stack
534       if (addr < thread->stack_base() &&
535           addr >= thread->stack_base() - thread->stack_size()) {
536         // stack overflow
537         if (thread->in_stack_yellow_zone(addr)) {
538           thread->disable_stack_yellow_zone();
539           if (thread->thread_state() == _thread_in_Java) {
540             // Throw a stack overflow exception.  Guard pages will be reenabled
541             // while unwinding the stack.
542             stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW);
543           } else {
544             // Thread was in the vm or native code.  Return and try to finish.
545             return 1;
546           }
547         } else if (thread->in_stack_red_zone(addr)) {
548           // Fatal red zone violation.  Disable the guard pages and fall through
549           // to handle_unexpected_exception way down below.
550           thread->disable_stack_red_zone();
551           tty->print_raw_cr("An irrecoverable stack overflow has occurred.");
552         }
553       }
554     }
555 
556     if ((sig == SIGSEGV || sig == SIGBUS) && VM_Version::is_cpuinfo_segv_addr(pc)) {
557       // Verify that OS save/restore AVX registers.
558       stub = VM_Version::cpuinfo_cont_addr();
559     }
560 
561     // We test if stub is already set (by the stack overflow code
562     // above) so it is not overwritten by the code that follows. This
563     // check is not required on other platforms, because on other
564     // platforms we check for SIGSEGV only or SIGBUS only, where here
565     // we have to check for both SIGSEGV and SIGBUS.
566     if (thread->thread_state() == _thread_in_Java && stub == NULL) {
567       // Java thread running in Java code => find exception handler if any
568       // a fault inside compiled code, the interpreter, or a stub
569 
570       if ((sig == SIGSEGV || sig == SIGBUS) && os::is_poll_address((address)info->si_addr)) {
571         stub = SharedRuntime::get_poll_stub(pc);
572 #if defined(__APPLE__)
573       // 32-bit Darwin reports a SIGBUS for nearly all memory access exceptions.
574       // 64-bit Darwin may also use a SIGBUS (seen with compressed oops).
575       // Catching SIGBUS here prevents the implicit SIGBUS NULL check below from
576       // being called, so only do so if the implicit NULL check is not necessary.
577       } else if (sig == SIGBUS && MacroAssembler::needs_explicit_null_check((intptr_t)info->si_addr)) {
578 #else
579       } else if (sig == SIGBUS /* && info->si_code == BUS_OBJERR */) {
580 #endif
581         // BugId 4454115: A read from a MappedByteBuffer can fault
582         // here if the underlying file has been truncated.
583         // Do not crash the VM in such a case.
584         CodeBlob* cb = CodeCache::find_blob_unsafe(pc);
585         nmethod* nm = (cb != NULL && cb->is_nmethod()) ? (nmethod*)cb : NULL;
586         if (nm != NULL && nm->has_unsafe_access()) {
587           stub = StubRoutines::handler_for_unsafe_access();
588         }
589       }
590       else
591 
592 #ifdef AMD64
593       if (sig == SIGFPE  &&
594           (info->si_code == FPE_INTDIV || info->si_code == FPE_FLTDIV)) {
595         stub =
596           SharedRuntime::
597           continuation_for_implicit_exception(thread,
598                                               pc,
599                                               SharedRuntime::
600                                               IMPLICIT_DIVIDE_BY_ZERO);
601 #ifdef __APPLE__
602       } else if (sig == SIGFPE && info->si_code == FPE_NOOP) {
603         int op = pc[0];
604 
605         // Skip REX
606         if ((pc[0] & 0xf0) == 0x40) {
607           op = pc[1];
608         } else {
609           op = pc[0];
610         }
611 
612         // Check for IDIV
613         if (op == 0xF7) {
614           stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime:: IMPLICIT_DIVIDE_BY_ZERO);
615         } else {
616           // TODO: handle more cases if we are using other x86 instructions
617           //   that can generate SIGFPE signal.
618           tty->print_cr("unknown opcode 0x%X with SIGFPE.", op);
619           fatal("please update this code.");
620         }
621 #endif /* __APPLE__ */
622 
623 #else
624       if (sig == SIGFPE /* && info->si_code == FPE_INTDIV */) {
625         // HACK: si_code does not work on bsd 2.2.12-20!!!
626         int op = pc[0];
627         if (op == 0xDB) {
628           // FIST
629           // TODO: The encoding of D2I in i486.ad can cause an exception
630           // prior to the fist instruction if there was an invalid operation
631           // pending. We want to dismiss that exception. From the win_32
632           // side it also seems that if it really was the fist causing
633           // the exception that we do the d2i by hand with different
634           // rounding. Seems kind of weird.
635           // NOTE: that we take the exception at the NEXT floating point instruction.
636           assert(pc[0] == 0xDB, "not a FIST opcode");
637           assert(pc[1] == 0x14, "not a FIST opcode");
638           assert(pc[2] == 0x24, "not a FIST opcode");
639           return true;
640         } else if (op == 0xF7) {
641           // IDIV
642           stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_DIVIDE_BY_ZERO);
643         } else {
644           // TODO: handle more cases if we are using other x86 instructions
645           //   that can generate SIGFPE signal on bsd.
646           tty->print_cr("unknown opcode 0x%X with SIGFPE.", op);
647           fatal("please update this code.");
648         }
649 #endif // AMD64
650       } else if ((sig == SIGSEGV || sig == SIGBUS) &&
651                !MacroAssembler::needs_explicit_null_check((intptr_t)info->si_addr)) {
652           // Determination of interpreter/vtable stub/compiled code null exception
653           stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
654       }
655     } else if (thread->thread_state() == _thread_in_vm &&
656 #if defined(__FreeBSD__) || defined(__DragonFly__)
657                (sig == SIGBUS || sig == SIGSEGV) &&
658 #else
659                sig == SIGBUS && /* info->si_code == BUS_OBJERR && */
660 #endif
661                thread->doing_unsafe_access()) {
662         stub = StubRoutines::handler_for_unsafe_access();
663     }
664 
665     // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks in
666     // and the heap gets shrunk before the field access.
667     if ((sig == SIGSEGV) || (sig == SIGBUS)) {
668       address addr = JNI_FastGetField::find_slowcase_pc(pc);
669       if (addr != (address)-1) {
670         stub = addr;
671       }
672     }
673 
674     // Check to see if we caught the safepoint code in the
675     // process of write protecting the memory serialization page.
676     // It write enables the page immediately after protecting it
677     // so we can just return to retry the write.
678     if ((sig == SIGSEGV || sig == SIGBUS) &&
679         os::is_memory_serialize_page(thread, (address) info->si_addr)) {
680       // Block current thread until the memory serialize page permission restored.
681       os::block_on_serialize_page_trap();
682       return true;
683     }
684   }
685 
686 #ifndef AMD64
687   // Execution protection violation
688   //
689   // This should be kept as the last step in the triage.  We don't
690   // have a dedicated trap number for a no-execute fault, so be
691   // conservative and allow other handlers the first shot.
692   //
693   // Note: We don't test that info->si_code == SEGV_ACCERR here.
694   // this si_code is so generic that it is almost meaningless; and
695   // the si_code for this condition may change in the future.
696   // Furthermore, a false-positive should be harmless.
697   if (UnguardOnExecutionViolation > 0 &&
698       (sig == SIGSEGV || sig == SIGBUS) &&
699       uc->context_trapno == trap_page_fault) {
700     int page_size = os::vm_page_size();
701     address addr = (address) info->si_addr;
702     address pc = os::Bsd::ucontext_get_pc(uc);
703     // Make sure the pc and the faulting address are sane.
704     //
705     // If an instruction spans a page boundary, and the page containing
706     // the beginning of the instruction is executable but the following
707     // page is not, the pc and the faulting address might be slightly
708     // different - we still want to unguard the 2nd page in this case.
709     //
710     // 15 bytes seems to be a (very) safe value for max instruction size.
711     bool pc_is_near_addr =
712       (pointer_delta((void*) addr, (void*) pc, sizeof(char)) < 15);
713     bool instr_spans_page_boundary =
714       (align_size_down((intptr_t) pc ^ (intptr_t) addr,
715                        (intptr_t) page_size) > 0);
716 
717     if (pc == addr || (pc_is_near_addr && instr_spans_page_boundary)) {
718       static volatile address last_addr =
719         (address) os::non_memory_address_word();
720 
721       // In conservative mode, don't unguard unless the address is in the VM
722       if (addr != last_addr &&
723           (UnguardOnExecutionViolation > 1 || os::address_is_in_vm(addr))) {
724 
725         // Set memory to RWX and retry
726         address page_start =
727           (address) align_size_down((intptr_t) addr, (intptr_t) page_size);
728         bool res = os::protect_memory((char*) page_start, page_size,
729                                       os::MEM_PROT_RWX);
730 
731         if (PrintMiscellaneous && Verbose) {
732           char buf[256];
733           jio_snprintf(buf, sizeof(buf), "Execution protection violation "
734                        "at " INTPTR_FORMAT
735                        ", unguarding " INTPTR_FORMAT ": %s, errno=%d", addr,
736                        page_start, (res ? "success" : "failed"), errno);
737           tty->print_raw_cr(buf);
738         }
739         stub = pc;
740 
741         // Set last_addr so if we fault again at the same address, we don't end
742         // up in an endless loop.
743         //
744         // There are two potential complications here.  Two threads trapping at
745         // the same address at the same time could cause one of the threads to
746         // think it already unguarded, and abort the VM.  Likely very rare.
747         //
748         // The other race involves two threads alternately trapping at
749         // different addresses and failing to unguard the page, resulting in
750         // an endless loop.  This condition is probably even more unlikely than
751         // the first.
752         //
753         // Although both cases could be avoided by using locks or thread local
754         // last_addr, these solutions are unnecessary complication: this
755         // handler is a best-effort safety net, not a complete solution.  It is
756         // disabled by default and should only be used as a workaround in case
757         // we missed any no-execute-unsafe VM code.
758 
759         last_addr = addr;
760       }
761     }
762   }
763 #endif // !AMD64
764 
765   if (stub != NULL) {
766     // save all thread context in case we need to restore it
767     if (thread != NULL) thread->set_saved_exception_pc(pc);
768 
769     uc->context_pc = (intptr_t)stub;
770     return true;
771   }
772 
773   // signal-chaining
774   if (os::Bsd::chained_handler(sig, info, ucVoid)) {
775      return true;
776   }
777 
778   if (!abort_if_unrecognized) {
779     // caller wants another chance, so give it to him
780     return false;
781   }
782 
783   if (pc == NULL && uc != NULL) {
784     pc = os::Bsd::ucontext_get_pc(uc);
785   }
786 
787   // unmask current signal
788   sigset_t newset;
789   sigemptyset(&newset);
790   sigaddset(&newset, sig);
791   sigprocmask(SIG_UNBLOCK, &newset, NULL);
792 
793   VMError err(t, sig, pc, info, ucVoid);
794   err.report_and_die();
795 
796   ShouldNotReachHere();
797   return false;
798 }
799 
800 // From solaris_i486.s ported to bsd_i486.s
801 extern "C" void fixcw();
802 
803 void os::Bsd::init_thread_fpu_state(void) {
804 #ifndef AMD64
805   // Set fpu to 53 bit precision. This happens too early to use a stub.
806   fixcw();
807 #endif // !AMD64
808 }
809 
810 
811 // Check that the bsd kernel version is 2.4 or higher since earlier
812 // versions do not support SSE without patches.
813 bool os::supports_sse() {
814   return true;
815 }
816 
817 bool os::is_allocatable(size_t bytes) {
818 #ifdef AMD64
819   // unused on amd64?
820   return true;
821 #else
822 
823   if (bytes < 2 * G) {
824     return true;
825   }
826 
827   char* addr = reserve_memory(bytes, NULL);
828 
829   if (addr != NULL) {
830     release_memory(addr, bytes);
831   }
832 
833   return addr != NULL;
834 #endif // AMD64
835 }
836 
837 ////////////////////////////////////////////////////////////////////////////////
838 // thread stack
839 
840 #ifdef AMD64
841 size_t os::Bsd::min_stack_allowed  = 64 * K;
842 
843 // amd64: pthread on amd64 is always in floating stack mode
844 bool os::Bsd::supports_variable_stack_size() {  return true; }
845 #else
846 size_t os::Bsd::min_stack_allowed  =  (48 DEBUG_ONLY(+4))*K;
847 
848 #ifdef __GNUC__
849 #define GET_GS() ({int gs; __asm__ volatile("movw %%gs, %w0":"=q"(gs)); gs&0xffff;})
850 #endif
851 
852 bool os::Bsd::supports_variable_stack_size() { return true; }
853 #endif // AMD64
854 
855 // return default stack size for thr_type
856 size_t os::Bsd::default_stack_size(os::ThreadType thr_type) {
857   // default stack size (compiler thread needs larger stack)
858 #ifdef AMD64
859   size_t s = (thr_type == os::compiler_thread ? 4 * M : 1 * M);
860 #else
861   size_t s = (thr_type == os::compiler_thread ? 2 * M : 512 * K);
862 #endif // AMD64
863   return s;
864 }
865 
866 size_t os::Bsd::default_guard_size(os::ThreadType thr_type) {
867   // Creating guard page is very expensive. Java thread has HotSpot
868   // guard page, only enable glibc guard page for non-Java threads.
869   return (thr_type == java_thread ? 0 : page_size());
870 }
871 
872 // Java thread:
873 //
874 //   Low memory addresses
875 //    +------------------------+
876 //    |                        |\  JavaThread created by VM does not have glibc
877 //    |    glibc guard page    | - guard, attached Java thread usually has
878 //    |                        |/  1 page glibc guard.
879 // P1 +------------------------+ Thread::stack_base() - Thread::stack_size()
880 //    |                        |\
881 //    |  HotSpot Guard Pages   | - red and yellow pages
882 //    |                        |/
883 //    +------------------------+ JavaThread::stack_yellow_zone_base()
884 //    |                        |\
885 //    |      Normal Stack      | -
886 //    |                        |/
887 // P2 +------------------------+ Thread::stack_base()
888 //
889 // Non-Java thread:
890 //
891 //   Low memory addresses
892 //    +------------------------+
893 //    |                        |\
894 //    |  glibc guard page      | - usually 1 page
895 //    |                        |/
896 // P1 +------------------------+ Thread::stack_base() - Thread::stack_size()
897 //    |                        |\
898 //    |      Normal Stack      | -
899 //    |                        |/
900 // P2 +------------------------+ Thread::stack_base()
901 //
902 // ** P1 (aka bottom) and size ( P2 = P1 - size) are the address and stack size returned from
903 //    pthread_attr_getstack()
904 
905 static void current_stack_region(address * bottom, size_t * size) {
906 #ifdef __APPLE__
907   pthread_t self = pthread_self();
908   void *stacktop = pthread_get_stackaddr_np(self);
909   *size = pthread_get_stacksize_np(self);
910   // workaround for OS X 10.9.0 (Mavericks)
911   // pthread_get_stacksize_np returns 128 pages even though the actual size is 2048 pages
912   if (::pthread_main_np() == 1) {
913     if ((*size) < (DEFAULT_MAIN_THREAD_STACK_PAGES * (size_t)getpagesize())) {
914       char kern_osrelease[256];
915       size_t kern_osrelease_size = sizeof(kern_osrelease);
916       int ret = sysctlbyname("kern.osrelease", kern_osrelease, &kern_osrelease_size, NULL, 0);
917       if (ret == 0) {
918         // get the major number, atoi will ignore the minor amd micro portions of the version string
919         if (atoi(kern_osrelease) >= OS_X_10_9_0_KERNEL_MAJOR_VERSION) {
920           *size = (DEFAULT_MAIN_THREAD_STACK_PAGES*getpagesize());
921         }
922       }
923     }
924   }
925   *bottom = (address) stacktop - *size;
926 #elif defined(__OpenBSD__)
927   stack_t ss;
928   int rslt = pthread_stackseg_np(pthread_self(), &ss);
929 
930   if (rslt != 0)
931     fatal(err_msg("pthread_stackseg_np failed with err = %d", rslt));
932 
933   *bottom = (address)((char *)ss.ss_sp - ss.ss_size);
934   *size   = ss.ss_size;
935 #else
936   pthread_attr_t attr;
937 
938   int rslt = pthread_attr_init(&attr);
939 
940   // JVM needs to know exact stack location, abort if it fails
941   if (rslt != 0)
942     fatal(err_msg("pthread_attr_init failed with err = %d", rslt));
943 
944   rslt = pthread_attr_get_np(pthread_self(), &attr);
945 
946   if (rslt != 0)
947     fatal(err_msg("pthread_attr_get_np failed with err = %d", rslt));
948 
949   if (pthread_attr_getstackaddr(&attr, (void **)bottom) != 0 ||
950     pthread_attr_getstacksize(&attr, size) != 0) {
951     fatal("Can not locate current stack attributes!");
952   }
953 
954   pthread_attr_destroy(&attr);
955 #endif
956   assert(os::current_stack_pointer() >= *bottom &&
957          os::current_stack_pointer() < *bottom + *size, "just checking");
958 }
959 
960 address os::current_stack_base() {
961   address bottom;
962   size_t size;
963   current_stack_region(&bottom, &size);
964   return (bottom + size);
965 }
966 
967 size_t os::current_stack_size() {
968   // stack size includes normal stack and HotSpot guard pages
969   address bottom;
970   size_t size;
971   current_stack_region(&bottom, &size);
972   return size;
973 }
974 
975 /////////////////////////////////////////////////////////////////////////////
976 // helper functions for fatal error handler
977 
978 void os::print_context(outputStream *st, void *context) {
979   if (context == NULL) return;
980 
981   ucontext_t *uc = (ucontext_t*)context;
982   st->print_cr("Registers:");
983 #ifdef AMD64
984   st->print(  "RAX=" INTPTR_FORMAT, uc->context_rax);
985   st->print(", RBX=" INTPTR_FORMAT, uc->context_rbx);
986   st->print(", RCX=" INTPTR_FORMAT, uc->context_rcx);
987   st->print(", RDX=" INTPTR_FORMAT, uc->context_rdx);
988   st->cr();
989   st->print(  "RSP=" INTPTR_FORMAT, uc->context_rsp);
990   st->print(", RBP=" INTPTR_FORMAT, uc->context_rbp);
991   st->print(", RSI=" INTPTR_FORMAT, uc->context_rsi);
992   st->print(", RDI=" INTPTR_FORMAT, uc->context_rdi);
993   st->cr();
994   st->print(  "R8 =" INTPTR_FORMAT, uc->context_r8);
995   st->print(", R9 =" INTPTR_FORMAT, uc->context_r9);
996   st->print(", R10=" INTPTR_FORMAT, uc->context_r10);
997   st->print(", R11=" INTPTR_FORMAT, uc->context_r11);
998   st->cr();
999   st->print(  "R12=" INTPTR_FORMAT, uc->context_r12);
1000   st->print(", R13=" INTPTR_FORMAT, uc->context_r13);
1001   st->print(", R14=" INTPTR_FORMAT, uc->context_r14);
1002   st->print(", R15=" INTPTR_FORMAT, uc->context_r15);
1003   st->cr();
1004   st->print(  "RIP=" INTPTR_FORMAT, uc->context_rip);
1005   st->print(", EFLAGS=" INTPTR_FORMAT, uc->context_flags);
1006   st->print(", ERR=" INTPTR_FORMAT, uc->context_err);
1007   st->cr();
1008   st->print("  TRAPNO=" INTPTR_FORMAT, uc->context_trapno);
1009 #else
1010   st->print(  "EAX=" INTPTR_FORMAT, uc->context_eax);
1011   st->print(", EBX=" INTPTR_FORMAT, uc->context_ebx);
1012   st->print(", ECX=" INTPTR_FORMAT, uc->context_ecx);
1013   st->print(", EDX=" INTPTR_FORMAT, uc->context_edx);
1014   st->cr();
1015   st->print(  "ESP=" INTPTR_FORMAT, uc->context_esp);
1016   st->print(", EBP=" INTPTR_FORMAT, uc->context_ebp);
1017   st->print(", ESI=" INTPTR_FORMAT, uc->context_esi);
1018   st->print(", EDI=" INTPTR_FORMAT, uc->context_edi);
1019   st->cr();
1020   st->print(  "EIP=" INTPTR_FORMAT, uc->context_eip);
1021   st->print(", EFLAGS=" INTPTR_FORMAT, uc->context_eflags);
1022 #endif // AMD64
1023   st->cr();
1024   st->cr();
1025 
1026   intptr_t *sp = (intptr_t *)os::Bsd::ucontext_get_sp(uc);
1027   st->print_cr("Top of Stack: (sp=" PTR_FORMAT ")", sp);
1028   print_hex_dump(st, (address)sp, (address)(sp + 8*sizeof(intptr_t)), sizeof(intptr_t));
1029   st->cr();
1030 
1031   // Note: it may be unsafe to inspect memory near pc. For example, pc may
1032   // point to garbage if entry point in an nmethod is corrupted. Leave
1033   // this at the end, and hope for the best.
1034   address pc = os::Bsd::ucontext_get_pc(uc);
1035   st->print_cr("Instructions: (pc=" PTR_FORMAT ")", pc);
1036   print_hex_dump(st, pc - 32, pc + 32, sizeof(char));
1037 }
1038 
1039 void os::print_register_info(outputStream *st, void *context) {
1040   if (context == NULL) return;
1041 
1042   ucontext_t *uc = (ucontext_t*)context;
1043 
1044   st->print_cr("Register to memory mapping:");
1045   st->cr();
1046 
1047   // this is horrendously verbose but the layout of the registers in the
1048   // context does not match how we defined our abstract Register set, so
1049   // we can't just iterate through the gregs area
1050 
1051   // this is only for the "general purpose" registers
1052 
1053 #ifdef AMD64
1054   st->print("RAX="); print_location(st, uc->context_rax);
1055   st->print("RBX="); print_location(st, uc->context_rbx);
1056   st->print("RCX="); print_location(st, uc->context_rcx);
1057   st->print("RDX="); print_location(st, uc->context_rdx);
1058   st->print("RSP="); print_location(st, uc->context_rsp);
1059   st->print("RBP="); print_location(st, uc->context_rbp);
1060   st->print("RSI="); print_location(st, uc->context_rsi);
1061   st->print("RDI="); print_location(st, uc->context_rdi);
1062   st->print("R8 ="); print_location(st, uc->context_r8);
1063   st->print("R9 ="); print_location(st, uc->context_r9);
1064   st->print("R10="); print_location(st, uc->context_r10);
1065   st->print("R11="); print_location(st, uc->context_r11);
1066   st->print("R12="); print_location(st, uc->context_r12);
1067   st->print("R13="); print_location(st, uc->context_r13);
1068   st->print("R14="); print_location(st, uc->context_r14);
1069   st->print("R15="); print_location(st, uc->context_r15);
1070 #else
1071   st->print("EAX="); print_location(st, uc->context_eax);
1072   st->print("EBX="); print_location(st, uc->context_ebx);
1073   st->print("ECX="); print_location(st, uc->context_ecx);
1074   st->print("EDX="); print_location(st, uc->context_edx);
1075   st->print("ESP="); print_location(st, uc->context_esp);
1076   st->print("EBP="); print_location(st, uc->context_ebp);
1077   st->print("ESI="); print_location(st, uc->context_esi);
1078   st->print("EDI="); print_location(st, uc->context_edi);
1079 #endif // AMD64
1080 
1081   st->cr();
1082 }
1083 
1084 void os::setup_fpu() {
1085 #ifndef AMD64
1086   address fpu_cntrl = StubRoutines::addr_fpu_cntrl_wrd_std();
1087   __asm__ volatile (  "fldcw (%0)" :
1088                       : "r" (fpu_cntrl) : "memory");
1089 #endif // !AMD64
1090 }
1091 
1092 #ifndef PRODUCT
1093 void os::verify_stack_alignment() {
1094 }
1095 #endif
1096