1 /* 2 * Copyright (c) 1999, 2015, 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 "classfile/classLoader.hpp" 27 #include "classfile/systemDictionary.hpp" 28 #include "classfile/vmSymbols.hpp" 29 #include "code/icBuffer.hpp" 30 #include "code/vtableStubs.hpp" 31 #include "compiler/compileBroker.hpp" 32 #include "compiler/disassembler.hpp" 33 #include "interpreter/interpreter.hpp" 34 #include "jvm_linux.h" 35 #include "memory/allocation.inline.hpp" 36 #include "memory/filemap.hpp" 37 #include "mutex_linux.inline.hpp" 38 #include "oops/oop.inline.hpp" 39 #include "os_linux.inline.hpp" 40 #include "os_share_linux.hpp" 41 #include "prims/jniFastGetField.hpp" 42 #include "prims/jvm.h" 43 #include "prims/jvm_misc.hpp" 44 #include "runtime/arguments.hpp" 45 #include "runtime/atomic.inline.hpp" 46 #include "runtime/extendedPC.hpp" 47 #include "runtime/globals.hpp" 48 #include "runtime/interfaceSupport.hpp" 49 #include "runtime/init.hpp" 50 #include "runtime/java.hpp" 51 #include "runtime/javaCalls.hpp" 52 #include "runtime/mutexLocker.hpp" 53 #include "runtime/objectMonitor.hpp" 54 #include "runtime/orderAccess.inline.hpp" 55 #include "runtime/osThread.hpp" 56 #include "runtime/perfMemory.hpp" 57 #include "runtime/sharedRuntime.hpp" 58 #include "runtime/statSampler.hpp" 59 #include "runtime/stubRoutines.hpp" 60 #include "runtime/thread.inline.hpp" 61 #include "runtime/threadCritical.hpp" 62 #include "runtime/timer.hpp" 63 #include "services/attachListener.hpp" 64 #include "services/memTracker.hpp" 65 #include "services/runtimeService.hpp" 66 #include "utilities/decoder.hpp" 67 #include "utilities/defaultStream.hpp" 68 #include "utilities/events.hpp" 69 #include "utilities/elfFile.hpp" 70 #include "utilities/growableArray.hpp" 71 #include "utilities/macros.hpp" 72 #include "utilities/vmError.hpp" 73 74 // put OS-includes here 75 # include <sys/types.h> 76 # include <sys/mman.h> 77 # include <sys/stat.h> 78 # include <sys/select.h> 79 # include <pthread.h> 80 # include <signal.h> 81 # include <errno.h> 82 # include <dlfcn.h> 83 # include <stdio.h> 84 # include <unistd.h> 85 # include <sys/resource.h> 86 # include <pthread.h> 87 # include <sys/stat.h> 88 # include <sys/time.h> 89 # include <sys/times.h> 90 # include <sys/utsname.h> 91 # include <sys/socket.h> 92 # include <sys/wait.h> 93 # include <pwd.h> 94 # include <poll.h> 95 # include <semaphore.h> 96 # include <fcntl.h> 97 # include <string.h> 98 # include <syscall.h> 99 # include <sys/sysinfo.h> 100 # include <gnu/libc-version.h> 101 # include <sys/ipc.h> 102 # include <sys/shm.h> 103 # include <link.h> 104 # include <stdint.h> 105 # include <inttypes.h> 106 # include <sys/ioctl.h> 107 108 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC 109 110 // if RUSAGE_THREAD for getrusage() has not been defined, do it here. The code calling 111 // getrusage() is prepared to handle the associated failure. 112 #ifndef RUSAGE_THREAD 113 #define RUSAGE_THREAD (1) /* only the calling thread */ 114 #endif 115 116 #define MAX_PATH (2 * K) 117 118 #define MAX_SECS 100000000 119 120 // for timer info max values which include all bits 121 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF) 122 123 #define LARGEPAGES_BIT (1 << 6) 124 //////////////////////////////////////////////////////////////////////////////// 125 // global variables 126 julong os::Linux::_physical_memory = 0; 127 128 address os::Linux::_initial_thread_stack_bottom = NULL; 129 uintptr_t os::Linux::_initial_thread_stack_size = 0; 130 131 int (*os::Linux::_clock_gettime)(clockid_t, struct timespec *) = NULL; 132 int (*os::Linux::_pthread_getcpuclockid)(pthread_t, clockid_t *) = NULL; 133 int (*os::Linux::_pthread_setname_np)(pthread_t, const char*) = NULL; 134 Mutex* os::Linux::_createThread_lock = NULL; 135 pthread_t os::Linux::_main_thread; 136 int os::Linux::_page_size = -1; 137 const int os::Linux::_vm_default_page_size = (8 * K); 138 bool os::Linux::_is_floating_stack = false; 139 bool os::Linux::_is_NPTL = false; 140 bool os::Linux::_supports_fast_thread_cpu_time = false; 141 const char * os::Linux::_glibc_version = NULL; 142 const char * os::Linux::_libpthread_version = NULL; 143 pthread_condattr_t os::Linux::_condattr[1]; 144 145 static jlong initial_time_count=0; 146 147 static int clock_tics_per_sec = 100; 148 149 // For diagnostics to print a message once. see run_periodic_checks 150 static sigset_t check_signal_done; 151 static bool check_signals = true; 152 153 static pid_t _initial_pid = 0; 154 155 // Signal number used to suspend/resume a thread 156 157 // do not use any signal number less than SIGSEGV, see 4355769 158 static int SR_signum = SIGUSR2; 159 sigset_t SR_sigset; 160 161 // Used to protect dlsym() calls 162 static pthread_mutex_t dl_mutex; 163 164 // Declarations 165 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time); 166 167 // utility functions 168 169 static int SR_initialize(); 170 171 julong os::available_memory() { 172 return Linux::available_memory(); 173 } 174 175 julong os::Linux::available_memory() { 176 // values in struct sysinfo are "unsigned long" 177 struct sysinfo si; 178 sysinfo(&si); 179 180 return (julong)si.freeram * si.mem_unit; 181 } 182 183 julong os::physical_memory() { 184 return Linux::physical_memory(); 185 } 186 187 //////////////////////////////////////////////////////////////////////////////// 188 // environment support 189 190 bool os::getenv(const char* name, char* buf, int len) { 191 const char* val = ::getenv(name); 192 if (val != NULL && strlen(val) < (size_t)len) { 193 strcpy(buf, val); 194 return true; 195 } 196 if (len > 0) buf[0] = 0; // return a null string 197 return false; 198 } 199 200 201 // Return true if user is running as root. 202 203 bool os::have_special_privileges() { 204 static bool init = false; 205 static bool privileges = false; 206 if (!init) { 207 privileges = (getuid() != geteuid()) || (getgid() != getegid()); 208 init = true; 209 } 210 return privileges; 211 } 212 213 214 #ifndef SYS_gettid 215 // i386: 224, ia64: 1105, amd64: 186, sparc 143 216 #ifdef __ia64__ 217 #define SYS_gettid 1105 218 #elif __i386__ 219 #define SYS_gettid 224 220 #elif __amd64__ 221 #define SYS_gettid 186 222 #elif __sparc__ 223 #define SYS_gettid 143 224 #else 225 #error define gettid for the arch 226 #endif 227 #endif 228 229 // Cpu architecture string 230 #if defined(ZERO) 231 static char cpu_arch[] = ZERO_LIBARCH; 232 #elif defined(IA64) 233 static char cpu_arch[] = "ia64"; 234 #elif defined(IA32) 235 static char cpu_arch[] = "i386"; 236 #elif defined(AMD64) 237 static char cpu_arch[] = "amd64"; 238 #elif defined(ARM) 239 static char cpu_arch[] = "arm"; 240 #elif defined(PPC32) 241 static char cpu_arch[] = "ppc"; 242 #elif defined(PPC64) 243 #if defined(VM_LITTLE_ENDIAN) 244 static char cpu_arch[] = "ppc64le"; 245 #else 246 static char cpu_arch[] = "ppc64"; 247 #endif 248 #elif defined(SPARC) 249 #ifdef _LP64 250 static char cpu_arch[] = "sparcv9"; 251 #else 252 static char cpu_arch[] = "sparc"; 253 #endif 254 #else 255 #error Add appropriate cpu_arch setting 256 #endif 257 258 259 // pid_t gettid() 260 // 261 // Returns the kernel thread id of the currently running thread. Kernel 262 // thread id is used to access /proc. 263 // 264 // (Note that getpid() on LinuxThreads returns kernel thread id too; but 265 // on NPTL, it returns the same pid for all threads, as required by POSIX.) 266 // 267 pid_t os::Linux::gettid() { 268 int rslt = syscall(SYS_gettid); 269 if (rslt == -1) { 270 // old kernel, no NPTL support 271 return getpid(); 272 } else { 273 return (pid_t)rslt; 274 } 275 } 276 277 // Most versions of linux have a bug where the number of processors are 278 // determined by looking at the /proc file system. In a chroot environment, 279 // the system call returns 1. This causes the VM to act as if it is 280 // a single processor and elide locking (see is_MP() call). 281 static bool unsafe_chroot_detected = false; 282 static const char *unstable_chroot_error = "/proc file system not found.\n" 283 "Java may be unstable running multithreaded in a chroot " 284 "environment on Linux when /proc filesystem is not mounted."; 285 286 void os::Linux::initialize_system_info() { 287 set_processor_count(sysconf(_SC_NPROCESSORS_CONF)); 288 if (processor_count() == 1) { 289 pid_t pid = os::Linux::gettid(); 290 char fname[32]; 291 jio_snprintf(fname, sizeof(fname), "/proc/%d", pid); 292 FILE *fp = fopen(fname, "r"); 293 if (fp == NULL) { 294 unsafe_chroot_detected = true; 295 } else { 296 fclose(fp); 297 } 298 } 299 _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * (julong)sysconf(_SC_PAGESIZE); 300 assert(processor_count() > 0, "linux error"); 301 } 302 303 void os::init_system_properties_values() { 304 // The next steps are taken in the product version: 305 // 306 // Obtain the JAVA_HOME value from the location of libjvm.so. 307 // This library should be located at: 308 // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so. 309 // 310 // If "/jre/lib/" appears at the right place in the path, then we 311 // assume libjvm.so is installed in a JDK and we use this path. 312 // 313 // Otherwise exit with message: "Could not create the Java virtual machine." 314 // 315 // The following extra steps are taken in the debugging version: 316 // 317 // If "/jre/lib/" does NOT appear at the right place in the path 318 // instead of exit check for $JAVA_HOME environment variable. 319 // 320 // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>, 321 // then we append a fake suffix "hotspot/libjvm.so" to this path so 322 // it looks like libjvm.so is installed there 323 // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so. 324 // 325 // Otherwise exit. 326 // 327 // Important note: if the location of libjvm.so changes this 328 // code needs to be changed accordingly. 329 330 // See ld(1): 331 // The linker uses the following search paths to locate required 332 // shared libraries: 333 // 1: ... 334 // ... 335 // 7: The default directories, normally /lib and /usr/lib. 336 #if defined(AMD64) || defined(_LP64) && (defined(SPARC) || defined(PPC) || defined(S390)) 337 #define DEFAULT_LIBPATH "/usr/lib64:/lib64:/lib:/usr/lib" 338 #else 339 #define DEFAULT_LIBPATH "/lib:/usr/lib" 340 #endif 341 342 // Base path of extensions installed on the system. 343 #define SYS_EXT_DIR "/usr/java/packages" 344 #define EXTENSIONS_DIR "/lib/ext" 345 346 // Buffer that fits several sprintfs. 347 // Note that the space for the colon and the trailing null are provided 348 // by the nulls included by the sizeof operator. 349 const size_t bufsize = 350 MAX2((size_t)MAXPATHLEN, // For dll_dir & friends. 351 (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR)); // extensions dir 352 char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal); 353 354 // sysclasspath, java_home, dll_dir 355 { 356 char *pslash; 357 os::jvm_path(buf, bufsize); 358 359 // Found the full path to libjvm.so. 360 // Now cut the path to <java_home>/jre if we can. 361 pslash = strrchr(buf, '/'); 362 if (pslash != NULL) { 363 *pslash = '\0'; // Get rid of /libjvm.so. 364 } 365 pslash = strrchr(buf, '/'); 366 if (pslash != NULL) { 367 *pslash = '\0'; // Get rid of /{client|server|hotspot}. 368 } 369 Arguments::set_dll_dir(buf); 370 371 if (pslash != NULL) { 372 pslash = strrchr(buf, '/'); 373 if (pslash != NULL) { 374 *pslash = '\0'; // Get rid of /<arch>. 375 pslash = strrchr(buf, '/'); 376 if (pslash != NULL) { 377 *pslash = '\0'; // Get rid of /lib. 378 } 379 } 380 } 381 Arguments::set_java_home(buf); 382 set_boot_path('/', ':'); 383 } 384 385 // Where to look for native libraries. 386 // 387 // Note: Due to a legacy implementation, most of the library path 388 // is set in the launcher. This was to accomodate linking restrictions 389 // on legacy Linux implementations (which are no longer supported). 390 // Eventually, all the library path setting will be done here. 391 // 392 // However, to prevent the proliferation of improperly built native 393 // libraries, the new path component /usr/java/packages is added here. 394 // Eventually, all the library path setting will be done here. 395 { 396 // Get the user setting of LD_LIBRARY_PATH, and prepended it. It 397 // should always exist (until the legacy problem cited above is 398 // addressed). 399 const char *v = ::getenv("LD_LIBRARY_PATH"); 400 const char *v_colon = ":"; 401 if (v == NULL) { v = ""; v_colon = ""; } 402 // That's +1 for the colon and +1 for the trailing '\0'. 403 char *ld_library_path = (char *)NEW_C_HEAP_ARRAY(char, 404 strlen(v) + 1 + 405 sizeof(SYS_EXT_DIR) + sizeof("/lib/") + strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH) + 1, 406 mtInternal); 407 sprintf(ld_library_path, "%s%s" SYS_EXT_DIR "/lib/%s:" DEFAULT_LIBPATH, v, v_colon, cpu_arch); 408 Arguments::set_library_path(ld_library_path); 409 FREE_C_HEAP_ARRAY(char, ld_library_path); 410 } 411 412 // Extensions directories. 413 sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home()); 414 Arguments::set_ext_dirs(buf); 415 416 FREE_C_HEAP_ARRAY(char, buf); 417 418 #undef DEFAULT_LIBPATH 419 #undef SYS_EXT_DIR 420 #undef EXTENSIONS_DIR 421 } 422 423 //////////////////////////////////////////////////////////////////////////////// 424 // breakpoint support 425 426 void os::breakpoint() { 427 BREAKPOINT; 428 } 429 430 extern "C" void breakpoint() { 431 // use debugger to set breakpoint here 432 } 433 434 //////////////////////////////////////////////////////////////////////////////// 435 // signal support 436 437 debug_only(static bool signal_sets_initialized = false); 438 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs; 439 440 bool os::Linux::is_sig_ignored(int sig) { 441 struct sigaction oact; 442 sigaction(sig, (struct sigaction*)NULL, &oact); 443 void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction) 444 : CAST_FROM_FN_PTR(void*, oact.sa_handler); 445 if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN)) { 446 return true; 447 } else { 448 return false; 449 } 450 } 451 452 void os::Linux::signal_sets_init() { 453 // Should also have an assertion stating we are still single-threaded. 454 assert(!signal_sets_initialized, "Already initialized"); 455 // Fill in signals that are necessarily unblocked for all threads in 456 // the VM. Currently, we unblock the following signals: 457 // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden 458 // by -Xrs (=ReduceSignalUsage)); 459 // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all 460 // other threads. The "ReduceSignalUsage" boolean tells us not to alter 461 // the dispositions or masks wrt these signals. 462 // Programs embedding the VM that want to use the above signals for their 463 // own purposes must, at this time, use the "-Xrs" option to prevent 464 // interference with shutdown hooks and BREAK_SIGNAL thread dumping. 465 // (See bug 4345157, and other related bugs). 466 // In reality, though, unblocking these signals is really a nop, since 467 // these signals are not blocked by default. 468 sigemptyset(&unblocked_sigs); 469 sigemptyset(&allowdebug_blocked_sigs); 470 sigaddset(&unblocked_sigs, SIGILL); 471 sigaddset(&unblocked_sigs, SIGSEGV); 472 sigaddset(&unblocked_sigs, SIGBUS); 473 sigaddset(&unblocked_sigs, SIGFPE); 474 #if defined(PPC64) 475 sigaddset(&unblocked_sigs, SIGTRAP); 476 #endif 477 sigaddset(&unblocked_sigs, SR_signum); 478 479 if (!ReduceSignalUsage) { 480 if (!os::Linux::is_sig_ignored(SHUTDOWN1_SIGNAL)) { 481 sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL); 482 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL); 483 } 484 if (!os::Linux::is_sig_ignored(SHUTDOWN2_SIGNAL)) { 485 sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL); 486 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL); 487 } 488 if (!os::Linux::is_sig_ignored(SHUTDOWN3_SIGNAL)) { 489 sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL); 490 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL); 491 } 492 } 493 // Fill in signals that are blocked by all but the VM thread. 494 sigemptyset(&vm_sigs); 495 if (!ReduceSignalUsage) { 496 sigaddset(&vm_sigs, BREAK_SIGNAL); 497 } 498 debug_only(signal_sets_initialized = true); 499 500 } 501 502 // These are signals that are unblocked while a thread is running Java. 503 // (For some reason, they get blocked by default.) 504 sigset_t* os::Linux::unblocked_signals() { 505 assert(signal_sets_initialized, "Not initialized"); 506 return &unblocked_sigs; 507 } 508 509 // These are the signals that are blocked while a (non-VM) thread is 510 // running Java. Only the VM thread handles these signals. 511 sigset_t* os::Linux::vm_signals() { 512 assert(signal_sets_initialized, "Not initialized"); 513 return &vm_sigs; 514 } 515 516 // These are signals that are blocked during cond_wait to allow debugger in 517 sigset_t* os::Linux::allowdebug_blocked_signals() { 518 assert(signal_sets_initialized, "Not initialized"); 519 return &allowdebug_blocked_sigs; 520 } 521 522 void os::Linux::hotspot_sigmask(Thread* thread) { 523 524 //Save caller's signal mask before setting VM signal mask 525 sigset_t caller_sigmask; 526 pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask); 527 528 OSThread* osthread = thread->osthread(); 529 osthread->set_caller_sigmask(caller_sigmask); 530 531 pthread_sigmask(SIG_UNBLOCK, os::Linux::unblocked_signals(), NULL); 532 533 if (!ReduceSignalUsage) { 534 if (thread->is_VM_thread()) { 535 // Only the VM thread handles BREAK_SIGNAL ... 536 pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL); 537 } else { 538 // ... all other threads block BREAK_SIGNAL 539 pthread_sigmask(SIG_BLOCK, vm_signals(), NULL); 540 } 541 } 542 } 543 544 ////////////////////////////////////////////////////////////////////////////// 545 // detecting pthread library 546 547 void os::Linux::libpthread_init() { 548 // Save glibc and pthread version strings. Note that _CS_GNU_LIBC_VERSION 549 // and _CS_GNU_LIBPTHREAD_VERSION are supported in glibc >= 2.3.2. Use a 550 // generic name for earlier versions. 551 // Define macros here so we can build HotSpot on old systems. 552 #ifndef _CS_GNU_LIBC_VERSION 553 #define _CS_GNU_LIBC_VERSION 2 554 #endif 555 #ifndef _CS_GNU_LIBPTHREAD_VERSION 556 #define _CS_GNU_LIBPTHREAD_VERSION 3 557 #endif 558 559 size_t n = confstr(_CS_GNU_LIBC_VERSION, NULL, 0); 560 if (n > 0) { 561 char *str = (char *)malloc(n, mtInternal); 562 confstr(_CS_GNU_LIBC_VERSION, str, n); 563 os::Linux::set_glibc_version(str); 564 } else { 565 // _CS_GNU_LIBC_VERSION is not supported, try gnu_get_libc_version() 566 static char _gnu_libc_version[32]; 567 jio_snprintf(_gnu_libc_version, sizeof(_gnu_libc_version), 568 "glibc %s %s", gnu_get_libc_version(), gnu_get_libc_release()); 569 os::Linux::set_glibc_version(_gnu_libc_version); 570 } 571 572 n = confstr(_CS_GNU_LIBPTHREAD_VERSION, NULL, 0); 573 if (n > 0) { 574 char *str = (char *)malloc(n, mtInternal); 575 confstr(_CS_GNU_LIBPTHREAD_VERSION, str, n); 576 // Vanilla RH-9 (glibc 2.3.2) has a bug that confstr() always tells 577 // us "NPTL-0.29" even we are running with LinuxThreads. Check if this 578 // is the case. LinuxThreads has a hard limit on max number of threads. 579 // So sysconf(_SC_THREAD_THREADS_MAX) will return a positive value. 580 // On the other hand, NPTL does not have such a limit, sysconf() 581 // will return -1 and errno is not changed. Check if it is really NPTL. 582 if (strcmp(os::Linux::glibc_version(), "glibc 2.3.2") == 0 && 583 strstr(str, "NPTL") && 584 sysconf(_SC_THREAD_THREADS_MAX) > 0) { 585 free(str); 586 os::Linux::set_libpthread_version("linuxthreads"); 587 } else { 588 os::Linux::set_libpthread_version(str); 589 } 590 } else { 591 // glibc before 2.3.2 only has LinuxThreads. 592 os::Linux::set_libpthread_version("linuxthreads"); 593 } 594 595 if (strstr(libpthread_version(), "NPTL")) { 596 os::Linux::set_is_NPTL(); 597 } else { 598 os::Linux::set_is_LinuxThreads(); 599 } 600 601 // LinuxThreads have two flavors: floating-stack mode, which allows variable 602 // stack size; and fixed-stack mode. NPTL is always floating-stack. 603 if (os::Linux::is_NPTL() || os::Linux::supports_variable_stack_size()) { 604 os::Linux::set_is_floating_stack(); 605 } 606 } 607 608 ///////////////////////////////////////////////////////////////////////////// 609 // thread stack 610 611 // Force Linux kernel to expand current thread stack. If "bottom" is close 612 // to the stack guard, caller should block all signals. 613 // 614 // MAP_GROWSDOWN: 615 // A special mmap() flag that is used to implement thread stacks. It tells 616 // kernel that the memory region should extend downwards when needed. This 617 // allows early versions of LinuxThreads to only mmap the first few pages 618 // when creating a new thread. Linux kernel will automatically expand thread 619 // stack as needed (on page faults). 620 // 621 // However, because the memory region of a MAP_GROWSDOWN stack can grow on 622 // demand, if a page fault happens outside an already mapped MAP_GROWSDOWN 623 // region, it's hard to tell if the fault is due to a legitimate stack 624 // access or because of reading/writing non-exist memory (e.g. buffer 625 // overrun). As a rule, if the fault happens below current stack pointer, 626 // Linux kernel does not expand stack, instead a SIGSEGV is sent to the 627 // application (see Linux kernel fault.c). 628 // 629 // This Linux feature can cause SIGSEGV when VM bangs thread stack for 630 // stack overflow detection. 631 // 632 // Newer version of LinuxThreads (since glibc-2.2, or, RH-7.x) and NPTL do 633 // not use this flag. However, the stack of initial thread is not created 634 // by pthread, it is still MAP_GROWSDOWN. Also it's possible (though 635 // unlikely) that user code can create a thread with MAP_GROWSDOWN stack 636 // and then attach the thread to JVM. 637 // 638 // To get around the problem and allow stack banging on Linux, we need to 639 // manually expand thread stack after receiving the SIGSEGV. 640 // 641 // There are two ways to expand thread stack to address "bottom", we used 642 // both of them in JVM before 1.5: 643 // 1. adjust stack pointer first so that it is below "bottom", and then 644 // touch "bottom" 645 // 2. mmap() the page in question 646 // 647 // Now alternate signal stack is gone, it's harder to use 2. For instance, 648 // if current sp is already near the lower end of page 101, and we need to 649 // call mmap() to map page 100, it is possible that part of the mmap() frame 650 // will be placed in page 100. When page 100 is mapped, it is zero-filled. 651 // That will destroy the mmap() frame and cause VM to crash. 652 // 653 // The following code works by adjusting sp first, then accessing the "bottom" 654 // page to force a page fault. Linux kernel will then automatically expand the 655 // stack mapping. 656 // 657 // _expand_stack_to() assumes its frame size is less than page size, which 658 // should always be true if the function is not inlined. 659 660 #if __GNUC__ < 3 // gcc 2.x does not support noinline attribute 661 #define NOINLINE 662 #else 663 #define NOINLINE __attribute__ ((noinline)) 664 #endif 665 666 static void _expand_stack_to(address bottom) NOINLINE; 667 668 static void _expand_stack_to(address bottom) { 669 address sp; 670 size_t size; 671 volatile char *p; 672 673 // Adjust bottom to point to the largest address within the same page, it 674 // gives us a one-page buffer if alloca() allocates slightly more memory. 675 bottom = (address)align_size_down((uintptr_t)bottom, os::Linux::page_size()); 676 bottom += os::Linux::page_size() - 1; 677 678 // sp might be slightly above current stack pointer; if that's the case, we 679 // will alloca() a little more space than necessary, which is OK. Don't use 680 // os::current_stack_pointer(), as its result can be slightly below current 681 // stack pointer, causing us to not alloca enough to reach "bottom". 682 sp = (address)&sp; 683 684 if (sp > bottom) { 685 size = sp - bottom; 686 p = (volatile char *)alloca(size); 687 assert(p != NULL && p <= (volatile char *)bottom, "alloca problem?"); 688 p[0] = '\0'; 689 } 690 } 691 692 bool os::Linux::manually_expand_stack(JavaThread * t, address addr) { 693 assert(t!=NULL, "just checking"); 694 assert(t->osthread()->expanding_stack(), "expand should be set"); 695 assert(t->stack_base() != NULL, "stack_base was not initialized"); 696 697 if (addr < t->stack_base() && addr >= t->stack_yellow_zone_base()) { 698 sigset_t mask_all, old_sigset; 699 sigfillset(&mask_all); 700 pthread_sigmask(SIG_SETMASK, &mask_all, &old_sigset); 701 _expand_stack_to(addr); 702 pthread_sigmask(SIG_SETMASK, &old_sigset, NULL); 703 return true; 704 } 705 return false; 706 } 707 708 ////////////////////////////////////////////////////////////////////////////// 709 // create new thread 710 711 static address highest_vm_reserved_address(); 712 713 // check if it's safe to start a new thread 714 static bool _thread_safety_check(Thread* thread) { 715 if (os::Linux::is_LinuxThreads() && !os::Linux::is_floating_stack()) { 716 // Fixed stack LinuxThreads (SuSE Linux/x86, and some versions of Redhat) 717 // Heap is mmap'ed at lower end of memory space. Thread stacks are 718 // allocated (MAP_FIXED) from high address space. Every thread stack 719 // occupies a fixed size slot (usually 2Mbytes, but user can change 720 // it to other values if they rebuild LinuxThreads). 721 // 722 // Problem with MAP_FIXED is that mmap() can still succeed even part of 723 // the memory region has already been mmap'ed. That means if we have too 724 // many threads and/or very large heap, eventually thread stack will 725 // collide with heap. 726 // 727 // Here we try to prevent heap/stack collision by comparing current 728 // stack bottom with the highest address that has been mmap'ed by JVM 729 // plus a safety margin for memory maps created by native code. 730 // 731 // This feature can be disabled by setting ThreadSafetyMargin to 0 732 // 733 if (ThreadSafetyMargin > 0) { 734 address stack_bottom = os::current_stack_base() - os::current_stack_size(); 735 736 // not safe if our stack extends below the safety margin 737 return stack_bottom - ThreadSafetyMargin >= highest_vm_reserved_address(); 738 } else { 739 return true; 740 } 741 } else { 742 // Floating stack LinuxThreads or NPTL: 743 // Unlike fixed stack LinuxThreads, thread stacks are not MAP_FIXED. When 744 // there's not enough space left, pthread_create() will fail. If we come 745 // here, that means enough space has been reserved for stack. 746 return true; 747 } 748 } 749 750 // Thread start routine for all newly created threads 751 static void *java_start(Thread *thread) { 752 // Try to randomize the cache line index of hot stack frames. 753 // This helps when threads of the same stack traces evict each other's 754 // cache lines. The threads can be either from the same JVM instance, or 755 // from different JVM instances. The benefit is especially true for 756 // processors with hyperthreading technology. 757 static int counter = 0; 758 int pid = os::current_process_id(); 759 alloca(((pid ^ counter++) & 7) * 128); 760 761 ThreadLocalStorage::set_thread(thread); 762 763 OSThread* osthread = thread->osthread(); 764 Monitor* sync = osthread->startThread_lock(); 765 766 // non floating stack LinuxThreads needs extra check, see above 767 if (!_thread_safety_check(thread)) { 768 // notify parent thread 769 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag); 770 osthread->set_state(ZOMBIE); 771 sync->notify_all(); 772 return NULL; 773 } 774 775 // thread_id is kernel thread id (similar to Solaris LWP id) 776 osthread->set_thread_id(os::Linux::gettid()); 777 778 if (UseNUMA) { 779 int lgrp_id = os::numa_get_group_id(); 780 if (lgrp_id != -1) { 781 thread->set_lgrp_id(lgrp_id); 782 } 783 } 784 // initialize signal mask for this thread 785 os::Linux::hotspot_sigmask(thread); 786 787 // initialize floating point control register 788 os::Linux::init_thread_fpu_state(); 789 790 // handshaking with parent thread 791 { 792 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag); 793 794 // notify parent thread 795 osthread->set_state(INITIALIZED); 796 sync->notify_all(); 797 798 // wait until os::start_thread() 799 while (osthread->get_state() == INITIALIZED) { 800 sync->wait(Mutex::_no_safepoint_check_flag); 801 } 802 } 803 804 // call one more level start routine 805 thread->run(); 806 807 return 0; 808 } 809 810 bool os::create_thread(Thread* thread, ThreadType thr_type, 811 size_t stack_size) { 812 assert(thread->osthread() == NULL, "caller responsible"); 813 814 // Allocate the OSThread object 815 OSThread* osthread = new OSThread(NULL, NULL); 816 if (osthread == NULL) { 817 return false; 818 } 819 820 // set the correct thread state 821 osthread->set_thread_type(thr_type); 822 823 // Initial state is ALLOCATED but not INITIALIZED 824 osthread->set_state(ALLOCATED); 825 826 thread->set_osthread(osthread); 827 828 // init thread attributes 829 pthread_attr_t attr; 830 pthread_attr_init(&attr); 831 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 832 833 // stack size 834 if (os::Linux::supports_variable_stack_size()) { 835 // calculate stack size if it's not specified by caller 836 if (stack_size == 0) { 837 stack_size = os::Linux::default_stack_size(thr_type); 838 839 switch (thr_type) { 840 case os::java_thread: 841 // Java threads use ThreadStackSize which default value can be 842 // changed with the flag -Xss 843 assert(JavaThread::stack_size_at_create() > 0, "this should be set"); 844 stack_size = JavaThread::stack_size_at_create(); 845 break; 846 case os::compiler_thread: 847 if (CompilerThreadStackSize > 0) { 848 stack_size = (size_t)(CompilerThreadStackSize * K); 849 break; 850 } // else fall through: 851 // use VMThreadStackSize if CompilerThreadStackSize is not defined 852 case os::vm_thread: 853 case os::pgc_thread: 854 case os::cgc_thread: 855 case os::watcher_thread: 856 if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K); 857 break; 858 } 859 } 860 861 stack_size = MAX2(stack_size, os::Linux::min_stack_allowed); 862 pthread_attr_setstacksize(&attr, stack_size); 863 } else { 864 // let pthread_create() pick the default value. 865 } 866 867 // glibc guard page 868 pthread_attr_setguardsize(&attr, os::Linux::default_guard_size(thr_type)); 869 870 ThreadState state; 871 872 { 873 // Serialize thread creation if we are running with fixed stack LinuxThreads 874 bool lock = os::Linux::is_LinuxThreads() && !os::Linux::is_floating_stack(); 875 if (lock) { 876 os::Linux::createThread_lock()->lock_without_safepoint_check(); 877 } 878 879 pthread_t tid; 880 int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread); 881 882 pthread_attr_destroy(&attr); 883 884 if (ret != 0) { 885 if (PrintMiscellaneous && (Verbose || WizardMode)) { 886 perror("pthread_create()"); 887 } 888 // Need to clean up stuff we've allocated so far 889 thread->set_osthread(NULL); 890 delete osthread; 891 if (lock) os::Linux::createThread_lock()->unlock(); 892 return false; 893 } 894 895 // Store pthread info into the OSThread 896 osthread->set_pthread_id(tid); 897 898 // Wait until child thread is either initialized or aborted 899 { 900 Monitor* sync_with_child = osthread->startThread_lock(); 901 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag); 902 while ((state = osthread->get_state()) == ALLOCATED) { 903 sync_with_child->wait(Mutex::_no_safepoint_check_flag); 904 } 905 } 906 907 if (lock) { 908 os::Linux::createThread_lock()->unlock(); 909 } 910 } 911 912 // Aborted due to thread limit being reached 913 if (state == ZOMBIE) { 914 thread->set_osthread(NULL); 915 delete osthread; 916 return false; 917 } 918 919 // The thread is returned suspended (in state INITIALIZED), 920 // and is started higher up in the call chain 921 assert(state == INITIALIZED, "race condition"); 922 return true; 923 } 924 925 ///////////////////////////////////////////////////////////////////////////// 926 // attach existing thread 927 928 // bootstrap the main thread 929 bool os::create_main_thread(JavaThread* thread) { 930 assert(os::Linux::_main_thread == pthread_self(), "should be called inside main thread"); 931 return create_attached_thread(thread); 932 } 933 934 bool os::create_attached_thread(JavaThread* thread) { 935 #ifdef ASSERT 936 thread->verify_not_published(); 937 #endif 938 939 // Allocate the OSThread object 940 OSThread* osthread = new OSThread(NULL, NULL); 941 942 if (osthread == NULL) { 943 return false; 944 } 945 946 // Store pthread info into the OSThread 947 osthread->set_thread_id(os::Linux::gettid()); 948 osthread->set_pthread_id(::pthread_self()); 949 950 // initialize floating point control register 951 os::Linux::init_thread_fpu_state(); 952 953 // Initial thread state is RUNNABLE 954 osthread->set_state(RUNNABLE); 955 956 thread->set_osthread(osthread); 957 958 if (UseNUMA) { 959 int lgrp_id = os::numa_get_group_id(); 960 if (lgrp_id != -1) { 961 thread->set_lgrp_id(lgrp_id); 962 } 963 } 964 965 if (os::Linux::is_initial_thread()) { 966 // If current thread is initial thread, its stack is mapped on demand, 967 // see notes about MAP_GROWSDOWN. Here we try to force kernel to map 968 // the entire stack region to avoid SEGV in stack banging. 969 // It is also useful to get around the heap-stack-gap problem on SuSE 970 // kernel (see 4821821 for details). We first expand stack to the top 971 // of yellow zone, then enable stack yellow zone (order is significant, 972 // enabling yellow zone first will crash JVM on SuSE Linux), so there 973 // is no gap between the last two virtual memory regions. 974 975 JavaThread *jt = (JavaThread *)thread; 976 address addr = jt->stack_yellow_zone_base(); 977 assert(addr != NULL, "initialization problem?"); 978 assert(jt->stack_available(addr) > 0, "stack guard should not be enabled"); 979 980 osthread->set_expanding_stack(); 981 os::Linux::manually_expand_stack(jt, addr); 982 osthread->clear_expanding_stack(); 983 } 984 985 // initialize signal mask for this thread 986 // and save the caller's signal mask 987 os::Linux::hotspot_sigmask(thread); 988 989 return true; 990 } 991 992 void os::pd_start_thread(Thread* thread) { 993 OSThread * osthread = thread->osthread(); 994 assert(osthread->get_state() != INITIALIZED, "just checking"); 995 Monitor* sync_with_child = osthread->startThread_lock(); 996 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag); 997 sync_with_child->notify(); 998 } 999 1000 // Free Linux resources related to the OSThread 1001 void os::free_thread(OSThread* osthread) { 1002 assert(osthread != NULL, "osthread not set"); 1003 1004 if (Thread::current()->osthread() == osthread) { 1005 // Restore caller's signal mask 1006 sigset_t sigmask = osthread->caller_sigmask(); 1007 pthread_sigmask(SIG_SETMASK, &sigmask, NULL); 1008 } 1009 1010 delete osthread; 1011 } 1012 1013 ////////////////////////////////////////////////////////////////////////////// 1014 // thread local storage 1015 1016 // Restore the thread pointer if the destructor is called. This is in case 1017 // someone from JNI code sets up a destructor with pthread_key_create to run 1018 // detachCurrentThread on thread death. Unless we restore the thread pointer we 1019 // will hang or crash. When detachCurrentThread is called the key will be set 1020 // to null and we will not be called again. If detachCurrentThread is never 1021 // called we could loop forever depending on the pthread implementation. 1022 static void restore_thread_pointer(void* p) { 1023 Thread* thread = (Thread*) p; 1024 os::thread_local_storage_at_put(ThreadLocalStorage::thread_index(), thread); 1025 } 1026 1027 int os::allocate_thread_local_storage() { 1028 pthread_key_t key; 1029 int rslt = pthread_key_create(&key, restore_thread_pointer); 1030 assert(rslt == 0, "cannot allocate thread local storage"); 1031 return (int)key; 1032 } 1033 1034 // Note: This is currently not used by VM, as we don't destroy TLS key 1035 // on VM exit. 1036 void os::free_thread_local_storage(int index) { 1037 int rslt = pthread_key_delete((pthread_key_t)index); 1038 assert(rslt == 0, "invalid index"); 1039 } 1040 1041 void os::thread_local_storage_at_put(int index, void* value) { 1042 int rslt = pthread_setspecific((pthread_key_t)index, value); 1043 assert(rslt == 0, "pthread_setspecific failed"); 1044 } 1045 1046 extern "C" Thread* get_thread() { 1047 return ThreadLocalStorage::thread(); 1048 } 1049 1050 ////////////////////////////////////////////////////////////////////////////// 1051 // initial thread 1052 1053 // Check if current thread is the initial thread, similar to Solaris thr_main. 1054 bool os::Linux::is_initial_thread(void) { 1055 char dummy; 1056 // If called before init complete, thread stack bottom will be null. 1057 // Can be called if fatal error occurs before initialization. 1058 if (initial_thread_stack_bottom() == NULL) return false; 1059 assert(initial_thread_stack_bottom() != NULL && 1060 initial_thread_stack_size() != 0, 1061 "os::init did not locate initial thread's stack region"); 1062 if ((address)&dummy >= initial_thread_stack_bottom() && 1063 (address)&dummy < initial_thread_stack_bottom() + initial_thread_stack_size()) { 1064 return true; 1065 } else { 1066 return false; 1067 } 1068 } 1069 1070 // Find the virtual memory area that contains addr 1071 static bool find_vma(address addr, address* vma_low, address* vma_high) { 1072 FILE *fp = fopen("/proc/self/maps", "r"); 1073 if (fp) { 1074 address low, high; 1075 while (!feof(fp)) { 1076 if (fscanf(fp, "%p-%p", &low, &high) == 2) { 1077 if (low <= addr && addr < high) { 1078 if (vma_low) *vma_low = low; 1079 if (vma_high) *vma_high = high; 1080 fclose(fp); 1081 return true; 1082 } 1083 } 1084 for (;;) { 1085 int ch = fgetc(fp); 1086 if (ch == EOF || ch == (int)'\n') break; 1087 } 1088 } 1089 fclose(fp); 1090 } 1091 return false; 1092 } 1093 1094 // Locate initial thread stack. This special handling of initial thread stack 1095 // is needed because pthread_getattr_np() on most (all?) Linux distros returns 1096 // bogus value for initial thread. 1097 void os::Linux::capture_initial_stack(size_t max_size) { 1098 // stack size is the easy part, get it from RLIMIT_STACK 1099 size_t stack_size; 1100 struct rlimit rlim; 1101 getrlimit(RLIMIT_STACK, &rlim); 1102 stack_size = rlim.rlim_cur; 1103 1104 // 6308388: a bug in ld.so will relocate its own .data section to the 1105 // lower end of primordial stack; reduce ulimit -s value a little bit 1106 // so we won't install guard page on ld.so's data section. 1107 stack_size -= 2 * page_size(); 1108 1109 // 4441425: avoid crash with "unlimited" stack size on SuSE 7.1 or Redhat 1110 // 7.1, in both cases we will get 2G in return value. 1111 // 4466587: glibc 2.2.x compiled w/o "--enable-kernel=2.4.0" (RH 7.0, 1112 // SuSE 7.2, Debian) can not handle alternate signal stack correctly 1113 // for initial thread if its stack size exceeds 6M. Cap it at 2M, 1114 // in case other parts in glibc still assumes 2M max stack size. 1115 // FIXME: alt signal stack is gone, maybe we can relax this constraint? 1116 // Problem still exists RH7.2 (IA64 anyway) but 2MB is a little small 1117 if (stack_size > 2 * K * K IA64_ONLY(*2)) { 1118 stack_size = 2 * K * K IA64_ONLY(*2); 1119 } 1120 // Try to figure out where the stack base (top) is. This is harder. 1121 // 1122 // When an application is started, glibc saves the initial stack pointer in 1123 // a global variable "__libc_stack_end", which is then used by system 1124 // libraries. __libc_stack_end should be pretty close to stack top. The 1125 // variable is available since the very early days. However, because it is 1126 // a private interface, it could disappear in the future. 1127 // 1128 // Linux kernel saves start_stack information in /proc/<pid>/stat. Similar 1129 // to __libc_stack_end, it is very close to stack top, but isn't the real 1130 // stack top. Note that /proc may not exist if VM is running as a chroot 1131 // program, so reading /proc/<pid>/stat could fail. Also the contents of 1132 // /proc/<pid>/stat could change in the future (though unlikely). 1133 // 1134 // We try __libc_stack_end first. If that doesn't work, look for 1135 // /proc/<pid>/stat. If neither of them works, we use current stack pointer 1136 // as a hint, which should work well in most cases. 1137 1138 uintptr_t stack_start; 1139 1140 // try __libc_stack_end first 1141 uintptr_t *p = (uintptr_t *)dlsym(RTLD_DEFAULT, "__libc_stack_end"); 1142 if (p && *p) { 1143 stack_start = *p; 1144 } else { 1145 // see if we can get the start_stack field from /proc/self/stat 1146 FILE *fp; 1147 int pid; 1148 char state; 1149 int ppid; 1150 int pgrp; 1151 int session; 1152 int nr; 1153 int tpgrp; 1154 unsigned long flags; 1155 unsigned long minflt; 1156 unsigned long cminflt; 1157 unsigned long majflt; 1158 unsigned long cmajflt; 1159 unsigned long utime; 1160 unsigned long stime; 1161 long cutime; 1162 long cstime; 1163 long prio; 1164 long nice; 1165 long junk; 1166 long it_real; 1167 uintptr_t start; 1168 uintptr_t vsize; 1169 intptr_t rss; 1170 uintptr_t rsslim; 1171 uintptr_t scodes; 1172 uintptr_t ecode; 1173 int i; 1174 1175 // Figure what the primordial thread stack base is. Code is inspired 1176 // by email from Hans Boehm. /proc/self/stat begins with current pid, 1177 // followed by command name surrounded by parentheses, state, etc. 1178 char stat[2048]; 1179 int statlen; 1180 1181 fp = fopen("/proc/self/stat", "r"); 1182 if (fp) { 1183 statlen = fread(stat, 1, 2047, fp); 1184 stat[statlen] = '\0'; 1185 fclose(fp); 1186 1187 // Skip pid and the command string. Note that we could be dealing with 1188 // weird command names, e.g. user could decide to rename java launcher 1189 // to "java 1.4.2 :)", then the stat file would look like 1190 // 1234 (java 1.4.2 :)) R ... ... 1191 // We don't really need to know the command string, just find the last 1192 // occurrence of ")" and then start parsing from there. See bug 4726580. 1193 char * s = strrchr(stat, ')'); 1194 1195 i = 0; 1196 if (s) { 1197 // Skip blank chars 1198 do { s++; } while (s && isspace(*s)); 1199 1200 #define _UFM UINTX_FORMAT 1201 #define _DFM INTX_FORMAT 1202 1203 // 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 1204 // 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 1205 i = sscanf(s, "%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %ld %ld %ld %ld %ld %ld " _UFM _UFM _DFM _UFM _UFM _UFM _UFM, 1206 &state, // 3 %c 1207 &ppid, // 4 %d 1208 &pgrp, // 5 %d 1209 &session, // 6 %d 1210 &nr, // 7 %d 1211 &tpgrp, // 8 %d 1212 &flags, // 9 %lu 1213 &minflt, // 10 %lu 1214 &cminflt, // 11 %lu 1215 &majflt, // 12 %lu 1216 &cmajflt, // 13 %lu 1217 &utime, // 14 %lu 1218 &stime, // 15 %lu 1219 &cutime, // 16 %ld 1220 &cstime, // 17 %ld 1221 &prio, // 18 %ld 1222 &nice, // 19 %ld 1223 &junk, // 20 %ld 1224 &it_real, // 21 %ld 1225 &start, // 22 UINTX_FORMAT 1226 &vsize, // 23 UINTX_FORMAT 1227 &rss, // 24 INTX_FORMAT 1228 &rsslim, // 25 UINTX_FORMAT 1229 &scodes, // 26 UINTX_FORMAT 1230 &ecode, // 27 UINTX_FORMAT 1231 &stack_start); // 28 UINTX_FORMAT 1232 } 1233 1234 #undef _UFM 1235 #undef _DFM 1236 1237 if (i != 28 - 2) { 1238 assert(false, "Bad conversion from /proc/self/stat"); 1239 // product mode - assume we are the initial thread, good luck in the 1240 // embedded case. 1241 warning("Can't detect initial thread stack location - bad conversion"); 1242 stack_start = (uintptr_t) &rlim; 1243 } 1244 } else { 1245 // For some reason we can't open /proc/self/stat (for example, running on 1246 // FreeBSD with a Linux emulator, or inside chroot), this should work for 1247 // most cases, so don't abort: 1248 warning("Can't detect initial thread stack location - no /proc/self/stat"); 1249 stack_start = (uintptr_t) &rlim; 1250 } 1251 } 1252 1253 // Now we have a pointer (stack_start) very close to the stack top, the 1254 // next thing to do is to figure out the exact location of stack top. We 1255 // can find out the virtual memory area that contains stack_start by 1256 // reading /proc/self/maps, it should be the last vma in /proc/self/maps, 1257 // and its upper limit is the real stack top. (again, this would fail if 1258 // running inside chroot, because /proc may not exist.) 1259 1260 uintptr_t stack_top; 1261 address low, high; 1262 if (find_vma((address)stack_start, &low, &high)) { 1263 // success, "high" is the true stack top. (ignore "low", because initial 1264 // thread stack grows on demand, its real bottom is high - RLIMIT_STACK.) 1265 stack_top = (uintptr_t)high; 1266 } else { 1267 // failed, likely because /proc/self/maps does not exist 1268 warning("Can't detect initial thread stack location - find_vma failed"); 1269 // best effort: stack_start is normally within a few pages below the real 1270 // stack top, use it as stack top, and reduce stack size so we won't put 1271 // guard page outside stack. 1272 stack_top = stack_start; 1273 stack_size -= 16 * page_size(); 1274 } 1275 1276 // stack_top could be partially down the page so align it 1277 stack_top = align_size_up(stack_top, page_size()); 1278 1279 if (max_size && stack_size > max_size) { 1280 _initial_thread_stack_size = max_size; 1281 } else { 1282 _initial_thread_stack_size = stack_size; 1283 } 1284 1285 _initial_thread_stack_size = align_size_down(_initial_thread_stack_size, page_size()); 1286 _initial_thread_stack_bottom = (address)stack_top - _initial_thread_stack_size; 1287 } 1288 1289 //////////////////////////////////////////////////////////////////////////////// 1290 // time support 1291 1292 // Time since start-up in seconds to a fine granularity. 1293 // Used by VMSelfDestructTimer and the MemProfiler. 1294 double os::elapsedTime() { 1295 1296 return ((double)os::elapsed_counter()) / os::elapsed_frequency(); // nanosecond resolution 1297 } 1298 1299 jlong os::elapsed_counter() { 1300 return javaTimeNanos() - initial_time_count; 1301 } 1302 1303 jlong os::elapsed_frequency() { 1304 return NANOSECS_PER_SEC; // nanosecond resolution 1305 } 1306 1307 bool os::supports_vtime() { return true; } 1308 bool os::enable_vtime() { return false; } 1309 bool os::vtime_enabled() { return false; } 1310 1311 double os::elapsedVTime() { 1312 struct rusage usage; 1313 int retval = getrusage(RUSAGE_THREAD, &usage); 1314 if (retval == 0) { 1315 return (double) (usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) + (double) (usage.ru_utime.tv_usec + usage.ru_stime.tv_usec) / (1000 * 1000); 1316 } else { 1317 // better than nothing, but not much 1318 return elapsedTime(); 1319 } 1320 } 1321 1322 jlong os::javaTimeMillis() { 1323 timeval time; 1324 int status = gettimeofday(&time, NULL); 1325 assert(status != -1, "linux error"); 1326 return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000); 1327 } 1328 1329 void os::javaTimeSystemUTC(jlong &seconds, jlong &nanos) { 1330 timeval time; 1331 int status = gettimeofday(&time, NULL); 1332 assert(status != -1, "linux error"); 1333 seconds = jlong(time.tv_sec); 1334 nanos = jlong(time.tv_usec) * 1000; 1335 } 1336 1337 1338 #ifndef CLOCK_MONOTONIC 1339 #define CLOCK_MONOTONIC (1) 1340 #endif 1341 1342 void os::Linux::clock_init() { 1343 // we do dlopen's in this particular order due to bug in linux 1344 // dynamical loader (see 6348968) leading to crash on exit 1345 void* handle = dlopen("librt.so.1", RTLD_LAZY); 1346 if (handle == NULL) { 1347 handle = dlopen("librt.so", RTLD_LAZY); 1348 } 1349 1350 if (handle) { 1351 int (*clock_getres_func)(clockid_t, struct timespec*) = 1352 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_getres"); 1353 int (*clock_gettime_func)(clockid_t, struct timespec*) = 1354 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_gettime"); 1355 if (clock_getres_func && clock_gettime_func) { 1356 // See if monotonic clock is supported by the kernel. Note that some 1357 // early implementations simply return kernel jiffies (updated every 1358 // 1/100 or 1/1000 second). It would be bad to use such a low res clock 1359 // for nano time (though the monotonic property is still nice to have). 1360 // It's fixed in newer kernels, however clock_getres() still returns 1361 // 1/HZ. We check if clock_getres() works, but will ignore its reported 1362 // resolution for now. Hopefully as people move to new kernels, this 1363 // won't be a problem. 1364 struct timespec res; 1365 struct timespec tp; 1366 if (clock_getres_func (CLOCK_MONOTONIC, &res) == 0 && 1367 clock_gettime_func(CLOCK_MONOTONIC, &tp) == 0) { 1368 // yes, monotonic clock is supported 1369 _clock_gettime = clock_gettime_func; 1370 return; 1371 } else { 1372 // close librt if there is no monotonic clock 1373 dlclose(handle); 1374 } 1375 } 1376 } 1377 warning("No monotonic clock was available - timed services may " \ 1378 "be adversely affected if the time-of-day clock changes"); 1379 } 1380 1381 #ifndef SYS_clock_getres 1382 #if defined(IA32) || defined(AMD64) 1383 #define SYS_clock_getres IA32_ONLY(266) AMD64_ONLY(229) 1384 #define sys_clock_getres(x,y) ::syscall(SYS_clock_getres, x, y) 1385 #else 1386 #warning "SYS_clock_getres not defined for this platform, disabling fast_thread_cpu_time" 1387 #define sys_clock_getres(x,y) -1 1388 #endif 1389 #else 1390 #define sys_clock_getres(x,y) ::syscall(SYS_clock_getres, x, y) 1391 #endif 1392 1393 void os::Linux::fast_thread_clock_init() { 1394 if (!UseLinuxPosixThreadCPUClocks) { 1395 return; 1396 } 1397 clockid_t clockid; 1398 struct timespec tp; 1399 int (*pthread_getcpuclockid_func)(pthread_t, clockid_t *) = 1400 (int(*)(pthread_t, clockid_t *)) dlsym(RTLD_DEFAULT, "pthread_getcpuclockid"); 1401 1402 // Switch to using fast clocks for thread cpu time if 1403 // the sys_clock_getres() returns 0 error code. 1404 // Note, that some kernels may support the current thread 1405 // clock (CLOCK_THREAD_CPUTIME_ID) but not the clocks 1406 // returned by the pthread_getcpuclockid(). 1407 // If the fast Posix clocks are supported then the sys_clock_getres() 1408 // must return at least tp.tv_sec == 0 which means a resolution 1409 // better than 1 sec. This is extra check for reliability. 1410 1411 if (pthread_getcpuclockid_func && 1412 pthread_getcpuclockid_func(_main_thread, &clockid) == 0 && 1413 sys_clock_getres(clockid, &tp) == 0 && tp.tv_sec == 0) { 1414 _supports_fast_thread_cpu_time = true; 1415 _pthread_getcpuclockid = pthread_getcpuclockid_func; 1416 } 1417 } 1418 1419 jlong os::javaTimeNanos() { 1420 if (os::supports_monotonic_clock()) { 1421 struct timespec tp; 1422 int status = Linux::clock_gettime(CLOCK_MONOTONIC, &tp); 1423 assert(status == 0, "gettime error"); 1424 jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec); 1425 return result; 1426 } else { 1427 timeval time; 1428 int status = gettimeofday(&time, NULL); 1429 assert(status != -1, "linux error"); 1430 jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec); 1431 return 1000 * usecs; 1432 } 1433 } 1434 1435 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) { 1436 if (os::supports_monotonic_clock()) { 1437 info_ptr->max_value = ALL_64_BITS; 1438 1439 // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past 1440 info_ptr->may_skip_backward = false; // not subject to resetting or drifting 1441 info_ptr->may_skip_forward = false; // not subject to resetting or drifting 1442 } else { 1443 // gettimeofday - based on time in seconds since the Epoch thus does not wrap 1444 info_ptr->max_value = ALL_64_BITS; 1445 1446 // gettimeofday is a real time clock so it skips 1447 info_ptr->may_skip_backward = true; 1448 info_ptr->may_skip_forward = true; 1449 } 1450 1451 info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time 1452 } 1453 1454 // Return the real, user, and system times in seconds from an 1455 // arbitrary fixed point in the past. 1456 bool os::getTimesSecs(double* process_real_time, 1457 double* process_user_time, 1458 double* process_system_time) { 1459 struct tms ticks; 1460 clock_t real_ticks = times(&ticks); 1461 1462 if (real_ticks == (clock_t) (-1)) { 1463 return false; 1464 } else { 1465 double ticks_per_second = (double) clock_tics_per_sec; 1466 *process_user_time = ((double) ticks.tms_utime) / ticks_per_second; 1467 *process_system_time = ((double) ticks.tms_stime) / ticks_per_second; 1468 *process_real_time = ((double) real_ticks) / ticks_per_second; 1469 1470 return true; 1471 } 1472 } 1473 1474 1475 char * os::local_time_string(char *buf, size_t buflen) { 1476 struct tm t; 1477 time_t long_time; 1478 time(&long_time); 1479 localtime_r(&long_time, &t); 1480 jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d", 1481 t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, 1482 t.tm_hour, t.tm_min, t.tm_sec); 1483 return buf; 1484 } 1485 1486 struct tm* os::localtime_pd(const time_t* clock, struct tm* res) { 1487 return localtime_r(clock, res); 1488 } 1489 1490 //////////////////////////////////////////////////////////////////////////////// 1491 // runtime exit support 1492 1493 // Note: os::shutdown() might be called very early during initialization, or 1494 // called from signal handler. Before adding something to os::shutdown(), make 1495 // sure it is async-safe and can handle partially initialized VM. 1496 void os::shutdown() { 1497 1498 // allow PerfMemory to attempt cleanup of any persistent resources 1499 perfMemory_exit(); 1500 1501 // needs to remove object in file system 1502 AttachListener::abort(); 1503 1504 // flush buffered output, finish log files 1505 ostream_abort(); 1506 1507 // Check for abort hook 1508 abort_hook_t abort_hook = Arguments::abort_hook(); 1509 if (abort_hook != NULL) { 1510 abort_hook(); 1511 } 1512 1513 } 1514 1515 // Note: os::abort() might be called very early during initialization, or 1516 // called from signal handler. Before adding something to os::abort(), make 1517 // sure it is async-safe and can handle partially initialized VM. 1518 void os::abort(bool dump_core) { 1519 os::shutdown(); 1520 if (dump_core) { 1521 #ifndef PRODUCT 1522 fdStream out(defaultStream::output_fd()); 1523 out.print_raw("Current thread is "); 1524 char buf[16]; 1525 jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id()); 1526 out.print_raw_cr(buf); 1527 out.print_raw_cr("Dumping core ..."); 1528 #endif 1529 ::abort(); // dump core 1530 } 1531 1532 ::exit(1); 1533 } 1534 1535 // Die immediately, no exit hook, no abort hook, no cleanup. 1536 void os::die() { 1537 // _exit() on LinuxThreads only kills current thread 1538 ::abort(); 1539 } 1540 1541 1542 // This method is a copy of JDK's sysGetLastErrorString 1543 // from src/solaris/hpi/src/system_md.c 1544 1545 size_t os::lasterror(char *buf, size_t len) { 1546 if (errno == 0) return 0; 1547 1548 const char *s = ::strerror(errno); 1549 size_t n = ::strlen(s); 1550 if (n >= len) { 1551 n = len - 1; 1552 } 1553 ::strncpy(buf, s, n); 1554 buf[n] = '\0'; 1555 return n; 1556 } 1557 1558 intx os::current_thread_id() { return (intx)pthread_self(); } 1559 int os::current_process_id() { 1560 1561 // Under the old linux thread library, linux gives each thread 1562 // its own process id. Because of this each thread will return 1563 // a different pid if this method were to return the result 1564 // of getpid(2). Linux provides no api that returns the pid 1565 // of the launcher thread for the vm. This implementation 1566 // returns a unique pid, the pid of the launcher thread 1567 // that starts the vm 'process'. 1568 1569 // Under the NPTL, getpid() returns the same pid as the 1570 // launcher thread rather than a unique pid per thread. 1571 // Use gettid() if you want the old pre NPTL behaviour. 1572 1573 // if you are looking for the result of a call to getpid() that 1574 // returns a unique pid for the calling thread, then look at the 1575 // OSThread::thread_id() method in osThread_linux.hpp file 1576 1577 return (int)(_initial_pid ? _initial_pid : getpid()); 1578 } 1579 1580 // DLL functions 1581 1582 const char* os::dll_file_extension() { return ".so"; } 1583 1584 // This must be hard coded because it's the system's temporary 1585 // directory not the java application's temp directory, ala java.io.tmpdir. 1586 const char* os::get_temp_directory() { return "/tmp"; } 1587 1588 static bool file_exists(const char* filename) { 1589 struct stat statbuf; 1590 if (filename == NULL || strlen(filename) == 0) { 1591 return false; 1592 } 1593 return os::stat(filename, &statbuf) == 0; 1594 } 1595 1596 bool os::dll_build_name(char* buffer, size_t buflen, 1597 const char* pname, const char* fname) { 1598 bool retval = false; 1599 // Copied from libhpi 1600 const size_t pnamelen = pname ? strlen(pname) : 0; 1601 1602 // Return error on buffer overflow. 1603 if (pnamelen + strlen(fname) + 10 > (size_t) buflen) { 1604 return retval; 1605 } 1606 1607 if (pnamelen == 0) { 1608 snprintf(buffer, buflen, "lib%s.so", fname); 1609 retval = true; 1610 } else if (strchr(pname, *os::path_separator()) != NULL) { 1611 int n; 1612 char** pelements = split_path(pname, &n); 1613 if (pelements == NULL) { 1614 return false; 1615 } 1616 for (int i = 0; i < n; i++) { 1617 // Really shouldn't be NULL, but check can't hurt 1618 if (pelements[i] == NULL || strlen(pelements[i]) == 0) { 1619 continue; // skip the empty path values 1620 } 1621 snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname); 1622 if (file_exists(buffer)) { 1623 retval = true; 1624 break; 1625 } 1626 } 1627 // release the storage 1628 for (int i = 0; i < n; i++) { 1629 if (pelements[i] != NULL) { 1630 FREE_C_HEAP_ARRAY(char, pelements[i]); 1631 } 1632 } 1633 if (pelements != NULL) { 1634 FREE_C_HEAP_ARRAY(char*, pelements); 1635 } 1636 } else { 1637 snprintf(buffer, buflen, "%s/lib%s.so", pname, fname); 1638 retval = true; 1639 } 1640 return retval; 1641 } 1642 1643 // check if addr is inside libjvm.so 1644 bool os::address_is_in_vm(address addr) { 1645 static address libjvm_base_addr; 1646 Dl_info dlinfo; 1647 1648 if (libjvm_base_addr == NULL) { 1649 if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) { 1650 libjvm_base_addr = (address)dlinfo.dli_fbase; 1651 } 1652 assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm"); 1653 } 1654 1655 if (dladdr((void *)addr, &dlinfo) != 0) { 1656 if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true; 1657 } 1658 1659 return false; 1660 } 1661 1662 bool os::dll_address_to_function_name(address addr, char *buf, 1663 int buflen, int *offset) { 1664 // buf is not optional, but offset is optional 1665 assert(buf != NULL, "sanity check"); 1666 1667 Dl_info dlinfo; 1668 1669 if (dladdr((void*)addr, &dlinfo) != 0) { 1670 // see if we have a matching symbol 1671 if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) { 1672 if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) { 1673 jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname); 1674 } 1675 if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr; 1676 return true; 1677 } 1678 // no matching symbol so try for just file info 1679 if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) { 1680 if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase), 1681 buf, buflen, offset, dlinfo.dli_fname)) { 1682 return true; 1683 } 1684 } 1685 } 1686 1687 buf[0] = '\0'; 1688 if (offset != NULL) *offset = -1; 1689 return false; 1690 } 1691 1692 struct _address_to_library_name { 1693 address addr; // input : memory address 1694 size_t buflen; // size of fname 1695 char* fname; // output: library name 1696 address base; // library base addr 1697 }; 1698 1699 static int address_to_library_name_callback(struct dl_phdr_info *info, 1700 size_t size, void *data) { 1701 int i; 1702 bool found = false; 1703 address libbase = NULL; 1704 struct _address_to_library_name * d = (struct _address_to_library_name *)data; 1705 1706 // iterate through all loadable segments 1707 for (i = 0; i < info->dlpi_phnum; i++) { 1708 address segbase = (address)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr); 1709 if (info->dlpi_phdr[i].p_type == PT_LOAD) { 1710 // base address of a library is the lowest address of its loaded 1711 // segments. 1712 if (libbase == NULL || libbase > segbase) { 1713 libbase = segbase; 1714 } 1715 // see if 'addr' is within current segment 1716 if (segbase <= d->addr && 1717 d->addr < segbase + info->dlpi_phdr[i].p_memsz) { 1718 found = true; 1719 } 1720 } 1721 } 1722 1723 // dlpi_name is NULL or empty if the ELF file is executable, return 0 1724 // so dll_address_to_library_name() can fall through to use dladdr() which 1725 // can figure out executable name from argv[0]. 1726 if (found && info->dlpi_name && info->dlpi_name[0]) { 1727 d->base = libbase; 1728 if (d->fname) { 1729 jio_snprintf(d->fname, d->buflen, "%s", info->dlpi_name); 1730 } 1731 return 1; 1732 } 1733 return 0; 1734 } 1735 1736 bool os::dll_address_to_library_name(address addr, char* buf, 1737 int buflen, int* offset) { 1738 // buf is not optional, but offset is optional 1739 assert(buf != NULL, "sanity check"); 1740 1741 Dl_info dlinfo; 1742 struct _address_to_library_name data; 1743 1744 // There is a bug in old glibc dladdr() implementation that it could resolve 1745 // to wrong library name if the .so file has a base address != NULL. Here 1746 // we iterate through the program headers of all loaded libraries to find 1747 // out which library 'addr' really belongs to. This workaround can be 1748 // removed once the minimum requirement for glibc is moved to 2.3.x. 1749 data.addr = addr; 1750 data.fname = buf; 1751 data.buflen = buflen; 1752 data.base = NULL; 1753 int rslt = dl_iterate_phdr(address_to_library_name_callback, (void *)&data); 1754 1755 if (rslt) { 1756 // buf already contains library name 1757 if (offset) *offset = addr - data.base; 1758 return true; 1759 } 1760 if (dladdr((void*)addr, &dlinfo) != 0) { 1761 if (dlinfo.dli_fname != NULL) { 1762 jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname); 1763 } 1764 if (dlinfo.dli_fbase != NULL && offset != NULL) { 1765 *offset = addr - (address)dlinfo.dli_fbase; 1766 } 1767 return true; 1768 } 1769 1770 buf[0] = '\0'; 1771 if (offset) *offset = -1; 1772 return false; 1773 } 1774 1775 // Loads .dll/.so and 1776 // in case of error it checks if .dll/.so was built for the 1777 // same architecture as Hotspot is running on 1778 1779 1780 // Remember the stack's state. The Linux dynamic linker will change 1781 // the stack to 'executable' at most once, so we must safepoint only once. 1782 bool os::Linux::_stack_is_executable = false; 1783 1784 // VM operation that loads a library. This is necessary if stack protection 1785 // of the Java stacks can be lost during loading the library. If we 1786 // do not stop the Java threads, they can stack overflow before the stacks 1787 // are protected again. 1788 class VM_LinuxDllLoad: public VM_Operation { 1789 private: 1790 const char *_filename; 1791 char *_ebuf; 1792 int _ebuflen; 1793 void *_lib; 1794 public: 1795 VM_LinuxDllLoad(const char *fn, char *ebuf, int ebuflen) : 1796 _filename(fn), _ebuf(ebuf), _ebuflen(ebuflen), _lib(NULL) {} 1797 VMOp_Type type() const { return VMOp_LinuxDllLoad; } 1798 void doit() { 1799 _lib = os::Linux::dll_load_in_vmthread(_filename, _ebuf, _ebuflen); 1800 os::Linux::_stack_is_executable = true; 1801 } 1802 void* loaded_library() { return _lib; } 1803 }; 1804 1805 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) { 1806 void * result = NULL; 1807 bool load_attempted = false; 1808 1809 // Check whether the library to load might change execution rights 1810 // of the stack. If they are changed, the protection of the stack 1811 // guard pages will be lost. We need a safepoint to fix this. 1812 // 1813 // See Linux man page execstack(8) for more info. 1814 if (os::uses_stack_guard_pages() && !os::Linux::_stack_is_executable) { 1815 ElfFile ef(filename); 1816 if (!ef.specifies_noexecstack()) { 1817 if (!is_init_completed()) { 1818 os::Linux::_stack_is_executable = true; 1819 // This is OK - No Java threads have been created yet, and hence no 1820 // stack guard pages to fix. 1821 // 1822 // This should happen only when you are building JDK7 using a very 1823 // old version of JDK6 (e.g., with JPRT) and running test_gamma. 1824 // 1825 // Dynamic loader will make all stacks executable after 1826 // this function returns, and will not do that again. 1827 assert(Threads::first() == NULL, "no Java threads should exist yet."); 1828 } else { 1829 warning("You have loaded library %s which might have disabled stack guard. " 1830 "The VM will try to fix the stack guard now.\n" 1831 "It's highly recommended that you fix the library with " 1832 "'execstack -c <libfile>', or link it with '-z noexecstack'.", 1833 filename); 1834 1835 assert(Thread::current()->is_Java_thread(), "must be Java thread"); 1836 JavaThread *jt = JavaThread::current(); 1837 if (jt->thread_state() != _thread_in_native) { 1838 // This happens when a compiler thread tries to load a hsdis-<arch>.so file 1839 // that requires ExecStack. Cannot enter safe point. Let's give up. 1840 warning("Unable to fix stack guard. Giving up."); 1841 } else { 1842 if (!LoadExecStackDllInVMThread) { 1843 // This is for the case where the DLL has an static 1844 // constructor function that executes JNI code. We cannot 1845 // load such DLLs in the VMThread. 1846 result = os::Linux::dlopen_helper(filename, ebuf, ebuflen); 1847 } 1848 1849 ThreadInVMfromNative tiv(jt); 1850 debug_only(VMNativeEntryWrapper vew;) 1851 1852 VM_LinuxDllLoad op(filename, ebuf, ebuflen); 1853 VMThread::execute(&op); 1854 if (LoadExecStackDllInVMThread) { 1855 result = op.loaded_library(); 1856 } 1857 load_attempted = true; 1858 } 1859 } 1860 } 1861 } 1862 1863 if (!load_attempted) { 1864 result = os::Linux::dlopen_helper(filename, ebuf, ebuflen); 1865 } 1866 1867 if (result != NULL) { 1868 // Successful loading 1869 return result; 1870 } 1871 1872 Elf32_Ehdr elf_head; 1873 int diag_msg_max_length=ebuflen-strlen(ebuf); 1874 char* diag_msg_buf=ebuf+strlen(ebuf); 1875 1876 if (diag_msg_max_length==0) { 1877 // No more space in ebuf for additional diagnostics message 1878 return NULL; 1879 } 1880 1881 1882 int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK); 1883 1884 if (file_descriptor < 0) { 1885 // Can't open library, report dlerror() message 1886 return NULL; 1887 } 1888 1889 bool failed_to_read_elf_head= 1890 (sizeof(elf_head)!= 1891 (::read(file_descriptor, &elf_head,sizeof(elf_head)))); 1892 1893 ::close(file_descriptor); 1894 if (failed_to_read_elf_head) { 1895 // file i/o error - report dlerror() msg 1896 return NULL; 1897 } 1898 1899 typedef struct { 1900 Elf32_Half code; // Actual value as defined in elf.h 1901 Elf32_Half compat_class; // Compatibility of archs at VM's sense 1902 char elf_class; // 32 or 64 bit 1903 char endianess; // MSB or LSB 1904 char* name; // String representation 1905 } arch_t; 1906 1907 #ifndef EM_486 1908 #define EM_486 6 /* Intel 80486 */ 1909 #endif 1910 1911 static const arch_t arch_array[]={ 1912 {EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, 1913 {EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, 1914 {EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"}, 1915 {EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"}, 1916 {EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, 1917 {EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, 1918 {EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"}, 1919 {EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"}, 1920 #if defined(VM_LITTLE_ENDIAN) 1921 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2LSB, (char*)"Power PC 64"}, 1922 #else 1923 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"}, 1924 #endif 1925 {EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM"}, 1926 {EM_S390, EM_S390, ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"}, 1927 {EM_ALPHA, EM_ALPHA, ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"}, 1928 {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"}, 1929 {EM_MIPS, EM_MIPS, ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"}, 1930 {EM_PARISC, EM_PARISC, ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"}, 1931 {EM_68K, EM_68K, ELFCLASS32, ELFDATA2MSB, (char*)"M68k"} 1932 }; 1933 1934 #if (defined IA32) 1935 static Elf32_Half running_arch_code=EM_386; 1936 #elif (defined AMD64) 1937 static Elf32_Half running_arch_code=EM_X86_64; 1938 #elif (defined IA64) 1939 static Elf32_Half running_arch_code=EM_IA_64; 1940 #elif (defined __sparc) && (defined _LP64) 1941 static Elf32_Half running_arch_code=EM_SPARCV9; 1942 #elif (defined __sparc) && (!defined _LP64) 1943 static Elf32_Half running_arch_code=EM_SPARC; 1944 #elif (defined __powerpc64__) 1945 static Elf32_Half running_arch_code=EM_PPC64; 1946 #elif (defined __powerpc__) 1947 static Elf32_Half running_arch_code=EM_PPC; 1948 #elif (defined ARM) 1949 static Elf32_Half running_arch_code=EM_ARM; 1950 #elif (defined S390) 1951 static Elf32_Half running_arch_code=EM_S390; 1952 #elif (defined ALPHA) 1953 static Elf32_Half running_arch_code=EM_ALPHA; 1954 #elif (defined MIPSEL) 1955 static Elf32_Half running_arch_code=EM_MIPS_RS3_LE; 1956 #elif (defined PARISC) 1957 static Elf32_Half running_arch_code=EM_PARISC; 1958 #elif (defined MIPS) 1959 static Elf32_Half running_arch_code=EM_MIPS; 1960 #elif (defined M68K) 1961 static Elf32_Half running_arch_code=EM_68K; 1962 #else 1963 #error Method os::dll_load requires that one of following is defined:\ 1964 IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K 1965 #endif 1966 1967 // Identify compatability class for VM's architecture and library's architecture 1968 // Obtain string descriptions for architectures 1969 1970 arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL}; 1971 int running_arch_index=-1; 1972 1973 for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) { 1974 if (running_arch_code == arch_array[i].code) { 1975 running_arch_index = i; 1976 } 1977 if (lib_arch.code == arch_array[i].code) { 1978 lib_arch.compat_class = arch_array[i].compat_class; 1979 lib_arch.name = arch_array[i].name; 1980 } 1981 } 1982 1983 assert(running_arch_index != -1, 1984 "Didn't find running architecture code (running_arch_code) in arch_array"); 1985 if (running_arch_index == -1) { 1986 // Even though running architecture detection failed 1987 // we may still continue with reporting dlerror() message 1988 return NULL; 1989 } 1990 1991 if (lib_arch.endianess != arch_array[running_arch_index].endianess) { 1992 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)"); 1993 return NULL; 1994 } 1995 1996 #ifndef S390 1997 if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) { 1998 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)"); 1999 return NULL; 2000 } 2001 #endif // !S390 2002 2003 if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) { 2004 if (lib_arch.name!=NULL) { 2005 ::snprintf(diag_msg_buf, diag_msg_max_length-1, 2006 " (Possible cause: can't load %s-bit .so on a %s-bit platform)", 2007 lib_arch.name, arch_array[running_arch_index].name); 2008 } else { 2009 ::snprintf(diag_msg_buf, diag_msg_max_length-1, 2010 " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)", 2011 lib_arch.code, 2012 arch_array[running_arch_index].name); 2013 } 2014 } 2015 2016 return NULL; 2017 } 2018 2019 void * os::Linux::dlopen_helper(const char *filename, char *ebuf, 2020 int ebuflen) { 2021 void * result = ::dlopen(filename, RTLD_LAZY); 2022 if (result == NULL) { 2023 ::strncpy(ebuf, ::dlerror(), ebuflen - 1); 2024 ebuf[ebuflen-1] = '\0'; 2025 } 2026 return result; 2027 } 2028 2029 void * os::Linux::dll_load_in_vmthread(const char *filename, char *ebuf, 2030 int ebuflen) { 2031 void * result = NULL; 2032 if (LoadExecStackDllInVMThread) { 2033 result = dlopen_helper(filename, ebuf, ebuflen); 2034 } 2035 2036 // Since 7019808, libjvm.so is linked with -noexecstack. If the VM loads a 2037 // library that requires an executable stack, or which does not have this 2038 // stack attribute set, dlopen changes the stack attribute to executable. The 2039 // read protection of the guard pages gets lost. 2040 // 2041 // Need to check _stack_is_executable again as multiple VM_LinuxDllLoad 2042 // may have been queued at the same time. 2043 2044 if (!_stack_is_executable) { 2045 JavaThread *jt = Threads::first(); 2046 2047 while (jt) { 2048 if (!jt->stack_guard_zone_unused() && // Stack not yet fully initialized 2049 jt->stack_yellow_zone_enabled()) { // No pending stack overflow exceptions 2050 if (!os::guard_memory((char *) jt->stack_red_zone_base() - jt->stack_red_zone_size(), 2051 jt->stack_yellow_zone_size() + jt->stack_red_zone_size())) { 2052 warning("Attempt to reguard stack yellow zone failed."); 2053 } 2054 } 2055 jt = jt->next(); 2056 } 2057 } 2058 2059 return result; 2060 } 2061 2062 // glibc-2.0 libdl is not MT safe. If you are building with any glibc, 2063 // chances are you might want to run the generated bits against glibc-2.0 2064 // libdl.so, so always use locking for any version of glibc. 2065 // 2066 void* os::dll_lookup(void* handle, const char* name) { 2067 pthread_mutex_lock(&dl_mutex); 2068 void* res = dlsym(handle, name); 2069 pthread_mutex_unlock(&dl_mutex); 2070 return res; 2071 } 2072 2073 void* os::get_default_process_handle() { 2074 return (void*)::dlopen(NULL, RTLD_LAZY); 2075 } 2076 2077 static bool _print_ascii_file(const char* filename, outputStream* st) { 2078 int fd = ::open(filename, O_RDONLY); 2079 if (fd == -1) { 2080 return false; 2081 } 2082 2083 char buf[32]; 2084 int bytes; 2085 while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) { 2086 st->print_raw(buf, bytes); 2087 } 2088 2089 ::close(fd); 2090 2091 return true; 2092 } 2093 2094 void os::print_dll_info(outputStream *st) { 2095 st->print_cr("Dynamic libraries:"); 2096 2097 char fname[32]; 2098 pid_t pid = os::Linux::gettid(); 2099 2100 jio_snprintf(fname, sizeof(fname), "/proc/%d/maps", pid); 2101 2102 if (!_print_ascii_file(fname, st)) { 2103 st->print("Can not get library information for pid = %d\n", pid); 2104 } 2105 } 2106 2107 int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *param) { 2108 FILE *procmapsFile = NULL; 2109 2110 // Open the procfs maps file for the current process 2111 if ((procmapsFile = fopen("/proc/self/maps", "r")) != NULL) { 2112 // Allocate PATH_MAX for file name plus a reasonable size for other fields. 2113 char line[PATH_MAX + 100]; 2114 2115 // Read line by line from 'file' 2116 while (fgets(line, sizeof(line), procmapsFile) != NULL) { 2117 u8 base, top, offset, inode; 2118 char permissions[5]; 2119 char device[6]; 2120 char name[PATH_MAX + 1]; 2121 2122 // Parse fields from line 2123 sscanf(line, "%lx-%lx %4s %lx %5s %ld %s", &base, &top, permissions, &offset, device, &inode, name); 2124 2125 // Filter by device id '00:00' so that we only get file system mapped files. 2126 if (strcmp(device, "00:00") != 0) { 2127 2128 // Call callback with the fields of interest 2129 if(callback(name, (address)base, (address)top, param)) { 2130 // Oops abort, callback aborted 2131 fclose(procmapsFile); 2132 return 1; 2133 } 2134 } 2135 } 2136 fclose(procmapsFile); 2137 } 2138 return 0; 2139 } 2140 2141 void os::print_os_info_brief(outputStream* st) { 2142 os::Linux::print_distro_info(st); 2143 2144 os::Posix::print_uname_info(st); 2145 2146 os::Linux::print_libversion_info(st); 2147 2148 } 2149 2150 void os::print_os_info(outputStream* st) { 2151 st->print("OS:"); 2152 2153 os::Linux::print_distro_info(st); 2154 2155 os::Posix::print_uname_info(st); 2156 2157 // Print warning if unsafe chroot environment detected 2158 if (unsafe_chroot_detected) { 2159 st->print("WARNING!! "); 2160 st->print_cr("%s", unstable_chroot_error); 2161 } 2162 2163 os::Linux::print_libversion_info(st); 2164 2165 os::Posix::print_rlimit_info(st); 2166 2167 os::Posix::print_load_average(st); 2168 2169 os::Linux::print_full_memory_info(st); 2170 } 2171 2172 // Try to identify popular distros. 2173 // Most Linux distributions have a /etc/XXX-release file, which contains 2174 // the OS version string. Newer Linux distributions have a /etc/lsb-release 2175 // file that also contains the OS version string. Some have more than one 2176 // /etc/XXX-release file (e.g. Mandrake has both /etc/mandrake-release and 2177 // /etc/redhat-release.), so the order is important. 2178 // Any Linux that is based on Redhat (i.e. Oracle, Mandrake, Sun JDS...) have 2179 // their own specific XXX-release file as well as a redhat-release file. 2180 // Because of this the XXX-release file needs to be searched for before the 2181 // redhat-release file. 2182 // Since Red Hat has a lsb-release file that is not very descriptive the 2183 // search for redhat-release needs to be before lsb-release. 2184 // Since the lsb-release file is the new standard it needs to be searched 2185 // before the older style release files. 2186 // Searching system-release (Red Hat) and os-release (other Linuxes) are a 2187 // next to last resort. The os-release file is a new standard that contains 2188 // distribution information and the system-release file seems to be an old 2189 // standard that has been replaced by the lsb-release and os-release files. 2190 // Searching for the debian_version file is the last resort. It contains 2191 // an informative string like "6.0.6" or "wheezy/sid". Because of this 2192 // "Debian " is printed before the contents of the debian_version file. 2193 void os::Linux::print_distro_info(outputStream* st) { 2194 if (!_print_ascii_file("/etc/oracle-release", st) && 2195 !_print_ascii_file("/etc/mandriva-release", st) && 2196 !_print_ascii_file("/etc/mandrake-release", st) && 2197 !_print_ascii_file("/etc/sun-release", st) && 2198 !_print_ascii_file("/etc/redhat-release", st) && 2199 !_print_ascii_file("/etc/lsb-release", st) && 2200 !_print_ascii_file("/etc/SuSE-release", st) && 2201 !_print_ascii_file("/etc/turbolinux-release", st) && 2202 !_print_ascii_file("/etc/gentoo-release", st) && 2203 !_print_ascii_file("/etc/ltib-release", st) && 2204 !_print_ascii_file("/etc/angstrom-version", st) && 2205 !_print_ascii_file("/etc/system-release", st) && 2206 !_print_ascii_file("/etc/os-release", st)) { 2207 2208 if (file_exists("/etc/debian_version")) { 2209 st->print("Debian "); 2210 _print_ascii_file("/etc/debian_version", st); 2211 } else { 2212 st->print("Linux"); 2213 } 2214 } 2215 st->cr(); 2216 } 2217 2218 void os::Linux::print_libversion_info(outputStream* st) { 2219 // libc, pthread 2220 st->print("libc:"); 2221 st->print("%s ", os::Linux::glibc_version()); 2222 st->print("%s ", os::Linux::libpthread_version()); 2223 if (os::Linux::is_LinuxThreads()) { 2224 st->print("(%s stack)", os::Linux::is_floating_stack() ? "floating" : "fixed"); 2225 } 2226 st->cr(); 2227 } 2228 2229 void os::Linux::print_full_memory_info(outputStream* st) { 2230 st->print("\n/proc/meminfo:\n"); 2231 _print_ascii_file("/proc/meminfo", st); 2232 st->cr(); 2233 } 2234 2235 void os::print_memory_info(outputStream* st) { 2236 2237 st->print("Memory:"); 2238 st->print(" %dk page", os::vm_page_size()>>10); 2239 2240 // values in struct sysinfo are "unsigned long" 2241 struct sysinfo si; 2242 sysinfo(&si); 2243 2244 st->print(", physical " UINT64_FORMAT "k", 2245 os::physical_memory() >> 10); 2246 st->print("(" UINT64_FORMAT "k free)", 2247 os::available_memory() >> 10); 2248 st->print(", swap " UINT64_FORMAT "k", 2249 ((jlong)si.totalswap * si.mem_unit) >> 10); 2250 st->print("(" UINT64_FORMAT "k free)", 2251 ((jlong)si.freeswap * si.mem_unit) >> 10); 2252 st->cr(); 2253 } 2254 2255 void os::pd_print_cpu_info(outputStream* st) { 2256 st->print("\n/proc/cpuinfo:\n"); 2257 if (!_print_ascii_file("/proc/cpuinfo", st)) { 2258 st->print(" <Not Available>"); 2259 } 2260 st->cr(); 2261 } 2262 2263 void os::print_siginfo(outputStream* st, void* siginfo) { 2264 const siginfo_t* si = (const siginfo_t*)siginfo; 2265 2266 os::Posix::print_siginfo_brief(st, si); 2267 #if INCLUDE_CDS 2268 if (si && (si->si_signo == SIGBUS || si->si_signo == SIGSEGV) && 2269 UseSharedSpaces) { 2270 FileMapInfo* mapinfo = FileMapInfo::current_info(); 2271 if (mapinfo->is_in_shared_space(si->si_addr)) { 2272 st->print("\n\nError accessing class data sharing archive." \ 2273 " Mapped file inaccessible during execution, " \ 2274 " possible disk/network problem."); 2275 } 2276 } 2277 #endif 2278 st->cr(); 2279 } 2280 2281 2282 static void print_signal_handler(outputStream* st, int sig, 2283 char* buf, size_t buflen); 2284 2285 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) { 2286 st->print_cr("Signal Handlers:"); 2287 print_signal_handler(st, SIGSEGV, buf, buflen); 2288 print_signal_handler(st, SIGBUS , buf, buflen); 2289 print_signal_handler(st, SIGFPE , buf, buflen); 2290 print_signal_handler(st, SIGPIPE, buf, buflen); 2291 print_signal_handler(st, SIGXFSZ, buf, buflen); 2292 print_signal_handler(st, SIGILL , buf, buflen); 2293 print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen); 2294 print_signal_handler(st, SR_signum, buf, buflen); 2295 print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen); 2296 print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen); 2297 print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen); 2298 print_signal_handler(st, BREAK_SIGNAL, buf, buflen); 2299 #if defined(PPC64) 2300 print_signal_handler(st, SIGTRAP, buf, buflen); 2301 #endif 2302 } 2303 2304 static char saved_jvm_path[MAXPATHLEN] = {0}; 2305 2306 // Find the full path to the current module, libjvm.so 2307 void os::jvm_path(char *buf, jint buflen) { 2308 // Error checking. 2309 if (buflen < MAXPATHLEN) { 2310 assert(false, "must use a large-enough buffer"); 2311 buf[0] = '\0'; 2312 return; 2313 } 2314 // Lazy resolve the path to current module. 2315 if (saved_jvm_path[0] != 0) { 2316 strcpy(buf, saved_jvm_path); 2317 return; 2318 } 2319 2320 char dli_fname[MAXPATHLEN]; 2321 bool ret = dll_address_to_library_name( 2322 CAST_FROM_FN_PTR(address, os::jvm_path), 2323 dli_fname, sizeof(dli_fname), NULL); 2324 assert(ret, "cannot locate libjvm"); 2325 char *rp = NULL; 2326 if (ret && dli_fname[0] != '\0') { 2327 rp = realpath(dli_fname, buf); 2328 } 2329 if (rp == NULL) { 2330 return; 2331 } 2332 2333 if (Arguments::sun_java_launcher_is_altjvm()) { 2334 // Support for the java launcher's '-XXaltjvm=<path>' option. Typical 2335 // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so". 2336 // If "/jre/lib/" appears at the right place in the string, then 2337 // assume we are installed in a JDK and we're done. Otherwise, check 2338 // for a JAVA_HOME environment variable and fix up the path so it 2339 // looks like libjvm.so is installed there (append a fake suffix 2340 // hotspot/libjvm.so). 2341 const char *p = buf + strlen(buf) - 1; 2342 for (int count = 0; p > buf && count < 5; ++count) { 2343 for (--p; p > buf && *p != '/'; --p) 2344 /* empty */ ; 2345 } 2346 2347 if (strncmp(p, "/jre/lib/", 9) != 0) { 2348 // Look for JAVA_HOME in the environment. 2349 char* java_home_var = ::getenv("JAVA_HOME"); 2350 if (java_home_var != NULL && java_home_var[0] != 0) { 2351 char* jrelib_p; 2352 int len; 2353 2354 // Check the current module name "libjvm.so". 2355 p = strrchr(buf, '/'); 2356 if (p == NULL) { 2357 return; 2358 } 2359 assert(strstr(p, "/libjvm") == p, "invalid library name"); 2360 2361 rp = realpath(java_home_var, buf); 2362 if (rp == NULL) { 2363 return; 2364 } 2365 2366 // determine if this is a legacy image or modules image 2367 // modules image doesn't have "jre" subdirectory 2368 len = strlen(buf); 2369 assert(len < buflen, "Ran out of buffer room"); 2370 jrelib_p = buf + len; 2371 snprintf(jrelib_p, buflen-len, "/jre/lib/%s", cpu_arch); 2372 if (0 != access(buf, F_OK)) { 2373 snprintf(jrelib_p, buflen-len, "/lib/%s", cpu_arch); 2374 } 2375 2376 if (0 == access(buf, F_OK)) { 2377 // Use current module name "libjvm.so" 2378 len = strlen(buf); 2379 snprintf(buf + len, buflen-len, "/hotspot/libjvm.so"); 2380 } else { 2381 // Go back to path of .so 2382 rp = realpath(dli_fname, buf); 2383 if (rp == NULL) { 2384 return; 2385 } 2386 } 2387 } 2388 } 2389 } 2390 2391 strncpy(saved_jvm_path, buf, MAXPATHLEN); 2392 saved_jvm_path[MAXPATHLEN - 1] = '\0'; 2393 } 2394 2395 void os::print_jni_name_prefix_on(outputStream* st, int args_size) { 2396 // no prefix required, not even "_" 2397 } 2398 2399 void os::print_jni_name_suffix_on(outputStream* st, int args_size) { 2400 // no suffix required 2401 } 2402 2403 //////////////////////////////////////////////////////////////////////////////// 2404 // sun.misc.Signal support 2405 2406 static volatile jint sigint_count = 0; 2407 2408 static void UserHandler(int sig, void *siginfo, void *context) { 2409 // 4511530 - sem_post is serialized and handled by the manager thread. When 2410 // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We 2411 // don't want to flood the manager thread with sem_post requests. 2412 if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1) { 2413 return; 2414 } 2415 2416 // Ctrl-C is pressed during error reporting, likely because the error 2417 // handler fails to abort. Let VM die immediately. 2418 if (sig == SIGINT && is_error_reported()) { 2419 os::die(); 2420 } 2421 2422 os::signal_notify(sig); 2423 } 2424 2425 void* os::user_handler() { 2426 return CAST_FROM_FN_PTR(void*, UserHandler); 2427 } 2428 2429 class Semaphore : public StackObj { 2430 public: 2431 Semaphore(); 2432 ~Semaphore(); 2433 void signal(); 2434 void wait(); 2435 bool trywait(); 2436 bool timedwait(unsigned int sec, int nsec); 2437 private: 2438 sem_t _semaphore; 2439 }; 2440 2441 Semaphore::Semaphore() { 2442 sem_init(&_semaphore, 0, 0); 2443 } 2444 2445 Semaphore::~Semaphore() { 2446 sem_destroy(&_semaphore); 2447 } 2448 2449 void Semaphore::signal() { 2450 sem_post(&_semaphore); 2451 } 2452 2453 void Semaphore::wait() { 2454 sem_wait(&_semaphore); 2455 } 2456 2457 bool Semaphore::trywait() { 2458 return sem_trywait(&_semaphore) == 0; 2459 } 2460 2461 bool Semaphore::timedwait(unsigned int sec, int nsec) { 2462 2463 struct timespec ts; 2464 // Semaphore's are always associated with CLOCK_REALTIME 2465 os::Linux::clock_gettime(CLOCK_REALTIME, &ts); 2466 // see unpackTime for discussion on overflow checking 2467 if (sec >= MAX_SECS) { 2468 ts.tv_sec += MAX_SECS; 2469 ts.tv_nsec = 0; 2470 } else { 2471 ts.tv_sec += sec; 2472 ts.tv_nsec += nsec; 2473 if (ts.tv_nsec >= NANOSECS_PER_SEC) { 2474 ts.tv_nsec -= NANOSECS_PER_SEC; 2475 ++ts.tv_sec; // note: this must be <= max_secs 2476 } 2477 } 2478 2479 while (1) { 2480 int result = sem_timedwait(&_semaphore, &ts); 2481 if (result == 0) { 2482 return true; 2483 } else if (errno == EINTR) { 2484 continue; 2485 } else if (errno == ETIMEDOUT) { 2486 return false; 2487 } else { 2488 return false; 2489 } 2490 } 2491 } 2492 2493 extern "C" { 2494 typedef void (*sa_handler_t)(int); 2495 typedef void (*sa_sigaction_t)(int, siginfo_t *, void *); 2496 } 2497 2498 void* os::signal(int signal_number, void* handler) { 2499 struct sigaction sigAct, oldSigAct; 2500 2501 sigfillset(&(sigAct.sa_mask)); 2502 sigAct.sa_flags = SA_RESTART|SA_SIGINFO; 2503 sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler); 2504 2505 if (sigaction(signal_number, &sigAct, &oldSigAct)) { 2506 // -1 means registration failed 2507 return (void *)-1; 2508 } 2509 2510 return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler); 2511 } 2512 2513 void os::signal_raise(int signal_number) { 2514 ::raise(signal_number); 2515 } 2516 2517 // The following code is moved from os.cpp for making this 2518 // code platform specific, which it is by its very nature. 2519 2520 // Will be modified when max signal is changed to be dynamic 2521 int os::sigexitnum_pd() { 2522 return NSIG; 2523 } 2524 2525 // a counter for each possible signal value 2526 static volatile jint pending_signals[NSIG+1] = { 0 }; 2527 2528 // Linux(POSIX) specific hand shaking semaphore. 2529 static sem_t sig_sem; 2530 static Semaphore sr_semaphore; 2531 2532 void os::signal_init_pd() { 2533 // Initialize signal structures 2534 ::memset((void*)pending_signals, 0, sizeof(pending_signals)); 2535 2536 // Initialize signal semaphore 2537 ::sem_init(&sig_sem, 0, 0); 2538 } 2539 2540 void os::signal_notify(int sig) { 2541 Atomic::inc(&pending_signals[sig]); 2542 ::sem_post(&sig_sem); 2543 } 2544 2545 static int check_pending_signals(bool wait) { 2546 Atomic::store(0, &sigint_count); 2547 for (;;) { 2548 for (int i = 0; i < NSIG + 1; i++) { 2549 jint n = pending_signals[i]; 2550 if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) { 2551 return i; 2552 } 2553 } 2554 if (!wait) { 2555 return -1; 2556 } 2557 JavaThread *thread = JavaThread::current(); 2558 ThreadBlockInVM tbivm(thread); 2559 2560 bool threadIsSuspended; 2561 do { 2562 thread->set_suspend_equivalent(); 2563 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 2564 ::sem_wait(&sig_sem); 2565 2566 // were we externally suspended while we were waiting? 2567 threadIsSuspended = thread->handle_special_suspend_equivalent_condition(); 2568 if (threadIsSuspended) { 2569 // The semaphore has been incremented, but while we were waiting 2570 // another thread suspended us. We don't want to continue running 2571 // while suspended because that would surprise the thread that 2572 // suspended us. 2573 ::sem_post(&sig_sem); 2574 2575 thread->java_suspend_self(); 2576 } 2577 } while (threadIsSuspended); 2578 } 2579 } 2580 2581 int os::signal_lookup() { 2582 return check_pending_signals(false); 2583 } 2584 2585 int os::signal_wait() { 2586 return check_pending_signals(true); 2587 } 2588 2589 //////////////////////////////////////////////////////////////////////////////// 2590 // Virtual Memory 2591 2592 int os::vm_page_size() { 2593 // Seems redundant as all get out 2594 assert(os::Linux::page_size() != -1, "must call os::init"); 2595 return os::Linux::page_size(); 2596 } 2597 2598 // Solaris allocates memory by pages. 2599 int os::vm_allocation_granularity() { 2600 assert(os::Linux::page_size() != -1, "must call os::init"); 2601 return os::Linux::page_size(); 2602 } 2603 2604 // Rationale behind this function: 2605 // current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable 2606 // mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get 2607 // samples for JITted code. Here we create private executable mapping over the code cache 2608 // and then we can use standard (well, almost, as mapping can change) way to provide 2609 // info for the reporting script by storing timestamp and location of symbol 2610 void linux_wrap_code(char* base, size_t size) { 2611 static volatile jint cnt = 0; 2612 2613 if (!UseOprofile) { 2614 return; 2615 } 2616 2617 char buf[PATH_MAX+1]; 2618 int num = Atomic::add(1, &cnt); 2619 2620 snprintf(buf, sizeof(buf), "%s/hs-vm-%d-%d", 2621 os::get_temp_directory(), os::current_process_id(), num); 2622 unlink(buf); 2623 2624 int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU); 2625 2626 if (fd != -1) { 2627 off_t rv = ::lseek(fd, size-2, SEEK_SET); 2628 if (rv != (off_t)-1) { 2629 if (::write(fd, "", 1) == 1) { 2630 mmap(base, size, 2631 PROT_READ|PROT_WRITE|PROT_EXEC, 2632 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0); 2633 } 2634 } 2635 ::close(fd); 2636 unlink(buf); 2637 } 2638 } 2639 2640 static bool recoverable_mmap_error(int err) { 2641 // See if the error is one we can let the caller handle. This 2642 // list of errno values comes from JBS-6843484. I can't find a 2643 // Linux man page that documents this specific set of errno 2644 // values so while this list currently matches Solaris, it may 2645 // change as we gain experience with this failure mode. 2646 switch (err) { 2647 case EBADF: 2648 case EINVAL: 2649 case ENOTSUP: 2650 // let the caller deal with these errors 2651 return true; 2652 2653 default: 2654 // Any remaining errors on this OS can cause our reserved mapping 2655 // to be lost. That can cause confusion where different data 2656 // structures think they have the same memory mapped. The worst 2657 // scenario is if both the VM and a library think they have the 2658 // same memory mapped. 2659 return false; 2660 } 2661 } 2662 2663 static void warn_fail_commit_memory(char* addr, size_t size, bool exec, 2664 int err) { 2665 warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT 2666 ", %d) failed; error='%s' (errno=%d)", addr, size, exec, 2667 strerror(err), err); 2668 } 2669 2670 static void warn_fail_commit_memory(char* addr, size_t size, 2671 size_t alignment_hint, bool exec, 2672 int err) { 2673 warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT 2674 ", " SIZE_FORMAT ", %d) failed; error='%s' (errno=%d)", addr, size, 2675 alignment_hint, exec, strerror(err), err); 2676 } 2677 2678 // NOTE: Linux kernel does not really reserve the pages for us. 2679 // All it does is to check if there are enough free pages 2680 // left at the time of mmap(). This could be a potential 2681 // problem. 2682 int os::Linux::commit_memory_impl(char* addr, size_t size, bool exec) { 2683 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE; 2684 uintptr_t res = (uintptr_t) ::mmap(addr, size, prot, 2685 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0); 2686 if (res != (uintptr_t) MAP_FAILED) { 2687 if (UseNUMAInterleaving) { 2688 numa_make_global(addr, size); 2689 } 2690 return 0; 2691 } 2692 2693 int err = errno; // save errno from mmap() call above 2694 2695 if (!recoverable_mmap_error(err)) { 2696 warn_fail_commit_memory(addr, size, exec, err); 2697 vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "committing reserved memory."); 2698 } 2699 2700 return err; 2701 } 2702 2703 bool os::pd_commit_memory(char* addr, size_t size, bool exec) { 2704 return os::Linux::commit_memory_impl(addr, size, exec) == 0; 2705 } 2706 2707 void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec, 2708 const char* mesg) { 2709 assert(mesg != NULL, "mesg must be specified"); 2710 int err = os::Linux::commit_memory_impl(addr, size, exec); 2711 if (err != 0) { 2712 // the caller wants all commit errors to exit with the specified mesg: 2713 warn_fail_commit_memory(addr, size, exec, err); 2714 vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg); 2715 } 2716 } 2717 2718 // Define MAP_HUGETLB here so we can build HotSpot on old systems. 2719 #ifndef MAP_HUGETLB 2720 #define MAP_HUGETLB 0x40000 2721 #endif 2722 2723 // Define MADV_HUGEPAGE here so we can build HotSpot on old systems. 2724 #ifndef MADV_HUGEPAGE 2725 #define MADV_HUGEPAGE 14 2726 #endif 2727 2728 int os::Linux::commit_memory_impl(char* addr, size_t size, 2729 size_t alignment_hint, bool exec) { 2730 int err = os::Linux::commit_memory_impl(addr, size, exec); 2731 if (err == 0) { 2732 realign_memory(addr, size, alignment_hint); 2733 } 2734 return err; 2735 } 2736 2737 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint, 2738 bool exec) { 2739 return os::Linux::commit_memory_impl(addr, size, alignment_hint, exec) == 0; 2740 } 2741 2742 void os::pd_commit_memory_or_exit(char* addr, size_t size, 2743 size_t alignment_hint, bool exec, 2744 const char* mesg) { 2745 assert(mesg != NULL, "mesg must be specified"); 2746 int err = os::Linux::commit_memory_impl(addr, size, alignment_hint, exec); 2747 if (err != 0) { 2748 // the caller wants all commit errors to exit with the specified mesg: 2749 warn_fail_commit_memory(addr, size, alignment_hint, exec, err); 2750 vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg); 2751 } 2752 } 2753 2754 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) { 2755 if (UseTransparentHugePages && alignment_hint > (size_t)vm_page_size()) { 2756 // We don't check the return value: madvise(MADV_HUGEPAGE) may not 2757 // be supported or the memory may already be backed by huge pages. 2758 ::madvise(addr, bytes, MADV_HUGEPAGE); 2759 } 2760 } 2761 2762 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) { 2763 // This method works by doing an mmap over an existing mmaping and effectively discarding 2764 // the existing pages. However it won't work for SHM-based large pages that cannot be 2765 // uncommitted at all. We don't do anything in this case to avoid creating a segment with 2766 // small pages on top of the SHM segment. This method always works for small pages, so we 2767 // allow that in any case. 2768 if (alignment_hint <= (size_t)os::vm_page_size() || can_commit_large_page_memory()) { 2769 commit_memory(addr, bytes, alignment_hint, !ExecMem); 2770 } 2771 } 2772 2773 void os::numa_make_global(char *addr, size_t bytes) { 2774 Linux::numa_interleave_memory(addr, bytes); 2775 } 2776 2777 // Define for numa_set_bind_policy(int). Setting the argument to 0 will set the 2778 // bind policy to MPOL_PREFERRED for the current thread. 2779 #define USE_MPOL_PREFERRED 0 2780 2781 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) { 2782 // To make NUMA and large pages more robust when both enabled, we need to ease 2783 // the requirements on where the memory should be allocated. MPOL_BIND is the 2784 // default policy and it will force memory to be allocated on the specified 2785 // node. Changing this to MPOL_PREFERRED will prefer to allocate the memory on 2786 // the specified node, but will not force it. Using this policy will prevent 2787 // getting SIGBUS when trying to allocate large pages on NUMA nodes with no 2788 // free large pages. 2789 Linux::numa_set_bind_policy(USE_MPOL_PREFERRED); 2790 Linux::numa_tonode_memory(addr, bytes, lgrp_hint); 2791 } 2792 2793 bool os::numa_topology_changed() { return false; } 2794 2795 size_t os::numa_get_groups_num() { 2796 int max_node = Linux::numa_max_node(); 2797 return max_node > 0 ? max_node + 1 : 1; 2798 } 2799 2800 int os::numa_get_group_id() { 2801 int cpu_id = Linux::sched_getcpu(); 2802 if (cpu_id != -1) { 2803 int lgrp_id = Linux::get_node_by_cpu(cpu_id); 2804 if (lgrp_id != -1) { 2805 return lgrp_id; 2806 } 2807 } 2808 return 0; 2809 } 2810 2811 size_t os::numa_get_leaf_groups(int *ids, size_t size) { 2812 for (size_t i = 0; i < size; i++) { 2813 ids[i] = i; 2814 } 2815 return size; 2816 } 2817 2818 bool os::get_page_info(char *start, page_info* info) { 2819 return false; 2820 } 2821 2822 char *os::scan_pages(char *start, char* end, page_info* page_expected, 2823 page_info* page_found) { 2824 return end; 2825 } 2826 2827 2828 int os::Linux::sched_getcpu_syscall(void) { 2829 unsigned int cpu; 2830 int retval = -1; 2831 2832 #if defined(IA32) 2833 #ifndef SYS_getcpu 2834 #define SYS_getcpu 318 2835 #endif 2836 retval = syscall(SYS_getcpu, &cpu, NULL, NULL); 2837 #elif defined(AMD64) 2838 // Unfortunately we have to bring all these macros here from vsyscall.h 2839 // to be able to compile on old linuxes. 2840 #define __NR_vgetcpu 2 2841 #define VSYSCALL_START (-10UL << 20) 2842 #define VSYSCALL_SIZE 1024 2843 #define VSYSCALL_ADDR(vsyscall_nr) (VSYSCALL_START+VSYSCALL_SIZE*(vsyscall_nr)) 2844 typedef long (*vgetcpu_t)(unsigned int *cpu, unsigned int *node, unsigned long *tcache); 2845 vgetcpu_t vgetcpu = (vgetcpu_t)VSYSCALL_ADDR(__NR_vgetcpu); 2846 retval = vgetcpu(&cpu, NULL, NULL); 2847 #endif 2848 2849 return (retval == -1) ? retval : cpu; 2850 } 2851 2852 // Something to do with the numa-aware allocator needs these symbols 2853 extern "C" JNIEXPORT void numa_warn(int number, char *where, ...) { } 2854 extern "C" JNIEXPORT void numa_error(char *where) { } 2855 extern "C" JNIEXPORT int fork1() { return fork(); } 2856 2857 2858 // If we are running with libnuma version > 2, then we should 2859 // be trying to use symbols with versions 1.1 2860 // If we are running with earlier version, which did not have symbol versions, 2861 // we should use the base version. 2862 void* os::Linux::libnuma_dlsym(void* handle, const char *name) { 2863 void *f = dlvsym(handle, name, "libnuma_1.1"); 2864 if (f == NULL) { 2865 f = dlsym(handle, name); 2866 } 2867 return f; 2868 } 2869 2870 bool os::Linux::libnuma_init() { 2871 // sched_getcpu() should be in libc. 2872 set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t, 2873 dlsym(RTLD_DEFAULT, "sched_getcpu"))); 2874 2875 // If it's not, try a direct syscall. 2876 if (sched_getcpu() == -1) { 2877 set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t, 2878 (void*)&sched_getcpu_syscall)); 2879 } 2880 2881 if (sched_getcpu() != -1) { // Does it work? 2882 void *handle = dlopen("libnuma.so.1", RTLD_LAZY); 2883 if (handle != NULL) { 2884 set_numa_node_to_cpus(CAST_TO_FN_PTR(numa_node_to_cpus_func_t, 2885 libnuma_dlsym(handle, "numa_node_to_cpus"))); 2886 set_numa_max_node(CAST_TO_FN_PTR(numa_max_node_func_t, 2887 libnuma_dlsym(handle, "numa_max_node"))); 2888 set_numa_available(CAST_TO_FN_PTR(numa_available_func_t, 2889 libnuma_dlsym(handle, "numa_available"))); 2890 set_numa_tonode_memory(CAST_TO_FN_PTR(numa_tonode_memory_func_t, 2891 libnuma_dlsym(handle, "numa_tonode_memory"))); 2892 set_numa_interleave_memory(CAST_TO_FN_PTR(numa_interleave_memory_func_t, 2893 libnuma_dlsym(handle, "numa_interleave_memory"))); 2894 set_numa_set_bind_policy(CAST_TO_FN_PTR(numa_set_bind_policy_func_t, 2895 libnuma_dlsym(handle, "numa_set_bind_policy"))); 2896 2897 2898 if (numa_available() != -1) { 2899 set_numa_all_nodes((unsigned long*)libnuma_dlsym(handle, "numa_all_nodes")); 2900 // Create a cpu -> node mapping 2901 _cpu_to_node = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<int>(0, true); 2902 rebuild_cpu_to_node_map(); 2903 return true; 2904 } 2905 } 2906 } 2907 return false; 2908 } 2909 2910 // rebuild_cpu_to_node_map() constructs a table mapping cpud id to node id. 2911 // The table is later used in get_node_by_cpu(). 2912 void os::Linux::rebuild_cpu_to_node_map() { 2913 const size_t NCPUS = 32768; // Since the buffer size computation is very obscure 2914 // in libnuma (possible values are starting from 16, 2915 // and continuing up with every other power of 2, but less 2916 // than the maximum number of CPUs supported by kernel), and 2917 // is a subject to change (in libnuma version 2 the requirements 2918 // are more reasonable) we'll just hardcode the number they use 2919 // in the library. 2920 const size_t BitsPerCLong = sizeof(long) * CHAR_BIT; 2921 2922 size_t cpu_num = os::active_processor_count(); 2923 size_t cpu_map_size = NCPUS / BitsPerCLong; 2924 size_t cpu_map_valid_size = 2925 MIN2((cpu_num + BitsPerCLong - 1) / BitsPerCLong, cpu_map_size); 2926 2927 cpu_to_node()->clear(); 2928 cpu_to_node()->at_grow(cpu_num - 1); 2929 size_t node_num = numa_get_groups_num(); 2930 2931 unsigned long *cpu_map = NEW_C_HEAP_ARRAY(unsigned long, cpu_map_size, mtInternal); 2932 for (size_t i = 0; i < node_num; i++) { 2933 if (numa_node_to_cpus(i, cpu_map, cpu_map_size * sizeof(unsigned long)) != -1) { 2934 for (size_t j = 0; j < cpu_map_valid_size; j++) { 2935 if (cpu_map[j] != 0) { 2936 for (size_t k = 0; k < BitsPerCLong; k++) { 2937 if (cpu_map[j] & (1UL << k)) { 2938 cpu_to_node()->at_put(j * BitsPerCLong + k, i); 2939 } 2940 } 2941 } 2942 } 2943 } 2944 } 2945 FREE_C_HEAP_ARRAY(unsigned long, cpu_map); 2946 } 2947 2948 int os::Linux::get_node_by_cpu(int cpu_id) { 2949 if (cpu_to_node() != NULL && cpu_id >= 0 && cpu_id < cpu_to_node()->length()) { 2950 return cpu_to_node()->at(cpu_id); 2951 } 2952 return -1; 2953 } 2954 2955 GrowableArray<int>* os::Linux::_cpu_to_node; 2956 os::Linux::sched_getcpu_func_t os::Linux::_sched_getcpu; 2957 os::Linux::numa_node_to_cpus_func_t os::Linux::_numa_node_to_cpus; 2958 os::Linux::numa_max_node_func_t os::Linux::_numa_max_node; 2959 os::Linux::numa_available_func_t os::Linux::_numa_available; 2960 os::Linux::numa_tonode_memory_func_t os::Linux::_numa_tonode_memory; 2961 os::Linux::numa_interleave_memory_func_t os::Linux::_numa_interleave_memory; 2962 os::Linux::numa_set_bind_policy_func_t os::Linux::_numa_set_bind_policy; 2963 unsigned long* os::Linux::_numa_all_nodes; 2964 2965 bool os::pd_uncommit_memory(char* addr, size_t size) { 2966 uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE, 2967 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0); 2968 return res != (uintptr_t) MAP_FAILED; 2969 } 2970 2971 static address get_stack_commited_bottom(address bottom, size_t size) { 2972 address nbot = bottom; 2973 address ntop = bottom + size; 2974 2975 size_t page_sz = os::vm_page_size(); 2976 unsigned pages = size / page_sz; 2977 2978 unsigned char vec[1]; 2979 unsigned imin = 1, imax = pages + 1, imid; 2980 int mincore_return_value = 0; 2981 2982 assert(imin <= imax, "Unexpected page size"); 2983 2984 while (imin < imax) { 2985 imid = (imax + imin) / 2; 2986 nbot = ntop - (imid * page_sz); 2987 2988 // Use a trick with mincore to check whether the page is mapped or not. 2989 // mincore sets vec to 1 if page resides in memory and to 0 if page 2990 // is swapped output but if page we are asking for is unmapped 2991 // it returns -1,ENOMEM 2992 mincore_return_value = mincore(nbot, page_sz, vec); 2993 2994 if (mincore_return_value == -1) { 2995 // Page is not mapped go up 2996 // to find first mapped page 2997 if (errno != EAGAIN) { 2998 assert(errno == ENOMEM, "Unexpected mincore errno"); 2999 imax = imid; 3000 } 3001 } else { 3002 // Page is mapped go down 3003 // to find first not mapped page 3004 imin = imid + 1; 3005 } 3006 } 3007 3008 nbot = nbot + page_sz; 3009 3010 // Adjust stack bottom one page up if last checked page is not mapped 3011 if (mincore_return_value == -1) { 3012 nbot = nbot + page_sz; 3013 } 3014 3015 return nbot; 3016 } 3017 3018 3019 // Linux uses a growable mapping for the stack, and if the mapping for 3020 // the stack guard pages is not removed when we detach a thread the 3021 // stack cannot grow beyond the pages where the stack guard was 3022 // mapped. If at some point later in the process the stack expands to 3023 // that point, the Linux kernel cannot expand the stack any further 3024 // because the guard pages are in the way, and a segfault occurs. 3025 // 3026 // However, it's essential not to split the stack region by unmapping 3027 // a region (leaving a hole) that's already part of the stack mapping, 3028 // so if the stack mapping has already grown beyond the guard pages at 3029 // the time we create them, we have to truncate the stack mapping. 3030 // So, we need to know the extent of the stack mapping when 3031 // create_stack_guard_pages() is called. 3032 3033 // We only need this for stacks that are growable: at the time of 3034 // writing thread stacks don't use growable mappings (i.e. those 3035 // creeated with MAP_GROWSDOWN), and aren't marked "[stack]", so this 3036 // only applies to the main thread. 3037 3038 // If the (growable) stack mapping already extends beyond the point 3039 // where we're going to put our guard pages, truncate the mapping at 3040 // that point by munmap()ping it. This ensures that when we later 3041 // munmap() the guard pages we don't leave a hole in the stack 3042 // mapping. This only affects the main/initial thread 3043 3044 bool os::pd_create_stack_guard_pages(char* addr, size_t size) { 3045 if (os::Linux::is_initial_thread()) { 3046 // As we manually grow stack up to bottom inside create_attached_thread(), 3047 // it's likely that os::Linux::initial_thread_stack_bottom is mapped and 3048 // we don't need to do anything special. 3049 // Check it first, before calling heavy function. 3050 uintptr_t stack_extent = (uintptr_t) os::Linux::initial_thread_stack_bottom(); 3051 unsigned char vec[1]; 3052 3053 if (mincore((address)stack_extent, os::vm_page_size(), vec) == -1) { 3054 // Fallback to slow path on all errors, including EAGAIN 3055 stack_extent = (uintptr_t) get_stack_commited_bottom( 3056 os::Linux::initial_thread_stack_bottom(), 3057 (size_t)addr - stack_extent); 3058 } 3059 3060 if (stack_extent < (uintptr_t)addr) { 3061 ::munmap((void*)stack_extent, (uintptr_t)(addr - stack_extent)); 3062 } 3063 } 3064 3065 return os::commit_memory(addr, size, !ExecMem); 3066 } 3067 3068 // If this is a growable mapping, remove the guard pages entirely by 3069 // munmap()ping them. If not, just call uncommit_memory(). This only 3070 // affects the main/initial thread, but guard against future OS changes 3071 // It's safe to always unmap guard pages for initial thread because we 3072 // always place it right after end of the mapped region 3073 3074 bool os::remove_stack_guard_pages(char* addr, size_t size) { 3075 uintptr_t stack_extent, stack_base; 3076 3077 if (os::Linux::is_initial_thread()) { 3078 return ::munmap(addr, size) == 0; 3079 } 3080 3081 return os::uncommit_memory(addr, size); 3082 } 3083 3084 static address _highest_vm_reserved_address = NULL; 3085 3086 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory 3087 // at 'requested_addr'. If there are existing memory mappings at the same 3088 // location, however, they will be overwritten. If 'fixed' is false, 3089 // 'requested_addr' is only treated as a hint, the return value may or 3090 // may not start from the requested address. Unlike Linux mmap(), this 3091 // function returns NULL to indicate failure. 3092 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) { 3093 char * addr; 3094 int flags; 3095 3096 flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS; 3097 if (fixed) { 3098 assert((uintptr_t)requested_addr % os::Linux::page_size() == 0, "unaligned address"); 3099 flags |= MAP_FIXED; 3100 } 3101 3102 // Map reserved/uncommitted pages PROT_NONE so we fail early if we 3103 // touch an uncommitted page. Otherwise, the read/write might 3104 // succeed if we have enough swap space to back the physical page. 3105 addr = (char*)::mmap(requested_addr, bytes, PROT_NONE, 3106 flags, -1, 0); 3107 3108 if (addr != MAP_FAILED) { 3109 // anon_mmap() should only get called during VM initialization, 3110 // don't need lock (actually we can skip locking even it can be called 3111 // from multiple threads, because _highest_vm_reserved_address is just a 3112 // hint about the upper limit of non-stack memory regions.) 3113 if ((address)addr + bytes > _highest_vm_reserved_address) { 3114 _highest_vm_reserved_address = (address)addr + bytes; 3115 } 3116 } 3117 3118 return addr == MAP_FAILED ? NULL : addr; 3119 } 3120 3121 // Don't update _highest_vm_reserved_address, because there might be memory 3122 // regions above addr + size. If so, releasing a memory region only creates 3123 // a hole in the address space, it doesn't help prevent heap-stack collision. 3124 // 3125 static int anon_munmap(char * addr, size_t size) { 3126 return ::munmap(addr, size) == 0; 3127 } 3128 3129 char* os::pd_reserve_memory(size_t bytes, char* requested_addr, 3130 size_t alignment_hint) { 3131 return anon_mmap(requested_addr, bytes, (requested_addr != NULL)); 3132 } 3133 3134 bool os::pd_release_memory(char* addr, size_t size) { 3135 return anon_munmap(addr, size); 3136 } 3137 3138 static address highest_vm_reserved_address() { 3139 return _highest_vm_reserved_address; 3140 } 3141 3142 static bool linux_mprotect(char* addr, size_t size, int prot) { 3143 // Linux wants the mprotect address argument to be page aligned. 3144 char* bottom = (char*)align_size_down((intptr_t)addr, os::Linux::page_size()); 3145 3146 // According to SUSv3, mprotect() should only be used with mappings 3147 // established by mmap(), and mmap() always maps whole pages. Unaligned 3148 // 'addr' likely indicates problem in the VM (e.g. trying to change 3149 // protection of malloc'ed or statically allocated memory). Check the 3150 // caller if you hit this assert. 3151 assert(addr == bottom, "sanity check"); 3152 3153 size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Linux::page_size()); 3154 return ::mprotect(bottom, size, prot) == 0; 3155 } 3156 3157 // Set protections specified 3158 bool os::protect_memory(char* addr, size_t bytes, ProtType prot, 3159 bool is_committed) { 3160 unsigned int p = 0; 3161 switch (prot) { 3162 case MEM_PROT_NONE: p = PROT_NONE; break; 3163 case MEM_PROT_READ: p = PROT_READ; break; 3164 case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break; 3165 case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break; 3166 default: 3167 ShouldNotReachHere(); 3168 } 3169 // is_committed is unused. 3170 return linux_mprotect(addr, bytes, p); 3171 } 3172 3173 bool os::guard_memory(char* addr, size_t size) { 3174 return linux_mprotect(addr, size, PROT_NONE); 3175 } 3176 3177 bool os::unguard_memory(char* addr, size_t size) { 3178 return linux_mprotect(addr, size, PROT_READ|PROT_WRITE); 3179 } 3180 3181 bool os::Linux::transparent_huge_pages_sanity_check(bool warn, 3182 size_t page_size) { 3183 bool result = false; 3184 void *p = mmap(NULL, page_size * 2, PROT_READ|PROT_WRITE, 3185 MAP_ANONYMOUS|MAP_PRIVATE, 3186 -1, 0); 3187 if (p != MAP_FAILED) { 3188 void *aligned_p = align_ptr_up(p, page_size); 3189 3190 result = madvise(aligned_p, page_size, MADV_HUGEPAGE) == 0; 3191 3192 munmap(p, page_size * 2); 3193 } 3194 3195 if (warn && !result) { 3196 warning("TransparentHugePages is not supported by the operating system."); 3197 } 3198 3199 return result; 3200 } 3201 3202 bool os::Linux::hugetlbfs_sanity_check(bool warn, size_t page_size) { 3203 bool result = false; 3204 void *p = mmap(NULL, page_size, PROT_READ|PROT_WRITE, 3205 MAP_ANONYMOUS|MAP_PRIVATE|MAP_HUGETLB, 3206 -1, 0); 3207 3208 if (p != MAP_FAILED) { 3209 // We don't know if this really is a huge page or not. 3210 FILE *fp = fopen("/proc/self/maps", "r"); 3211 if (fp) { 3212 while (!feof(fp)) { 3213 char chars[257]; 3214 long x = 0; 3215 if (fgets(chars, sizeof(chars), fp)) { 3216 if (sscanf(chars, "%lx-%*x", &x) == 1 3217 && x == (long)p) { 3218 if (strstr (chars, "hugepage")) { 3219 result = true; 3220 break; 3221 } 3222 } 3223 } 3224 } 3225 fclose(fp); 3226 } 3227 munmap(p, page_size); 3228 } 3229 3230 if (warn && !result) { 3231 warning("HugeTLBFS is not supported by the operating system."); 3232 } 3233 3234 return result; 3235 } 3236 3237 // Set the coredump_filter bits to include largepages in core dump (bit 6) 3238 // 3239 // From the coredump_filter documentation: 3240 // 3241 // - (bit 0) anonymous private memory 3242 // - (bit 1) anonymous shared memory 3243 // - (bit 2) file-backed private memory 3244 // - (bit 3) file-backed shared memory 3245 // - (bit 4) ELF header pages in file-backed private memory areas (it is 3246 // effective only if the bit 2 is cleared) 3247 // - (bit 5) hugetlb private memory 3248 // - (bit 6) hugetlb shared memory 3249 // 3250 static void set_coredump_filter(void) { 3251 FILE *f; 3252 long cdm; 3253 3254 if ((f = fopen("/proc/self/coredump_filter", "r+")) == NULL) { 3255 return; 3256 } 3257 3258 if (fscanf(f, "%lx", &cdm) != 1) { 3259 fclose(f); 3260 return; 3261 } 3262 3263 rewind(f); 3264 3265 if ((cdm & LARGEPAGES_BIT) == 0) { 3266 cdm |= LARGEPAGES_BIT; 3267 fprintf(f, "%#lx", cdm); 3268 } 3269 3270 fclose(f); 3271 } 3272 3273 // Large page support 3274 3275 static size_t _large_page_size = 0; 3276 3277 size_t os::Linux::find_large_page_size() { 3278 size_t large_page_size = 0; 3279 3280 // large_page_size on Linux is used to round up heap size. x86 uses either 3281 // 2M or 4M page, depending on whether PAE (Physical Address Extensions) 3282 // mode is enabled. AMD64/EM64T uses 2M page in 64bit mode. IA64 can use 3283 // page as large as 256M. 3284 // 3285 // Here we try to figure out page size by parsing /proc/meminfo and looking 3286 // for a line with the following format: 3287 // Hugepagesize: 2048 kB 3288 // 3289 // If we can't determine the value (e.g. /proc is not mounted, or the text 3290 // format has been changed), we'll use the largest page size supported by 3291 // the processor. 3292 3293 #ifndef ZERO 3294 large_page_size = IA32_ONLY(4 * M) AMD64_ONLY(2 * M) IA64_ONLY(256 * M) SPARC_ONLY(4 * M) 3295 ARM_ONLY(2 * M) PPC_ONLY(4 * M); 3296 #endif // ZERO 3297 3298 FILE *fp = fopen("/proc/meminfo", "r"); 3299 if (fp) { 3300 while (!feof(fp)) { 3301 int x = 0; 3302 char buf[16]; 3303 if (fscanf(fp, "Hugepagesize: %d", &x) == 1) { 3304 if (x && fgets(buf, sizeof(buf), fp) && strcmp(buf, " kB\n") == 0) { 3305 large_page_size = x * K; 3306 break; 3307 } 3308 } else { 3309 // skip to next line 3310 for (;;) { 3311 int ch = fgetc(fp); 3312 if (ch == EOF || ch == (int)'\n') break; 3313 } 3314 } 3315 } 3316 fclose(fp); 3317 } 3318 3319 if (!FLAG_IS_DEFAULT(LargePageSizeInBytes) && LargePageSizeInBytes != large_page_size) { 3320 warning("Setting LargePageSizeInBytes has no effect on this OS. Large page size is " 3321 SIZE_FORMAT "%s.", byte_size_in_proper_unit(large_page_size), 3322 proper_unit_for_byte_size(large_page_size)); 3323 } 3324 3325 return large_page_size; 3326 } 3327 3328 size_t os::Linux::setup_large_page_size() { 3329 _large_page_size = Linux::find_large_page_size(); 3330 const size_t default_page_size = (size_t)Linux::page_size(); 3331 if (_large_page_size > default_page_size) { 3332 _page_sizes[0] = _large_page_size; 3333 _page_sizes[1] = default_page_size; 3334 _page_sizes[2] = 0; 3335 } 3336 3337 return _large_page_size; 3338 } 3339 3340 bool os::Linux::setup_large_page_type(size_t page_size) { 3341 if (FLAG_IS_DEFAULT(UseHugeTLBFS) && 3342 FLAG_IS_DEFAULT(UseSHM) && 3343 FLAG_IS_DEFAULT(UseTransparentHugePages)) { 3344 3345 // The type of large pages has not been specified by the user. 3346 3347 // Try UseHugeTLBFS and then UseSHM. 3348 UseHugeTLBFS = UseSHM = true; 3349 3350 // Don't try UseTransparentHugePages since there are known 3351 // performance issues with it turned on. This might change in the future. 3352 UseTransparentHugePages = false; 3353 } 3354 3355 if (UseTransparentHugePages) { 3356 bool warn_on_failure = !FLAG_IS_DEFAULT(UseTransparentHugePages); 3357 if (transparent_huge_pages_sanity_check(warn_on_failure, page_size)) { 3358 UseHugeTLBFS = false; 3359 UseSHM = false; 3360 return true; 3361 } 3362 UseTransparentHugePages = false; 3363 } 3364 3365 if (UseHugeTLBFS) { 3366 bool warn_on_failure = !FLAG_IS_DEFAULT(UseHugeTLBFS); 3367 if (hugetlbfs_sanity_check(warn_on_failure, page_size)) { 3368 UseSHM = false; 3369 return true; 3370 } 3371 UseHugeTLBFS = false; 3372 } 3373 3374 return UseSHM; 3375 } 3376 3377 void os::large_page_init() { 3378 if (!UseLargePages && 3379 !UseTransparentHugePages && 3380 !UseHugeTLBFS && 3381 !UseSHM) { 3382 // Not using large pages. 3383 return; 3384 } 3385 3386 if (!FLAG_IS_DEFAULT(UseLargePages) && !UseLargePages) { 3387 // The user explicitly turned off large pages. 3388 // Ignore the rest of the large pages flags. 3389 UseTransparentHugePages = false; 3390 UseHugeTLBFS = false; 3391 UseSHM = false; 3392 return; 3393 } 3394 3395 size_t large_page_size = Linux::setup_large_page_size(); 3396 UseLargePages = Linux::setup_large_page_type(large_page_size); 3397 3398 set_coredump_filter(); 3399 } 3400 3401 #ifndef SHM_HUGETLB 3402 #define SHM_HUGETLB 04000 3403 #endif 3404 3405 char* os::Linux::reserve_memory_special_shm(size_t bytes, size_t alignment, 3406 char* req_addr, bool exec) { 3407 // "exec" is passed in but not used. Creating the shared image for 3408 // the code cache doesn't have an SHM_X executable permission to check. 3409 assert(UseLargePages && UseSHM, "only for SHM large pages"); 3410 assert(is_ptr_aligned(req_addr, os::large_page_size()), "Unaligned address"); 3411 3412 if (!is_size_aligned(bytes, os::large_page_size()) || alignment > os::large_page_size()) { 3413 return NULL; // Fallback to small pages. 3414 } 3415 3416 key_t key = IPC_PRIVATE; 3417 char *addr; 3418 3419 bool warn_on_failure = UseLargePages && 3420 (!FLAG_IS_DEFAULT(UseLargePages) || 3421 !FLAG_IS_DEFAULT(UseSHM) || 3422 !FLAG_IS_DEFAULT(LargePageSizeInBytes)); 3423 char msg[128]; 3424 3425 // Create a large shared memory region to attach to based on size. 3426 // Currently, size is the total size of the heap 3427 int shmid = shmget(key, bytes, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W); 3428 if (shmid == -1) { 3429 // Possible reasons for shmget failure: 3430 // 1. shmmax is too small for Java heap. 3431 // > check shmmax value: cat /proc/sys/kernel/shmmax 3432 // > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax 3433 // 2. not enough large page memory. 3434 // > check available large pages: cat /proc/meminfo 3435 // > increase amount of large pages: 3436 // echo new_value > /proc/sys/vm/nr_hugepages 3437 // Note 1: different Linux may use different name for this property, 3438 // e.g. on Redhat AS-3 it is "hugetlb_pool". 3439 // Note 2: it's possible there's enough physical memory available but 3440 // they are so fragmented after a long run that they can't 3441 // coalesce into large pages. Try to reserve large pages when 3442 // the system is still "fresh". 3443 if (warn_on_failure) { 3444 jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno); 3445 warning("%s", msg); 3446 } 3447 return NULL; 3448 } 3449 3450 // attach to the region 3451 addr = (char*)shmat(shmid, req_addr, 0); 3452 int err = errno; 3453 3454 // Remove shmid. If shmat() is successful, the actual shared memory segment 3455 // will be deleted when it's detached by shmdt() or when the process 3456 // terminates. If shmat() is not successful this will remove the shared 3457 // segment immediately. 3458 shmctl(shmid, IPC_RMID, NULL); 3459 3460 if ((intptr_t)addr == -1) { 3461 if (warn_on_failure) { 3462 jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err); 3463 warning("%s", msg); 3464 } 3465 return NULL; 3466 } 3467 3468 return addr; 3469 } 3470 3471 static void warn_on_large_pages_failure(char* req_addr, size_t bytes, 3472 int error) { 3473 assert(error == ENOMEM, "Only expect to fail if no memory is available"); 3474 3475 bool warn_on_failure = UseLargePages && 3476 (!FLAG_IS_DEFAULT(UseLargePages) || 3477 !FLAG_IS_DEFAULT(UseHugeTLBFS) || 3478 !FLAG_IS_DEFAULT(LargePageSizeInBytes)); 3479 3480 if (warn_on_failure) { 3481 char msg[128]; 3482 jio_snprintf(msg, sizeof(msg), "Failed to reserve large pages memory req_addr: " 3483 PTR_FORMAT " bytes: " SIZE_FORMAT " (errno = %d).", req_addr, bytes, error); 3484 warning("%s", msg); 3485 } 3486 } 3487 3488 char* os::Linux::reserve_memory_special_huge_tlbfs_only(size_t bytes, 3489 char* req_addr, 3490 bool exec) { 3491 assert(UseLargePages && UseHugeTLBFS, "only for Huge TLBFS large pages"); 3492 assert(is_size_aligned(bytes, os::large_page_size()), "Unaligned size"); 3493 assert(is_ptr_aligned(req_addr, os::large_page_size()), "Unaligned address"); 3494 3495 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE; 3496 char* addr = (char*)::mmap(req_addr, bytes, prot, 3497 MAP_PRIVATE|MAP_ANONYMOUS|MAP_HUGETLB, 3498 -1, 0); 3499 3500 if (addr == MAP_FAILED) { 3501 warn_on_large_pages_failure(req_addr, bytes, errno); 3502 return NULL; 3503 } 3504 3505 assert(is_ptr_aligned(addr, os::large_page_size()), "Must be"); 3506 3507 return addr; 3508 } 3509 3510 char* os::Linux::reserve_memory_special_huge_tlbfs_mixed(size_t bytes, 3511 size_t alignment, 3512 char* req_addr, 3513 bool exec) { 3514 size_t large_page_size = os::large_page_size(); 3515 3516 assert(bytes >= large_page_size, "Shouldn't allocate large pages for small sizes"); 3517 3518 // Allocate small pages. 3519 3520 char* start; 3521 if (req_addr != NULL) { 3522 assert(is_ptr_aligned(req_addr, alignment), "Must be"); 3523 assert(is_size_aligned(bytes, alignment), "Must be"); 3524 start = os::reserve_memory(bytes, req_addr); 3525 assert(start == NULL || start == req_addr, "Must be"); 3526 } else { 3527 start = os::reserve_memory_aligned(bytes, alignment); 3528 } 3529 3530 if (start == NULL) { 3531 return NULL; 3532 } 3533 3534 assert(is_ptr_aligned(start, alignment), "Must be"); 3535 3536 if (MemTracker::tracking_level() > NMT_minimal) { 3537 // os::reserve_memory_special will record this memory area. 3538 // Need to release it here to prevent overlapping reservations. 3539 Tracker tkr = MemTracker::get_virtual_memory_release_tracker(); 3540 tkr.record((address)start, bytes); 3541 } 3542 3543 char* end = start + bytes; 3544 3545 // Find the regions of the allocated chunk that can be promoted to large pages. 3546 char* lp_start = (char*)align_ptr_up(start, large_page_size); 3547 char* lp_end = (char*)align_ptr_down(end, large_page_size); 3548 3549 size_t lp_bytes = lp_end - lp_start; 3550 3551 assert(is_size_aligned(lp_bytes, large_page_size), "Must be"); 3552 3553 if (lp_bytes == 0) { 3554 // The mapped region doesn't even span the start and the end of a large page. 3555 // Fall back to allocate a non-special area. 3556 ::munmap(start, end - start); 3557 return NULL; 3558 } 3559 3560 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE; 3561 3562 3563 void* result; 3564 3565 if (start != lp_start) { 3566 result = ::mmap(start, lp_start - start, prot, 3567 MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, 3568 -1, 0); 3569 if (result == MAP_FAILED) { 3570 ::munmap(lp_start, end - lp_start); 3571 return NULL; 3572 } 3573 } 3574 3575 result = ::mmap(lp_start, lp_bytes, prot, 3576 MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED|MAP_HUGETLB, 3577 -1, 0); 3578 if (result == MAP_FAILED) { 3579 warn_on_large_pages_failure(req_addr, bytes, errno); 3580 // If the mmap above fails, the large pages region will be unmapped and we 3581 // have regions before and after with small pages. Release these regions. 3582 // 3583 // | mapped | unmapped | mapped | 3584 // ^ ^ ^ ^ 3585 // start lp_start lp_end end 3586 // 3587 ::munmap(start, lp_start - start); 3588 ::munmap(lp_end, end - lp_end); 3589 return NULL; 3590 } 3591 3592 if (lp_end != end) { 3593 result = ::mmap(lp_end, end - lp_end, prot, 3594 MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, 3595 -1, 0); 3596 if (result == MAP_FAILED) { 3597 ::munmap(start, lp_end - start); 3598 return NULL; 3599 } 3600 } 3601 3602 return start; 3603 } 3604 3605 char* os::Linux::reserve_memory_special_huge_tlbfs(size_t bytes, 3606 size_t alignment, 3607 char* req_addr, 3608 bool exec) { 3609 assert(UseLargePages && UseHugeTLBFS, "only for Huge TLBFS large pages"); 3610 assert(is_ptr_aligned(req_addr, alignment), "Must be"); 3611 assert(is_power_of_2(alignment), "Must be"); 3612 assert(is_power_of_2(os::large_page_size()), "Must be"); 3613 assert(bytes >= os::large_page_size(), "Shouldn't allocate large pages for small sizes"); 3614 3615 if (is_size_aligned(bytes, os::large_page_size()) && alignment <= os::large_page_size()) { 3616 return reserve_memory_special_huge_tlbfs_only(bytes, req_addr, exec); 3617 } else { 3618 return reserve_memory_special_huge_tlbfs_mixed(bytes, alignment, req_addr, exec); 3619 } 3620 } 3621 3622 char* os::reserve_memory_special(size_t bytes, size_t alignment, 3623 char* req_addr, bool exec) { 3624 assert(UseLargePages, "only for large pages"); 3625 3626 char* addr; 3627 if (UseSHM) { 3628 addr = os::Linux::reserve_memory_special_shm(bytes, alignment, req_addr, exec); 3629 } else { 3630 assert(UseHugeTLBFS, "must be"); 3631 addr = os::Linux::reserve_memory_special_huge_tlbfs(bytes, alignment, req_addr, exec); 3632 } 3633 3634 if (addr != NULL) { 3635 if (UseNUMAInterleaving) { 3636 numa_make_global(addr, bytes); 3637 } 3638 3639 // The memory is committed 3640 MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, CALLER_PC); 3641 } 3642 3643 return addr; 3644 } 3645 3646 bool os::Linux::release_memory_special_shm(char* base, size_t bytes) { 3647 // detaching the SHM segment will also delete it, see reserve_memory_special_shm() 3648 return shmdt(base) == 0; 3649 } 3650 3651 bool os::Linux::release_memory_special_huge_tlbfs(char* base, size_t bytes) { 3652 return pd_release_memory(base, bytes); 3653 } 3654 3655 bool os::release_memory_special(char* base, size_t bytes) { 3656 bool res; 3657 if (MemTracker::tracking_level() > NMT_minimal) { 3658 Tracker tkr = MemTracker::get_virtual_memory_release_tracker(); 3659 res = os::Linux::release_memory_special_impl(base, bytes); 3660 if (res) { 3661 tkr.record((address)base, bytes); 3662 } 3663 3664 } else { 3665 res = os::Linux::release_memory_special_impl(base, bytes); 3666 } 3667 return res; 3668 } 3669 3670 bool os::Linux::release_memory_special_impl(char* base, size_t bytes) { 3671 assert(UseLargePages, "only for large pages"); 3672 bool res; 3673 3674 if (UseSHM) { 3675 res = os::Linux::release_memory_special_shm(base, bytes); 3676 } else { 3677 assert(UseHugeTLBFS, "must be"); 3678 res = os::Linux::release_memory_special_huge_tlbfs(base, bytes); 3679 } 3680 return res; 3681 } 3682 3683 size_t os::large_page_size() { 3684 return _large_page_size; 3685 } 3686 3687 // With SysV SHM the entire memory region must be allocated as shared 3688 // memory. 3689 // HugeTLBFS allows application to commit large page memory on demand. 3690 // However, when committing memory with HugeTLBFS fails, the region 3691 // that was supposed to be committed will lose the old reservation 3692 // and allow other threads to steal that memory region. Because of this 3693 // behavior we can't commit HugeTLBFS memory. 3694 bool os::can_commit_large_page_memory() { 3695 return UseTransparentHugePages; 3696 } 3697 3698 bool os::can_execute_large_page_memory() { 3699 return UseTransparentHugePages || UseHugeTLBFS; 3700 } 3701 3702 // Reserve memory at an arbitrary address, only if that area is 3703 // available (and not reserved for something else). 3704 3705 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) { 3706 const int max_tries = 10; 3707 char* base[max_tries]; 3708 size_t size[max_tries]; 3709 const size_t gap = 0x000000; 3710 3711 // Assert only that the size is a multiple of the page size, since 3712 // that's all that mmap requires, and since that's all we really know 3713 // about at this low abstraction level. If we need higher alignment, 3714 // we can either pass an alignment to this method or verify alignment 3715 // in one of the methods further up the call chain. See bug 5044738. 3716 assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block"); 3717 3718 // Repeatedly allocate blocks until the block is allocated at the 3719 // right spot. Give up after max_tries. Note that reserve_memory() will 3720 // automatically update _highest_vm_reserved_address if the call is 3721 // successful. The variable tracks the highest memory address every reserved 3722 // by JVM. It is used to detect heap-stack collision if running with 3723 // fixed-stack LinuxThreads. Because here we may attempt to reserve more 3724 // space than needed, it could confuse the collision detecting code. To 3725 // solve the problem, save current _highest_vm_reserved_address and 3726 // calculate the correct value before return. 3727 address old_highest = _highest_vm_reserved_address; 3728 3729 // Linux mmap allows caller to pass an address as hint; give it a try first, 3730 // if kernel honors the hint then we can return immediately. 3731 char * addr = anon_mmap(requested_addr, bytes, false); 3732 if (addr == requested_addr) { 3733 return requested_addr; 3734 } 3735 3736 if (addr != NULL) { 3737 // mmap() is successful but it fails to reserve at the requested address 3738 anon_munmap(addr, bytes); 3739 } 3740 3741 int i; 3742 for (i = 0; i < max_tries; ++i) { 3743 base[i] = reserve_memory(bytes); 3744 3745 if (base[i] != NULL) { 3746 // Is this the block we wanted? 3747 if (base[i] == requested_addr) { 3748 size[i] = bytes; 3749 break; 3750 } 3751 3752 // Does this overlap the block we wanted? Give back the overlapped 3753 // parts and try again. 3754 3755 size_t top_overlap = requested_addr + (bytes + gap) - base[i]; 3756 if (top_overlap >= 0 && top_overlap < bytes) { 3757 unmap_memory(base[i], top_overlap); 3758 base[i] += top_overlap; 3759 size[i] = bytes - top_overlap; 3760 } else { 3761 size_t bottom_overlap = base[i] + bytes - requested_addr; 3762 if (bottom_overlap >= 0 && bottom_overlap < bytes) { 3763 unmap_memory(requested_addr, bottom_overlap); 3764 size[i] = bytes - bottom_overlap; 3765 } else { 3766 size[i] = bytes; 3767 } 3768 } 3769 } 3770 } 3771 3772 // Give back the unused reserved pieces. 3773 3774 for (int j = 0; j < i; ++j) { 3775 if (base[j] != NULL) { 3776 unmap_memory(base[j], size[j]); 3777 } 3778 } 3779 3780 if (i < max_tries) { 3781 _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes); 3782 return requested_addr; 3783 } else { 3784 _highest_vm_reserved_address = old_highest; 3785 return NULL; 3786 } 3787 } 3788 3789 size_t os::read(int fd, void *buf, unsigned int nBytes) { 3790 return ::read(fd, buf, nBytes); 3791 } 3792 3793 size_t os::read_at(int fd, void *buf, unsigned int nBytes, jlong offset) { 3794 return ::pread(fd, buf, nBytes, offset); 3795 } 3796 3797 // Short sleep, direct OS call. 3798 // 3799 // Note: certain versions of Linux CFS scheduler (since 2.6.23) do not guarantee 3800 // sched_yield(2) will actually give up the CPU: 3801 // 3802 // * Alone on this pariticular CPU, keeps running. 3803 // * Before the introduction of "skip_buddy" with "compat_yield" disabled 3804 // (pre 2.6.39). 3805 // 3806 // So calling this with 0 is an alternative. 3807 // 3808 void os::naked_short_sleep(jlong ms) { 3809 struct timespec req; 3810 3811 assert(ms < 1000, "Un-interruptable sleep, short time use only"); 3812 req.tv_sec = 0; 3813 if (ms > 0) { 3814 req.tv_nsec = (ms % 1000) * 1000000; 3815 } else { 3816 req.tv_nsec = 1; 3817 } 3818 3819 nanosleep(&req, NULL); 3820 3821 return; 3822 } 3823 3824 // Sleep forever; naked call to OS-specific sleep; use with CAUTION 3825 void os::infinite_sleep() { 3826 while (true) { // sleep forever ... 3827 ::sleep(100); // ... 100 seconds at a time 3828 } 3829 } 3830 3831 // Used to convert frequent JVM_Yield() to nops 3832 bool os::dont_yield() { 3833 return DontYieldALot; 3834 } 3835 3836 void os::naked_yield() { 3837 sched_yield(); 3838 } 3839 3840 //////////////////////////////////////////////////////////////////////////////// 3841 // thread priority support 3842 3843 // Note: Normal Linux applications are run with SCHED_OTHER policy. SCHED_OTHER 3844 // only supports dynamic priority, static priority must be zero. For real-time 3845 // applications, Linux supports SCHED_RR which allows static priority (1-99). 3846 // However, for large multi-threaded applications, SCHED_RR is not only slower 3847 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out 3848 // of 5 runs - Sep 2005). 3849 // 3850 // The following code actually changes the niceness of kernel-thread/LWP. It 3851 // has an assumption that setpriority() only modifies one kernel-thread/LWP, 3852 // not the entire user process, and user level threads are 1:1 mapped to kernel 3853 // threads. It has always been the case, but could change in the future. For 3854 // this reason, the code should not be used as default (ThreadPriorityPolicy=0). 3855 // It is only used when ThreadPriorityPolicy=1 and requires root privilege. 3856 3857 int os::java_to_os_priority[CriticalPriority + 1] = { 3858 19, // 0 Entry should never be used 3859 3860 4, // 1 MinPriority 3861 3, // 2 3862 2, // 3 3863 3864 1, // 4 3865 0, // 5 NormPriority 3866 -1, // 6 3867 3868 -2, // 7 3869 -3, // 8 3870 -4, // 9 NearMaxPriority 3871 3872 -5, // 10 MaxPriority 3873 3874 -5 // 11 CriticalPriority 3875 }; 3876 3877 static int prio_init() { 3878 if (ThreadPriorityPolicy == 1) { 3879 // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1 3880 // if effective uid is not root. Perhaps, a more elegant way of doing 3881 // this is to test CAP_SYS_NICE capability, but that will require libcap.so 3882 if (geteuid() != 0) { 3883 if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) { 3884 warning("-XX:ThreadPriorityPolicy requires root privilege on Linux"); 3885 } 3886 ThreadPriorityPolicy = 0; 3887 } 3888 } 3889 if (UseCriticalJavaThreadPriority) { 3890 os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority]; 3891 } 3892 return 0; 3893 } 3894 3895 OSReturn os::set_native_priority(Thread* thread, int newpri) { 3896 if (!UseThreadPriorities || ThreadPriorityPolicy == 0) return OS_OK; 3897 3898 int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri); 3899 return (ret == 0) ? OS_OK : OS_ERR; 3900 } 3901 3902 OSReturn os::get_native_priority(const Thread* const thread, 3903 int *priority_ptr) { 3904 if (!UseThreadPriorities || ThreadPriorityPolicy == 0) { 3905 *priority_ptr = java_to_os_priority[NormPriority]; 3906 return OS_OK; 3907 } 3908 3909 errno = 0; 3910 *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id()); 3911 return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR); 3912 } 3913 3914 // Hint to the underlying OS that a task switch would not be good. 3915 // Void return because it's a hint and can fail. 3916 void os::hint_no_preempt() {} 3917 3918 //////////////////////////////////////////////////////////////////////////////// 3919 // suspend/resume support 3920 3921 // the low-level signal-based suspend/resume support is a remnant from the 3922 // old VM-suspension that used to be for java-suspension, safepoints etc, 3923 // within hotspot. Now there is a single use-case for this: 3924 // - calling get_thread_pc() on the VMThread by the flat-profiler task 3925 // that runs in the watcher thread. 3926 // The remaining code is greatly simplified from the more general suspension 3927 // code that used to be used. 3928 // 3929 // The protocol is quite simple: 3930 // - suspend: 3931 // - sends a signal to the target thread 3932 // - polls the suspend state of the osthread using a yield loop 3933 // - target thread signal handler (SR_handler) sets suspend state 3934 // and blocks in sigsuspend until continued 3935 // - resume: 3936 // - sets target osthread state to continue 3937 // - sends signal to end the sigsuspend loop in the SR_handler 3938 // 3939 // Note that the SR_lock plays no role in this suspend/resume protocol. 3940 3941 static void resume_clear_context(OSThread *osthread) { 3942 osthread->set_ucontext(NULL); 3943 osthread->set_siginfo(NULL); 3944 } 3945 3946 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, 3947 ucontext_t* context) { 3948 osthread->set_ucontext(context); 3949 osthread->set_siginfo(siginfo); 3950 } 3951 3952 // Handler function invoked when a thread's execution is suspended or 3953 // resumed. We have to be careful that only async-safe functions are 3954 // called here (Note: most pthread functions are not async safe and 3955 // should be avoided.) 3956 // 3957 // Note: sigwait() is a more natural fit than sigsuspend() from an 3958 // interface point of view, but sigwait() prevents the signal hander 3959 // from being run. libpthread would get very confused by not having 3960 // its signal handlers run and prevents sigwait()'s use with the 3961 // mutex granting granting signal. 3962 // 3963 // Currently only ever called on the VMThread and JavaThreads (PC sampling) 3964 // 3965 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) { 3966 // Save and restore errno to avoid confusing native code with EINTR 3967 // after sigsuspend. 3968 int old_errno = errno; 3969 3970 Thread* thread = Thread::current(); 3971 OSThread* osthread = thread->osthread(); 3972 assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread"); 3973 3974 os::SuspendResume::State current = osthread->sr.state(); 3975 if (current == os::SuspendResume::SR_SUSPEND_REQUEST) { 3976 suspend_save_context(osthread, siginfo, context); 3977 3978 // attempt to switch the state, we assume we had a SUSPEND_REQUEST 3979 os::SuspendResume::State state = osthread->sr.suspended(); 3980 if (state == os::SuspendResume::SR_SUSPENDED) { 3981 sigset_t suspend_set; // signals for sigsuspend() 3982 3983 // get current set of blocked signals and unblock resume signal 3984 pthread_sigmask(SIG_BLOCK, NULL, &suspend_set); 3985 sigdelset(&suspend_set, SR_signum); 3986 3987 sr_semaphore.signal(); 3988 // wait here until we are resumed 3989 while (1) { 3990 sigsuspend(&suspend_set); 3991 3992 os::SuspendResume::State result = osthread->sr.running(); 3993 if (result == os::SuspendResume::SR_RUNNING) { 3994 sr_semaphore.signal(); 3995 break; 3996 } 3997 } 3998 3999 } else if (state == os::SuspendResume::SR_RUNNING) { 4000 // request was cancelled, continue 4001 } else { 4002 ShouldNotReachHere(); 4003 } 4004 4005 resume_clear_context(osthread); 4006 } else if (current == os::SuspendResume::SR_RUNNING) { 4007 // request was cancelled, continue 4008 } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) { 4009 // ignore 4010 } else { 4011 // ignore 4012 } 4013 4014 errno = old_errno; 4015 } 4016 4017 4018 static int SR_initialize() { 4019 struct sigaction act; 4020 char *s; 4021 // Get signal number to use for suspend/resume 4022 if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) { 4023 int sig = ::strtol(s, 0, 10); 4024 if (sig > 0 || sig < _NSIG) { 4025 SR_signum = sig; 4026 } 4027 } 4028 4029 assert(SR_signum > SIGSEGV && SR_signum > SIGBUS, 4030 "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769"); 4031 4032 sigemptyset(&SR_sigset); 4033 sigaddset(&SR_sigset, SR_signum); 4034 4035 // Set up signal handler for suspend/resume 4036 act.sa_flags = SA_RESTART|SA_SIGINFO; 4037 act.sa_handler = (void (*)(int)) SR_handler; 4038 4039 // SR_signum is blocked by default. 4040 // 4528190 - We also need to block pthread restart signal (32 on all 4041 // supported Linux platforms). Note that LinuxThreads need to block 4042 // this signal for all threads to work properly. So we don't have 4043 // to use hard-coded signal number when setting up the mask. 4044 pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask); 4045 4046 if (sigaction(SR_signum, &act, 0) == -1) { 4047 return -1; 4048 } 4049 4050 // Save signal flag 4051 os::Linux::set_our_sigflags(SR_signum, act.sa_flags); 4052 return 0; 4053 } 4054 4055 static int sr_notify(OSThread* osthread) { 4056 int status = pthread_kill(osthread->pthread_id(), SR_signum); 4057 assert_status(status == 0, status, "pthread_kill"); 4058 return status; 4059 } 4060 4061 // "Randomly" selected value for how long we want to spin 4062 // before bailing out on suspending a thread, also how often 4063 // we send a signal to a thread we want to resume 4064 static const int RANDOMLY_LARGE_INTEGER = 1000000; 4065 static const int RANDOMLY_LARGE_INTEGER2 = 100; 4066 4067 // returns true on success and false on error - really an error is fatal 4068 // but this seems the normal response to library errors 4069 static bool do_suspend(OSThread* osthread) { 4070 assert(osthread->sr.is_running(), "thread should be running"); 4071 assert(!sr_semaphore.trywait(), "semaphore has invalid state"); 4072 4073 // mark as suspended and send signal 4074 if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) { 4075 // failed to switch, state wasn't running? 4076 ShouldNotReachHere(); 4077 return false; 4078 } 4079 4080 if (sr_notify(osthread) != 0) { 4081 ShouldNotReachHere(); 4082 } 4083 4084 // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED 4085 while (true) { 4086 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) { 4087 break; 4088 } else { 4089 // timeout 4090 os::SuspendResume::State cancelled = osthread->sr.cancel_suspend(); 4091 if (cancelled == os::SuspendResume::SR_RUNNING) { 4092 return false; 4093 } else if (cancelled == os::SuspendResume::SR_SUSPENDED) { 4094 // make sure that we consume the signal on the semaphore as well 4095 sr_semaphore.wait(); 4096 break; 4097 } else { 4098 ShouldNotReachHere(); 4099 return false; 4100 } 4101 } 4102 } 4103 4104 guarantee(osthread->sr.is_suspended(), "Must be suspended"); 4105 return true; 4106 } 4107 4108 static void do_resume(OSThread* osthread) { 4109 assert(osthread->sr.is_suspended(), "thread should be suspended"); 4110 assert(!sr_semaphore.trywait(), "invalid semaphore state"); 4111 4112 if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) { 4113 // failed to switch to WAKEUP_REQUEST 4114 ShouldNotReachHere(); 4115 return; 4116 } 4117 4118 while (true) { 4119 if (sr_notify(osthread) == 0) { 4120 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) { 4121 if (osthread->sr.is_running()) { 4122 return; 4123 } 4124 } 4125 } else { 4126 ShouldNotReachHere(); 4127 } 4128 } 4129 4130 guarantee(osthread->sr.is_running(), "Must be running!"); 4131 } 4132 4133 /////////////////////////////////////////////////////////////////////////////////// 4134 // signal handling (except suspend/resume) 4135 4136 // This routine may be used by user applications as a "hook" to catch signals. 4137 // The user-defined signal handler must pass unrecognized signals to this 4138 // routine, and if it returns true (non-zero), then the signal handler must 4139 // return immediately. If the flag "abort_if_unrecognized" is true, then this 4140 // routine will never retun false (zero), but instead will execute a VM panic 4141 // routine kill the process. 4142 // 4143 // If this routine returns false, it is OK to call it again. This allows 4144 // the user-defined signal handler to perform checks either before or after 4145 // the VM performs its own checks. Naturally, the user code would be making 4146 // a serious error if it tried to handle an exception (such as a null check 4147 // or breakpoint) that the VM was generating for its own correct operation. 4148 // 4149 // This routine may recognize any of the following kinds of signals: 4150 // SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1. 4151 // It should be consulted by handlers for any of those signals. 4152 // 4153 // The caller of this routine must pass in the three arguments supplied 4154 // to the function referred to in the "sa_sigaction" (not the "sa_handler") 4155 // field of the structure passed to sigaction(). This routine assumes that 4156 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART. 4157 // 4158 // Note that the VM will print warnings if it detects conflicting signal 4159 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers". 4160 // 4161 extern "C" JNIEXPORT int JVM_handle_linux_signal(int signo, 4162 siginfo_t* siginfo, 4163 void* ucontext, 4164 int abort_if_unrecognized); 4165 4166 void signalHandler(int sig, siginfo_t* info, void* uc) { 4167 assert(info != NULL && uc != NULL, "it must be old kernel"); 4168 int orig_errno = errno; // Preserve errno value over signal handler. 4169 JVM_handle_linux_signal(sig, info, uc, true); 4170 errno = orig_errno; 4171 } 4172 4173 4174 // This boolean allows users to forward their own non-matching signals 4175 // to JVM_handle_linux_signal, harmlessly. 4176 bool os::Linux::signal_handlers_are_installed = false; 4177 4178 // For signal-chaining 4179 struct sigaction os::Linux::sigact[MAXSIGNUM]; 4180 unsigned int os::Linux::sigs = 0; 4181 bool os::Linux::libjsig_is_loaded = false; 4182 typedef struct sigaction *(*get_signal_t)(int); 4183 get_signal_t os::Linux::get_signal_action = NULL; 4184 4185 struct sigaction* os::Linux::get_chained_signal_action(int sig) { 4186 struct sigaction *actp = NULL; 4187 4188 if (libjsig_is_loaded) { 4189 // Retrieve the old signal handler from libjsig 4190 actp = (*get_signal_action)(sig); 4191 } 4192 if (actp == NULL) { 4193 // Retrieve the preinstalled signal handler from jvm 4194 actp = get_preinstalled_handler(sig); 4195 } 4196 4197 return actp; 4198 } 4199 4200 static bool call_chained_handler(struct sigaction *actp, int sig, 4201 siginfo_t *siginfo, void *context) { 4202 // Call the old signal handler 4203 if (actp->sa_handler == SIG_DFL) { 4204 // It's more reasonable to let jvm treat it as an unexpected exception 4205 // instead of taking the default action. 4206 return false; 4207 } else if (actp->sa_handler != SIG_IGN) { 4208 if ((actp->sa_flags & SA_NODEFER) == 0) { 4209 // automaticlly block the signal 4210 sigaddset(&(actp->sa_mask), sig); 4211 } 4212 4213 sa_handler_t hand; 4214 sa_sigaction_t sa; 4215 bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0; 4216 // retrieve the chained handler 4217 if (siginfo_flag_set) { 4218 sa = actp->sa_sigaction; 4219 } else { 4220 hand = actp->sa_handler; 4221 } 4222 4223 if ((actp->sa_flags & SA_RESETHAND) != 0) { 4224 actp->sa_handler = SIG_DFL; 4225 } 4226 4227 // try to honor the signal mask 4228 sigset_t oset; 4229 pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset); 4230 4231 // call into the chained handler 4232 if (siginfo_flag_set) { 4233 (*sa)(sig, siginfo, context); 4234 } else { 4235 (*hand)(sig); 4236 } 4237 4238 // restore the signal mask 4239 pthread_sigmask(SIG_SETMASK, &oset, 0); 4240 } 4241 // Tell jvm's signal handler the signal is taken care of. 4242 return true; 4243 } 4244 4245 bool os::Linux::chained_handler(int sig, siginfo_t* siginfo, void* context) { 4246 bool chained = false; 4247 // signal-chaining 4248 if (UseSignalChaining) { 4249 struct sigaction *actp = get_chained_signal_action(sig); 4250 if (actp != NULL) { 4251 chained = call_chained_handler(actp, sig, siginfo, context); 4252 } 4253 } 4254 return chained; 4255 } 4256 4257 struct sigaction* os::Linux::get_preinstalled_handler(int sig) { 4258 if ((((unsigned int)1 << sig) & sigs) != 0) { 4259 return &sigact[sig]; 4260 } 4261 return NULL; 4262 } 4263 4264 void os::Linux::save_preinstalled_handler(int sig, struct sigaction& oldAct) { 4265 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 4266 sigact[sig] = oldAct; 4267 sigs |= (unsigned int)1 << sig; 4268 } 4269 4270 // for diagnostic 4271 int os::Linux::sigflags[MAXSIGNUM]; 4272 4273 int os::Linux::get_our_sigflags(int sig) { 4274 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 4275 return sigflags[sig]; 4276 } 4277 4278 void os::Linux::set_our_sigflags(int sig, int flags) { 4279 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 4280 sigflags[sig] = flags; 4281 } 4282 4283 void os::Linux::set_signal_handler(int sig, bool set_installed) { 4284 // Check for overwrite. 4285 struct sigaction oldAct; 4286 sigaction(sig, (struct sigaction*)NULL, &oldAct); 4287 4288 void* oldhand = oldAct.sa_sigaction 4289 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) 4290 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); 4291 if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) && 4292 oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) && 4293 oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) { 4294 if (AllowUserSignalHandlers || !set_installed) { 4295 // Do not overwrite; user takes responsibility to forward to us. 4296 return; 4297 } else if (UseSignalChaining) { 4298 // save the old handler in jvm 4299 save_preinstalled_handler(sig, oldAct); 4300 // libjsig also interposes the sigaction() call below and saves the 4301 // old sigaction on it own. 4302 } else { 4303 fatal(err_msg("Encountered unexpected pre-existing sigaction handler " 4304 "%#lx for signal %d.", (long)oldhand, sig)); 4305 } 4306 } 4307 4308 struct sigaction sigAct; 4309 sigfillset(&(sigAct.sa_mask)); 4310 sigAct.sa_handler = SIG_DFL; 4311 if (!set_installed) { 4312 sigAct.sa_flags = SA_SIGINFO|SA_RESTART; 4313 } else { 4314 sigAct.sa_sigaction = signalHandler; 4315 sigAct.sa_flags = SA_SIGINFO|SA_RESTART; 4316 } 4317 // Save flags, which are set by ours 4318 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 4319 sigflags[sig] = sigAct.sa_flags; 4320 4321 int ret = sigaction(sig, &sigAct, &oldAct); 4322 assert(ret == 0, "check"); 4323 4324 void* oldhand2 = oldAct.sa_sigaction 4325 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) 4326 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); 4327 assert(oldhand2 == oldhand, "no concurrent signal handler installation"); 4328 } 4329 4330 // install signal handlers for signals that HotSpot needs to 4331 // handle in order to support Java-level exception handling. 4332 4333 void os::Linux::install_signal_handlers() { 4334 if (!signal_handlers_are_installed) { 4335 signal_handlers_are_installed = true; 4336 4337 // signal-chaining 4338 typedef void (*signal_setting_t)(); 4339 signal_setting_t begin_signal_setting = NULL; 4340 signal_setting_t end_signal_setting = NULL; 4341 begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t, 4342 dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting")); 4343 if (begin_signal_setting != NULL) { 4344 end_signal_setting = CAST_TO_FN_PTR(signal_setting_t, 4345 dlsym(RTLD_DEFAULT, "JVM_end_signal_setting")); 4346 get_signal_action = CAST_TO_FN_PTR(get_signal_t, 4347 dlsym(RTLD_DEFAULT, "JVM_get_signal_action")); 4348 libjsig_is_loaded = true; 4349 assert(UseSignalChaining, "should enable signal-chaining"); 4350 } 4351 if (libjsig_is_loaded) { 4352 // Tell libjsig jvm is setting signal handlers 4353 (*begin_signal_setting)(); 4354 } 4355 4356 set_signal_handler(SIGSEGV, true); 4357 set_signal_handler(SIGPIPE, true); 4358 set_signal_handler(SIGBUS, true); 4359 set_signal_handler(SIGILL, true); 4360 set_signal_handler(SIGFPE, true); 4361 #if defined(PPC64) 4362 set_signal_handler(SIGTRAP, true); 4363 #endif 4364 set_signal_handler(SIGXFSZ, true); 4365 4366 if (libjsig_is_loaded) { 4367 // Tell libjsig jvm finishes setting signal handlers 4368 (*end_signal_setting)(); 4369 } 4370 4371 // We don't activate signal checker if libjsig is in place, we trust ourselves 4372 // and if UserSignalHandler is installed all bets are off. 4373 // Log that signal checking is off only if -verbose:jni is specified. 4374 if (CheckJNICalls) { 4375 if (libjsig_is_loaded) { 4376 if (PrintJNIResolving) { 4377 tty->print_cr("Info: libjsig is activated, all active signal checking is disabled"); 4378 } 4379 check_signals = false; 4380 } 4381 if (AllowUserSignalHandlers) { 4382 if (PrintJNIResolving) { 4383 tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled"); 4384 } 4385 check_signals = false; 4386 } 4387 } 4388 } 4389 } 4390 4391 // This is the fastest way to get thread cpu time on Linux. 4392 // Returns cpu time (user+sys) for any thread, not only for current. 4393 // POSIX compliant clocks are implemented in the kernels 2.6.16+. 4394 // It might work on 2.6.10+ with a special kernel/glibc patch. 4395 // For reference, please, see IEEE Std 1003.1-2004: 4396 // http://www.unix.org/single_unix_specification 4397 4398 jlong os::Linux::fast_thread_cpu_time(clockid_t clockid) { 4399 struct timespec tp; 4400 int rc = os::Linux::clock_gettime(clockid, &tp); 4401 assert(rc == 0, "clock_gettime is expected to return 0 code"); 4402 4403 return (tp.tv_sec * NANOSECS_PER_SEC) + tp.tv_nsec; 4404 } 4405 4406 ///// 4407 // glibc on Linux platform uses non-documented flag 4408 // to indicate, that some special sort of signal 4409 // trampoline is used. 4410 // We will never set this flag, and we should 4411 // ignore this flag in our diagnostic 4412 #ifdef SIGNIFICANT_SIGNAL_MASK 4413 #undef SIGNIFICANT_SIGNAL_MASK 4414 #endif 4415 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000) 4416 4417 static const char* get_signal_handler_name(address handler, 4418 char* buf, int buflen) { 4419 int offset; 4420 bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset); 4421 if (found) { 4422 // skip directory names 4423 const char *p1, *p2; 4424 p1 = buf; 4425 size_t len = strlen(os::file_separator()); 4426 while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len; 4427 jio_snprintf(buf, buflen, "%s+0x%x", p1, offset); 4428 } else { 4429 jio_snprintf(buf, buflen, PTR_FORMAT, handler); 4430 } 4431 return buf; 4432 } 4433 4434 static void print_signal_handler(outputStream* st, int sig, 4435 char* buf, size_t buflen) { 4436 struct sigaction sa; 4437 4438 sigaction(sig, NULL, &sa); 4439 4440 // See comment for SIGNIFICANT_SIGNAL_MASK define 4441 sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK; 4442 4443 st->print("%s: ", os::exception_name(sig, buf, buflen)); 4444 4445 address handler = (sa.sa_flags & SA_SIGINFO) 4446 ? CAST_FROM_FN_PTR(address, sa.sa_sigaction) 4447 : CAST_FROM_FN_PTR(address, sa.sa_handler); 4448 4449 if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) { 4450 st->print("SIG_DFL"); 4451 } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) { 4452 st->print("SIG_IGN"); 4453 } else { 4454 st->print("[%s]", get_signal_handler_name(handler, buf, buflen)); 4455 } 4456 4457 st->print(", sa_mask[0]="); 4458 os::Posix::print_signal_set_short(st, &sa.sa_mask); 4459 4460 address rh = VMError::get_resetted_sighandler(sig); 4461 // May be, handler was resetted by VMError? 4462 if (rh != NULL) { 4463 handler = rh; 4464 sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK; 4465 } 4466 4467 st->print(", sa_flags="); 4468 os::Posix::print_sa_flags(st, sa.sa_flags); 4469 4470 // Check: is it our handler? 4471 if (handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) || 4472 handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) { 4473 // It is our signal handler 4474 // check for flags, reset system-used one! 4475 if ((int)sa.sa_flags != os::Linux::get_our_sigflags(sig)) { 4476 st->print( 4477 ", flags was changed from " PTR32_FORMAT ", consider using jsig library", 4478 os::Linux::get_our_sigflags(sig)); 4479 } 4480 } 4481 st->cr(); 4482 } 4483 4484 4485 #define DO_SIGNAL_CHECK(sig) \ 4486 do { \ 4487 if (!sigismember(&check_signal_done, sig)) { \ 4488 os::Linux::check_signal_handler(sig); \ 4489 } \ 4490 } while (0) 4491 4492 // This method is a periodic task to check for misbehaving JNI applications 4493 // under CheckJNI, we can add any periodic checks here 4494 4495 void os::run_periodic_checks() { 4496 if (check_signals == false) return; 4497 4498 // SEGV and BUS if overridden could potentially prevent 4499 // generation of hs*.log in the event of a crash, debugging 4500 // such a case can be very challenging, so we absolutely 4501 // check the following for a good measure: 4502 DO_SIGNAL_CHECK(SIGSEGV); 4503 DO_SIGNAL_CHECK(SIGILL); 4504 DO_SIGNAL_CHECK(SIGFPE); 4505 DO_SIGNAL_CHECK(SIGBUS); 4506 DO_SIGNAL_CHECK(SIGPIPE); 4507 DO_SIGNAL_CHECK(SIGXFSZ); 4508 #if defined(PPC64) 4509 DO_SIGNAL_CHECK(SIGTRAP); 4510 #endif 4511 4512 // ReduceSignalUsage allows the user to override these handlers 4513 // see comments at the very top and jvm_solaris.h 4514 if (!ReduceSignalUsage) { 4515 DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL); 4516 DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL); 4517 DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL); 4518 DO_SIGNAL_CHECK(BREAK_SIGNAL); 4519 } 4520 4521 DO_SIGNAL_CHECK(SR_signum); 4522 DO_SIGNAL_CHECK(INTERRUPT_SIGNAL); 4523 } 4524 4525 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *); 4526 4527 static os_sigaction_t os_sigaction = NULL; 4528 4529 void os::Linux::check_signal_handler(int sig) { 4530 char buf[O_BUFLEN]; 4531 address jvmHandler = NULL; 4532 4533 4534 struct sigaction act; 4535 if (os_sigaction == NULL) { 4536 // only trust the default sigaction, in case it has been interposed 4537 os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction"); 4538 if (os_sigaction == NULL) return; 4539 } 4540 4541 os_sigaction(sig, (struct sigaction*)NULL, &act); 4542 4543 4544 act.sa_flags &= SIGNIFICANT_SIGNAL_MASK; 4545 4546 address thisHandler = (act.sa_flags & SA_SIGINFO) 4547 ? CAST_FROM_FN_PTR(address, act.sa_sigaction) 4548 : CAST_FROM_FN_PTR(address, act.sa_handler); 4549 4550 4551 switch (sig) { 4552 case SIGSEGV: 4553 case SIGBUS: 4554 case SIGFPE: 4555 case SIGPIPE: 4556 case SIGILL: 4557 case SIGXFSZ: 4558 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler); 4559 break; 4560 4561 case SHUTDOWN1_SIGNAL: 4562 case SHUTDOWN2_SIGNAL: 4563 case SHUTDOWN3_SIGNAL: 4564 case BREAK_SIGNAL: 4565 jvmHandler = (address)user_handler(); 4566 break; 4567 4568 case INTERRUPT_SIGNAL: 4569 jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL); 4570 break; 4571 4572 default: 4573 if (sig == SR_signum) { 4574 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler); 4575 } else { 4576 return; 4577 } 4578 break; 4579 } 4580 4581 if (thisHandler != jvmHandler) { 4582 tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN)); 4583 tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN)); 4584 tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN)); 4585 // No need to check this sig any longer 4586 sigaddset(&check_signal_done, sig); 4587 // Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN 4588 if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) { 4589 tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell", 4590 exception_name(sig, buf, O_BUFLEN)); 4591 } 4592 } else if(os::Linux::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Linux::get_our_sigflags(sig)) { 4593 tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN)); 4594 tty->print("expected:" PTR32_FORMAT, os::Linux::get_our_sigflags(sig)); 4595 tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags); 4596 // No need to check this sig any longer 4597 sigaddset(&check_signal_done, sig); 4598 } 4599 4600 // Dump all the signal 4601 if (sigismember(&check_signal_done, sig)) { 4602 print_signal_handlers(tty, buf, O_BUFLEN); 4603 } 4604 } 4605 4606 extern void report_error(char* file_name, int line_no, char* title, 4607 char* format, ...); 4608 4609 extern bool signal_name(int signo, char* buf, size_t len); 4610 4611 const char* os::exception_name(int exception_code, char* buf, size_t size) { 4612 if (0 < exception_code && exception_code <= SIGRTMAX) { 4613 // signal 4614 if (!signal_name(exception_code, buf, size)) { 4615 jio_snprintf(buf, size, "SIG%d", exception_code); 4616 } 4617 return buf; 4618 } else { 4619 return NULL; 4620 } 4621 } 4622 4623 // this is called _before_ the most of global arguments have been parsed 4624 void os::init(void) { 4625 char dummy; // used to get a guess on initial stack address 4626 // first_hrtime = gethrtime(); 4627 4628 // With LinuxThreads the JavaMain thread pid (primordial thread) 4629 // is different than the pid of the java launcher thread. 4630 // So, on Linux, the launcher thread pid is passed to the VM 4631 // via the sun.java.launcher.pid property. 4632 // Use this property instead of getpid() if it was correctly passed. 4633 // See bug 6351349. 4634 pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid(); 4635 4636 _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid(); 4637 4638 clock_tics_per_sec = sysconf(_SC_CLK_TCK); 4639 4640 init_random(1234567); 4641 4642 ThreadCritical::initialize(); 4643 4644 Linux::set_page_size(sysconf(_SC_PAGESIZE)); 4645 if (Linux::page_size() == -1) { 4646 fatal(err_msg("os_linux.cpp: os::init: sysconf failed (%s)", 4647 strerror(errno))); 4648 } 4649 init_page_sizes((size_t) Linux::page_size()); 4650 4651 Linux::initialize_system_info(); 4652 4653 // main_thread points to the aboriginal thread 4654 Linux::_main_thread = pthread_self(); 4655 4656 Linux::clock_init(); 4657 initial_time_count = javaTimeNanos(); 4658 4659 // pthread_condattr initialization for monotonic clock 4660 int status; 4661 pthread_condattr_t* _condattr = os::Linux::condAttr(); 4662 if ((status = pthread_condattr_init(_condattr)) != 0) { 4663 fatal(err_msg("pthread_condattr_init: %s", strerror(status))); 4664 } 4665 // Only set the clock if CLOCK_MONOTONIC is available 4666 if (os::supports_monotonic_clock()) { 4667 if ((status = pthread_condattr_setclock(_condattr, CLOCK_MONOTONIC)) != 0) { 4668 if (status == EINVAL) { 4669 warning("Unable to use monotonic clock with relative timed-waits" \ 4670 " - changes to the time-of-day clock may have adverse affects"); 4671 } else { 4672 fatal(err_msg("pthread_condattr_setclock: %s", strerror(status))); 4673 } 4674 } 4675 } 4676 // else it defaults to CLOCK_REALTIME 4677 4678 pthread_mutex_init(&dl_mutex, NULL); 4679 4680 // If the pagesize of the VM is greater than 8K determine the appropriate 4681 // number of initial guard pages. The user can change this with the 4682 // command line arguments, if needed. 4683 if (vm_page_size() > (int)Linux::vm_default_page_size()) { 4684 StackYellowPages = 1; 4685 StackRedPages = 1; 4686 StackShadowPages = round_to((StackShadowPages*Linux::vm_default_page_size()), vm_page_size()) / vm_page_size(); 4687 } 4688 4689 // retrieve entry point for pthread_setname_np 4690 Linux::_pthread_setname_np = 4691 (int(*)(pthread_t, const char*))dlsym(RTLD_DEFAULT, "pthread_setname_np"); 4692 4693 } 4694 4695 // To install functions for atexit system call 4696 extern "C" { 4697 static void perfMemory_exit_helper() { 4698 perfMemory_exit(); 4699 } 4700 } 4701 4702 // this is called _after_ the global arguments have been parsed 4703 jint os::init_2(void) { 4704 Linux::fast_thread_clock_init(); 4705 4706 // Allocate a single page and mark it as readable for safepoint polling 4707 address polling_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); 4708 guarantee(polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page"); 4709 4710 os::set_polling_page(polling_page); 4711 4712 #ifndef PRODUCT 4713 if (Verbose && PrintMiscellaneous) { 4714 tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", 4715 (intptr_t)polling_page); 4716 } 4717 #endif 4718 4719 if (!UseMembar) { 4720 address mem_serialize_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); 4721 guarantee(mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page"); 4722 os::set_memory_serialize_page(mem_serialize_page); 4723 4724 #ifndef PRODUCT 4725 if (Verbose && PrintMiscellaneous) { 4726 tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", 4727 (intptr_t)mem_serialize_page); 4728 } 4729 #endif 4730 } 4731 4732 // initialize suspend/resume support - must do this before signal_sets_init() 4733 if (SR_initialize() != 0) { 4734 perror("SR_initialize failed"); 4735 return JNI_ERR; 4736 } 4737 4738 Linux::signal_sets_init(); 4739 Linux::install_signal_handlers(); 4740 4741 // Check minimum allowable stack size for thread creation and to initialize 4742 // the java system classes, including StackOverflowError - depends on page 4743 // size. Add a page for compiler2 recursion in main thread. 4744 // Add in 2*BytesPerWord times page size to account for VM stack during 4745 // class initialization depending on 32 or 64 bit VM. 4746 os::Linux::min_stack_allowed = MAX2(os::Linux::min_stack_allowed, 4747 (size_t)(StackYellowPages+StackRedPages+StackShadowPages) * Linux::page_size() + 4748 (2*BytesPerWord COMPILER2_PRESENT(+1)) * Linux::vm_default_page_size()); 4749 4750 size_t threadStackSizeInBytes = ThreadStackSize * K; 4751 if (threadStackSizeInBytes != 0 && 4752 threadStackSizeInBytes < os::Linux::min_stack_allowed) { 4753 tty->print_cr("\nThe stack size specified is too small, " 4754 "Specify at least %dk", 4755 os::Linux::min_stack_allowed/ K); 4756 return JNI_ERR; 4757 } 4758 4759 // Make the stack size a multiple of the page size so that 4760 // the yellow/red zones can be guarded. 4761 JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes, 4762 vm_page_size())); 4763 4764 Linux::capture_initial_stack(JavaThread::stack_size_at_create()); 4765 4766 #if defined(IA32) 4767 workaround_expand_exec_shield_cs_limit(); 4768 #endif 4769 4770 Linux::libpthread_init(); 4771 if (PrintMiscellaneous && (Verbose || WizardMode)) { 4772 tty->print_cr("[HotSpot is running with %s, %s(%s)]\n", 4773 Linux::glibc_version(), Linux::libpthread_version(), 4774 Linux::is_floating_stack() ? "floating stack" : "fixed stack"); 4775 } 4776 4777 if (UseNUMA) { 4778 if (!Linux::libnuma_init()) { 4779 UseNUMA = false; 4780 } else { 4781 if ((Linux::numa_max_node() < 1)) { 4782 // There's only one node(they start from 0), disable NUMA. 4783 UseNUMA = false; 4784 } 4785 } 4786 // With SHM and HugeTLBFS large pages we cannot uncommit a page, so there's no way 4787 // we can make the adaptive lgrp chunk resizing work. If the user specified 4788 // both UseNUMA and UseLargePages (or UseSHM/UseHugeTLBFS) on the command line - warn and 4789 // disable adaptive resizing. 4790 if (UseNUMA && UseLargePages && !can_commit_large_page_memory()) { 4791 if (FLAG_IS_DEFAULT(UseNUMA)) { 4792 UseNUMA = false; 4793 } else { 4794 if (FLAG_IS_DEFAULT(UseLargePages) && 4795 FLAG_IS_DEFAULT(UseSHM) && 4796 FLAG_IS_DEFAULT(UseHugeTLBFS)) { 4797 UseLargePages = false; 4798 } else { 4799 warning("UseNUMA is not fully compatible with SHM/HugeTLBFS large pages, disabling adaptive resizing"); 4800 UseAdaptiveSizePolicy = false; 4801 UseAdaptiveNUMAChunkSizing = false; 4802 } 4803 } 4804 } 4805 if (!UseNUMA && ForceNUMA) { 4806 UseNUMA = true; 4807 } 4808 } 4809 4810 if (MaxFDLimit) { 4811 // set the number of file descriptors to max. print out error 4812 // if getrlimit/setrlimit fails but continue regardless. 4813 struct rlimit nbr_files; 4814 int status = getrlimit(RLIMIT_NOFILE, &nbr_files); 4815 if (status != 0) { 4816 if (PrintMiscellaneous && (Verbose || WizardMode)) { 4817 perror("os::init_2 getrlimit failed"); 4818 } 4819 } else { 4820 nbr_files.rlim_cur = nbr_files.rlim_max; 4821 status = setrlimit(RLIMIT_NOFILE, &nbr_files); 4822 if (status != 0) { 4823 if (PrintMiscellaneous && (Verbose || WizardMode)) { 4824 perror("os::init_2 setrlimit failed"); 4825 } 4826 } 4827 } 4828 } 4829 4830 // Initialize lock used to serialize thread creation (see os::create_thread) 4831 Linux::set_createThread_lock(new Mutex(Mutex::leaf, "createThread_lock", false)); 4832 4833 // at-exit methods are called in the reverse order of their registration. 4834 // atexit functions are called on return from main or as a result of a 4835 // call to exit(3C). There can be only 32 of these functions registered 4836 // and atexit() does not set errno. 4837 4838 if (PerfAllowAtExitRegistration) { 4839 // only register atexit functions if PerfAllowAtExitRegistration is set. 4840 // atexit functions can be delayed until process exit time, which 4841 // can be problematic for embedded VM situations. Embedded VMs should 4842 // call DestroyJavaVM() to assure that VM resources are released. 4843 4844 // note: perfMemory_exit_helper atexit function may be removed in 4845 // the future if the appropriate cleanup code can be added to the 4846 // VM_Exit VMOperation's doit method. 4847 if (atexit(perfMemory_exit_helper) != 0) { 4848 warning("os::init_2 atexit(perfMemory_exit_helper) failed"); 4849 } 4850 } 4851 4852 // initialize thread priority policy 4853 prio_init(); 4854 4855 return JNI_OK; 4856 } 4857 4858 // Mark the polling page as unreadable 4859 void os::make_polling_page_unreadable(void) { 4860 if (!guard_memory((char*)_polling_page, Linux::page_size())) { 4861 fatal("Could not disable polling page"); 4862 } 4863 } 4864 4865 // Mark the polling page as readable 4866 void os::make_polling_page_readable(void) { 4867 if (!linux_mprotect((char *)_polling_page, Linux::page_size(), PROT_READ)) { 4868 fatal("Could not enable polling page"); 4869 } 4870 } 4871 4872 int os::active_processor_count() { 4873 // Linux doesn't yet have a (official) notion of processor sets, 4874 // so just return the number of online processors. 4875 int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN); 4876 assert(online_cpus > 0 && online_cpus <= processor_count(), "sanity check"); 4877 return online_cpus; 4878 } 4879 4880 void os::set_native_thread_name(const char *name) { 4881 if (Linux::_pthread_setname_np) { 4882 char buf [16]; // according to glibc manpage, 16 chars incl. '/0' 4883 snprintf(buf, sizeof(buf), "%s", name); 4884 buf[sizeof(buf) - 1] = '\0'; 4885 const int rc = Linux::_pthread_setname_np(pthread_self(), buf); 4886 // ERANGE should not happen; all other errors should just be ignored. 4887 assert(rc != ERANGE, "pthread_setname_np failed"); 4888 } 4889 } 4890 4891 bool os::distribute_processes(uint length, uint* distribution) { 4892 // Not yet implemented. 4893 return false; 4894 } 4895 4896 bool os::bind_to_processor(uint processor_id) { 4897 // Not yet implemented. 4898 return false; 4899 } 4900 4901 /// 4902 4903 void os::SuspendedThreadTask::internal_do_task() { 4904 if (do_suspend(_thread->osthread())) { 4905 SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext()); 4906 do_task(context); 4907 do_resume(_thread->osthread()); 4908 } 4909 } 4910 4911 class PcFetcher : public os::SuspendedThreadTask { 4912 public: 4913 PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {} 4914 ExtendedPC result(); 4915 protected: 4916 void do_task(const os::SuspendedThreadTaskContext& context); 4917 private: 4918 ExtendedPC _epc; 4919 }; 4920 4921 ExtendedPC PcFetcher::result() { 4922 guarantee(is_done(), "task is not done yet."); 4923 return _epc; 4924 } 4925 4926 void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) { 4927 Thread* thread = context.thread(); 4928 OSThread* osthread = thread->osthread(); 4929 if (osthread->ucontext() != NULL) { 4930 _epc = os::Linux::ucontext_get_pc((ucontext_t *) context.ucontext()); 4931 } else { 4932 // NULL context is unexpected, double-check this is the VMThread 4933 guarantee(thread->is_VM_thread(), "can only be called for VMThread"); 4934 } 4935 } 4936 4937 // Suspends the target using the signal mechanism and then grabs the PC before 4938 // resuming the target. Used by the flat-profiler only 4939 ExtendedPC os::get_thread_pc(Thread* thread) { 4940 // Make sure that it is called by the watcher for the VMThread 4941 assert(Thread::current()->is_Watcher_thread(), "Must be watcher"); 4942 assert(thread->is_VM_thread(), "Can only be called for VMThread"); 4943 4944 PcFetcher fetcher(thread); 4945 fetcher.run(); 4946 return fetcher.result(); 4947 } 4948 4949 int os::Linux::safe_cond_timedwait(pthread_cond_t *_cond, 4950 pthread_mutex_t *_mutex, 4951 const struct timespec *_abstime) { 4952 if (is_NPTL()) { 4953 return pthread_cond_timedwait(_cond, _mutex, _abstime); 4954 } else { 4955 // 6292965: LinuxThreads pthread_cond_timedwait() resets FPU control 4956 // word back to default 64bit precision if condvar is signaled. Java 4957 // wants 53bit precision. Save and restore current value. 4958 int fpu = get_fpu_control_word(); 4959 int status = pthread_cond_timedwait(_cond, _mutex, _abstime); 4960 set_fpu_control_word(fpu); 4961 return status; 4962 } 4963 } 4964 4965 //////////////////////////////////////////////////////////////////////////////// 4966 // debug support 4967 4968 bool os::find(address addr, outputStream* st) { 4969 Dl_info dlinfo; 4970 memset(&dlinfo, 0, sizeof(dlinfo)); 4971 if (dladdr(addr, &dlinfo) != 0) { 4972 st->print(PTR_FORMAT ": ", addr); 4973 if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) { 4974 st->print("%s+%#x", dlinfo.dli_sname, 4975 addr - (intptr_t)dlinfo.dli_saddr); 4976 } else if (dlinfo.dli_fbase != NULL) { 4977 st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase); 4978 } else { 4979 st->print("<absolute address>"); 4980 } 4981 if (dlinfo.dli_fname != NULL) { 4982 st->print(" in %s", dlinfo.dli_fname); 4983 } 4984 if (dlinfo.dli_fbase != NULL) { 4985 st->print(" at " PTR_FORMAT, dlinfo.dli_fbase); 4986 } 4987 st->cr(); 4988 4989 if (Verbose) { 4990 // decode some bytes around the PC 4991 address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size()); 4992 address end = clamp_address_in_page(addr+40, addr, os::vm_page_size()); 4993 address lowest = (address) dlinfo.dli_sname; 4994 if (!lowest) lowest = (address) dlinfo.dli_fbase; 4995 if (begin < lowest) begin = lowest; 4996 Dl_info dlinfo2; 4997 if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr 4998 && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) { 4999 end = (address) dlinfo2.dli_saddr; 5000 } 5001 Disassembler::decode(begin, end, st); 5002 } 5003 return true; 5004 } 5005 return false; 5006 } 5007 5008 //////////////////////////////////////////////////////////////////////////////// 5009 // misc 5010 5011 // This does not do anything on Linux. This is basically a hook for being 5012 // able to use structured exception handling (thread-local exception filters) 5013 // on, e.g., Win32. 5014 void 5015 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method, 5016 JavaCallArguments* args, Thread* thread) { 5017 f(value, method, args, thread); 5018 } 5019 5020 void os::print_statistics() { 5021 } 5022 5023 int os::message_box(const char* title, const char* message) { 5024 int i; 5025 fdStream err(defaultStream::error_fd()); 5026 for (i = 0; i < 78; i++) err.print_raw("="); 5027 err.cr(); 5028 err.print_raw_cr(title); 5029 for (i = 0; i < 78; i++) err.print_raw("-"); 5030 err.cr(); 5031 err.print_raw_cr(message); 5032 for (i = 0; i < 78; i++) err.print_raw("="); 5033 err.cr(); 5034 5035 char buf[16]; 5036 // Prevent process from exiting upon "read error" without consuming all CPU 5037 while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); } 5038 5039 return buf[0] == 'y' || buf[0] == 'Y'; 5040 } 5041 5042 int os::stat(const char *path, struct stat *sbuf) { 5043 char pathbuf[MAX_PATH]; 5044 if (strlen(path) > MAX_PATH - 1) { 5045 errno = ENAMETOOLONG; 5046 return -1; 5047 } 5048 os::native_path(strcpy(pathbuf, path)); 5049 return ::stat(pathbuf, sbuf); 5050 } 5051 5052 bool os::check_heap(bool force) { 5053 return true; 5054 } 5055 5056 // Is a (classpath) directory empty? 5057 bool os::dir_is_empty(const char* path) { 5058 DIR *dir = NULL; 5059 struct dirent *ptr; 5060 5061 dir = opendir(path); 5062 if (dir == NULL) return true; 5063 5064 // Scan the directory 5065 bool result = true; 5066 char buf[sizeof(struct dirent) + MAX_PATH]; 5067 while (result && (ptr = ::readdir(dir)) != NULL) { 5068 if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) { 5069 result = false; 5070 } 5071 } 5072 closedir(dir); 5073 return result; 5074 } 5075 5076 // This code originates from JDK's sysOpen and open64_w 5077 // from src/solaris/hpi/src/system_md.c 5078 5079 int os::open(const char *path, int oflag, int mode) { 5080 if (strlen(path) > MAX_PATH - 1) { 5081 errno = ENAMETOOLONG; 5082 return -1; 5083 } 5084 5085 // All file descriptors that are opened in the Java process and not 5086 // specifically destined for a subprocess should have the close-on-exec 5087 // flag set. If we don't set it, then careless 3rd party native code 5088 // might fork and exec without closing all appropriate file descriptors 5089 // (e.g. as we do in closeDescriptors in UNIXProcess.c), and this in 5090 // turn might: 5091 // 5092 // - cause end-of-file to fail to be detected on some file 5093 // descriptors, resulting in mysterious hangs, or 5094 // 5095 // - might cause an fopen in the subprocess to fail on a system 5096 // suffering from bug 1085341. 5097 // 5098 // (Yes, the default setting of the close-on-exec flag is a Unix 5099 // design flaw) 5100 // 5101 // See: 5102 // 1085341: 32-bit stdio routines should support file descriptors >255 5103 // 4843136: (process) pipe file descriptor from Runtime.exec not being closed 5104 // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9 5105 // 5106 // Modern Linux kernels (after 2.6.23 2007) support O_CLOEXEC with open(). 5107 // O_CLOEXEC is preferable to using FD_CLOEXEC on an open file descriptor 5108 // because it saves a system call and removes a small window where the flag 5109 // is unset. On ancient Linux kernels the O_CLOEXEC flag will be ignored 5110 // and we fall back to using FD_CLOEXEC (see below). 5111 #ifdef O_CLOEXEC 5112 oflag |= O_CLOEXEC; 5113 #endif 5114 5115 int fd = ::open64(path, oflag, mode); 5116 if (fd == -1) return -1; 5117 5118 //If the open succeeded, the file might still be a directory 5119 { 5120 struct stat64 buf64; 5121 int ret = ::fstat64(fd, &buf64); 5122 int st_mode = buf64.st_mode; 5123 5124 if (ret != -1) { 5125 if ((st_mode & S_IFMT) == S_IFDIR) { 5126 errno = EISDIR; 5127 ::close(fd); 5128 return -1; 5129 } 5130 } else { 5131 ::close(fd); 5132 return -1; 5133 } 5134 } 5135 5136 #ifdef FD_CLOEXEC 5137 // Validate that the use of the O_CLOEXEC flag on open above worked. 5138 // With recent kernels, we will perform this check exactly once. 5139 static sig_atomic_t O_CLOEXEC_is_known_to_work = 0; 5140 if (!O_CLOEXEC_is_known_to_work) { 5141 int flags = ::fcntl(fd, F_GETFD); 5142 if (flags != -1) { 5143 if ((flags & FD_CLOEXEC) != 0) 5144 O_CLOEXEC_is_known_to_work = 1; 5145 else 5146 ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC); 5147 } 5148 } 5149 #endif 5150 5151 return fd; 5152 } 5153 5154 5155 // create binary file, rewriting existing file if required 5156 int os::create_binary_file(const char* path, bool rewrite_existing) { 5157 int oflags = O_WRONLY | O_CREAT; 5158 if (!rewrite_existing) { 5159 oflags |= O_EXCL; 5160 } 5161 return ::open64(path, oflags, S_IREAD | S_IWRITE); 5162 } 5163 5164 // return current position of file pointer 5165 jlong os::current_file_offset(int fd) { 5166 return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR); 5167 } 5168 5169 // move file pointer to the specified offset 5170 jlong os::seek_to_file_offset(int fd, jlong offset) { 5171 return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET); 5172 } 5173 5174 // This code originates from JDK's sysAvailable 5175 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c 5176 5177 int os::available(int fd, jlong *bytes) { 5178 jlong cur, end; 5179 int mode; 5180 struct stat64 buf64; 5181 5182 if (::fstat64(fd, &buf64) >= 0) { 5183 mode = buf64.st_mode; 5184 if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) { 5185 // XXX: is the following call interruptible? If so, this might 5186 // need to go through the INTERRUPT_IO() wrapper as for other 5187 // blocking, interruptible calls in this file. 5188 int n; 5189 if (::ioctl(fd, FIONREAD, &n) >= 0) { 5190 *bytes = n; 5191 return 1; 5192 } 5193 } 5194 } 5195 if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) { 5196 return 0; 5197 } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) { 5198 return 0; 5199 } else if (::lseek64(fd, cur, SEEK_SET) == -1) { 5200 return 0; 5201 } 5202 *bytes = end - cur; 5203 return 1; 5204 } 5205 5206 // Map a block of memory. 5207 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset, 5208 char *addr, size_t bytes, bool read_only, 5209 bool allow_exec) { 5210 int prot; 5211 int flags = MAP_PRIVATE; 5212 5213 if (read_only) { 5214 prot = PROT_READ; 5215 } else { 5216 prot = PROT_READ | PROT_WRITE; 5217 } 5218 5219 if (allow_exec) { 5220 prot |= PROT_EXEC; 5221 } 5222 5223 if (addr != NULL) { 5224 flags |= MAP_FIXED; 5225 } 5226 5227 char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags, 5228 fd, file_offset); 5229 if (mapped_address == MAP_FAILED) { 5230 return NULL; 5231 } 5232 return mapped_address; 5233 } 5234 5235 5236 // Remap a block of memory. 5237 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset, 5238 char *addr, size_t bytes, bool read_only, 5239 bool allow_exec) { 5240 // same as map_memory() on this OS 5241 return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only, 5242 allow_exec); 5243 } 5244 5245 5246 // Unmap a block of memory. 5247 bool os::pd_unmap_memory(char* addr, size_t bytes) { 5248 return munmap(addr, bytes) == 0; 5249 } 5250 5251 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time); 5252 5253 static clockid_t thread_cpu_clockid(Thread* thread) { 5254 pthread_t tid = thread->osthread()->pthread_id(); 5255 clockid_t clockid; 5256 5257 // Get thread clockid 5258 int rc = os::Linux::pthread_getcpuclockid(tid, &clockid); 5259 assert(rc == 0, "pthread_getcpuclockid is expected to return 0 code"); 5260 return clockid; 5261 } 5262 5263 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool) 5264 // are used by JVM M&M and JVMTI to get user+sys or user CPU time 5265 // of a thread. 5266 // 5267 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns 5268 // the fast estimate available on the platform. 5269 5270 jlong os::current_thread_cpu_time() { 5271 if (os::Linux::supports_fast_thread_cpu_time()) { 5272 return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID); 5273 } else { 5274 // return user + sys since the cost is the same 5275 return slow_thread_cpu_time(Thread::current(), true /* user + sys */); 5276 } 5277 } 5278 5279 jlong os::thread_cpu_time(Thread* thread) { 5280 // consistent with what current_thread_cpu_time() returns 5281 if (os::Linux::supports_fast_thread_cpu_time()) { 5282 return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread)); 5283 } else { 5284 return slow_thread_cpu_time(thread, true /* user + sys */); 5285 } 5286 } 5287 5288 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) { 5289 if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) { 5290 return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID); 5291 } else { 5292 return slow_thread_cpu_time(Thread::current(), user_sys_cpu_time); 5293 } 5294 } 5295 5296 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { 5297 if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) { 5298 return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread)); 5299 } else { 5300 return slow_thread_cpu_time(thread, user_sys_cpu_time); 5301 } 5302 } 5303 5304 // -1 on error. 5305 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { 5306 pid_t tid = thread->osthread()->thread_id(); 5307 char *s; 5308 char stat[2048]; 5309 int statlen; 5310 char proc_name[64]; 5311 int count; 5312 long sys_time, user_time; 5313 char cdummy; 5314 int idummy; 5315 long ldummy; 5316 FILE *fp; 5317 5318 snprintf(proc_name, 64, "/proc/self/task/%d/stat", tid); 5319 fp = fopen(proc_name, "r"); 5320 if (fp == NULL) return -1; 5321 statlen = fread(stat, 1, 2047, fp); 5322 stat[statlen] = '\0'; 5323 fclose(fp); 5324 5325 // Skip pid and the command string. Note that we could be dealing with 5326 // weird command names, e.g. user could decide to rename java launcher 5327 // to "java 1.4.2 :)", then the stat file would look like 5328 // 1234 (java 1.4.2 :)) R ... ... 5329 // We don't really need to know the command string, just find the last 5330 // occurrence of ")" and then start parsing from there. See bug 4726580. 5331 s = strrchr(stat, ')'); 5332 if (s == NULL) return -1; 5333 5334 // Skip blank chars 5335 do { s++; } while (s && isspace(*s)); 5336 5337 count = sscanf(s,"%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu", 5338 &cdummy, &idummy, &idummy, &idummy, &idummy, &idummy, 5339 &ldummy, &ldummy, &ldummy, &ldummy, &ldummy, 5340 &user_time, &sys_time); 5341 if (count != 13) return -1; 5342 if (user_sys_cpu_time) { 5343 return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec); 5344 } else { 5345 return (jlong)user_time * (1000000000 / clock_tics_per_sec); 5346 } 5347 } 5348 5349 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 5350 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits 5351 info_ptr->may_skip_backward = false; // elapsed time not wall time 5352 info_ptr->may_skip_forward = false; // elapsed time not wall time 5353 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned 5354 } 5355 5356 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 5357 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits 5358 info_ptr->may_skip_backward = false; // elapsed time not wall time 5359 info_ptr->may_skip_forward = false; // elapsed time not wall time 5360 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned 5361 } 5362 5363 bool os::is_thread_cpu_time_supported() { 5364 return true; 5365 } 5366 5367 // System loadavg support. Returns -1 if load average cannot be obtained. 5368 // Linux doesn't yet have a (official) notion of processor sets, 5369 // so just return the system wide load average. 5370 int os::loadavg(double loadavg[], int nelem) { 5371 return ::getloadavg(loadavg, nelem); 5372 } 5373 5374 void os::pause() { 5375 char filename[MAX_PATH]; 5376 if (PauseAtStartupFile && PauseAtStartupFile[0]) { 5377 jio_snprintf(filename, MAX_PATH, PauseAtStartupFile); 5378 } else { 5379 jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id()); 5380 } 5381 5382 int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666); 5383 if (fd != -1) { 5384 struct stat buf; 5385 ::close(fd); 5386 while (::stat(filename, &buf) == 0) { 5387 (void)::poll(NULL, 0, 100); 5388 } 5389 } else { 5390 jio_fprintf(stderr, 5391 "Could not open pause file '%s', continuing immediately.\n", filename); 5392 } 5393 } 5394 5395 5396 // Refer to the comments in os_solaris.cpp park-unpark. The next two 5397 // comment paragraphs are worth repeating here: 5398 // 5399 // Assumption: 5400 // Only one parker can exist on an event, which is why we allocate 5401 // them per-thread. Multiple unparkers can coexist. 5402 // 5403 // _Event serves as a restricted-range semaphore. 5404 // -1 : thread is blocked, i.e. there is a waiter 5405 // 0 : neutral: thread is running or ready, 5406 // could have been signaled after a wait started 5407 // 1 : signaled - thread is running or ready 5408 // 5409 // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can 5410 // hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable. 5411 // For specifics regarding the bug see GLIBC BUGID 261237 : 5412 // http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html. 5413 // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future 5414 // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar 5415 // is used. (The simple C test-case provided in the GLIBC bug report manifests the 5416 // hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos() 5417 // and monitorenter when we're using 1-0 locking. All those operations may result in 5418 // calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version 5419 // of libpthread avoids the problem, but isn't practical. 5420 // 5421 // Possible remedies: 5422 // 5423 // 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work. 5424 // This is palliative and probabilistic, however. If the thread is preempted 5425 // between the call to compute_abstime() and pthread_cond_timedwait(), more 5426 // than the minimum period may have passed, and the abstime may be stale (in the 5427 // past) resultin in a hang. Using this technique reduces the odds of a hang 5428 // but the JVM is still vulnerable, particularly on heavily loaded systems. 5429 // 5430 // 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead 5431 // of the usual flag-condvar-mutex idiom. The write side of the pipe is set 5432 // NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo) 5433 // reduces to poll()+read(). This works well, but consumes 2 FDs per extant 5434 // thread. 5435 // 5436 // 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread 5437 // that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing 5438 // a timeout request to the chron thread and then blocking via pthread_cond_wait(). 5439 // This also works well. In fact it avoids kernel-level scalability impediments 5440 // on certain platforms that don't handle lots of active pthread_cond_timedwait() 5441 // timers in a graceful fashion. 5442 // 5443 // 4. When the abstime value is in the past it appears that control returns 5444 // correctly from pthread_cond_timedwait(), but the condvar is left corrupt. 5445 // Subsequent timedwait/wait calls may hang indefinitely. Given that, we 5446 // can avoid the problem by reinitializing the condvar -- by cond_destroy() 5447 // followed by cond_init() -- after all calls to pthread_cond_timedwait(). 5448 // It may be possible to avoid reinitialization by checking the return 5449 // value from pthread_cond_timedwait(). In addition to reinitializing the 5450 // condvar we must establish the invariant that cond_signal() is only called 5451 // within critical sections protected by the adjunct mutex. This prevents 5452 // cond_signal() from "seeing" a condvar that's in the midst of being 5453 // reinitialized or that is corrupt. Sadly, this invariant obviates the 5454 // desirable signal-after-unlock optimization that avoids futile context switching. 5455 // 5456 // I'm also concerned that some versions of NTPL might allocate an auxilliary 5457 // structure when a condvar is used or initialized. cond_destroy() would 5458 // release the helper structure. Our reinitialize-after-timedwait fix 5459 // put excessive stress on malloc/free and locks protecting the c-heap. 5460 // 5461 // We currently use (4). See the WorkAroundNTPLTimedWaitHang flag. 5462 // It may be possible to refine (4) by checking the kernel and NTPL verisons 5463 // and only enabling the work-around for vulnerable environments. 5464 5465 // utility to compute the abstime argument to timedwait: 5466 // millis is the relative timeout time 5467 // abstime will be the absolute timeout time 5468 // TODO: replace compute_abstime() with unpackTime() 5469 5470 static struct timespec* compute_abstime(timespec* abstime, jlong millis) { 5471 if (millis < 0) millis = 0; 5472 5473 jlong seconds = millis / 1000; 5474 millis %= 1000; 5475 if (seconds > 50000000) { // see man cond_timedwait(3T) 5476 seconds = 50000000; 5477 } 5478 5479 if (os::supports_monotonic_clock()) { 5480 struct timespec now; 5481 int status = os::Linux::clock_gettime(CLOCK_MONOTONIC, &now); 5482 assert_status(status == 0, status, "clock_gettime"); 5483 abstime->tv_sec = now.tv_sec + seconds; 5484 long nanos = now.tv_nsec + millis * NANOSECS_PER_MILLISEC; 5485 if (nanos >= NANOSECS_PER_SEC) { 5486 abstime->tv_sec += 1; 5487 nanos -= NANOSECS_PER_SEC; 5488 } 5489 abstime->tv_nsec = nanos; 5490 } else { 5491 struct timeval now; 5492 int status = gettimeofday(&now, NULL); 5493 assert(status == 0, "gettimeofday"); 5494 abstime->tv_sec = now.tv_sec + seconds; 5495 long usec = now.tv_usec + millis * 1000; 5496 if (usec >= 1000000) { 5497 abstime->tv_sec += 1; 5498 usec -= 1000000; 5499 } 5500 abstime->tv_nsec = usec * 1000; 5501 } 5502 return abstime; 5503 } 5504 5505 void os::PlatformEvent::park() { // AKA "down()" 5506 // Transitions for _Event: 5507 // -1 => -1 : illegal 5508 // 1 => 0 : pass - return immediately 5509 // 0 => -1 : block; then set _Event to 0 before returning 5510 5511 // Invariant: Only the thread associated with the Event/PlatformEvent 5512 // may call park(). 5513 // TODO: assert that _Assoc != NULL or _Assoc == Self 5514 assert(_nParked == 0, "invariant"); 5515 5516 int v; 5517 for (;;) { 5518 v = _Event; 5519 if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; 5520 } 5521 guarantee(v >= 0, "invariant"); 5522 if (v == 0) { 5523 // Do this the hard way by blocking ... 5524 int status = pthread_mutex_lock(_mutex); 5525 assert_status(status == 0, status, "mutex_lock"); 5526 guarantee(_nParked == 0, "invariant"); 5527 ++_nParked; 5528 while (_Event < 0) { 5529 status = pthread_cond_wait(_cond, _mutex); 5530 // for some reason, under 2.7 lwp_cond_wait() may return ETIME ... 5531 // Treat this the same as if the wait was interrupted 5532 if (status == ETIME) { status = EINTR; } 5533 assert_status(status == 0 || status == EINTR, status, "cond_wait"); 5534 } 5535 --_nParked; 5536 5537 _Event = 0; 5538 status = pthread_mutex_unlock(_mutex); 5539 assert_status(status == 0, status, "mutex_unlock"); 5540 // Paranoia to ensure our locked and lock-free paths interact 5541 // correctly with each other. 5542 OrderAccess::fence(); 5543 } 5544 guarantee(_Event >= 0, "invariant"); 5545 } 5546 5547 int os::PlatformEvent::park(jlong millis) { 5548 // Transitions for _Event: 5549 // -1 => -1 : illegal 5550 // 1 => 0 : pass - return immediately 5551 // 0 => -1 : block; then set _Event to 0 before returning 5552 5553 guarantee(_nParked == 0, "invariant"); 5554 5555 int v; 5556 for (;;) { 5557 v = _Event; 5558 if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; 5559 } 5560 guarantee(v >= 0, "invariant"); 5561 if (v != 0) return OS_OK; 5562 5563 // We do this the hard way, by blocking the thread. 5564 // Consider enforcing a minimum timeout value. 5565 struct timespec abst; 5566 compute_abstime(&abst, millis); 5567 5568 int ret = OS_TIMEOUT; 5569 int status = pthread_mutex_lock(_mutex); 5570 assert_status(status == 0, status, "mutex_lock"); 5571 guarantee(_nParked == 0, "invariant"); 5572 ++_nParked; 5573 5574 // Object.wait(timo) will return because of 5575 // (a) notification 5576 // (b) timeout 5577 // (c) thread.interrupt 5578 // 5579 // Thread.interrupt and object.notify{All} both call Event::set. 5580 // That is, we treat thread.interrupt as a special case of notification. 5581 // We ignore spurious OS wakeups unless FilterSpuriousWakeups is false. 5582 // We assume all ETIME returns are valid. 5583 // 5584 // TODO: properly differentiate simultaneous notify+interrupt. 5585 // In that case, we should propagate the notify to another waiter. 5586 5587 while (_Event < 0) { 5588 status = os::Linux::safe_cond_timedwait(_cond, _mutex, &abst); 5589 if (status != 0 && WorkAroundNPTLTimedWaitHang) { 5590 pthread_cond_destroy(_cond); 5591 pthread_cond_init(_cond, os::Linux::condAttr()); 5592 } 5593 assert_status(status == 0 || status == EINTR || 5594 status == ETIME || status == ETIMEDOUT, 5595 status, "cond_timedwait"); 5596 if (!FilterSpuriousWakeups) break; // previous semantics 5597 if (status == ETIME || status == ETIMEDOUT) break; 5598 // We consume and ignore EINTR and spurious wakeups. 5599 } 5600 --_nParked; 5601 if (_Event >= 0) { 5602 ret = OS_OK; 5603 } 5604 _Event = 0; 5605 status = pthread_mutex_unlock(_mutex); 5606 assert_status(status == 0, status, "mutex_unlock"); 5607 assert(_nParked == 0, "invariant"); 5608 // Paranoia to ensure our locked and lock-free paths interact 5609 // correctly with each other. 5610 OrderAccess::fence(); 5611 return ret; 5612 } 5613 5614 void os::PlatformEvent::unpark() { 5615 // Transitions for _Event: 5616 // 0 => 1 : just return 5617 // 1 => 1 : just return 5618 // -1 => either 0 or 1; must signal target thread 5619 // That is, we can safely transition _Event from -1 to either 5620 // 0 or 1. 5621 // See also: "Semaphores in Plan 9" by Mullender & Cox 5622 // 5623 // Note: Forcing a transition from "-1" to "1" on an unpark() means 5624 // that it will take two back-to-back park() calls for the owning 5625 // thread to block. This has the benefit of forcing a spurious return 5626 // from the first park() call after an unpark() call which will help 5627 // shake out uses of park() and unpark() without condition variables. 5628 5629 if (Atomic::xchg(1, &_Event) >= 0) return; 5630 5631 // Wait for the thread associated with the event to vacate 5632 int status = pthread_mutex_lock(_mutex); 5633 assert_status(status == 0, status, "mutex_lock"); 5634 int AnyWaiters = _nParked; 5635 assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant"); 5636 if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) { 5637 AnyWaiters = 0; 5638 pthread_cond_signal(_cond); 5639 } 5640 status = pthread_mutex_unlock(_mutex); 5641 assert_status(status == 0, status, "mutex_unlock"); 5642 if (AnyWaiters != 0) { 5643 // Note that we signal() *after* dropping the lock for "immortal" Events. 5644 // This is safe and avoids a common class of futile wakeups. In rare 5645 // circumstances this can cause a thread to return prematurely from 5646 // cond_{timed}wait() but the spurious wakeup is benign and the victim 5647 // will simply re-test the condition and re-park itself. 5648 // This provides particular benefit if the underlying platform does not 5649 // provide wait morphing. 5650 status = pthread_cond_signal(_cond); 5651 assert_status(status == 0, status, "cond_signal"); 5652 } 5653 } 5654 5655 5656 // JSR166 5657 // ------------------------------------------------------- 5658 5659 // The solaris and linux implementations of park/unpark are fairly 5660 // conservative for now, but can be improved. They currently use a 5661 // mutex/condvar pair, plus a a count. 5662 // Park decrements count if > 0, else does a condvar wait. Unpark 5663 // sets count to 1 and signals condvar. Only one thread ever waits 5664 // on the condvar. Contention seen when trying to park implies that someone 5665 // is unparking you, so don't wait. And spurious returns are fine, so there 5666 // is no need to track notifications. 5667 5668 // This code is common to linux and solaris and will be moved to a 5669 // common place in dolphin. 5670 // 5671 // The passed in time value is either a relative time in nanoseconds 5672 // or an absolute time in milliseconds. Either way it has to be unpacked 5673 // into suitable seconds and nanoseconds components and stored in the 5674 // given timespec structure. 5675 // Given time is a 64-bit value and the time_t used in the timespec is only 5676 // a signed-32-bit value (except on 64-bit Linux) we have to watch for 5677 // overflow if times way in the future are given. Further on Solaris versions 5678 // prior to 10 there is a restriction (see cond_timedwait) that the specified 5679 // number of seconds, in abstime, is less than current_time + 100,000,000. 5680 // As it will be 28 years before "now + 100000000" will overflow we can 5681 // ignore overflow and just impose a hard-limit on seconds using the value 5682 // of "now + 100,000,000". This places a limit on the timeout of about 3.17 5683 // years from "now". 5684 5685 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) { 5686 assert(time > 0, "convertTime"); 5687 time_t max_secs = 0; 5688 5689 if (!os::supports_monotonic_clock() || isAbsolute) { 5690 struct timeval now; 5691 int status = gettimeofday(&now, NULL); 5692 assert(status == 0, "gettimeofday"); 5693 5694 max_secs = now.tv_sec + MAX_SECS; 5695 5696 if (isAbsolute) { 5697 jlong secs = time / 1000; 5698 if (secs > max_secs) { 5699 absTime->tv_sec = max_secs; 5700 } else { 5701 absTime->tv_sec = secs; 5702 } 5703 absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC; 5704 } else { 5705 jlong secs = time / NANOSECS_PER_SEC; 5706 if (secs >= MAX_SECS) { 5707 absTime->tv_sec = max_secs; 5708 absTime->tv_nsec = 0; 5709 } else { 5710 absTime->tv_sec = now.tv_sec + secs; 5711 absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000; 5712 if (absTime->tv_nsec >= NANOSECS_PER_SEC) { 5713 absTime->tv_nsec -= NANOSECS_PER_SEC; 5714 ++absTime->tv_sec; // note: this must be <= max_secs 5715 } 5716 } 5717 } 5718 } else { 5719 // must be relative using monotonic clock 5720 struct timespec now; 5721 int status = os::Linux::clock_gettime(CLOCK_MONOTONIC, &now); 5722 assert_status(status == 0, status, "clock_gettime"); 5723 max_secs = now.tv_sec + MAX_SECS; 5724 jlong secs = time / NANOSECS_PER_SEC; 5725 if (secs >= MAX_SECS) { 5726 absTime->tv_sec = max_secs; 5727 absTime->tv_nsec = 0; 5728 } else { 5729 absTime->tv_sec = now.tv_sec + secs; 5730 absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_nsec; 5731 if (absTime->tv_nsec >= NANOSECS_PER_SEC) { 5732 absTime->tv_nsec -= NANOSECS_PER_SEC; 5733 ++absTime->tv_sec; // note: this must be <= max_secs 5734 } 5735 } 5736 } 5737 assert(absTime->tv_sec >= 0, "tv_sec < 0"); 5738 assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs"); 5739 assert(absTime->tv_nsec >= 0, "tv_nsec < 0"); 5740 assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec"); 5741 } 5742 5743 void Parker::park(bool isAbsolute, jlong time) { 5744 // Ideally we'd do something useful while spinning, such 5745 // as calling unpackTime(). 5746 5747 // Optional fast-path check: 5748 // Return immediately if a permit is available. 5749 // We depend on Atomic::xchg() having full barrier semantics 5750 // since we are doing a lock-free update to _counter. 5751 if (Atomic::xchg(0, &_counter) > 0) return; 5752 5753 Thread* thread = Thread::current(); 5754 assert(thread->is_Java_thread(), "Must be JavaThread"); 5755 JavaThread *jt = (JavaThread *)thread; 5756 5757 // Optional optimization -- avoid state transitions if there's an interrupt pending. 5758 // Check interrupt before trying to wait 5759 if (Thread::is_interrupted(thread, false)) { 5760 return; 5761 } 5762 5763 // Next, demultiplex/decode time arguments 5764 timespec absTime; 5765 if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all 5766 return; 5767 } 5768 if (time > 0) { 5769 unpackTime(&absTime, isAbsolute, time); 5770 } 5771 5772 5773 // Enter safepoint region 5774 // Beware of deadlocks such as 6317397. 5775 // The per-thread Parker:: mutex is a classic leaf-lock. 5776 // In particular a thread must never block on the Threads_lock while 5777 // holding the Parker:: mutex. If safepoints are pending both the 5778 // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock. 5779 ThreadBlockInVM tbivm(jt); 5780 5781 // Don't wait if cannot get lock since interference arises from 5782 // unblocking. Also. check interrupt before trying wait 5783 if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) { 5784 return; 5785 } 5786 5787 int status; 5788 if (_counter > 0) { // no wait needed 5789 _counter = 0; 5790 status = pthread_mutex_unlock(_mutex); 5791 assert(status == 0, "invariant"); 5792 // Paranoia to ensure our locked and lock-free paths interact 5793 // correctly with each other and Java-level accesses. 5794 OrderAccess::fence(); 5795 return; 5796 } 5797 5798 #ifdef ASSERT 5799 // Don't catch signals while blocked; let the running threads have the signals. 5800 // (This allows a debugger to break into the running thread.) 5801 sigset_t oldsigs; 5802 sigset_t* allowdebug_blocked = os::Linux::allowdebug_blocked_signals(); 5803 pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs); 5804 #endif 5805 5806 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); 5807 jt->set_suspend_equivalent(); 5808 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 5809 5810 assert(_cur_index == -1, "invariant"); 5811 if (time == 0) { 5812 _cur_index = REL_INDEX; // arbitrary choice when not timed 5813 status = pthread_cond_wait(&_cond[_cur_index], _mutex); 5814 } else { 5815 _cur_index = isAbsolute ? ABS_INDEX : REL_INDEX; 5816 status = os::Linux::safe_cond_timedwait(&_cond[_cur_index], _mutex, &absTime); 5817 if (status != 0 && WorkAroundNPTLTimedWaitHang) { 5818 pthread_cond_destroy(&_cond[_cur_index]); 5819 pthread_cond_init(&_cond[_cur_index], isAbsolute ? NULL : os::Linux::condAttr()); 5820 } 5821 } 5822 _cur_index = -1; 5823 assert_status(status == 0 || status == EINTR || 5824 status == ETIME || status == ETIMEDOUT, 5825 status, "cond_timedwait"); 5826 5827 #ifdef ASSERT 5828 pthread_sigmask(SIG_SETMASK, &oldsigs, NULL); 5829 #endif 5830 5831 _counter = 0; 5832 status = pthread_mutex_unlock(_mutex); 5833 assert_status(status == 0, status, "invariant"); 5834 // Paranoia to ensure our locked and lock-free paths interact 5835 // correctly with each other and Java-level accesses. 5836 OrderAccess::fence(); 5837 5838 // If externally suspended while waiting, re-suspend 5839 if (jt->handle_special_suspend_equivalent_condition()) { 5840 jt->java_suspend_self(); 5841 } 5842 } 5843 5844 void Parker::unpark() { 5845 int status = pthread_mutex_lock(_mutex); 5846 assert(status == 0, "invariant"); 5847 const int s = _counter; 5848 _counter = 1; 5849 if (s < 1) { 5850 // thread might be parked 5851 if (_cur_index != -1) { 5852 // thread is definitely parked 5853 if (WorkAroundNPTLTimedWaitHang) { 5854 status = pthread_cond_signal(&_cond[_cur_index]); 5855 assert(status == 0, "invariant"); 5856 status = pthread_mutex_unlock(_mutex); 5857 assert(status == 0, "invariant"); 5858 } else { 5859 status = pthread_mutex_unlock(_mutex); 5860 assert(status == 0, "invariant"); 5861 status = pthread_cond_signal(&_cond[_cur_index]); 5862 assert(status == 0, "invariant"); 5863 } 5864 } else { 5865 pthread_mutex_unlock(_mutex); 5866 assert(status == 0, "invariant"); 5867 } 5868 } else { 5869 pthread_mutex_unlock(_mutex); 5870 assert(status == 0, "invariant"); 5871 } 5872 } 5873 5874 5875 extern char** environ; 5876 5877 #ifndef __NR_fork 5878 #define __NR_fork IA32_ONLY(2) IA64_ONLY(not defined) AMD64_ONLY(57) 5879 #endif 5880 5881 #ifndef __NR_execve 5882 #define __NR_execve IA32_ONLY(11) IA64_ONLY(1033) AMD64_ONLY(59) 5883 #endif 5884 5885 // Run the specified command in a separate process. Return its exit value, 5886 // or -1 on failure (e.g. can't fork a new process). 5887 // Unlike system(), this function can be called from signal handler. It 5888 // doesn't block SIGINT et al. 5889 int os::fork_and_exec(char* cmd) { 5890 const char * argv[4] = {"sh", "-c", cmd, NULL}; 5891 5892 // fork() in LinuxThreads/NPTL is not async-safe. It needs to run 5893 // pthread_atfork handlers and reset pthread library. All we need is a 5894 // separate process to execve. Make a direct syscall to fork process. 5895 // On IA64 there's no fork syscall, we have to use fork() and hope for 5896 // the best... 5897 pid_t pid = NOT_IA64(syscall(__NR_fork);) 5898 IA64_ONLY(fork();) 5899 5900 if (pid < 0) { 5901 // fork failed 5902 return -1; 5903 5904 } else if (pid == 0) { 5905 // child process 5906 5907 // execve() in LinuxThreads will call pthread_kill_other_threads_np() 5908 // first to kill every thread on the thread list. Because this list is 5909 // not reset by fork() (see notes above), execve() will instead kill 5910 // every thread in the parent process. We know this is the only thread 5911 // in the new process, so make a system call directly. 5912 // IA64 should use normal execve() from glibc to match the glibc fork() 5913 // above. 5914 NOT_IA64(syscall(__NR_execve, "/bin/sh", argv, environ);) 5915 IA64_ONLY(execve("/bin/sh", (char* const*)argv, environ);) 5916 5917 // execve failed 5918 _exit(-1); 5919 5920 } else { 5921 // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't 5922 // care about the actual exit code, for now. 5923 5924 int status; 5925 5926 // Wait for the child process to exit. This returns immediately if 5927 // the child has already exited. */ 5928 while (waitpid(pid, &status, 0) < 0) { 5929 switch (errno) { 5930 case ECHILD: return 0; 5931 case EINTR: break; 5932 default: return -1; 5933 } 5934 } 5935 5936 if (WIFEXITED(status)) { 5937 // The child exited normally; get its exit code. 5938 return WEXITSTATUS(status); 5939 } else if (WIFSIGNALED(status)) { 5940 // The child exited because of a signal 5941 // The best value to return is 0x80 + signal number, 5942 // because that is what all Unix shells do, and because 5943 // it allows callers to distinguish between process exit and 5944 // process death by signal. 5945 return 0x80 + WTERMSIG(status); 5946 } else { 5947 // Unknown exit code; pass it through 5948 return status; 5949 } 5950 } 5951 } 5952 5953 // is_headless_jre() 5954 // 5955 // Test for the existence of xawt/libmawt.so or libawt_xawt.so 5956 // in order to report if we are running in a headless jre 5957 // 5958 // Since JDK8 xawt/libmawt.so was moved into the same directory 5959 // as libawt.so, and renamed libawt_xawt.so 5960 // 5961 bool os::is_headless_jre() { 5962 struct stat statbuf; 5963 char buf[MAXPATHLEN]; 5964 char libmawtpath[MAXPATHLEN]; 5965 const char *xawtstr = "/xawt/libmawt.so"; 5966 const char *new_xawtstr = "/libawt_xawt.so"; 5967 char *p; 5968 5969 // Get path to libjvm.so 5970 os::jvm_path(buf, sizeof(buf)); 5971 5972 // Get rid of libjvm.so 5973 p = strrchr(buf, '/'); 5974 if (p == NULL) { 5975 return false; 5976 } else { 5977 *p = '\0'; 5978 } 5979 5980 // Get rid of client or server 5981 p = strrchr(buf, '/'); 5982 if (p == NULL) { 5983 return false; 5984 } else { 5985 *p = '\0'; 5986 } 5987 5988 // check xawt/libmawt.so 5989 strcpy(libmawtpath, buf); 5990 strcat(libmawtpath, xawtstr); 5991 if (::stat(libmawtpath, &statbuf) == 0) return false; 5992 5993 // check libawt_xawt.so 5994 strcpy(libmawtpath, buf); 5995 strcat(libmawtpath, new_xawtstr); 5996 if (::stat(libmawtpath, &statbuf) == 0) return false; 5997 5998 return true; 5999 } 6000 6001 // Get the default path to the core file 6002 // Returns the length of the string 6003 int os::get_core_path(char* buffer, size_t bufferSize) { 6004 /* 6005 * Max length of /proc/sys/kernel/core_pattern is 128 characters. 6006 * See https://www.kernel.org/doc/Documentation/sysctl/kernel.txt 6007 */ 6008 const int core_pattern_len = 129; 6009 char core_pattern[core_pattern_len] = {0}; 6010 6011 int core_pattern_file = ::open("/proc/sys/kernel/core_pattern", O_RDONLY); 6012 if (core_pattern_file != -1) { 6013 ssize_t ret = ::read(core_pattern_file, core_pattern, core_pattern_len); 6014 ::close(core_pattern_file); 6015 6016 if (ret > 0) { 6017 char *last_char = core_pattern + strlen(core_pattern) - 1; 6018 6019 if (*last_char == '\n') { 6020 *last_char = '\0'; 6021 } 6022 } 6023 } 6024 6025 if (strlen(core_pattern) == 0) { 6026 return 0; 6027 } 6028 6029 char *pid_pos = strstr(core_pattern, "%p"); 6030 size_t written; 6031 6032 if (core_pattern[0] == '/') { 6033 written = jio_snprintf(buffer, bufferSize, core_pattern); 6034 } else { 6035 char cwd[PATH_MAX]; 6036 6037 const char* p = get_current_directory(cwd, PATH_MAX); 6038 if (p == NULL) { 6039 assert(p != NULL, "failed to get current directory"); 6040 return 0; 6041 } 6042 6043 if (core_pattern[0] == '|') { 6044 written = jio_snprintf(buffer, bufferSize, 6045 "\"%s\" (or dumping to %s/core.%d)", 6046 &core_pattern[1], p, current_process_id()); 6047 } else { 6048 written = jio_snprintf(buffer, bufferSize, "%s/%s", p, core_pattern); 6049 } 6050 } 6051 6052 if ((written >= 0) && (written < bufferSize) 6053 && (pid_pos == NULL) && (core_pattern[0] != '|')) { 6054 int core_uses_pid_file = ::open("/proc/sys/kernel/core_uses_pid", O_RDONLY); 6055 6056 if (core_uses_pid_file != -1) { 6057 char core_uses_pid = 0; 6058 ssize_t ret = ::read(core_uses_pid_file, &core_uses_pid, 1); 6059 ::close(core_uses_pid_file); 6060 6061 if (core_uses_pid == '1'){ 6062 jio_snprintf(buffer + written, bufferSize - written, 6063 ".%d", current_process_id()); 6064 } 6065 } 6066 } 6067 6068 return strlen(buffer); 6069 } 6070 6071 /////////////// Unit tests /////////////// 6072 6073 #ifndef PRODUCT 6074 6075 #define test_log(...) \ 6076 do { \ 6077 if (VerboseInternalVMTests) { \ 6078 tty->print_cr(__VA_ARGS__); \ 6079 tty->flush(); \ 6080 } \ 6081 } while (false) 6082 6083 class TestReserveMemorySpecial : AllStatic { 6084 public: 6085 static void small_page_write(void* addr, size_t size) { 6086 size_t page_size = os::vm_page_size(); 6087 6088 char* end = (char*)addr + size; 6089 for (char* p = (char*)addr; p < end; p += page_size) { 6090 *p = 1; 6091 } 6092 } 6093 6094 static void test_reserve_memory_special_huge_tlbfs_only(size_t size) { 6095 if (!UseHugeTLBFS) { 6096 return; 6097 } 6098 6099 test_log("test_reserve_memory_special_huge_tlbfs_only(" SIZE_FORMAT ")", size); 6100 6101 char* addr = os::Linux::reserve_memory_special_huge_tlbfs_only(size, NULL, false); 6102 6103 if (addr != NULL) { 6104 small_page_write(addr, size); 6105 6106 os::Linux::release_memory_special_huge_tlbfs(addr, size); 6107 } 6108 } 6109 6110 static void test_reserve_memory_special_huge_tlbfs_only() { 6111 if (!UseHugeTLBFS) { 6112 return; 6113 } 6114 6115 size_t lp = os::large_page_size(); 6116 6117 for (size_t size = lp; size <= lp * 10; size += lp) { 6118 test_reserve_memory_special_huge_tlbfs_only(size); 6119 } 6120 } 6121 6122 static void test_reserve_memory_special_huge_tlbfs_mixed(size_t size, size_t alignment) { 6123 if (!UseHugeTLBFS) { 6124 return; 6125 } 6126 6127 test_log("test_reserve_memory_special_huge_tlbfs_mixed(" SIZE_FORMAT ", " SIZE_FORMAT ")", 6128 size, alignment); 6129 6130 assert(size >= os::large_page_size(), "Incorrect input to test"); 6131 6132 char* addr = os::Linux::reserve_memory_special_huge_tlbfs_mixed(size, alignment, NULL, false); 6133 6134 if (addr != NULL) { 6135 small_page_write(addr, size); 6136 6137 os::Linux::release_memory_special_huge_tlbfs(addr, size); 6138 } 6139 } 6140 6141 static void test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(size_t size) { 6142 size_t lp = os::large_page_size(); 6143 size_t ag = os::vm_allocation_granularity(); 6144 6145 for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) { 6146 test_reserve_memory_special_huge_tlbfs_mixed(size, alignment); 6147 } 6148 } 6149 6150 static void test_reserve_memory_special_huge_tlbfs_mixed() { 6151 size_t lp = os::large_page_size(); 6152 size_t ag = os::vm_allocation_granularity(); 6153 6154 test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp); 6155 test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp + ag); 6156 test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp + lp / 2); 6157 test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp * 2); 6158 test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp * 2 + ag); 6159 test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp * 2 - ag); 6160 test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp * 2 + lp / 2); 6161 test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp * 10); 6162 test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp * 10 + lp / 2); 6163 } 6164 6165 static void test_reserve_memory_special_huge_tlbfs() { 6166 if (!UseHugeTLBFS) { 6167 return; 6168 } 6169 6170 test_reserve_memory_special_huge_tlbfs_only(); 6171 test_reserve_memory_special_huge_tlbfs_mixed(); 6172 } 6173 6174 static void test_reserve_memory_special_shm(size_t size, size_t alignment) { 6175 if (!UseSHM) { 6176 return; 6177 } 6178 6179 test_log("test_reserve_memory_special_shm(" SIZE_FORMAT ", " SIZE_FORMAT ")", size, alignment); 6180 6181 char* addr = os::Linux::reserve_memory_special_shm(size, alignment, NULL, false); 6182 6183 if (addr != NULL) { 6184 assert(is_ptr_aligned(addr, alignment), "Check"); 6185 assert(is_ptr_aligned(addr, os::large_page_size()), "Check"); 6186 6187 small_page_write(addr, size); 6188 6189 os::Linux::release_memory_special_shm(addr, size); 6190 } 6191 } 6192 6193 static void test_reserve_memory_special_shm() { 6194 size_t lp = os::large_page_size(); 6195 size_t ag = os::vm_allocation_granularity(); 6196 6197 for (size_t size = ag; size < lp * 3; size += ag) { 6198 for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) { 6199 test_reserve_memory_special_shm(size, alignment); 6200 } 6201 } 6202 } 6203 6204 static void test() { 6205 test_reserve_memory_special_huge_tlbfs(); 6206 test_reserve_memory_special_shm(); 6207 } 6208 }; 6209 6210 void TestReserveMemorySpecial_test() { 6211 TestReserveMemorySpecial::test(); 6212 } 6213 6214 #endif