1 /*
2  * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
3  * Copyright 2012, 2014 SAP AG. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.
9  *
10  * This code is distributed in the hope that it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13  * version 2 for more details (a copy is included in the LICENSE file that
14  * accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License version
17  * 2 along with this work; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19  *
20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21  * or visit www.oracle.com if you need additional information or have any
22  * questions.
23  *
24  */
25 
26 // no precompiled headers
27 #include "assembler_ppc.inline.hpp"
28 #include "classfile/classLoader.hpp"
29 #include "classfile/systemDictionary.hpp"
30 #include "classfile/vmSymbols.hpp"
31 #include "code/icBuffer.hpp"
32 #include "code/vtableStubs.hpp"
33 #include "interpreter/interpreter.hpp"
34 #include "jvm_aix.h"
35 #include "memory/allocation.inline.hpp"
36 #include "mutex_aix.inline.hpp"
37 #include "nativeInst_ppc.hpp"
38 #include "os_share_aix.hpp"
39 #include "prims/jniFastGetField.hpp"
40 #include "prims/jvm.h"
41 #include "prims/jvm_misc.hpp"
42 #include "runtime/arguments.hpp"
43 #include "runtime/extendedPC.hpp"
44 #include "runtime/frame.inline.hpp"
45 #include "runtime/interfaceSupport.hpp"
46 #include "runtime/java.hpp"
47 #include "runtime/javaCalls.hpp"
48 #include "runtime/mutexLocker.hpp"
49 #include "runtime/osThread.hpp"
50 #include "runtime/sharedRuntime.hpp"
51 #include "runtime/stubRoutines.hpp"
52 #include "runtime/thread.inline.hpp"
53 #include "runtime/timer.hpp"
54 #include "utilities/events.hpp"
55 #include "utilities/vmError.hpp"
56 #ifdef COMPILER1
57 #include "c1/c1_Runtime1.hpp"
58 #endif
59 #ifdef COMPILER2
60 #include "opto/runtime.hpp"
61 #endif
62 
63 // put OS-includes here
64 # include <ucontext.h>
65 
current_stack_pointer()66 address os::current_stack_pointer() {
67   address csp;
68 
69 #if !defined(USE_XLC_BUILTINS)
70   // inline assembly for `mr regno(csp), R1_SP':
71   __asm__ __volatile__ ("mr %0, 1":"=r"(csp):);
72 #else
73   csp = (address) __builtin_frame_address(0);
74 #endif
75 
76   return csp;
77 }
78 
non_memory_address_word()79 char* os::non_memory_address_word() {
80   // Must never look like an address returned by reserve_memory,
81   // even in its subfields (as defined by the CPU immediate fields,
82   // if the CPU splits constants across multiple instructions).
83 
84   return (char*) -1;
85 }
86 
87 // OS specific thread initialization
88 //
89 // Calculate and store the limits of the memory stack.
initialize_thread(Thread * thread)90 void os::initialize_thread(Thread *thread) { }
91 
92 // Frame information (pc, sp, fp) retrieved via ucontext
93 // always looks like a C-frame according to the frame
94 // conventions in frame_ppc.hpp.
95 
ucontext_get_pc(const ucontext_t * uc)96 address os::Aix::ucontext_get_pc(const ucontext_t * uc) {
97   return (address)uc->uc_mcontext.jmp_context.iar;
98 }
99 
ucontext_get_sp(ucontext_t * uc)100 intptr_t* os::Aix::ucontext_get_sp(ucontext_t * uc) {
101   // gpr1 holds the stack pointer on aix
102   return (intptr_t*)uc->uc_mcontext.jmp_context.gpr[1/*REG_SP*/];
103 }
104 
ucontext_get_fp(ucontext_t * uc)105 intptr_t* os::Aix::ucontext_get_fp(ucontext_t * uc) {
106   return NULL;
107 }
108 
ucontext_set_pc(ucontext_t * uc,address new_pc)109 void os::Aix::ucontext_set_pc(ucontext_t* uc, address new_pc) {
110   uc->uc_mcontext.jmp_context.iar = (uint64_t) new_pc;
111 }
112 
fetch_frame_from_context(void * ucVoid,intptr_t ** ret_sp,intptr_t ** ret_fp)113 ExtendedPC os::fetch_frame_from_context(void* ucVoid,
114                                         intptr_t** ret_sp, intptr_t** ret_fp) {
115 
116   ExtendedPC  epc;
117   ucontext_t* uc = (ucontext_t*)ucVoid;
118 
119   if (uc != NULL) {
120     epc = ExtendedPC(os::Aix::ucontext_get_pc(uc));
121     if (ret_sp) *ret_sp = os::Aix::ucontext_get_sp(uc);
122     if (ret_fp) *ret_fp = os::Aix::ucontext_get_fp(uc);
123   } else {
124     // construct empty ExtendedPC for return value checking
125     epc = ExtendedPC(NULL);
126     if (ret_sp) *ret_sp = (intptr_t *)NULL;
127     if (ret_fp) *ret_fp = (intptr_t *)NULL;
128   }
129 
130   return epc;
131 }
132 
fetch_frame_from_context(void * ucVoid)133 frame os::fetch_frame_from_context(void* ucVoid) {
134   intptr_t* sp;
135   intptr_t* fp;
136   ExtendedPC epc = fetch_frame_from_context(ucVoid, &sp, &fp);
137   // Avoid crash during crash if pc broken.
138   if (epc.pc()) {
139     frame fr(sp, epc.pc());
140     return fr;
141   }
142   frame fr(sp);
143   return fr;
144 }
145 
get_sender_for_C_frame(frame * fr)146 frame os::get_sender_for_C_frame(frame* fr) {
147   if (*fr->sp() == NULL) {
148     // fr is the last C frame
149     return frame(NULL, NULL);
150   }
151   return frame(fr->sender_sp(), fr->sender_pc());
152 }
153 
154 
current_frame()155 frame os::current_frame() {
156   intptr_t* csp = (intptr_t*) *((intptr_t*) os::current_stack_pointer());
157   // hack.
158   frame topframe(csp, (address)0x8);
159   // return sender of current topframe which hopefully has pc != NULL.
160   return os::get_sender_for_C_frame(&topframe);
161 }
162 
163 // Utility functions
164 
165 extern "C" JNIEXPORT int
JVM_handle_aix_signal(int sig,siginfo_t * info,void * ucVoid,int abort_if_unrecognized)166 JVM_handle_aix_signal(int sig, siginfo_t* info, void* ucVoid, int abort_if_unrecognized) {
167 
168   ucontext_t* uc = (ucontext_t*) ucVoid;
169 
170   Thread* t = ThreadLocalStorage::get_thread_slow();   // slow & steady
171 
172   SignalHandlerMark shm(t);
173 
174   // Note: it's not uncommon that JNI code uses signal/sigset to install
175   // then restore certain signal handler (e.g. to temporarily block SIGPIPE,
176   // or have a SIGILL handler when detecting CPU type). When that happens,
177   // JVM_handle_aix_signal() might be invoked with junk info/ucVoid. To
178   // avoid unnecessary crash when libjsig is not preloaded, try handle signals
179   // that do not require siginfo/ucontext first.
180 
181   if (sig == SIGPIPE || sig == SIGXFSZ) {
182     if (os::Aix::chained_handler(sig, info, ucVoid)) {
183       return 1;
184     } else {
185       if (PrintMiscellaneous && (WizardMode || Verbose)) {
186         warning("Ignoring SIGPIPE - see bug 4229104");
187       }
188       return 1;
189     }
190   }
191 
192   JavaThread* thread = NULL;
193   VMThread* vmthread = NULL;
194   if (os::Aix::signal_handlers_are_installed) {
195     if (t != NULL) {
196       if(t->is_Java_thread()) {
197         thread = (JavaThread*)t;
198       }
199       else if(t->is_VM_thread()) {
200         vmthread = (VMThread *)t;
201       }
202     }
203   }
204 
205   // Decide if this trap can be handled by a stub.
206   address stub = NULL;
207 
208   // retrieve program counter
209   address const pc = uc ? os::Aix::ucontext_get_pc(uc) : NULL;
210 
211   // retrieve crash address
212   address const addr = info ? (const address) info->si_addr : NULL;
213 
214   // SafeFetch 32 handling:
215   // - make it work if _thread is null
216   // - make it use the standard os::...::ucontext_get/set_pc APIs
217   if (uc) {
218     address const pc = os::Aix::ucontext_get_pc(uc);
219     if (pc && StubRoutines::is_safefetch_fault(pc)) {
220       os::Aix::ucontext_set_pc(uc, StubRoutines::continuation_for_safefetch_fault(pc));
221       return true;
222     }
223   }
224 
225   // Handle SIGDANGER right away. AIX would raise SIGDANGER whenever available swap
226   // space falls below 30%. This is only a chance for the process to gracefully abort.
227   // We can't hope to proceed after SIGDANGER since SIGKILL tailgates.
228   if (sig == SIGDANGER) {
229     goto report_and_die;
230   }
231 
232   if (info == NULL || uc == NULL || thread == NULL && vmthread == NULL) {
233     goto run_chained_handler;
234   }
235 
236   // If we are a java thread...
237   if (thread != NULL) {
238 
239     // Handle ALL stack overflow variations here
240     if (sig == SIGSEGV && (addr < thread->stack_base() &&
241                            addr >= thread->stack_base() - thread->stack_size())) {
242       // stack overflow
243       //
244       // If we are in a yellow zone and we are inside java, we disable the yellow zone and
245       // throw a stack overflow exception.
246       // If we are in native code or VM C code, we report-and-die. The original coding tried
247       // to continue with yellow zone disabled, but that doesn't buy us much and prevents
248       // hs_err_pid files.
249       if (thread->in_stack_yellow_zone(addr)) {
250         thread->disable_stack_yellow_zone();
251         if (thread->thread_state() == _thread_in_Java) {
252           // Throw a stack overflow exception.
253           // Guard pages will be reenabled while unwinding the stack.
254           stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW);
255           goto run_stub;
256         } else {
257           // Thread was in the vm or native code. Return and try to finish.
258           return 1;
259         }
260       } else if (thread->in_stack_red_zone(addr)) {
261         // Fatal red zone violation. Disable the guard pages and fall through
262         // to handle_unexpected_exception way down below.
263         thread->disable_stack_red_zone();
264         tty->print_raw_cr("An irrecoverable stack overflow has occurred.");
265         goto report_and_die;
266       } else {
267         // This means a segv happened inside our stack, but not in
268         // the guarded zone. I'd like to know when this happens,
269         tty->print_raw_cr("SIGSEGV happened inside stack but outside yellow and red zone.");
270         goto report_and_die;
271       }
272 
273     } // end handle SIGSEGV inside stack boundaries
274 
275     if (thread->thread_state() == _thread_in_Java) {
276       // Java thread running in Java code
277 
278       // The following signals are used for communicating VM events:
279       //
280       // SIGILL: the compiler generates illegal opcodes
281       //   at places where it wishes to interrupt the VM:
282       //   Safepoints, Unreachable Code, Entry points of Zombie methods,
283       //    This results in a SIGILL with (*pc) == inserted illegal instruction.
284       //
285       //   (so, SIGILLs with a pc inside the zero page are real errors)
286       //
287       // SIGTRAP:
288       //   The ppc trap instruction raises a SIGTRAP and is very efficient if it
289       //   does not trap. It is used for conditional branches that are expected
290       //   to be never taken. These are:
291       //     - zombie methods
292       //     - IC (inline cache) misses.
293       //     - null checks leading to UncommonTraps.
294       //     - range checks leading to Uncommon Traps.
295       //   On Aix, these are especially null checks, as the ImplicitNullCheck
296       //   optimization works only in rare cases, as the page at address 0 is only
297       //   write protected.      //
298       //   Note: !UseSIGTRAP is used to prevent SIGTRAPS altogether, to facilitate debugging.
299       //
300       // SIGSEGV:
301       //   used for safe point polling:
302       //     To notify all threads that they have to reach a safe point, safe point polling is used:
303       //     All threads poll a certain mapped memory page. Normally, this page has read access.
304       //     If the VM wants to inform the threads about impending safe points, it puts this
305       //     page to read only ("poisens" the page), and the threads then reach a safe point.
306       //   used for null checks:
307       //     If the compiler finds a store it uses it for a null check. Unfortunately this
308       //     happens rarely.  In heap based and disjoint base compressd oop modes also loads
309       //     are used for null checks.
310 
311       // A VM-related SIGILL may only occur if we are not in the zero page.
312       // On AIX, we get a SIGILL if we jump to 0x0 or to somewhere else
313       // in the zero page, because it is filled with 0x0. We ignore
314       // explicit SIGILLs in the zero page.
315       if (sig == SIGILL && (pc < (address) 0x200)) {
316         if (TraceTraps) {
317           tty->print_raw_cr("SIGILL happened inside zero page.");
318         }
319         goto report_and_die;
320       }
321 
322       // Handle signal from NativeJump::patch_verified_entry().
323       if (( TrapBasedNotEntrantChecks && sig == SIGTRAP && nativeInstruction_at(pc)->is_sigtrap_zombie_not_entrant()) ||
324           (!TrapBasedNotEntrantChecks && sig == SIGILL  && nativeInstruction_at(pc)->is_sigill_zombie_not_entrant())) {
325         if (TraceTraps) {
326           tty->print_cr("trap: zombie_not_entrant (%s)", (sig == SIGTRAP) ? "SIGTRAP" : "SIGILL");
327         }
328         stub = SharedRuntime::get_handle_wrong_method_stub();
329         goto run_stub;
330       }
331 
332       else if (sig == SIGSEGV && os::is_poll_address(addr)) {
333         if (TraceTraps) {
334           tty->print_cr("trap: safepoint_poll at " INTPTR_FORMAT " (SIGSEGV)", pc);
335         }
336         stub = SharedRuntime::get_poll_stub(pc);
337         goto run_stub;
338       }
339 
340       // SIGTRAP-based ic miss check in compiled code.
341       else if (sig == SIGTRAP && TrapBasedICMissChecks &&
342                nativeInstruction_at(pc)->is_sigtrap_ic_miss_check()) {
343         if (TraceTraps) {
344           tty->print_cr("trap: ic_miss_check at " INTPTR_FORMAT " (SIGTRAP)", pc);
345         }
346         stub = SharedRuntime::get_ic_miss_stub();
347         goto run_stub;
348       }
349 
350       // SIGTRAP-based implicit null check in compiled code.
351       else if (sig == SIGTRAP && TrapBasedNullChecks &&
352                nativeInstruction_at(pc)->is_sigtrap_null_check()) {
353         if (TraceTraps) {
354           tty->print_cr("trap: null_check at " INTPTR_FORMAT " (SIGTRAP)", pc);
355         }
356         stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
357         goto run_stub;
358       }
359 
360       // SIGSEGV-based implicit null check in compiled code.
361       else if (sig == SIGSEGV && ImplicitNullChecks &&
362                CodeCache::contains((void*) pc) &&
363                !MacroAssembler::needs_explicit_null_check((intptr_t) info->si_addr)) {
364         if (TraceTraps) {
365           tty->print_cr("trap: null_check at " INTPTR_FORMAT " (SIGSEGV)", pc);
366         }
367         stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
368       }
369 
370 #ifdef COMPILER2
371       // SIGTRAP-based implicit range check in compiled code.
372       else if (sig == SIGTRAP && TrapBasedRangeChecks &&
373                nativeInstruction_at(pc)->is_sigtrap_range_check()) {
374         if (TraceTraps) {
375           tty->print_cr("trap: range_check at " INTPTR_FORMAT " (SIGTRAP)", pc);
376         }
377         stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
378         goto run_stub;
379       }
380 #endif
381 
382       else if (sig == SIGFPE /* && info->si_code == FPE_INTDIV */) {
383         if (TraceTraps) {
384           tty->print_raw_cr("Fix SIGFPE handler, trying divide by zero handler.");
385         }
386         stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_DIVIDE_BY_ZERO);
387         goto run_stub;
388       }
389 
390       else if (sig == SIGBUS) {
391         // BugId 4454115: A read from a MappedByteBuffer can fault here if the
392         // underlying file has been truncated. Do not crash the VM in such a case.
393         CodeBlob* cb = CodeCache::find_blob_unsafe(pc);
394         nmethod* nm = cb->is_nmethod() ? (nmethod*)cb : NULL;
395         if (nm != NULL && nm->has_unsafe_access()) {
396           // We don't really need a stub here! Just set the pending exeption and
397           // continue at the next instruction after the faulting read. Returning
398           // garbage from this read is ok.
399           thread->set_pending_unsafe_access_error();
400           uc->uc_mcontext.jmp_context.iar = ((unsigned long)pc) + 4;
401           return 1;
402         }
403       }
404     }
405 
406     else { // thread->thread_state() != _thread_in_Java
407       // Detect CPU features. This is only done at the very start of the VM. Later, the
408       // VM_Version::is_determine_features_test_running() flag should be false.
409 
410       if (sig == SIGILL && VM_Version::is_determine_features_test_running()) {
411         // SIGILL must be caused by VM_Version::determine_features().
412         *(int *)pc = 0; // patch instruction to 0 to indicate that it causes a SIGILL,
413                         // flushing of icache is not necessary.
414         stub = pc + 4;  // continue with next instruction.
415         goto run_stub;
416       }
417       else if (thread->thread_state() == _thread_in_vm &&
418                sig == SIGBUS && thread->doing_unsafe_access()) {
419         // We don't really need a stub here! Just set the pending exeption and
420         // continue at the next instruction after the faulting read. Returning
421         // garbage from this read is ok.
422         thread->set_pending_unsafe_access_error();
423         uc->uc_mcontext.jmp_context.iar = ((unsigned long)pc) + 4;
424         return 1;
425       }
426     }
427 
428     // Check to see if we caught the safepoint code in the
429     // process of write protecting the memory serialization page.
430     // It write enables the page immediately after protecting it
431     // so we can just return to retry the write.
432     if ((sig == SIGSEGV) &&
433         os::is_memory_serialize_page(thread, addr)) {
434       // Synchronization problem in the pseudo memory barrier code (bug id 6546278)
435       // Block current thread until the memory serialize page permission restored.
436       os::block_on_serialize_page_trap();
437       return true;
438     }
439   }
440 
441 run_stub:
442 
443   // One of the above code blocks ininitalized the stub, so we want to
444   // delegate control to that stub.
445   if (stub != NULL) {
446     // Save all thread context in case we need to restore it.
447     if (thread != NULL) thread->set_saved_exception_pc(pc);
448     uc->uc_mcontext.jmp_context.iar = (unsigned long)stub;
449     return 1;
450   }
451 
452 run_chained_handler:
453 
454   // signal-chaining
455   if (os::Aix::chained_handler(sig, info, ucVoid)) {
456     return 1;
457   }
458   if (!abort_if_unrecognized) {
459     // caller wants another chance, so give it to him
460     return 0;
461   }
462 
463 report_and_die:
464 
465   // Use sigthreadmask instead of sigprocmask on AIX and unmask current signal.
466   sigset_t newset;
467   sigemptyset(&newset);
468   sigaddset(&newset, sig);
469   sigthreadmask(SIG_UNBLOCK, &newset, NULL);
470 
471   VMError err(t, sig, pc, info, ucVoid);
472   err.report_and_die();
473 
474   ShouldNotReachHere();
475   return 0;
476 }
477 
init_thread_fpu_state(void)478 void os::Aix::init_thread_fpu_state(void) {
479 #if !defined(USE_XLC_BUILTINS)
480   // Disable FP exceptions.
481   __asm__ __volatile__ ("mtfsfi 6,0");
482 #else
483   __mtfsfi(6, 0);
484 #endif
485 }
486 
487 ////////////////////////////////////////////////////////////////////////////////
488 // thread stack
489 
490 size_t os::Aix::min_stack_allowed = 128*K;
491 
492 // Aix is always in floating stack mode. The stack size for a new
493 // thread can be set via pthread_attr_setstacksize().
supports_variable_stack_size()494 bool os::Aix::supports_variable_stack_size() { return true; }
495 
496 // return default stack size for thr_type
default_stack_size(os::ThreadType thr_type)497 size_t os::Aix::default_stack_size(os::ThreadType thr_type) {
498   // default stack size (compiler thread needs larger stack)
499   // Notice that the setting for compiler threads here have no impact
500   // because of the strange 'fallback logic' in os::create_thread().
501   // Better set CompilerThreadStackSize in globals_<os_cpu>.hpp if you want to
502   // specify a different stack size for compiler threads!
503   size_t s = (thr_type == os::compiler_thread ? 4 * M : 1 * M);
504   return s;
505 }
506 
default_guard_size(os::ThreadType thr_type)507 size_t os::Aix::default_guard_size(os::ThreadType thr_type) {
508   return 2 * page_size();
509 }
510 
511 /////////////////////////////////////////////////////////////////////////////
512 // helper functions for fatal error handler
513 
print_context(outputStream * st,void * context)514 void os::print_context(outputStream *st, void *context) {
515   if (context == NULL) return;
516 
517   ucontext_t* uc = (ucontext_t*)context;
518 
519   st->print_cr("Registers:");
520   st->print("pc =" INTPTR_FORMAT "  ", uc->uc_mcontext.jmp_context.iar);
521   st->print("lr =" INTPTR_FORMAT "  ", uc->uc_mcontext.jmp_context.lr);
522   st->print("ctr=" INTPTR_FORMAT "  ", uc->uc_mcontext.jmp_context.ctr);
523   st->cr();
524   for (int i = 0; i < 32; i++) {
525     st->print("r%-2d=" INTPTR_FORMAT "  ", i, uc->uc_mcontext.jmp_context.gpr[i]);
526     if (i % 3 == 2) st->cr();
527   }
528   st->cr();
529   st->cr();
530 
531   intptr_t *sp = (intptr_t *)os::Aix::ucontext_get_sp(uc);
532   st->print_cr("Top of Stack: (sp=" PTR_FORMAT ")", sp);
533   print_hex_dump(st, (address)sp, (address)(sp + 128), sizeof(intptr_t));
534   st->cr();
535 
536   // Note: it may be unsafe to inspect memory near pc. For example, pc may
537   // point to garbage if entry point in an nmethod is corrupted. Leave
538   // this at the end, and hope for the best.
539   address pc = os::Aix::ucontext_get_pc(uc);
540   st->print_cr("Instructions: (pc=" PTR_FORMAT ")", pc);
541   print_hex_dump(st, pc - 64, pc + 64, /*instrsize=*/4);
542   st->cr();
543 
544   // Try to decode the instructions.
545   st->print_cr("Decoded instructions: (pc=" PTR_FORMAT ")", pc);
546   st->print("<TODO: PPC port - print_context>");
547   // TODO: PPC port Disassembler::decode(pc, 16, 16, st);
548   st->cr();
549 }
550 
print_register_info(outputStream * st,void * context)551 void os::print_register_info(outputStream *st, void *context) {
552   if (context == NULL) return;
553   st->print("Not ported - print_register_info\n");
554 }
555 
556 extern "C" {
SpinPause()557   int SpinPause() {
558     return 0;
559   }
560 }
561 
562 #ifndef PRODUCT
verify_stack_alignment()563 void os::verify_stack_alignment() {
564   assert(((intptr_t)os::current_stack_pointer() & (StackAlignmentInBytes-1)) == 0, "incorrect stack alignment");
565 }
566 #endif
567