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