1 /*
2  * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.
3  * Copyright (c) 2012, 2019 SAP SE. 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 "jvm.h"
28 #include "asm/assembler.inline.hpp"
29 #include "classfile/classLoader.hpp"
30 #include "classfile/systemDictionary.hpp"
31 #include "classfile/vmSymbols.hpp"
32 #include "code/codeCache.hpp"
33 #include "code/icBuffer.hpp"
34 #include "code/vtableStubs.hpp"
35 #include "interpreter/interpreter.hpp"
36 #include "memory/allocation.inline.hpp"
37 #include "nativeInst_ppc.hpp"
38 #include "os_share_linux.hpp"
39 #include "prims/jniFastGetField.hpp"
40 #include "prims/jvm_misc.hpp"
41 #include "runtime/arguments.hpp"
42 #include "runtime/frame.inline.hpp"
43 #include "runtime/interfaceSupport.inline.hpp"
44 #include "runtime/java.hpp"
45 #include "runtime/javaCalls.hpp"
46 #include "runtime/mutexLocker.hpp"
47 #include "runtime/osThread.hpp"
48 #include "runtime/safepointMechanism.hpp"
49 #include "runtime/sharedRuntime.hpp"
50 #include "runtime/stubRoutines.hpp"
51 #include "runtime/thread.inline.hpp"
52 #include "runtime/timer.hpp"
53 #include "signals_posix.hpp"
54 #include "utilities/debug.hpp"
55 #include "utilities/events.hpp"
56 #include "utilities/vmError.hpp"
57 
58 // put OS-includes here
59 # include <sys/types.h>
60 # include <sys/mman.h>
61 # include <pthread.h>
62 # include <signal.h>
63 # include <errno.h>
64 # include <dlfcn.h>
65 # include <stdlib.h>
66 # include <stdio.h>
67 # include <unistd.h>
68 # include <sys/resource.h>
69 # include <pthread.h>
70 # include <sys/stat.h>
71 # include <sys/time.h>
72 # include <sys/utsname.h>
73 # include <sys/socket.h>
74 # include <sys/wait.h>
75 # include <pwd.h>
76 # include <poll.h>
77 # include <ucontext.h>
78 
79 
current_stack_pointer()80 address os::current_stack_pointer() {
81   return (address)__builtin_frame_address(0);
82 }
83 
non_memory_address_word()84 char* os::non_memory_address_word() {
85   // Must never look like an address returned by reserve_memory,
86   // even in its subfields (as defined by the CPU immediate fields,
87   // if the CPU splits constants across multiple instructions).
88 
89   return (char*) -1;
90 }
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_ppc64.hpp.
ucontext_get_pc(const ucontext_t * uc)95 address os::Posix::ucontext_get_pc(const ucontext_t * uc) {
96   // On powerpc64, ucontext_t is not selfcontained but contains
97   // a pointer to an optional substructure (mcontext_t.regs) containing the volatile
98   // registers - NIP, among others.
99   // This substructure may or may not be there depending where uc came from:
100   // - if uc was handed over as the argument to a sigaction handler, a pointer to the
101   //   substructure was provided by the kernel when calling the signal handler, and
102   //   regs->nip can be accessed.
103   // - if uc was filled by getcontext(), it is undefined - getcontext() does not fill
104   //   it because the volatile registers are not needed to make setcontext() work.
105   //   Hopefully it was zero'd out beforehand.
106   guarantee(uc->uc_mcontext.regs != NULL, "only use ucontext_get_pc in sigaction context");
107   return (address)uc->uc_mcontext.regs->nip;
108 }
109 
110 // modify PC in ucontext.
111 // Note: Only use this for an ucontext handed down to a signal handler. See comment
112 // in ucontext_get_pc.
ucontext_set_pc(ucontext_t * uc,address pc)113 void os::Posix::ucontext_set_pc(ucontext_t * uc, address pc) {
114   guarantee(uc->uc_mcontext.regs != NULL, "only use ucontext_set_pc in sigaction context");
115   uc->uc_mcontext.regs->nip = (unsigned long)pc;
116 }
117 
ucontext_get_lr(const ucontext_t * uc)118 static address ucontext_get_lr(const ucontext_t * uc) {
119   return (address)uc->uc_mcontext.regs->link;
120 }
121 
ucontext_get_sp(const ucontext_t * uc)122 intptr_t* os::Linux::ucontext_get_sp(const ucontext_t * uc) {
123   return (intptr_t*)uc->uc_mcontext.regs->gpr[1/*REG_SP*/];
124 }
125 
ucontext_get_fp(const ucontext_t * uc)126 intptr_t* os::Linux::ucontext_get_fp(const ucontext_t * uc) {
127   return NULL;
128 }
129 
ucontext_get_trap(const ucontext_t * uc)130 static unsigned long ucontext_get_trap(const ucontext_t * uc) {
131   return uc->uc_mcontext.regs->trap;
132 }
133 
fetch_frame_from_context(const void * ucVoid,intptr_t ** ret_sp,intptr_t ** ret_fp)134 address os::fetch_frame_from_context(const void* ucVoid,
135                     intptr_t** ret_sp, intptr_t** ret_fp) {
136 
137   address epc;
138   const ucontext_t* uc = (const ucontext_t*)ucVoid;
139 
140   if (uc != NULL) {
141     epc = os::Posix::ucontext_get_pc(uc);
142     if (ret_sp) *ret_sp = os::Linux::ucontext_get_sp(uc);
143     if (ret_fp) *ret_fp = os::Linux::ucontext_get_fp(uc);
144   } else {
145     epc = NULL;
146     if (ret_sp) *ret_sp = (intptr_t *)NULL;
147     if (ret_fp) *ret_fp = (intptr_t *)NULL;
148   }
149 
150   return epc;
151 }
152 
fetch_frame_from_context(const void * ucVoid)153 frame os::fetch_frame_from_context(const void* ucVoid) {
154   intptr_t* sp;
155   intptr_t* fp;
156   address epc = fetch_frame_from_context(ucVoid, &sp, &fp);
157   return frame(sp, epc);
158 }
159 
fetch_compiled_frame_from_context(const void * ucVoid)160 frame os::fetch_compiled_frame_from_context(const void* ucVoid) {
161   const ucontext_t* uc = (const ucontext_t*)ucVoid;
162   intptr_t* sp = os::Linux::ucontext_get_sp(uc);
163   address lr = ucontext_get_lr(uc);
164   return frame(sp, lr);
165 }
166 
get_sender_for_C_frame(frame * fr)167 frame os::get_sender_for_C_frame(frame* fr) {
168   if (*fr->sp() == 0) {
169     // fr is the last C frame
170     return frame(NULL, NULL);
171   }
172   return frame(fr->sender_sp(), fr->sender_pc());
173 }
174 
175 
current_frame()176 frame os::current_frame() {
177   intptr_t* csp = *(intptr_t**) __builtin_frame_address(0);
178   frame topframe(csp, CAST_FROM_FN_PTR(address, os::current_frame));
179   return os::get_sender_for_C_frame(&topframe);
180 }
181 
pd_hotspot_signal_handler(int sig,siginfo_t * info,ucontext_t * uc,JavaThread * thread)182 bool PosixSignals::pd_hotspot_signal_handler(int sig, siginfo_t* info,
183                                              ucontext_t* uc, JavaThread* thread) {
184 
185   // Make the signal handler transaction-aware by checking the existence of a
186   // second (transactional) context with MSR TS bits active. If the signal is
187   // caught during a transaction, then just return to the HTM abort handler.
188   // Please refer to Linux kernel document powerpc/transactional_memory.txt,
189   // section "Signals".
190   if (uc && uc->uc_link) {
191     ucontext_t* second_uc = uc->uc_link;
192 
193     // MSR TS bits are 29 and 30 (Power ISA, v2.07B, Book III-S, pp. 857-858,
194     // 3.2.1 "Machine State Register"), however note that ISA notation for bit
195     // numbering is MSB 0, so for normal bit numbering (LSB 0) they come to be
196     // bits 33 and 34. It's not related to endianness, just a notation matter.
197     if (second_uc->uc_mcontext.regs->msr & 0x600000000) {
198       if (TraceTraps) {
199         tty->print_cr("caught signal in transaction, "
200                         "ignoring to jump to abort handler");
201       }
202       // Return control to the HTM abort handler.
203       return true;
204     }
205   }
206 
207   // Moved SafeFetch32 handling outside thread!=NULL conditional block to make
208   // it work if no associated JavaThread object exists.
209   if (uc) {
210     address const pc = os::Posix::ucontext_get_pc(uc);
211     if (pc && StubRoutines::is_safefetch_fault(pc)) {
212       os::Posix::ucontext_set_pc(uc, StubRoutines::continuation_for_safefetch_fault(pc));
213       return true;
214     }
215   }
216 
217   // decide if this trap can be handled by a stub
218   address stub = NULL;
219   address pc   = NULL;
220 
221   if (info != NULL && uc != NULL && thread != NULL) {
222     pc = (address) os::Posix::ucontext_get_pc(uc);
223 
224     // Handle ALL stack overflow variations here
225     if (sig == SIGSEGV) {
226       // si_addr may not be valid due to a bug in the linux-ppc64 kernel (see
227       // comment below). Use get_stack_bang_address instead of si_addr.
228       // If SIGSEGV is caused due to a branch to an invalid address an
229       // "Instruction Storage Interrupt" is generated and 'pc' (NIP) already
230       // contains the invalid address. Otherwise, the SIGSEGV is caused due to
231       // load/store instruction trying to load/store from/to an invalid address
232       // and causing a "Data Storage Interrupt", so we inspect the intruction
233       // in order to extract the faulty data addresss.
234       address addr;
235       if ((ucontext_get_trap(uc) & 0x0F00 /* no IRQ reply bits */) == 0x0400) {
236         // Instruction Storage Interrupt (ISI)
237         addr = pc;
238       } else {
239         // Data Storage Interrupt (DSI), i.e. 0x0300: extract faulty data address
240         addr = ((NativeInstruction*)pc)->get_stack_bang_address(uc);
241       }
242 
243       // Check if fault address is within thread stack.
244       if (thread->is_in_full_stack(addr)) {
245         // stack overflow
246         if (os::Posix::handle_stack_overflow(thread, addr, pc, uc, &stub)) {
247           return true; // continue
248         }
249       }
250     }
251 
252     if (thread->thread_state() == _thread_in_Java) {
253       // Java thread running in Java code => find exception handler if any
254       // a fault inside compiled code, the interpreter, or a stub
255 
256       CodeBlob *cb = NULL;
257       int stop_type = -1;
258       // Handle signal from NativeJump::patch_verified_entry().
259       if (sig == SIGILL && nativeInstruction_at(pc)->is_sigill_zombie_not_entrant()) {
260         if (TraceTraps) {
261           tty->print_cr("trap: zombie_not_entrant");
262         }
263         stub = SharedRuntime::get_handle_wrong_method_stub();
264       }
265 
266       else if ((sig == USE_POLL_BIT_ONLY ? SIGTRAP : SIGSEGV) &&
267                // A linux-ppc64 kernel before 2.6.6 doesn't set si_addr on some segfaults
268                // in 64bit mode (cf. http://www.kernel.org/pub/linux/kernel/v2.6/ChangeLog-2.6.6),
269                // especially when we try to read from the safepoint polling page. So the check
270                //   (address)info->si_addr == os::get_standard_polling_page()
271                // doesn't work for us. We use:
272                ((NativeInstruction*)pc)->is_safepoint_poll() &&
273                CodeCache::contains((void*) pc) &&
274                ((cb = CodeCache::find_blob(pc)) != NULL) &&
275                cb->is_compiled()) {
276         if (TraceTraps) {
277           tty->print_cr("trap: safepoint_poll at " INTPTR_FORMAT " (%s)", p2i(pc),
278                         USE_POLL_BIT_ONLY ? "SIGTRAP" : "SIGSEGV");
279         }
280         stub = SharedRuntime::get_poll_stub(pc);
281       }
282 
283       // SIGTRAP-based ic miss check in compiled code.
284       else if (sig == SIGTRAP && TrapBasedICMissChecks &&
285                nativeInstruction_at(pc)->is_sigtrap_ic_miss_check()) {
286         if (TraceTraps) {
287           tty->print_cr("trap: ic_miss_check at " INTPTR_FORMAT " (SIGTRAP)", p2i(pc));
288         }
289         stub = SharedRuntime::get_ic_miss_stub();
290       }
291 
292       // SIGTRAP-based implicit null check in compiled code.
293       else if (sig == SIGTRAP && TrapBasedNullChecks &&
294                nativeInstruction_at(pc)->is_sigtrap_null_check()) {
295         if (TraceTraps) {
296           tty->print_cr("trap: null_check at " INTPTR_FORMAT " (SIGTRAP)", p2i(pc));
297         }
298         stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
299       }
300 
301       // SIGSEGV-based implicit null check in compiled code.
302       else if (sig == SIGSEGV && ImplicitNullChecks &&
303                CodeCache::contains((void*) pc) &&
304                MacroAssembler::uses_implicit_null_check(info->si_addr)) {
305         if (TraceTraps) {
306           tty->print_cr("trap: null_check at " INTPTR_FORMAT " (SIGSEGV)", p2i(pc));
307         }
308         stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
309       }
310 
311 #ifdef COMPILER2
312       // SIGTRAP-based implicit range check in compiled code.
313       else if (sig == SIGTRAP && TrapBasedRangeChecks &&
314                nativeInstruction_at(pc)->is_sigtrap_range_check()) {
315         if (TraceTraps) {
316           tty->print_cr("trap: range_check at " INTPTR_FORMAT " (SIGTRAP)", p2i(pc));
317         }
318         stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
319       }
320 #endif
321 
322       // stop on request
323       else if (sig == SIGTRAP && (stop_type = nativeInstruction_at(pc)->get_stop_type()) != -1) {
324         bool msg_present = (stop_type & MacroAssembler::stop_msg_present);
325         stop_type = (stop_type &~ MacroAssembler::stop_msg_present);
326 
327         const char *msg = NULL;
328         switch (stop_type) {
329           case MacroAssembler::stop_stop              : msg = "stop"; break;
330           case MacroAssembler::stop_untested          : msg = "untested"; break;
331           case MacroAssembler::stop_unimplemented     : msg = "unimplemented"; break;
332           case MacroAssembler::stop_shouldnotreachhere: msg = "shouldnotreachhere"; break;
333           default: msg = "unknown"; break;
334         }
335 
336         const char **detail_msg_ptr = (const char**)(pc + 4);
337         const char *detail_msg = msg_present ? *detail_msg_ptr : "no details provided";
338 
339         if (TraceTraps) {
340           tty->print_cr("trap: %s: %s (SIGTRAP, stop type %d)", msg, detail_msg, stop_type);
341         }
342 
343         return false; // Fatal error
344       }
345 
346       else if (sig == SIGBUS) {
347         // BugId 4454115: A read from a MappedByteBuffer can fault here if the
348         // underlying file has been truncated. Do not crash the VM in such a case.
349         CodeBlob* cb = CodeCache::find_blob_unsafe(pc);
350         CompiledMethod* nm = (cb != NULL) ? cb->as_compiled_method_or_null() : NULL;
351         bool is_unsafe_arraycopy = (thread->doing_unsafe_access() && UnsafeCopyMemory::contains_pc(pc));
352         if ((nm != NULL && nm->has_unsafe_access()) || is_unsafe_arraycopy) {
353           address next_pc = pc + 4;
354           if (is_unsafe_arraycopy) {
355             next_pc = UnsafeCopyMemory::page_error_continue_pc(pc);
356           }
357           next_pc = SharedRuntime::handle_unsafe_access(thread, next_pc);
358           os::Posix::ucontext_set_pc(uc, next_pc);
359           return true;
360         }
361       }
362     }
363 
364     else { // thread->thread_state() != _thread_in_Java
365       if (sig == SIGILL && VM_Version::is_determine_features_test_running()) {
366         // SIGILL must be caused by VM_Version::determine_features().
367         *(int *)pc = 0; // patch instruction to 0 to indicate that it causes a SIGILL,
368                         // flushing of icache is not necessary.
369         stub = pc + 4;  // continue with next instruction.
370       }
371       else if ((thread->thread_state() == _thread_in_vm ||
372                 thread->thread_state() == _thread_in_native) &&
373                sig == SIGBUS && thread->doing_unsafe_access()) {
374         address next_pc = pc + 4;
375         if (UnsafeCopyMemory::contains_pc(pc)) {
376           next_pc = UnsafeCopyMemory::page_error_continue_pc(pc);
377         }
378         next_pc = SharedRuntime::handle_unsafe_access(thread, next_pc);
379         os::Posix::ucontext_set_pc(uc, next_pc);
380         return true;
381       }
382     }
383 
384     // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks in
385     // and the heap gets shrunk before the field access.
386     if ((sig == SIGSEGV) || (sig == SIGBUS)) {
387       address addr = JNI_FastGetField::find_slowcase_pc(pc);
388       if (addr != (address)-1) {
389         stub = addr;
390       }
391     }
392   }
393 
394   if (stub != NULL) {
395     // Save all thread context in case we need to restore it.
396     if (thread != NULL) thread->set_saved_exception_pc(pc);
397     os::Posix::ucontext_set_pc(uc, stub);
398     return true;
399   }
400 
401   return false;
402 }
403 
init_thread_fpu_state(void)404 void os::Linux::init_thread_fpu_state(void) {
405   // Disable FP exceptions.
406   __asm__ __volatile__ ("mtfsfi 6,0");
407 }
408 
get_fpu_control_word(void)409 int os::Linux::get_fpu_control_word(void) {
410   // x86 has problems with FPU precision after pthread_cond_timedwait().
411   // nothing to do on ppc64.
412   return 0;
413 }
414 
set_fpu_control_word(int fpu_control)415 void os::Linux::set_fpu_control_word(int fpu_control) {
416   // x86 has problems with FPU precision after pthread_cond_timedwait().
417   // nothing to do on ppc64.
418 }
419 
420 ////////////////////////////////////////////////////////////////////////////////
421 // thread stack
422 
423 // Minimum usable stack sizes required to get to user code. Space for
424 // HotSpot guard pages is added later.
425 size_t os::Posix::_compiler_thread_min_stack_allowed = 64 * K;
426 size_t os::Posix::_java_thread_min_stack_allowed = 64 * K;
427 size_t os::Posix::_vm_internal_thread_min_stack_allowed = 64 * K;
428 
429 // Return default stack size for thr_type.
default_stack_size(os::ThreadType thr_type)430 size_t os::Posix::default_stack_size(os::ThreadType thr_type) {
431   // Default stack size (compiler thread needs larger stack).
432   size_t s = (thr_type == os::compiler_thread ? 4 * M : 1024 * K);
433   return s;
434 }
435 
436 /////////////////////////////////////////////////////////////////////////////
437 // helper functions for fatal error handler
438 
print_context(outputStream * st,const void * context)439 void os::print_context(outputStream *st, const void *context) {
440   if (context == NULL) return;
441 
442   const ucontext_t* uc = (const ucontext_t*)context;
443 
444   st->print_cr("Registers:");
445   st->print("pc =" INTPTR_FORMAT "  ", uc->uc_mcontext.regs->nip);
446   st->print("lr =" INTPTR_FORMAT "  ", uc->uc_mcontext.regs->link);
447   st->print("ctr=" INTPTR_FORMAT "  ", uc->uc_mcontext.regs->ctr);
448   st->cr();
449   for (int i = 0; i < 32; i++) {
450     st->print("r%-2d=" INTPTR_FORMAT "  ", i, uc->uc_mcontext.regs->gpr[i]);
451     if (i % 3 == 2) st->cr();
452   }
453   st->cr();
454   st->cr();
455 
456   intptr_t *sp = (intptr_t *)os::Linux::ucontext_get_sp(uc);
457   st->print_cr("Top of Stack: (sp=" PTR_FORMAT ")", p2i(sp));
458   print_hex_dump(st, (address)sp, (address)(sp + 128), sizeof(intptr_t));
459   st->cr();
460 
461   // Note: it may be unsafe to inspect memory near pc. For example, pc may
462   // point to garbage if entry point in an nmethod is corrupted. Leave
463   // this at the end, and hope for the best.
464   address pc = os::Posix::ucontext_get_pc(uc);
465   print_instructions(st, pc, /*instrsize=*/4);
466   st->cr();
467 }
468 
print_register_info(outputStream * st,const void * context)469 void os::print_register_info(outputStream *st, const void *context) {
470   if (context == NULL) return;
471 
472   const ucontext_t *uc = (const ucontext_t*)context;
473 
474   st->print_cr("Register to memory mapping:");
475   st->cr();
476 
477   st->print("pc ="); print_location(st, (intptr_t)uc->uc_mcontext.regs->nip);
478   st->print("lr ="); print_location(st, (intptr_t)uc->uc_mcontext.regs->link);
479   st->print("ctr ="); print_location(st, (intptr_t)uc->uc_mcontext.regs->ctr);
480   for (int i = 0; i < 32; i++) {
481     st->print("r%-2d=", i);
482     print_location(st, uc->uc_mcontext.regs->gpr[i]);
483   }
484   st->cr();
485 }
486 
487 extern "C" {
SpinPause()488   int SpinPause() {
489     return 0;
490   }
491 }
492 
493 #ifndef PRODUCT
verify_stack_alignment()494 void os::verify_stack_alignment() {
495   assert(((intptr_t)os::current_stack_pointer() & (StackAlignmentInBytes-1)) == 0, "incorrect stack alignment");
496 }
497 #endif
498 
extra_bang_size_in_bytes()499 int os::extra_bang_size_in_bytes() {
500   // PPC does not require the additional stack bang.
501   return 0;
502 }
503