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