1 /*
   2  * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright 2007, 2008, 2009, 2010 Red Hat, Inc.
   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 "assembler_zero.inline.hpp"
  29 #include "classfile/classLoader.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "classfile/vmSymbols.hpp"
  32 #include "code/icBuffer.hpp"
  33 #include "code/vtableStubs.hpp"
  34 #include "interpreter/interpreter.hpp"
  35 #include "memory/allocation.inline.hpp"
  36 #include "nativeInst_zero.hpp"
  37 #include "os_share_linux.hpp"
  38 #include "prims/jniFastGetField.hpp"
  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.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/sharedRuntime.hpp"
  49 #include "runtime/stubRoutines.hpp"
  50 #include "runtime/thread.inline.hpp"
  51 #include "runtime/timer.hpp"
  52 #include "utilities/align.hpp"
  53 #include "utilities/events.hpp"
  54 #include "utilities/vmError.hpp"
  55 
  56 // See stubGenerator_zero.cpp
  57 #include <setjmp.h>
  58 extern sigjmp_buf* get_jmp_buf_for_continuation();
  59 
  60 address os::current_stack_pointer() {
  61   // return the address of the current function
  62   return (address)__builtin_frame_address(0);
  63 }
  64 
  65 frame os::get_sender_for_C_frame(frame* fr) {
  66   ShouldNotCallThis();
  67   return frame(NULL, NULL); // silence compile warning.
  68 }
  69 
  70 frame os::current_frame() {
  71   // The only thing that calls this is the stack printing code in
  72   // VMError::report:
  73   //   - Step 110 (printing stack bounds) uses the sp in the frame
  74   //     to determine the amount of free space on the stack.  We
  75   //     set the sp to a close approximation of the real value in
  76   //     order to allow this step to complete.
  77   //   - Step 120 (printing native stack) tries to walk the stack.
  78   //     The frame we create has a NULL pc, which is ignored as an
  79   //     invalid frame.
  80   frame dummy = frame();
  81   dummy.set_sp((intptr_t *) current_stack_pointer());
  82   return dummy;
  83 }
  84 
  85 char* os::non_memory_address_word() {
  86   // Must never look like an address returned by reserve_memory,
  87   // even in its subfields (as defined by the CPU immediate fields,
  88   // if the CPU splits constants across multiple instructions).
  89   // This is the value for x86; works pretty well for PPC too.
  90   return (char *) -1;
  91 }
  92 
  93 address os::Linux::ucontext_get_pc(const ucontext_t* uc) {
  94   ShouldNotCallThis();
  95   return NULL; // silence compile warnings
  96 }
  97 
  98 void os::Linux::ucontext_set_pc(ucontext_t * uc, address pc) {
  99   ShouldNotCallThis();
 100 }
 101 
 102 ExtendedPC os::fetch_frame_from_context(const void* ucVoid,
 103                                         intptr_t** ret_sp,
 104                                         intptr_t** ret_fp) {
 105   ShouldNotCallThis();
 106   return NULL; // silence compile warnings
 107 }
 108 
 109 frame os::fetch_frame_from_context(const void* ucVoid) {
 110   ShouldNotCallThis();
 111   return frame(NULL, NULL); // silence compile warnings
 112 }
 113 
 114 extern "C" JNIEXPORT int
 115 JVM_handle_linux_signal(int sig,
 116                         siginfo_t* info,
 117                         void* ucVoid,
 118                         int abort_if_unrecognized) {
 119   ucontext_t* uc = (ucontext_t*) ucVoid;
 120 
 121   Thread* t = Thread::current_or_null_safe();
 122 
 123   SignalHandlerMark shm(t);
 124 
 125   // handle SafeFetch faults
 126   if (sig == SIGSEGV || sig == SIGBUS) {
 127     sigjmp_buf* const pjb = get_jmp_buf_for_continuation();
 128     if (pjb) {
 129       siglongjmp(*pjb, 1);
 130     }
 131   }
 132 
 133   // Note: it's not uncommon that JNI code uses signal/sigset to
 134   // install then restore certain signal handler (e.g. to temporarily
 135   // block SIGPIPE, or have a SIGILL handler when detecting CPU
 136   // type). When that happens, JVM_handle_linux_signal() might be
 137   // invoked with junk info/ucVoid. To avoid unnecessary crash when
 138   // libjsig is not preloaded, try handle signals that do not require
 139   // siginfo/ucontext first.
 140 
 141   if (sig == SIGPIPE || sig == SIGXFSZ) {
 142     // allow chained handler to go first
 143     if (os::Linux::chained_handler(sig, info, ucVoid)) {
 144       return true;
 145     } else {
 146       // Ignoring SIGPIPE/SIGXFSZ - see bugs 4229104 or 6499219
 147       return true;
 148     }
 149   }
 150 
 151   JavaThread* thread = NULL;
 152   VMThread* vmthread = NULL;
 153   if (os::Linux::signal_handlers_are_installed) {
 154     if (t != NULL ){
 155       if(t->is_Java_thread()) {
 156         thread = (JavaThread*)t;
 157       }
 158       else if(t->is_VM_thread()){
 159         vmthread = (VMThread *)t;
 160       }
 161     }
 162   }
 163 
 164   if (info != NULL && thread != NULL) {
 165     // Handle ALL stack overflow variations here
 166     if (sig == SIGSEGV) {
 167       address addr = (address) info->si_addr;
 168 
 169       // check if fault address is within thread stack
 170       if (thread->is_in_full_stack(addr)) {
 171         // stack overflow
 172         if (thread->in_stack_yellow_reserved_zone(addr)) {
 173           thread->disable_stack_yellow_reserved_zone();
 174           ShouldNotCallThis();
 175         }
 176         else if (thread->in_stack_red_zone(addr)) {
 177           thread->disable_stack_red_zone();
 178           ShouldNotCallThis();
 179         }
 180         else {
 181           // Accessing stack address below sp may cause SEGV if
 182           // current thread has MAP_GROWSDOWN stack. This should
 183           // only happen when current thread was created by user
 184           // code with MAP_GROWSDOWN flag and then attached to VM.
 185           // See notes in os_linux.cpp.
 186           if (thread->osthread()->expanding_stack() == 0) {
 187             thread->osthread()->set_expanding_stack();
 188             if (os::Linux::manually_expand_stack(thread, addr)) {
 189               thread->osthread()->clear_expanding_stack();
 190               return true;
 191             }
 192             thread->osthread()->clear_expanding_stack();
 193           }
 194           else {
 195             fatal("recursive segv. expanding stack.");
 196           }
 197         }
 198       }
 199     }
 200 
 201     /*if (thread->thread_state() == _thread_in_Java) {
 202       ShouldNotCallThis();
 203     }
 204     else*/ if ((thread->thread_state() == _thread_in_vm ||
 205                thread->thread_state() == _thread_in_native) &&
 206                sig == SIGBUS && thread->doing_unsafe_access()) {
 207       ShouldNotCallThis();
 208     }
 209 
 210     // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC
 211     // kicks in and the heap gets shrunk before the field access.
 212     /*if (sig == SIGSEGV || sig == SIGBUS) {
 213       address addr = JNI_FastGetField::find_slowcase_pc(pc);
 214       if (addr != (address)-1) {
 215         stub = addr;
 216       }
 217     }*/
 218   }
 219 
 220   // signal-chaining
 221   if (os::Linux::chained_handler(sig, info, ucVoid)) {
 222      return true;
 223   }
 224 
 225   if (!abort_if_unrecognized) {
 226     // caller wants another chance, so give it to him
 227     return false;
 228   }
 229 
 230 #ifndef PRODUCT
 231   if (sig == SIGSEGV) {
 232     fatal("\n#"
 233           "\n#    /--------------------\\"
 234           "\n#    | segmentation fault |"
 235           "\n#    \\---\\ /--------------/"
 236           "\n#        /"
 237           "\n#    [-]        |\\_/|    "
 238           "\n#    (+)=C      |o o|__  "
 239           "\n#    | |        =-*-=__\\ "
 240           "\n#    OOO        c_c_(___)");
 241   }
 242 #endif // !PRODUCT
 243 
 244   char buf[64];
 245 
 246   sprintf(buf, "caught unhandled signal %d", sig);
 247 
 248 // Silence -Wformat-security warning for fatal()
 249 PRAGMA_DIAG_PUSH
 250 PRAGMA_FORMAT_NONLITERAL_IGNORED
 251   fatal(buf);
 252 PRAGMA_DIAG_POP
 253   return true; // silence compiler warnings
 254 }
 255 
 256 void os::Linux::init_thread_fpu_state(void) {
 257   // Nothing to do
 258 }
 259 
 260 int os::Linux::get_fpu_control_word() {
 261   ShouldNotCallThis();
 262   return -1; // silence compile warnings
 263 }
 264 
 265 void os::Linux::set_fpu_control_word(int fpu) {
 266   ShouldNotCallThis();
 267 }
 268 
 269 bool os::is_allocatable(size_t bytes) {
 270 #ifdef _LP64
 271   return true;
 272 #else
 273   if (bytes < 2 * G) {
 274     return true;
 275   }
 276 
 277   char* addr = reserve_memory(bytes, NULL);
 278 
 279   if (addr != NULL) {
 280     release_memory(addr, bytes);
 281   }
 282 
 283   return addr != NULL;
 284 #endif // _LP64
 285 }
 286 
 287 ///////////////////////////////////////////////////////////////////////////////
 288 // thread stack
 289 
 290 size_t os::Posix::_compiler_thread_min_stack_allowed = 64 * K;
 291 size_t os::Posix::_java_thread_min_stack_allowed = 64 * K;
 292 size_t os::Posix::_vm_internal_thread_min_stack_allowed = 64 * K;
 293 
 294 size_t os::Posix::default_stack_size(os::ThreadType thr_type) {
 295 #ifdef _LP64
 296   size_t s = (thr_type == os::compiler_thread ? 4 * M : 1 * M);
 297 #else
 298   size_t s = (thr_type == os::compiler_thread ? 2 * M : 512 * K);
 299 #endif // _LP64
 300   return s;
 301 }
 302 
 303 static void current_stack_region(address *bottom, size_t *size) {
 304   pthread_attr_t attr;
 305   int res = pthread_getattr_np(pthread_self(), &attr);
 306   if (res != 0) {
 307     if (res == ENOMEM) {
 308       vm_exit_out_of_memory(0, OOM_MMAP_ERROR, "pthread_getattr_np");
 309     }
 310     else {
 311       fatal("pthread_getattr_np failed with error = %d", res);
 312     }
 313   }
 314 
 315   address stack_bottom;
 316   size_t stack_bytes;
 317   res = pthread_attr_getstack(&attr, (void **) &stack_bottom, &stack_bytes);
 318   if (res != 0) {
 319     fatal("pthread_attr_getstack failed with error = %d", res);
 320   }
 321   address stack_top = stack_bottom + stack_bytes;
 322 
 323   // The block of memory returned by pthread_attr_getstack() includes
 324   // guard pages where present.  We need to trim these off.
 325   size_t page_bytes = os::Linux::page_size();
 326   assert(((intptr_t) stack_bottom & (page_bytes - 1)) == 0, "unaligned stack");
 327 
 328   size_t guard_bytes;
 329   res = pthread_attr_getguardsize(&attr, &guard_bytes);
 330   if (res != 0) {
 331     fatal("pthread_attr_getguardsize failed with errno = %d", res);
 332   }
 333   int guard_pages = align_up(guard_bytes, page_bytes) / page_bytes;
 334   assert(guard_bytes == guard_pages * page_bytes, "unaligned guard");
 335 
 336 #ifdef IA64
 337   // IA64 has two stacks sharing the same area of memory, a normal
 338   // stack growing downwards and a register stack growing upwards.
 339   // Guard pages, if present, are in the centre.  This code splits
 340   // the stack in two even without guard pages, though in theory
 341   // there's nothing to stop us allocating more to the normal stack
 342   // or more to the register stack if one or the other were found
 343   // to grow faster.
 344   int total_pages = align_down(stack_bytes, page_bytes) / page_bytes;
 345   stack_bottom += (total_pages - guard_pages) / 2 * page_bytes;
 346 #endif // IA64
 347 
 348   stack_bottom += guard_bytes;
 349 
 350   pthread_attr_destroy(&attr);
 351 
 352   // The initial thread has a growable stack, and the size reported
 353   // by pthread_attr_getstack is the maximum size it could possibly
 354   // be given what currently mapped.  This can be huge, so we cap it.
 355   if (os::is_primordial_thread()) {
 356     stack_bytes = stack_top - stack_bottom;
 357 
 358     if (stack_bytes > JavaThread::stack_size_at_create())
 359       stack_bytes = JavaThread::stack_size_at_create();
 360 
 361     stack_bottom = stack_top - stack_bytes;
 362   }
 363 
 364   assert(os::current_stack_pointer() >= stack_bottom, "should do");
 365   assert(os::current_stack_pointer() < stack_top, "should do");
 366 
 367   *bottom = stack_bottom;
 368   *size = stack_top - stack_bottom;
 369 }
 370 
 371 address os::current_stack_base() {
 372   address bottom;
 373   size_t size;
 374   current_stack_region(&bottom, &size);
 375   return bottom + size;
 376 }
 377 
 378 size_t os::current_stack_size() {
 379   // stack size includes normal stack and HotSpot guard pages
 380   address bottom;
 381   size_t size;
 382   current_stack_region(&bottom, &size);
 383   return size;
 384 }
 385 
 386 /////////////////////////////////////////////////////////////////////////////
 387 // helper functions for fatal error handler
 388 
 389 void os::print_context(outputStream* st, const void* context) {
 390   ShouldNotCallThis();
 391 }
 392 
 393 void os::print_register_info(outputStream *st, const void *context) {
 394   ShouldNotCallThis();
 395 }
 396 
 397 /////////////////////////////////////////////////////////////////////////////
 398 // Stubs for things that would be in linux_zero.s if it existed.
 399 // You probably want to disassemble these monkeys to check they're ok.
 400 
 401 extern "C" {
 402   int SpinPause() {
 403       return -1; // silence compile warnings
 404   }
 405 
 406 
 407   void _Copy_conjoint_jshorts_atomic(const jshort* from, jshort* to, size_t count) {
 408     if (from > to) {
 409       const jshort *end = from + count;
 410       while (from < end)
 411         *(to++) = *(from++);
 412     }
 413     else if (from < to) {
 414       const jshort *end = from;
 415       from += count - 1;
 416       to   += count - 1;
 417       while (from >= end)
 418         *(to--) = *(from--);
 419     }
 420   }
 421   void _Copy_conjoint_jints_atomic(const jint* from, jint* to, size_t count) {
 422     if (from > to) {
 423       const jint *end = from + count;
 424       while (from < end)
 425         *(to++) = *(from++);
 426     }
 427     else if (from < to) {
 428       const jint *end = from;
 429       from += count - 1;
 430       to   += count - 1;
 431       while (from >= end)
 432         *(to--) = *(from--);
 433     }
 434   }
 435   void _Copy_conjoint_jlongs_atomic(const jlong* from, jlong* to, size_t count) {
 436     if (from > to) {
 437       const jlong *end = from + count;
 438       while (from < end)
 439         os::atomic_copy64(from++, to++);
 440     }
 441     else if (from < to) {
 442       const jlong *end = from;
 443       from += count - 1;
 444       to   += count - 1;
 445       while (from >= end)
 446         os::atomic_copy64(from--, to--);
 447     }
 448   }
 449 
 450   void _Copy_arrayof_conjoint_bytes(const HeapWord* from,
 451                                     HeapWord* to,
 452                                     size_t    count) {
 453     memmove(to, from, count);
 454   }
 455   void _Copy_arrayof_conjoint_jshorts(const HeapWord* from,
 456                                       HeapWord* to,
 457                                       size_t    count) {
 458     memmove(to, from, count * 2);
 459   }
 460   void _Copy_arrayof_conjoint_jints(const HeapWord* from,
 461                                     HeapWord* to,
 462                                     size_t    count) {
 463     memmove(to, from, count * 4);
 464   }
 465   void _Copy_arrayof_conjoint_jlongs(const HeapWord* from,
 466                                      HeapWord* to,
 467                                      size_t    count) {
 468     memmove(to, from, count * 8);
 469   }
 470 };
 471 
 472 /////////////////////////////////////////////////////////////////////////////
 473 // Implementations of atomic operations not supported by processors.
 474 //  -- http://gcc.gnu.org/onlinedocs/gcc-4.2.1/gcc/Atomic-Builtins.html
 475 
 476 #ifndef _LP64
 477 extern "C" {
 478   long long unsigned int __sync_val_compare_and_swap_8(
 479     volatile void *ptr,
 480     long long unsigned int oldval,
 481     long long unsigned int newval) {
 482     ShouldNotCallThis();
 483   }
 484 };
 485 #endif // !_LP64
 486 
 487 #ifndef PRODUCT
 488 void os::verify_stack_alignment() {
 489 }
 490 #endif
 491 
 492 int os::extra_bang_size_in_bytes() {
 493   // Zero does not require an additional stack banging.
 494   return 0;
 495 }