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