1 /*
   2  * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2015, 2024 SAP SE. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 // no precompiled headers
  27 #include "classfile/vmSymbols.hpp"
  28 #include "code/icBuffer.hpp"
  29 #include "code/vtableStubs.hpp"
  30 #include "compiler/compileBroker.hpp"
  31 #include "compiler/disassembler.hpp"
  32 #include "hugepages.hpp"
  33 #include "interpreter/interpreter.hpp"
  34 #include "jvm.h"
  35 #include "jvmtifiles/jvmti.h"
  36 #include "logging/log.hpp"
  37 #include "logging/logStream.hpp"
  38 #include "memory/allocation.inline.hpp"
  39 #include "oops/oop.inline.hpp"
  40 #include "os_linux.inline.hpp"
  41 #include "os_posix.inline.hpp"
  42 #include "osContainer_linux.hpp"
  43 #include "prims/jniFastGetField.hpp"
  44 #include "prims/jvm_misc.hpp"
  45 #include "runtime/arguments.hpp"
  46 #include "runtime/atomic.hpp"
  47 #include "runtime/globals.hpp"
  48 #include "runtime/globals_extension.hpp"
  49 #include "runtime/init.hpp"
  50 #include "runtime/interfaceSupport.inline.hpp"
  51 #include "runtime/java.hpp"
  52 #include "runtime/javaCalls.hpp"
  53 #include "runtime/javaThread.hpp"
  54 #include "runtime/mutexLocker.hpp"
  55 #include "runtime/objectMonitor.hpp"
  56 #include "runtime/osInfo.hpp"
  57 #include "runtime/osThread.hpp"
  58 #include "runtime/perfMemory.hpp"
  59 #include "runtime/sharedRuntime.hpp"
  60 #include "runtime/statSampler.hpp"
  61 #include "runtime/stubRoutines.hpp"
  62 #include "runtime/threadCritical.hpp"
  63 #include "runtime/threads.hpp"
  64 #include "runtime/threadSMR.hpp"
  65 #include "runtime/timer.hpp"
  66 #include "runtime/vm_version.hpp"
  67 #include "signals_posix.hpp"
  68 #include "semaphore_posix.hpp"
  69 #include "services/memTracker.hpp"
  70 #include "services/runtimeService.hpp"
  71 #include "utilities/align.hpp"
  72 #include "utilities/decoder.hpp"
  73 #include "utilities/defaultStream.hpp"
  74 #include "utilities/events.hpp"
  75 #include "utilities/elfFile.hpp"
  76 #include "utilities/growableArray.hpp"
  77 #include "utilities/globalDefinitions.hpp"
  78 #include "utilities/macros.hpp"
  79 #include "utilities/powerOfTwo.hpp"
  80 #include "utilities/vmError.hpp"
  81 #if INCLUDE_JFR
  82 #include "jfr/jfrEvents.hpp"
  83 #endif
  84 
  85 // put OS-includes here
  86 # include <sys/types.h>
  87 # include <sys/mman.h>
  88 # include <sys/stat.h>
  89 # include <sys/select.h>
  90 # include <pthread.h>
  91 # include <signal.h>
  92 # include <endian.h>
  93 # include <errno.h>
  94 # include <dlfcn.h>
  95 # include <stdio.h>
  96 # include <unistd.h>
  97 # include <sys/resource.h>
  98 # include <pthread.h>
  99 # include <sys/stat.h>
 100 # include <sys/time.h>
 101 # include <sys/times.h>
 102 # include <sys/utsname.h>
 103 # include <sys/socket.h>
 104 # include <pwd.h>
 105 # include <poll.h>
 106 # include <fcntl.h>
 107 # include <string.h>
 108 # include <syscall.h>
 109 # include <sys/sysinfo.h>
 110 # include <sys/ipc.h>
 111 # include <sys/shm.h>
 112 # include <link.h>
 113 # include <stdint.h>
 114 # include <inttypes.h>
 115 # include <sys/ioctl.h>
 116 # include <linux/elf-em.h>
 117 # include <sys/prctl.h>
 118 #ifdef __GLIBC__
 119 # include <malloc.h>
 120 #endif
 121 
 122 #ifndef _GNU_SOURCE
 123   #define _GNU_SOURCE
 124   #include <sched.h>
 125   #undef _GNU_SOURCE
 126 #else
 127   #include <sched.h>
 128 #endif
 129 
 130 // if RUSAGE_THREAD for getrusage() has not been defined, do it here. The code calling
 131 // getrusage() is prepared to handle the associated failure.
 132 #ifndef RUSAGE_THREAD
 133   #define RUSAGE_THREAD   (1)               /* only the calling thread */
 134 #endif
 135 
 136 #define MAX_PATH    (2 * K)
 137 
 138 #define MAX_SECS 100000000
 139 
 140 // for timer info max values which include all bits
 141 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
 142 
 143 #ifdef MUSL_LIBC
 144 // dlvsym is not a part of POSIX
 145 // and musl libc doesn't implement it.
 146 static void *dlvsym(void *handle,
 147                     const char *symbol,
 148                     const char *version) {
 149    // load the latest version of symbol
 150    return dlsym(handle, symbol);
 151 }
 152 #endif
 153 
 154 enum CoredumpFilterBit {
 155   FILE_BACKED_PVT_BIT = 1 << 2,
 156   FILE_BACKED_SHARED_BIT = 1 << 3,
 157   LARGEPAGES_BIT = 1 << 6,
 158   DAX_SHARED_BIT = 1 << 8
 159 };
 160 
 161 ////////////////////////////////////////////////////////////////////////////////
 162 // global variables
 163 julong os::Linux::_physical_memory = 0;
 164 
 165 address   os::Linux::_initial_thread_stack_bottom = nullptr;
 166 uintptr_t os::Linux::_initial_thread_stack_size   = 0;
 167 
 168 int (*os::Linux::_pthread_getcpuclockid)(pthread_t, clockid_t *) = nullptr;
 169 int (*os::Linux::_pthread_setname_np)(pthread_t, const char*) = nullptr;
 170 pthread_t os::Linux::_main_thread;
 171 bool os::Linux::_supports_fast_thread_cpu_time = false;
 172 const char * os::Linux::_libc_version = nullptr;
 173 const char * os::Linux::_libpthread_version = nullptr;
 174 
 175 #ifdef __GLIBC__
 176 // We want to be buildable and runnable on older and newer glibcs, so resolve both
 177 // mallinfo and mallinfo2 dynamically.
 178 struct old_mallinfo {
 179   int arena;
 180   int ordblks;
 181   int smblks;
 182   int hblks;
 183   int hblkhd;
 184   int usmblks;
 185   int fsmblks;
 186   int uordblks;
 187   int fordblks;
 188   int keepcost;
 189 };
 190 typedef struct old_mallinfo (*mallinfo_func_t)(void);
 191 static mallinfo_func_t g_mallinfo = nullptr;
 192 
 193 struct new_mallinfo {
 194   size_t arena;
 195   size_t ordblks;
 196   size_t smblks;
 197   size_t hblks;
 198   size_t hblkhd;
 199   size_t usmblks;
 200   size_t fsmblks;
 201   size_t uordblks;
 202   size_t fordblks;
 203   size_t keepcost;
 204 };
 205 typedef struct new_mallinfo (*mallinfo2_func_t)(void);
 206 static mallinfo2_func_t g_mallinfo2 = nullptr;
 207 
 208 typedef int (*malloc_info_func_t)(int options, FILE *stream);
 209 static malloc_info_func_t g_malloc_info = nullptr;
 210 #endif // __GLIBC__
 211 
 212 static int clock_tics_per_sec = 100;
 213 
 214 // If the VM might have been created on the primordial thread, we need to resolve the
 215 // primordial thread stack bounds and check if the current thread might be the
 216 // primordial thread in places. If we know that the primordial thread is never used,
 217 // such as when the VM was created by one of the standard java launchers, we can
 218 // avoid this
 219 static bool suppress_primordial_thread_resolution = false;
 220 
 221 // utility functions
 222 
 223 julong os::Linux::available_memory_in_container() {
 224   julong avail_mem = static_cast<julong>(-1L);
 225   if (OSContainer::is_containerized()) {
 226     jlong mem_limit = OSContainer::memory_limit_in_bytes();
 227     jlong mem_usage;
 228     if (mem_limit > 0 && (mem_usage = OSContainer::memory_usage_in_bytes()) < 1) {
 229       log_debug(os, container)("container memory usage failed: " JLONG_FORMAT ", using host value", mem_usage);
 230     }
 231     if (mem_limit > 0 && mem_usage > 0) {
 232       avail_mem = mem_limit > mem_usage ? (julong)mem_limit - (julong)mem_usage : 0;
 233     }
 234   }
 235   return avail_mem;
 236 }
 237 
 238 julong os::available_memory() {
 239   return Linux::available_memory();
 240 }
 241 
 242 julong os::Linux::available_memory() {
 243   julong avail_mem = available_memory_in_container();
 244   if (avail_mem != static_cast<julong>(-1L)) {
 245     log_trace(os)("available container memory: " JULONG_FORMAT, avail_mem);
 246     return avail_mem;
 247   }
 248 
 249   FILE *fp = os::fopen("/proc/meminfo", "r");
 250   if (fp != nullptr) {
 251     char buf[80];
 252     do {
 253       if (fscanf(fp, "MemAvailable: " JULONG_FORMAT " kB", &avail_mem) == 1) {
 254         avail_mem *= K;
 255         break;
 256       }
 257     } while (fgets(buf, sizeof(buf), fp) != nullptr);
 258     fclose(fp);
 259   }
 260   if (avail_mem == static_cast<julong>(-1L)) {
 261     avail_mem = free_memory();
 262   }
 263   log_trace(os)("available memory: " JULONG_FORMAT, avail_mem);
 264   return avail_mem;
 265 }
 266 
 267 julong os::free_memory() {
 268   return Linux::free_memory();
 269 }
 270 
 271 julong os::Linux::free_memory() {
 272   // values in struct sysinfo are "unsigned long"
 273   struct sysinfo si;
 274   julong free_mem = available_memory_in_container();
 275   if (free_mem != static_cast<julong>(-1L)) {
 276     log_trace(os)("free container memory: " JULONG_FORMAT, free_mem);
 277     return free_mem;
 278   }
 279 
 280   sysinfo(&si);
 281   free_mem = (julong)si.freeram * si.mem_unit;
 282   log_trace(os)("free memory: " JULONG_FORMAT, free_mem);
 283   return free_mem;
 284 }
 285 
 286 julong os::physical_memory() {
 287   jlong phys_mem = 0;
 288   if (OSContainer::is_containerized()) {
 289     jlong mem_limit;
 290     if ((mem_limit = OSContainer::memory_limit_in_bytes()) > 0) {
 291       log_trace(os)("total container memory: " JLONG_FORMAT, mem_limit);
 292       return mem_limit;
 293     }
 294   }
 295 
 296   phys_mem = Linux::physical_memory();
 297   log_trace(os)("total system memory: " JLONG_FORMAT, phys_mem);
 298   return phys_mem;
 299 }
 300 
 301 static uint64_t initial_total_ticks = 0;
 302 static uint64_t initial_steal_ticks = 0;
 303 static bool     has_initial_tick_info = false;
 304 
 305 static void next_line(FILE *f) {
 306   int c;
 307   do {
 308     c = fgetc(f);
 309   } while (c != '\n' && c != EOF);
 310 }
 311 
 312 bool os::Linux::get_tick_information(CPUPerfTicks* pticks, int which_logical_cpu) {
 313   FILE*         fh;
 314   uint64_t      userTicks, niceTicks, systemTicks, idleTicks;
 315   // since at least kernel 2.6 : iowait: time waiting for I/O to complete
 316   // irq: time  servicing interrupts; softirq: time servicing softirqs
 317   uint64_t      iowTicks = 0, irqTicks = 0, sirqTicks= 0;
 318   // steal (since kernel 2.6.11): time spent in other OS when running in a virtualized environment
 319   uint64_t      stealTicks = 0;
 320   // guest (since kernel 2.6.24): time spent running a virtual CPU for guest OS under the
 321   // control of the Linux kernel
 322   uint64_t      guestNiceTicks = 0;
 323   int           logical_cpu = -1;
 324   const int     required_tickinfo_count = (which_logical_cpu == -1) ? 4 : 5;
 325   int           n;
 326 
 327   memset(pticks, 0, sizeof(CPUPerfTicks));
 328 
 329   if ((fh = os::fopen("/proc/stat", "r")) == nullptr) {
 330     return false;
 331   }
 332 
 333   if (which_logical_cpu == -1) {
 334     n = fscanf(fh, "cpu " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " "
 335             UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " "
 336             UINT64_FORMAT " " UINT64_FORMAT " ",
 337             &userTicks, &niceTicks, &systemTicks, &idleTicks,
 338             &iowTicks, &irqTicks, &sirqTicks,
 339             &stealTicks, &guestNiceTicks);
 340   } else {
 341     // Move to next line
 342     next_line(fh);
 343 
 344     // find the line for requested cpu faster to just iterate linefeeds?
 345     for (int i = 0; i < which_logical_cpu; i++) {
 346       next_line(fh);
 347     }
 348 
 349     n = fscanf(fh, "cpu%u " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " "
 350                UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " "
 351                UINT64_FORMAT " " UINT64_FORMAT " ",
 352                &logical_cpu, &userTicks, &niceTicks,
 353                &systemTicks, &idleTicks, &iowTicks, &irqTicks, &sirqTicks,
 354                &stealTicks, &guestNiceTicks);
 355   }
 356 
 357   fclose(fh);
 358   if (n < required_tickinfo_count || logical_cpu != which_logical_cpu) {
 359     return false;
 360   }
 361   pticks->used       = userTicks + niceTicks;
 362   pticks->usedKernel = systemTicks + irqTicks + sirqTicks;
 363   pticks->total      = userTicks + niceTicks + systemTicks + idleTicks +
 364                        iowTicks + irqTicks + sirqTicks + stealTicks + guestNiceTicks;
 365 
 366   if (n > required_tickinfo_count + 3) {
 367     pticks->steal = stealTicks;
 368     pticks->has_steal_ticks = true;
 369   } else {
 370     pticks->steal = 0;
 371     pticks->has_steal_ticks = false;
 372   }
 373 
 374   return true;
 375 }
 376 
 377 #ifndef SYS_gettid
 378 // i386: 224, ia64: 1105, amd64: 186, sparc: 143
 379   #ifdef __ia64__
 380     #define SYS_gettid 1105
 381   #else
 382     #ifdef __i386__
 383       #define SYS_gettid 224
 384     #else
 385       #ifdef __amd64__
 386         #define SYS_gettid 186
 387       #else
 388         #ifdef __sparc__
 389           #define SYS_gettid 143
 390         #else
 391           #error define gettid for the arch
 392         #endif
 393       #endif
 394     #endif
 395   #endif
 396 #endif
 397 
 398 
 399 // pid_t gettid()
 400 //
 401 // Returns the kernel thread id of the currently running thread. Kernel
 402 // thread id is used to access /proc.
 403 pid_t os::Linux::gettid() {
 404   int rslt = syscall(SYS_gettid);
 405   assert(rslt != -1, "must be."); // old linuxthreads implementation?
 406   return (pid_t)rslt;
 407 }
 408 
 409 // Returns the amount of swap currently configured, in bytes.
 410 // This can change at any time.
 411 julong os::Linux::host_swap() {
 412   struct sysinfo si;
 413   sysinfo(&si);
 414   return (julong)(si.totalswap * si.mem_unit);
 415 }
 416 
 417 // Most versions of linux have a bug where the number of processors are
 418 // determined by looking at the /proc file system.  In a chroot environment,
 419 // the system call returns 1.
 420 static bool unsafe_chroot_detected = false;
 421 static const char *unstable_chroot_error = "/proc file system not found.\n"
 422                      "Java may be unstable running multithreaded in a chroot "
 423                      "environment on Linux when /proc filesystem is not mounted.";
 424 
 425 void os::Linux::initialize_system_info() {
 426   set_processor_count(sysconf(_SC_NPROCESSORS_CONF));
 427   if (processor_count() == 1) {
 428     pid_t pid = os::Linux::gettid();
 429     char fname[32];
 430     jio_snprintf(fname, sizeof(fname), "/proc/%d", pid);
 431     FILE *fp = os::fopen(fname, "r");
 432     if (fp == nullptr) {
 433       unsafe_chroot_detected = true;
 434     } else {
 435       fclose(fp);
 436     }
 437   }
 438   _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * (julong)sysconf(_SC_PAGESIZE);
 439   assert(processor_count() > 0, "linux error");
 440 }
 441 
 442 void os::init_system_properties_values() {
 443   // The next steps are taken in the product version:
 444   //
 445   // Obtain the JAVA_HOME value from the location of libjvm.so.
 446   // This library should be located at:
 447   // <JAVA_HOME>/lib/{client|server}/libjvm.so.
 448   //
 449   // If "/jre/lib/" appears at the right place in the path, then we
 450   // assume libjvm.so is installed in a JDK and we use this path.
 451   //
 452   // Otherwise exit with message: "Could not create the Java virtual machine."
 453   //
 454   // The following extra steps are taken in the debugging version:
 455   //
 456   // If "/jre/lib/" does NOT appear at the right place in the path
 457   // instead of exit check for $JAVA_HOME environment variable.
 458   //
 459   // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
 460   // then we append a fake suffix "hotspot/libjvm.so" to this path so
 461   // it looks like libjvm.so is installed there
 462   // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.
 463   //
 464   // Otherwise exit.
 465   //
 466   // Important note: if the location of libjvm.so changes this
 467   // code needs to be changed accordingly.
 468 
 469   // See ld(1):
 470   //      The linker uses the following search paths to locate required
 471   //      shared libraries:
 472   //        1: ...
 473   //        ...
 474   //        7: The default directories, normally /lib and /usr/lib.
 475 #ifndef OVERRIDE_LIBPATH
 476   #if defined(_LP64)
 477     #define DEFAULT_LIBPATH "/usr/lib64:/lib64:/lib:/usr/lib"
 478   #else
 479     #define DEFAULT_LIBPATH "/lib:/usr/lib"
 480   #endif
 481 #else
 482   #define DEFAULT_LIBPATH OVERRIDE_LIBPATH
 483 #endif
 484 
 485 // Base path of extensions installed on the system.
 486 #define SYS_EXT_DIR     "/usr/java/packages"
 487 #define EXTENSIONS_DIR  "/lib/ext"
 488 
 489   // Buffer that fits several snprintfs.
 490   // Note that the space for the colon and the trailing null are provided
 491   // by the nulls included by the sizeof operator.
 492   const size_t bufsize =
 493     MAX2((size_t)MAXPATHLEN,  // For dll_dir & friends.
 494          (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR)); // extensions dir
 495   char *buf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
 496 
 497   // sysclasspath, java_home, dll_dir
 498   {
 499     char *pslash;
 500     os::jvm_path(buf, bufsize);
 501 
 502     // Found the full path to libjvm.so.
 503     // Now cut the path to <java_home>/jre if we can.
 504     pslash = strrchr(buf, '/');
 505     if (pslash != nullptr) {
 506       *pslash = '\0';            // Get rid of /libjvm.so.
 507     }
 508     pslash = strrchr(buf, '/');
 509     if (pslash != nullptr) {
 510       *pslash = '\0';            // Get rid of /{client|server|hotspot}.
 511     }
 512     Arguments::set_dll_dir(buf);
 513 
 514     if (pslash != nullptr) {
 515       pslash = strrchr(buf, '/');
 516       if (pslash != nullptr) {
 517         *pslash = '\0';        // Get rid of /lib.
 518       }
 519     }
 520     Arguments::set_java_home(buf);
 521     if (!set_boot_path('/', ':')) {
 522       vm_exit_during_initialization("Failed setting boot class path.", nullptr);
 523     }
 524   }
 525 
 526   // Where to look for native libraries.
 527   //
 528   // Note: Due to a legacy implementation, most of the library path
 529   // is set in the launcher. This was to accommodate linking restrictions
 530   // on legacy Linux implementations (which are no longer supported).
 531   // Eventually, all the library path setting will be done here.
 532   //
 533   // However, to prevent the proliferation of improperly built native
 534   // libraries, the new path component /usr/java/packages is added here.
 535   // Eventually, all the library path setting will be done here.
 536   {
 537     // Get the user setting of LD_LIBRARY_PATH, and prepended it. It
 538     // should always exist (until the legacy problem cited above is
 539     // addressed).
 540     const char *v = ::getenv("LD_LIBRARY_PATH");
 541     const char *v_colon = ":";
 542     if (v == nullptr) { v = ""; v_colon = ""; }
 543     // That's +1 for the colon and +1 for the trailing '\0'.
 544     size_t pathsize = strlen(v) + 1 + sizeof(SYS_EXT_DIR) + sizeof("/lib/") + sizeof(DEFAULT_LIBPATH) + 1;
 545     char *ld_library_path = NEW_C_HEAP_ARRAY(char, pathsize, mtInternal);
 546     os::snprintf_checked(ld_library_path, pathsize, "%s%s" SYS_EXT_DIR "/lib:" DEFAULT_LIBPATH, v, v_colon);
 547     Arguments::set_library_path(ld_library_path);
 548     FREE_C_HEAP_ARRAY(char, ld_library_path);
 549   }
 550 
 551   // Extensions directories.
 552   os::snprintf_checked(buf, bufsize, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home());
 553   Arguments::set_ext_dirs(buf);
 554 
 555   FREE_C_HEAP_ARRAY(char, buf);
 556 
 557 #undef DEFAULT_LIBPATH
 558 #undef SYS_EXT_DIR
 559 #undef EXTENSIONS_DIR
 560 }
 561 
 562 ////////////////////////////////////////////////////////////////////////////////
 563 // breakpoint support
 564 
 565 void os::breakpoint() {
 566   BREAKPOINT;
 567 }
 568 
 569 extern "C" void breakpoint() {
 570   // use debugger to set breakpoint here
 571 }
 572 
 573 //////////////////////////////////////////////////////////////////////////////
 574 // detecting pthread library
 575 
 576 void os::Linux::libpthread_init() {
 577   // Save glibc and pthread version strings.
 578 #if !defined(_CS_GNU_LIBC_VERSION) || \
 579     !defined(_CS_GNU_LIBPTHREAD_VERSION)
 580   #error "glibc too old (< 2.3.2)"
 581 #endif
 582 
 583 #ifdef MUSL_LIBC
 584   // confstr() from musl libc returns EINVAL for
 585   // _CS_GNU_LIBC_VERSION and _CS_GNU_LIBPTHREAD_VERSION
 586   os::Linux::set_libc_version("musl - unknown");
 587   os::Linux::set_libpthread_version("musl - unknown");
 588 #else
 589   size_t n = confstr(_CS_GNU_LIBC_VERSION, nullptr, 0);
 590   assert(n > 0, "cannot retrieve glibc version");
 591   char *str = (char *)malloc(n, mtInternal);
 592   confstr(_CS_GNU_LIBC_VERSION, str, n);
 593   os::Linux::set_libc_version(str);
 594 
 595   n = confstr(_CS_GNU_LIBPTHREAD_VERSION, nullptr, 0);
 596   assert(n > 0, "cannot retrieve pthread version");
 597   str = (char *)malloc(n, mtInternal);
 598   confstr(_CS_GNU_LIBPTHREAD_VERSION, str, n);
 599   os::Linux::set_libpthread_version(str);
 600 #endif
 601 }
 602 
 603 /////////////////////////////////////////////////////////////////////////////
 604 // thread stack expansion
 605 
 606 // os::Linux::manually_expand_stack() takes care of expanding the thread
 607 // stack. Note that this is normally not needed: pthread stacks allocate
 608 // thread stack using mmap() without MAP_NORESERVE, so the stack is already
 609 // committed. Therefore it is not necessary to expand the stack manually.
 610 //
 611 // Manually expanding the stack was historically needed on LinuxThreads
 612 // thread stacks, which were allocated with mmap(MAP_GROWSDOWN). Nowadays
 613 // it is kept to deal with very rare corner cases:
 614 //
 615 // For one, user may run the VM on an own implementation of threads
 616 // whose stacks are - like the old LinuxThreads - implemented using
 617 // mmap(MAP_GROWSDOWN).
 618 //
 619 // Also, this coding may be needed if the VM is running on the primordial
 620 // thread. Normally we avoid running on the primordial thread; however,
 621 // user may still invoke the VM on the primordial thread.
 622 //
 623 // The following historical comment describes the details about running
 624 // on a thread stack allocated with mmap(MAP_GROWSDOWN):
 625 
 626 
 627 // Force Linux kernel to expand current thread stack. If "bottom" is close
 628 // to the stack guard, caller should block all signals.
 629 //
 630 // MAP_GROWSDOWN:
 631 //   A special mmap() flag that is used to implement thread stacks. It tells
 632 //   kernel that the memory region should extend downwards when needed. This
 633 //   allows early versions of LinuxThreads to only mmap the first few pages
 634 //   when creating a new thread. Linux kernel will automatically expand thread
 635 //   stack as needed (on page faults).
 636 //
 637 //   However, because the memory region of a MAP_GROWSDOWN stack can grow on
 638 //   demand, if a page fault happens outside an already mapped MAP_GROWSDOWN
 639 //   region, it's hard to tell if the fault is due to a legitimate stack
 640 //   access or because of reading/writing non-exist memory (e.g. buffer
 641 //   overrun). As a rule, if the fault happens below current stack pointer,
 642 //   Linux kernel does not expand stack, instead a SIGSEGV is sent to the
 643 //   application (see Linux kernel fault.c).
 644 //
 645 //   This Linux feature can cause SIGSEGV when VM bangs thread stack for
 646 //   stack overflow detection.
 647 //
 648 //   Newer version of LinuxThreads (since glibc-2.2, or, RH-7.x) and NPTL do
 649 //   not use MAP_GROWSDOWN.
 650 //
 651 // To get around the problem and allow stack banging on Linux, we need to
 652 // manually expand thread stack after receiving the SIGSEGV.
 653 //
 654 // There are two ways to expand thread stack to address "bottom", we used
 655 // both of them in JVM before 1.5:
 656 //   1. adjust stack pointer first so that it is below "bottom", and then
 657 //      touch "bottom"
 658 //   2. mmap() the page in question
 659 //
 660 // Now alternate signal stack is gone, it's harder to use 2. For instance,
 661 // if current sp is already near the lower end of page 101, and we need to
 662 // call mmap() to map page 100, it is possible that part of the mmap() frame
 663 // will be placed in page 100. When page 100 is mapped, it is zero-filled.
 664 // That will destroy the mmap() frame and cause VM to crash.
 665 //
 666 // The following code works by adjusting sp first, then accessing the "bottom"
 667 // page to force a page fault. Linux kernel will then automatically expand the
 668 // stack mapping.
 669 //
 670 // _expand_stack_to() assumes its frame size is less than page size, which
 671 // should always be true if the function is not inlined.
 672 
 673 static void NOINLINE _expand_stack_to(address bottom) {
 674   address sp;
 675   size_t size;
 676   volatile char *p;
 677 
 678   // Adjust bottom to point to the largest address within the same page, it
 679   // gives us a one-page buffer if alloca() allocates slightly more memory.
 680   bottom = (address)align_down((uintptr_t)bottom, os::vm_page_size());
 681   bottom += os::vm_page_size() - 1;
 682 
 683   // sp might be slightly above current stack pointer; if that's the case, we
 684   // will alloca() a little more space than necessary, which is OK. Don't use
 685   // os::current_stack_pointer(), as its result can be slightly below current
 686   // stack pointer, causing us to not alloca enough to reach "bottom".
 687   sp = (address)&sp;
 688 
 689   if (sp > bottom) {
 690     size = sp - bottom;
 691     p = (volatile char *)alloca(size);
 692     assert(p != nullptr && p <= (volatile char *)bottom, "alloca problem?");
 693     p[0] = '\0';
 694   }
 695 }
 696 
 697 void os::Linux::expand_stack_to(address bottom) {
 698   _expand_stack_to(bottom);
 699 }
 700 
 701 bool os::Linux::manually_expand_stack(JavaThread * t, address addr) {
 702   assert(t!=nullptr, "just checking");
 703   assert(t->osthread()->expanding_stack(), "expand should be set");
 704 
 705   if (t->is_in_usable_stack(addr)) {
 706     sigset_t mask_all, old_sigset;
 707     sigfillset(&mask_all);
 708     pthread_sigmask(SIG_SETMASK, &mask_all, &old_sigset);
 709     _expand_stack_to(addr);
 710     pthread_sigmask(SIG_SETMASK, &old_sigset, nullptr);
 711     return true;
 712   }
 713   return false;
 714 }
 715 
 716 //////////////////////////////////////////////////////////////////////////////
 717 // create new thread
 718 
 719 // Thread start routine for all newly created threads
 720 static void *thread_native_entry(Thread *thread) {
 721 
 722   thread->record_stack_base_and_size();
 723 
 724 #ifndef __GLIBC__
 725   // Try to randomize the cache line index of hot stack frames.
 726   // This helps when threads of the same stack traces evict each other's
 727   // cache lines. The threads can be either from the same JVM instance, or
 728   // from different JVM instances. The benefit is especially true for
 729   // processors with hyperthreading technology.
 730   // This code is not needed anymore in glibc because it has MULTI_PAGE_ALIASING
 731   // and we did not see any degradation in performance without `alloca()`.
 732   static int counter = 0;
 733   int pid = os::current_process_id();
 734   int random = ((pid ^ counter++) & 7) * 128;
 735   void *stackmem = alloca(random != 0 ? random : 1); // ensure we allocate > 0
 736   // Ensure the alloca result is used in a way that prevents the compiler from eliding it.
 737   *(char *)stackmem = 1;
 738 #endif
 739 
 740   thread->initialize_thread_current();
 741 
 742   OSThread* osthread = thread->osthread();
 743   Monitor* sync = osthread->startThread_lock();
 744 
 745   osthread->set_thread_id(os::current_thread_id());
 746 
 747   if (UseNUMA) {
 748     int lgrp_id = os::numa_get_group_id();
 749     if (lgrp_id != -1) {
 750       thread->set_lgrp_id(lgrp_id);
 751     }
 752   }
 753   // initialize signal mask for this thread
 754   PosixSignals::hotspot_sigmask(thread);
 755 
 756   // initialize floating point control register
 757   os::Linux::init_thread_fpu_state();
 758 
 759   // handshaking with parent thread
 760   {
 761     MutexLocker ml(sync, Mutex::_no_safepoint_check_flag);
 762 
 763     // notify parent thread
 764     osthread->set_state(INITIALIZED);
 765     sync->notify_all();
 766 
 767     // wait until os::start_thread()
 768     while (osthread->get_state() == INITIALIZED) {
 769       sync->wait_without_safepoint_check();
 770     }
 771   }
 772 
 773   log_info(os, thread)("Thread is alive (tid: " UINTX_FORMAT ", pthread id: " UINTX_FORMAT ").",
 774     os::current_thread_id(), (uintx) pthread_self());
 775 
 776   assert(osthread->pthread_id() != 0, "pthread_id was not set as expected");
 777 
 778   if (DelayThreadStartALot) {
 779     os::naked_short_sleep(100);
 780   }
 781 
 782   // call one more level start routine
 783   thread->call_run();
 784 
 785   // Note: at this point the thread object may already have deleted itself.
 786   // Prevent dereferencing it from here on out.
 787   thread = nullptr;
 788 
 789   log_info(os, thread)("Thread finished (tid: " UINTX_FORMAT ", pthread id: " UINTX_FORMAT ").",
 790     os::current_thread_id(), (uintx) pthread_self());
 791 
 792   return 0;
 793 }
 794 
 795 // On Linux, glibc places static TLS blocks (for __thread variables) on
 796 // the thread stack. This decreases the stack size actually available
 797 // to threads.
 798 //
 799 // For large static TLS sizes, this may cause threads to malfunction due
 800 // to insufficient stack space. This is a well-known issue in glibc:
 801 // http://sourceware.org/bugzilla/show_bug.cgi?id=11787.
 802 //
 803 // As a workaround, we call a private but assumed-stable glibc function,
 804 // __pthread_get_minstack() to obtain the minstack size and derive the
 805 // static TLS size from it. We then increase the user requested stack
 806 // size by this TLS size. The same function is used to determine whether
 807 // adjustStackSizeForGuardPages() needs to be true.
 808 //
 809 // Due to compatibility concerns, this size adjustment is opt-in and
 810 // controlled via AdjustStackSizeForTLS.
 811 typedef size_t (*GetMinStack)(const pthread_attr_t *attr);
 812 
 813 GetMinStack _get_minstack_func = nullptr;  // Initialized via os::init_2()
 814 
 815 // Returns the size of the static TLS area glibc puts on thread stacks.
 816 // The value is cached on first use, which occurs when the first thread
 817 // is created during VM initialization.
 818 static size_t get_static_tls_area_size(const pthread_attr_t *attr) {
 819   size_t tls_size = 0;
 820   if (_get_minstack_func != nullptr) {
 821     // Obtain the pthread minstack size by calling __pthread_get_minstack.
 822     size_t minstack_size = _get_minstack_func(attr);
 823 
 824     // Remove non-TLS area size included in minstack size returned
 825     // by __pthread_get_minstack() to get the static TLS size.
 826     // If adjustStackSizeForGuardPages() is true, minstack size includes
 827     // guard_size. Otherwise guard_size is automatically added
 828     // to the stack size by pthread_create and is no longer included
 829     // in minstack size. In both cases, the guard_size is taken into
 830     // account, so there is no need to adjust the result for that.
 831     //
 832     // Although __pthread_get_minstack() is a private glibc function,
 833     // it is expected to have a stable behavior across future glibc
 834     // versions while glibc still allocates the static TLS blocks off
 835     // the stack. Following is glibc 2.28 __pthread_get_minstack():
 836     //
 837     // size_t
 838     // __pthread_get_minstack (const pthread_attr_t *attr)
 839     // {
 840     //   return GLRO(dl_pagesize) + __static_tls_size + PTHREAD_STACK_MIN;
 841     // }
 842     //
 843     //
 844     // The following 'minstack_size > os::vm_page_size() + PTHREAD_STACK_MIN'
 845     // if check is done for precaution.
 846     if (minstack_size > os::vm_page_size() + PTHREAD_STACK_MIN) {
 847       tls_size = minstack_size - os::vm_page_size() - PTHREAD_STACK_MIN;
 848     }
 849   }
 850 
 851   log_info(os, thread)("Stack size adjustment for TLS is " SIZE_FORMAT,
 852                        tls_size);
 853   return tls_size;
 854 }
 855 
 856 // In glibc versions prior to 2.27 the guard size mechanism
 857 // was not implemented properly. The POSIX standard requires adding
 858 // the size of the guard pages to the stack size, instead glibc
 859 // took the space out of 'stacksize'. Thus we need to adapt the requested
 860 // stack_size by the size of the guard pages to mimic proper behaviour.
 861 // The fix in glibc 2.27 has now been backported to numerous earlier
 862 // glibc versions so we need to do a dynamic runtime check.
 863 static bool _adjustStackSizeForGuardPages = true;
 864 bool os::Linux::adjustStackSizeForGuardPages() {
 865   return _adjustStackSizeForGuardPages;
 866 }
 867 
 868 #ifdef __GLIBC__
 869 static void init_adjust_stacksize_for_guard_pages() {
 870   assert(_get_minstack_func == nullptr, "initialization error");
 871   _get_minstack_func =(GetMinStack)dlsym(RTLD_DEFAULT, "__pthread_get_minstack");
 872   log_info(os, thread)("Lookup of __pthread_get_minstack %s",
 873                        _get_minstack_func == nullptr ? "failed" : "succeeded");
 874 
 875   if (_get_minstack_func != nullptr) {
 876     pthread_attr_t attr;
 877     pthread_attr_init(&attr);
 878     size_t min_stack = _get_minstack_func(&attr);
 879     size_t guard = 16 * K; // Actual value doesn't matter as it is not examined
 880     pthread_attr_setguardsize(&attr, guard);
 881     size_t min_stack2 = _get_minstack_func(&attr);
 882     pthread_attr_destroy(&attr);
 883     // If the minimum stack size changed when we added the guard page space
 884     // then we need to perform the adjustment.
 885     _adjustStackSizeForGuardPages = (min_stack2 != min_stack);
 886     log_info(os)("Glibc stack size guard page adjustment is %sneeded",
 887                  _adjustStackSizeForGuardPages ? "" : "not ");
 888   }
 889 }
 890 #endif // GLIBC
 891 
 892 bool os::create_thread(Thread* thread, ThreadType thr_type,
 893                        size_t req_stack_size) {
 894   assert(thread->osthread() == nullptr, "caller responsible");
 895 
 896   // Allocate the OSThread object
 897   OSThread* osthread = new (std::nothrow) OSThread();
 898   if (osthread == nullptr) {
 899     return false;
 900   }
 901 
 902   // set the correct thread state
 903   osthread->set_thread_type(thr_type);
 904 
 905   // Initial state is ALLOCATED but not INITIALIZED
 906   osthread->set_state(ALLOCATED);
 907 
 908   thread->set_osthread(osthread);
 909 
 910   // init thread attributes
 911   pthread_attr_t attr;
 912   pthread_attr_init(&attr);
 913   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
 914 
 915   // Calculate stack size if it's not specified by caller.
 916   size_t stack_size = os::Posix::get_initial_stack_size(thr_type, req_stack_size);
 917   size_t guard_size = os::Linux::default_guard_size(thr_type);
 918 
 919   // Configure glibc guard page. Must happen before calling
 920   // get_static_tls_area_size(), which uses the guard_size.
 921   pthread_attr_setguardsize(&attr, guard_size);
 922 
 923   // Apply stack size adjustments if needed. However, be careful not to end up
 924   // with a size of zero due to overflow. Don't add the adjustment in that case.
 925   size_t stack_adjust_size = 0;
 926   if (AdjustStackSizeForTLS) {
 927     // Adjust the stack_size for on-stack TLS - see get_static_tls_area_size().
 928     stack_adjust_size += get_static_tls_area_size(&attr);
 929   } else if (os::Linux::adjustStackSizeForGuardPages()) {
 930     stack_adjust_size += guard_size;
 931   }
 932 
 933   stack_adjust_size = align_up(stack_adjust_size, os::vm_page_size());
 934   if (stack_size <= SIZE_MAX - stack_adjust_size) {
 935     stack_size += stack_adjust_size;
 936   }
 937   assert(is_aligned(stack_size, os::vm_page_size()), "stack_size not aligned");
 938 
 939   if (THPStackMitigation) {
 940     // In addition to the glibc guard page that prevents inter-thread-stack hugepage
 941     // coalescing (see comment in os::Linux::default_guard_size()), we also make
 942     // sure the stack size itself is not huge-page-size aligned; that makes it much
 943     // more likely for thread stack boundaries to be unaligned as well and hence
 944     // protects thread stacks from being targeted by khugepaged.
 945     if (HugePages::thp_pagesize() > 0 &&
 946         is_aligned(stack_size, HugePages::thp_pagesize())) {
 947       stack_size += os::vm_page_size();
 948     }
 949   }
 950 
 951   int status = pthread_attr_setstacksize(&attr, stack_size);
 952   if (status != 0) {
 953     // pthread_attr_setstacksize() function can fail
 954     // if the stack size exceeds a system-imposed limit.
 955     assert_status(status == EINVAL, status, "pthread_attr_setstacksize");
 956     log_warning(os, thread)("The %sthread stack size specified is invalid: " SIZE_FORMAT "k",
 957                             (thr_type == compiler_thread) ? "compiler " : ((thr_type == java_thread) ? "" : "VM "),
 958                             stack_size / K);
 959     thread->set_osthread(nullptr);
 960     delete osthread;
 961     return false;
 962   }
 963 
 964   ThreadState state;
 965 
 966   {
 967     ResourceMark rm;
 968     pthread_t tid;
 969     int ret = 0;
 970     int limit = 3;
 971     do {
 972       ret = pthread_create(&tid, &attr, (void* (*)(void*)) thread_native_entry, thread);
 973     } while (ret == EAGAIN && limit-- > 0);
 974 
 975     char buf[64];
 976     if (ret == 0) {
 977       log_info(os, thread)("Thread \"%s\" started (pthread id: " UINTX_FORMAT ", attributes: %s). ",
 978                            thread->name(), (uintx) tid, os::Posix::describe_pthread_attr(buf, sizeof(buf), &attr));
 979 
 980       // Print current timer slack if override is enabled and timer slack value is available.
 981       // Avoid calling prctl otherwise for extra safety.
 982       if (TimerSlack >= 0) {
 983         int slack = prctl(PR_GET_TIMERSLACK);
 984         if (slack >= 0) {
 985           log_info(os, thread)("Thread \"%s\" (pthread id: " UINTX_FORMAT ") timer slack: %dns",
 986                                thread->name(), (uintx) tid, slack);
 987         }
 988       }
 989     } else {
 990       log_warning(os, thread)("Failed to start thread \"%s\" - pthread_create failed (%s) for attributes: %s.",
 991                               thread->name(), os::errno_name(ret), os::Posix::describe_pthread_attr(buf, sizeof(buf), &attr));
 992       // Log some OS information which might explain why creating the thread failed.
 993       log_info(os, thread)("Number of threads approx. running in the VM: %d", Threads::number_of_threads());
 994       LogStream st(Log(os, thread)::info());
 995       os::Posix::print_rlimit_info(&st);
 996       os::print_memory_info(&st);
 997       os::Linux::print_proc_sys_info(&st);
 998       os::Linux::print_container_info(&st);
 999     }
1000 
1001     pthread_attr_destroy(&attr);
1002 
1003     if (ret != 0) {
1004       // Need to clean up stuff we've allocated so far
1005       thread->set_osthread(nullptr);
1006       delete osthread;
1007       return false;
1008     }
1009 
1010     // Store pthread info into the OSThread
1011     osthread->set_pthread_id(tid);
1012 
1013     // Wait until child thread is either initialized or aborted
1014     {
1015       Monitor* sync_with_child = osthread->startThread_lock();
1016       MutexLocker ml(sync_with_child, Mutex::_no_safepoint_check_flag);
1017       while ((state = osthread->get_state()) == ALLOCATED) {
1018         sync_with_child->wait_without_safepoint_check();
1019       }
1020     }
1021   }
1022 
1023   // The thread is returned suspended (in state INITIALIZED),
1024   // and is started higher up in the call chain
1025   assert(state == INITIALIZED, "race condition");
1026   return true;
1027 }
1028 
1029 /////////////////////////////////////////////////////////////////////////////
1030 // attach existing thread
1031 
1032 // bootstrap the main thread
1033 bool os::create_main_thread(JavaThread* thread) {
1034   assert(os::Linux::_main_thread == pthread_self(), "should be called inside main thread");
1035   return create_attached_thread(thread);
1036 }
1037 
1038 bool os::create_attached_thread(JavaThread* thread) {
1039 #ifdef ASSERT
1040   thread->verify_not_published();
1041 #endif
1042 
1043   // Allocate the OSThread object
1044   OSThread* osthread = new (std::nothrow) OSThread();
1045 
1046   if (osthread == nullptr) {
1047     return false;
1048   }
1049 
1050   // Store pthread info into the OSThread
1051   osthread->set_thread_id(os::Linux::gettid());
1052   osthread->set_pthread_id(::pthread_self());
1053 
1054   // initialize floating point control register
1055   os::Linux::init_thread_fpu_state();
1056 
1057   // Initial thread state is RUNNABLE
1058   osthread->set_state(RUNNABLE);
1059 
1060   thread->set_osthread(osthread);
1061 
1062   if (UseNUMA) {
1063     int lgrp_id = os::numa_get_group_id();
1064     if (lgrp_id != -1) {
1065       thread->set_lgrp_id(lgrp_id);
1066     }
1067   }
1068 
1069   if (os::is_primordial_thread()) {
1070     // If current thread is primordial thread, its stack is mapped on demand,
1071     // see notes about MAP_GROWSDOWN. Here we try to force kernel to map
1072     // the entire stack region to avoid SEGV in stack banging.
1073     // It is also useful to get around the heap-stack-gap problem on SuSE
1074     // kernel (see 4821821 for details). We first expand stack to the top
1075     // of yellow zone, then enable stack yellow zone (order is significant,
1076     // enabling yellow zone first will crash JVM on SuSE Linux), so there
1077     // is no gap between the last two virtual memory regions.
1078 
1079     StackOverflow* overflow_state = thread->stack_overflow_state();
1080     address addr = overflow_state->stack_reserved_zone_base();
1081     assert(addr != nullptr, "initialization problem?");
1082     assert(overflow_state->stack_available(addr) > 0, "stack guard should not be enabled");
1083 
1084     osthread->set_expanding_stack();
1085     os::Linux::manually_expand_stack(thread, addr);
1086     osthread->clear_expanding_stack();
1087   }
1088 
1089   // initialize signal mask for this thread
1090   // and save the caller's signal mask
1091   PosixSignals::hotspot_sigmask(thread);
1092 
1093   log_info(os, thread)("Thread attached (tid: " UINTX_FORMAT ", pthread id: " UINTX_FORMAT
1094                        ", stack: " PTR_FORMAT " - " PTR_FORMAT " (" SIZE_FORMAT "K) ).",
1095                        os::current_thread_id(), (uintx) pthread_self(),
1096                        p2i(thread->stack_base()), p2i(thread->stack_end()), thread->stack_size() / K);
1097 
1098   return true;
1099 }
1100 
1101 void os::pd_start_thread(Thread* thread) {
1102   OSThread * osthread = thread->osthread();
1103   assert(osthread->get_state() != INITIALIZED, "just checking");
1104   Monitor* sync_with_child = osthread->startThread_lock();
1105   MutexLocker ml(sync_with_child, Mutex::_no_safepoint_check_flag);
1106   sync_with_child->notify();
1107 }
1108 
1109 // Free Linux resources related to the OSThread
1110 void os::free_thread(OSThread* osthread) {
1111   assert(osthread != nullptr, "osthread not set");
1112 
1113   // We are told to free resources of the argument thread,
1114   // but we can only really operate on the current thread.
1115   assert(Thread::current()->osthread() == osthread,
1116          "os::free_thread but not current thread");
1117 
1118 #ifdef ASSERT
1119   sigset_t current;
1120   sigemptyset(&current);
1121   pthread_sigmask(SIG_SETMASK, nullptr, &current);
1122   assert(!sigismember(&current, PosixSignals::SR_signum), "SR signal should not be blocked!");
1123 #endif
1124 
1125   // Restore caller's signal mask
1126   sigset_t sigmask = osthread->caller_sigmask();
1127   pthread_sigmask(SIG_SETMASK, &sigmask, nullptr);
1128 
1129   delete osthread;
1130 }
1131 
1132 //////////////////////////////////////////////////////////////////////////////
1133 // primordial thread
1134 
1135 // Check if current thread is the primordial thread, similar to Solaris thr_main.
1136 bool os::is_primordial_thread(void) {
1137   if (suppress_primordial_thread_resolution) {
1138     return false;
1139   }
1140   char dummy;
1141   // If called before init complete, thread stack bottom will be null.
1142   // Can be called if fatal error occurs before initialization.
1143   if (os::Linux::initial_thread_stack_bottom() == nullptr) return false;
1144   assert(os::Linux::initial_thread_stack_bottom() != nullptr &&
1145          os::Linux::initial_thread_stack_size()   != 0,
1146          "os::init did not locate primordial thread's stack region");
1147   if ((address)&dummy >= os::Linux::initial_thread_stack_bottom() &&
1148       (address)&dummy < os::Linux::initial_thread_stack_bottom() +
1149                         os::Linux::initial_thread_stack_size()) {
1150     return true;
1151   } else {
1152     return false;
1153   }
1154 }
1155 
1156 // Find the virtual memory area that contains addr
1157 static bool find_vma(address addr, address* vma_low, address* vma_high) {
1158   FILE *fp = os::fopen("/proc/self/maps", "r");
1159   if (fp) {
1160     address low, high;
1161     while (!feof(fp)) {
1162       if (fscanf(fp, "%p-%p", &low, &high) == 2) {
1163         if (low <= addr && addr < high) {
1164           if (vma_low)  *vma_low  = low;
1165           if (vma_high) *vma_high = high;
1166           fclose(fp);
1167           return true;
1168         }
1169       }
1170       for (;;) {
1171         int ch = fgetc(fp);
1172         if (ch == EOF || ch == (int)'\n') break;
1173       }
1174     }
1175     fclose(fp);
1176   }
1177   return false;
1178 }
1179 
1180 // Locate primordial thread stack. This special handling of primordial thread stack
1181 // is needed because pthread_getattr_np() on most (all?) Linux distros returns
1182 // bogus value for the primordial process thread. While the launcher has created
1183 // the VM in a new thread since JDK 6, we still have to allow for the use of the
1184 // JNI invocation API from a primordial thread.
1185 void os::Linux::capture_initial_stack(size_t max_size) {
1186 
1187   // max_size is either 0 (which means accept OS default for thread stacks) or
1188   // a user-specified value known to be at least the minimum needed. If we
1189   // are actually on the primordial thread we can make it appear that we have a
1190   // smaller max_size stack by inserting the guard pages at that location. But we
1191   // cannot do anything to emulate a larger stack than what has been provided by
1192   // the OS or threading library. In fact if we try to use a stack greater than
1193   // what is set by rlimit then we will crash the hosting process.
1194 
1195   // Maximum stack size is the easy part, get it from RLIMIT_STACK.
1196   // If this is "unlimited" then it will be a huge value.
1197   struct rlimit rlim;
1198   getrlimit(RLIMIT_STACK, &rlim);
1199   size_t stack_size = rlim.rlim_cur;
1200 
1201   // 6308388: a bug in ld.so will relocate its own .data section to the
1202   //   lower end of primordial stack; reduce ulimit -s value a little bit
1203   //   so we won't install guard page on ld.so's data section.
1204   //   But ensure we don't underflow the stack size - allow 1 page spare
1205   if (stack_size >= 3 * os::vm_page_size()) {
1206     stack_size -= 2 * os::vm_page_size();
1207   }
1208 
1209   // Try to figure out where the stack base (top) is. This is harder.
1210   //
1211   // When an application is started, glibc saves the initial stack pointer in
1212   // a global variable "__libc_stack_end", which is then used by system
1213   // libraries. __libc_stack_end should be pretty close to stack top. The
1214   // variable is available since the very early days. However, because it is
1215   // a private interface, it could disappear in the future.
1216   //
1217   // Linux kernel saves start_stack information in /proc/<pid>/stat. Similar
1218   // to __libc_stack_end, it is very close to stack top, but isn't the real
1219   // stack top. Note that /proc may not exist if VM is running as a chroot
1220   // program, so reading /proc/<pid>/stat could fail. Also the contents of
1221   // /proc/<pid>/stat could change in the future (though unlikely).
1222   //
1223   // We try __libc_stack_end first. If that doesn't work, look for
1224   // /proc/<pid>/stat. If neither of them works, we use current stack pointer
1225   // as a hint, which should work well in most cases.
1226 
1227   uintptr_t stack_start;
1228 
1229   // try __libc_stack_end first
1230   uintptr_t *p = (uintptr_t *)dlsym(RTLD_DEFAULT, "__libc_stack_end");
1231   if (p && *p) {
1232     stack_start = *p;
1233   } else {
1234     // see if we can get the start_stack field from /proc/self/stat
1235     FILE *fp;
1236     int pid;
1237     char state;
1238     int ppid;
1239     int pgrp;
1240     int session;
1241     int nr;
1242     int tpgrp;
1243     unsigned long flags;
1244     unsigned long minflt;
1245     unsigned long cminflt;
1246     unsigned long majflt;
1247     unsigned long cmajflt;
1248     unsigned long utime;
1249     unsigned long stime;
1250     long cutime;
1251     long cstime;
1252     long prio;
1253     long nice;
1254     long junk;
1255     long it_real;
1256     uintptr_t start;
1257     uintptr_t vsize;
1258     intptr_t rss;
1259     uintptr_t rsslim;
1260     uintptr_t scodes;
1261     uintptr_t ecode;
1262     int i;
1263 
1264     // Figure what the primordial thread stack base is. Code is inspired
1265     // by email from Hans Boehm. /proc/self/stat begins with current pid,
1266     // followed by command name surrounded by parentheses, state, etc.
1267     char stat[2048];
1268     int statlen;
1269 
1270     fp = os::fopen("/proc/self/stat", "r");
1271     if (fp) {
1272       statlen = fread(stat, 1, 2047, fp);
1273       stat[statlen] = '\0';
1274       fclose(fp);
1275 
1276       // Skip pid and the command string. Note that we could be dealing with
1277       // weird command names, e.g. user could decide to rename java launcher
1278       // to "java 1.4.2 :)", then the stat file would look like
1279       //                1234 (java 1.4.2 :)) R ... ...
1280       // We don't really need to know the command string, just find the last
1281       // occurrence of ")" and then start parsing from there. See bug 4726580.
1282       char * s = strrchr(stat, ')');
1283 
1284       i = 0;
1285       if (s) {
1286         // Skip blank chars
1287         do { s++; } while (s && isspace(*s));
1288 
1289 #define _UFM UINTX_FORMAT
1290 #define _DFM INTX_FORMAT
1291 
1292         //                                     1   1   1   1   1   1   1   1   1   1   2   2    2    2    2    2    2    2    2
1293         //              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
1294         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,
1295                    &state,          // 3  %c
1296                    &ppid,           // 4  %d
1297                    &pgrp,           // 5  %d
1298                    &session,        // 6  %d
1299                    &nr,             // 7  %d
1300                    &tpgrp,          // 8  %d
1301                    &flags,          // 9  %lu
1302                    &minflt,         // 10 %lu
1303                    &cminflt,        // 11 %lu
1304                    &majflt,         // 12 %lu
1305                    &cmajflt,        // 13 %lu
1306                    &utime,          // 14 %lu
1307                    &stime,          // 15 %lu
1308                    &cutime,         // 16 %ld
1309                    &cstime,         // 17 %ld
1310                    &prio,           // 18 %ld
1311                    &nice,           // 19 %ld
1312                    &junk,           // 20 %ld
1313                    &it_real,        // 21 %ld
1314                    &start,          // 22 UINTX_FORMAT
1315                    &vsize,          // 23 UINTX_FORMAT
1316                    &rss,            // 24 INTX_FORMAT
1317                    &rsslim,         // 25 UINTX_FORMAT
1318                    &scodes,         // 26 UINTX_FORMAT
1319                    &ecode,          // 27 UINTX_FORMAT
1320                    &stack_start);   // 28 UINTX_FORMAT
1321       }
1322 
1323 #undef _UFM
1324 #undef _DFM
1325 
1326       if (i != 28 - 2) {
1327         assert(false, "Bad conversion from /proc/self/stat");
1328         // product mode - assume we are the primordial thread, good luck in the
1329         // embedded case.
1330         warning("Can't detect primordial thread stack location - bad conversion");
1331         stack_start = (uintptr_t) &rlim;
1332       }
1333     } else {
1334       // For some reason we can't open /proc/self/stat (for example, running on
1335       // FreeBSD with a Linux emulator, or inside chroot), this should work for
1336       // most cases, so don't abort:
1337       warning("Can't detect primordial thread stack location - no /proc/self/stat");
1338       stack_start = (uintptr_t) &rlim;
1339     }
1340   }
1341 
1342   // Now we have a pointer (stack_start) very close to the stack top, the
1343   // next thing to do is to figure out the exact location of stack top. We
1344   // can find out the virtual memory area that contains stack_start by
1345   // reading /proc/self/maps, it should be the last vma in /proc/self/maps,
1346   // and its upper limit is the real stack top. (again, this would fail if
1347   // running inside chroot, because /proc may not exist.)
1348 
1349   uintptr_t stack_top;
1350   address low, high;
1351   if (find_vma((address)stack_start, &low, &high)) {
1352     // success, "high" is the true stack top. (ignore "low", because initial
1353     // thread stack grows on demand, its real bottom is high - RLIMIT_STACK.)
1354     stack_top = (uintptr_t)high;
1355   } else {
1356     // failed, likely because /proc/self/maps does not exist
1357     warning("Can't detect primordial thread stack location - find_vma failed");
1358     // best effort: stack_start is normally within a few pages below the real
1359     // stack top, use it as stack top, and reduce stack size so we won't put
1360     // guard page outside stack.
1361     stack_top = stack_start;
1362     stack_size -= 16 * os::vm_page_size();
1363   }
1364 
1365   // stack_top could be partially down the page so align it
1366   stack_top = align_up(stack_top, os::vm_page_size());
1367 
1368   // Allowed stack value is minimum of max_size and what we derived from rlimit
1369   if (max_size > 0) {
1370     _initial_thread_stack_size = MIN2(max_size, stack_size);
1371   } else {
1372     // Accept the rlimit max, but if stack is unlimited then it will be huge, so
1373     // clamp it at 8MB as we do on Solaris
1374     _initial_thread_stack_size = MIN2(stack_size, 8*M);
1375   }
1376   _initial_thread_stack_size = align_down(_initial_thread_stack_size, os::vm_page_size());
1377   _initial_thread_stack_bottom = (address)stack_top - _initial_thread_stack_size;
1378 
1379   assert(_initial_thread_stack_bottom < (address)stack_top, "overflow!");
1380 
1381   if (log_is_enabled(Info, os, thread)) {
1382     // See if we seem to be on primordial process thread
1383     bool primordial = uintptr_t(&rlim) > uintptr_t(_initial_thread_stack_bottom) &&
1384                       uintptr_t(&rlim) < stack_top;
1385 
1386     log_info(os, thread)("Capturing initial stack in %s thread: req. size: " SIZE_FORMAT "K, actual size: "
1387                          SIZE_FORMAT "K, top=" INTPTR_FORMAT ", bottom=" INTPTR_FORMAT,
1388                          primordial ? "primordial" : "user", max_size / K,  _initial_thread_stack_size / K,
1389                          stack_top, intptr_t(_initial_thread_stack_bottom));
1390   }
1391 }
1392 
1393 ////////////////////////////////////////////////////////////////////////////////
1394 // time support
1395 double os::elapsedVTime() {
1396   struct rusage usage;
1397   int retval = getrusage(RUSAGE_THREAD, &usage);
1398   if (retval == 0) {
1399     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);
1400   } else {
1401     // better than nothing, but not much
1402     return elapsedTime();
1403   }
1404 }
1405 
1406 void os::Linux::fast_thread_clock_init() {
1407   if (!UseLinuxPosixThreadCPUClocks) {
1408     return;
1409   }
1410   clockid_t clockid;
1411   struct timespec tp;
1412   int (*pthread_getcpuclockid_func)(pthread_t, clockid_t *) =
1413       (int(*)(pthread_t, clockid_t *)) dlsym(RTLD_DEFAULT, "pthread_getcpuclockid");
1414 
1415   // Switch to using fast clocks for thread cpu time if
1416   // the clock_getres() returns 0 error code.
1417   // Note, that some kernels may support the current thread
1418   // clock (CLOCK_THREAD_CPUTIME_ID) but not the clocks
1419   // returned by the pthread_getcpuclockid().
1420   // If the fast POSIX clocks are supported then the clock_getres()
1421   // must return at least tp.tv_sec == 0 which means a resolution
1422   // better than 1 sec. This is extra check for reliability.
1423 
1424   if (pthread_getcpuclockid_func &&
1425       pthread_getcpuclockid_func(_main_thread, &clockid) == 0 &&
1426       clock_getres(clockid, &tp) == 0 && tp.tv_sec == 0) {
1427     _supports_fast_thread_cpu_time = true;
1428     _pthread_getcpuclockid = pthread_getcpuclockid_func;
1429   }
1430 }
1431 
1432 // thread_id is kernel thread id (similar to Solaris LWP id)
1433 intx os::current_thread_id() { return os::Linux::gettid(); }
1434 int os::current_process_id() {
1435   return ::getpid();
1436 }
1437 
1438 // DLL functions
1439 
1440 // This must be hard coded because it's the system's temporary
1441 // directory not the java application's temp directory, ala java.io.tmpdir.
1442 const char* os::get_temp_directory() { return "/tmp"; }
1443 
1444 // check if addr is inside libjvm.so
1445 bool os::address_is_in_vm(address addr) {
1446   static address libjvm_base_addr;
1447   Dl_info dlinfo;
1448 
1449   if (libjvm_base_addr == nullptr) {
1450     if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {
1451       libjvm_base_addr = (address)dlinfo.dli_fbase;
1452     }
1453     assert(libjvm_base_addr !=nullptr, "Cannot obtain base address for libjvm");
1454   }
1455 
1456   if (dladdr((void *)addr, &dlinfo) != 0) {
1457     if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
1458   }
1459 
1460   return false;
1461 }
1462 
1463 void os::prepare_native_symbols() {
1464 }
1465 
1466 bool os::dll_address_to_function_name(address addr, char *buf,
1467                                       int buflen, int *offset,
1468                                       bool demangle) {
1469   // buf is not optional, but offset is optional
1470   assert(buf != nullptr, "sanity check");
1471 
1472   Dl_info dlinfo;
1473 
1474   if (dladdr((void*)addr, &dlinfo) != 0) {
1475     // see if we have a matching symbol
1476     if (dlinfo.dli_saddr != nullptr && dlinfo.dli_sname != nullptr) {
1477       if (!(demangle && Decoder::demangle(dlinfo.dli_sname, buf, buflen))) {
1478         jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
1479       }
1480       if (offset != nullptr) *offset = addr - (address)dlinfo.dli_saddr;
1481       return true;
1482     }
1483     // no matching symbol so try for just file info
1484     if (dlinfo.dli_fname != nullptr && dlinfo.dli_fbase != nullptr) {
1485       if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1486                           buf, buflen, offset, dlinfo.dli_fname, demangle)) {
1487         return true;
1488       }
1489     }
1490   }
1491 
1492   buf[0] = '\0';
1493   if (offset != nullptr) *offset = -1;
1494   return false;
1495 }
1496 
1497 bool os::dll_address_to_library_name(address addr, char* buf,
1498                                      int buflen, int* offset) {
1499   // buf is not optional, but offset is optional
1500   assert(buf != nullptr, "sanity check");
1501 
1502   Dl_info dlinfo;
1503   if (dladdr((void*)addr, &dlinfo) != 0) {
1504     if (dlinfo.dli_fname != nullptr) {
1505       jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
1506     }
1507     if (dlinfo.dli_fbase != nullptr && offset != nullptr) {
1508       *offset = addr - (address)dlinfo.dli_fbase;
1509     }
1510     return true;
1511   }
1512   buf[0] = '\0';
1513   if (offset) *offset = -1;
1514   return false;
1515 }
1516 
1517 // Remember the stack's state. The Linux dynamic linker will change
1518 // the stack to 'executable' at most once, so we must safepoint only once.
1519 bool os::Linux::_stack_is_executable = false;
1520 
1521 // VM operation that loads a library.  This is necessary if stack protection
1522 // of the Java stacks can be lost during loading the library.  If we
1523 // do not stop the Java threads, they can stack overflow before the stacks
1524 // are protected again.
1525 class VM_LinuxDllLoad: public VM_Operation {
1526  private:
1527   const char *_filename;
1528   char *_ebuf;
1529   int _ebuflen;
1530   void *_lib;
1531  public:
1532   VM_LinuxDllLoad(const char *fn, char *ebuf, int ebuflen) :
1533     _filename(fn), _ebuf(ebuf), _ebuflen(ebuflen), _lib(nullptr) {}
1534   VMOp_Type type() const { return VMOp_LinuxDllLoad; }
1535   void doit() {
1536     _lib = os::Linux::dll_load_in_vmthread(_filename, _ebuf, _ebuflen);
1537     os::Linux::_stack_is_executable = true;
1538   }
1539   void* loaded_library() { return _lib; }
1540 };
1541 
1542 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
1543   void * result = nullptr;
1544   bool load_attempted = false;
1545 
1546   log_info(os)("attempting shared library load of %s", filename);
1547 
1548   // Check whether the library to load might change execution rights
1549   // of the stack. If they are changed, the protection of the stack
1550   // guard pages will be lost. We need a safepoint to fix this.
1551   //
1552   // See Linux man page execstack(8) for more info.
1553   if (os::uses_stack_guard_pages() && !os::Linux::_stack_is_executable) {
1554     if (!ElfFile::specifies_noexecstack(filename)) {
1555       if (!is_init_completed()) {
1556         os::Linux::_stack_is_executable = true;
1557         // This is OK - No Java threads have been created yet, and hence no
1558         // stack guard pages to fix.
1559         //
1560         // Dynamic loader will make all stacks executable after
1561         // this function returns, and will not do that again.
1562         assert(Threads::number_of_threads() == 0, "no Java threads should exist yet.");
1563       } else {
1564         warning("You have loaded library %s which might have disabled stack guard. "
1565                 "The VM will try to fix the stack guard now.\n"
1566                 "It's highly recommended that you fix the library with "
1567                 "'execstack -c <libfile>', or link it with '-z noexecstack'.",
1568                 filename);
1569 
1570         JavaThread *jt = JavaThread::current();
1571         if (jt->thread_state() != _thread_in_native) {
1572           // This happens when a compiler thread tries to load a hsdis-<arch>.so file
1573           // that requires ExecStack. Cannot enter safe point. Let's give up.
1574           warning("Unable to fix stack guard. Giving up.");
1575         } else {
1576           if (!LoadExecStackDllInVMThread) {
1577             // This is for the case where the DLL has an static
1578             // constructor function that executes JNI code. We cannot
1579             // load such DLLs in the VMThread.
1580             result = os::Linux::dlopen_helper(filename, ebuf, ebuflen);
1581           }
1582 
1583           ThreadInVMfromNative tiv(jt);
1584           debug_only(VMNativeEntryWrapper vew;)
1585 
1586           VM_LinuxDllLoad op(filename, ebuf, ebuflen);
1587           VMThread::execute(&op);
1588           if (LoadExecStackDllInVMThread) {
1589             result = op.loaded_library();
1590           }
1591           load_attempted = true;
1592         }
1593       }
1594     }
1595   }
1596 
1597   if (!load_attempted) {
1598     result = os::Linux::dlopen_helper(filename, ebuf, ebuflen);
1599   }
1600 
1601   if (result != nullptr) {
1602     // Successful loading
1603     return result;
1604   }
1605 
1606   Elf32_Ehdr elf_head;
1607   int diag_msg_max_length=ebuflen-strlen(ebuf);
1608   char* diag_msg_buf=ebuf+strlen(ebuf);
1609 
1610   if (diag_msg_max_length==0) {
1611     // No more space in ebuf for additional diagnostics message
1612     return nullptr;
1613   }
1614 
1615 
1616   int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
1617 
1618   if (file_descriptor < 0) {
1619     // Can't open library, report dlerror() message
1620     return nullptr;
1621   }
1622 
1623   bool failed_to_read_elf_head=
1624     (sizeof(elf_head)!=
1625      (::read(file_descriptor, &elf_head,sizeof(elf_head))));
1626 
1627   ::close(file_descriptor);
1628   if (failed_to_read_elf_head) {
1629     // file i/o error - report dlerror() msg
1630     return nullptr;
1631   }
1632 
1633   if (elf_head.e_ident[EI_DATA] != LITTLE_ENDIAN_ONLY(ELFDATA2LSB) BIG_ENDIAN_ONLY(ELFDATA2MSB)) {
1634     // handle invalid/out of range endianness values
1635     if (elf_head.e_ident[EI_DATA] == 0 || elf_head.e_ident[EI_DATA] > 2) {
1636       return nullptr;
1637     }
1638 
1639 #if defined(VM_LITTLE_ENDIAN)
1640     // VM is LE, shared object BE
1641     elf_head.e_machine = be16toh(elf_head.e_machine);
1642 #else
1643     // VM is BE, shared object LE
1644     elf_head.e_machine = le16toh(elf_head.e_machine);
1645 #endif
1646   }
1647 
1648   typedef struct {
1649     Elf32_Half    code;         // Actual value as defined in elf.h
1650     Elf32_Half    compat_class; // Compatibility of archs at VM's sense
1651     unsigned char elf_class;    // 32 or 64 bit
1652     unsigned char endianness;   // MSB or LSB
1653     char*         name;         // String representation
1654   } arch_t;
1655 
1656 #ifndef EM_AARCH64
1657   #define EM_AARCH64    183               /* ARM AARCH64 */
1658 #endif
1659 #ifndef EM_RISCV
1660   #define EM_RISCV      243               /* RISC-V */
1661 #endif
1662 #ifndef EM_LOONGARCH
1663   #define EM_LOONGARCH  258               /* LoongArch */
1664 #endif
1665 
1666   static const arch_t arch_array[]={
1667     {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1668     {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1669     {EM_IA_64,       EM_IA_64,   ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
1670     {EM_X86_64,      EM_X86_64,  ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
1671     {EM_SPARC,       EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1672     {EM_SPARC32PLUS, EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1673     {EM_SPARCV9,     EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
1674     {EM_PPC,         EM_PPC,     ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
1675 #if defined(VM_LITTLE_ENDIAN)
1676     {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2LSB, (char*)"Power PC 64 LE"},
1677     {EM_SH,          EM_SH,      ELFCLASS32, ELFDATA2LSB, (char*)"SuperH"},
1678 #else
1679     {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1680     {EM_SH,          EM_SH,      ELFCLASS32, ELFDATA2MSB, (char*)"SuperH BE"},
1681 #endif
1682     {EM_ARM,         EM_ARM,     ELFCLASS32, ELFDATA2LSB, (char*)"ARM"},
1683     // we only support 64 bit z architecture
1684     {EM_S390,        EM_S390,    ELFCLASS64, ELFDATA2MSB, (char*)"IBM System/390"},
1685     {EM_ALPHA,       EM_ALPHA,   ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
1686     {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
1687     {EM_MIPS,        EM_MIPS,    ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
1688     {EM_PARISC,      EM_PARISC,  ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
1689     {EM_68K,         EM_68K,     ELFCLASS32, ELFDATA2MSB, (char*)"M68k"},
1690     {EM_AARCH64,     EM_AARCH64, ELFCLASS64, ELFDATA2LSB, (char*)"AARCH64"},
1691 #ifdef _LP64
1692     {EM_RISCV,       EM_RISCV,   ELFCLASS64, ELFDATA2LSB, (char*)"RISCV64"},
1693 #else
1694     {EM_RISCV,       EM_RISCV,   ELFCLASS32, ELFDATA2LSB, (char*)"RISCV32"},
1695 #endif
1696     {EM_LOONGARCH,   EM_LOONGARCH, ELFCLASS64, ELFDATA2LSB, (char*)"LoongArch"},
1697   };
1698 
1699 #if  (defined IA32)
1700   static  Elf32_Half running_arch_code=EM_386;
1701 #elif   (defined AMD64) || (defined X32)
1702   static  Elf32_Half running_arch_code=EM_X86_64;
1703 #elif  (defined IA64)
1704   static  Elf32_Half running_arch_code=EM_IA_64;
1705 #elif  (defined __sparc) && (defined _LP64)
1706   static  Elf32_Half running_arch_code=EM_SPARCV9;
1707 #elif  (defined __sparc) && (!defined _LP64)
1708   static  Elf32_Half running_arch_code=EM_SPARC;
1709 #elif  (defined __powerpc64__)
1710   static  Elf32_Half running_arch_code=EM_PPC64;
1711 #elif  (defined __powerpc__)
1712   static  Elf32_Half running_arch_code=EM_PPC;
1713 #elif  (defined AARCH64)
1714   static  Elf32_Half running_arch_code=EM_AARCH64;
1715 #elif  (defined ARM)
1716   static  Elf32_Half running_arch_code=EM_ARM;
1717 #elif  (defined S390)
1718   static  Elf32_Half running_arch_code=EM_S390;
1719 #elif  (defined ALPHA)
1720   static  Elf32_Half running_arch_code=EM_ALPHA;
1721 #elif  (defined MIPSEL)
1722   static  Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
1723 #elif  (defined PARISC)
1724   static  Elf32_Half running_arch_code=EM_PARISC;
1725 #elif  (defined MIPS)
1726   static  Elf32_Half running_arch_code=EM_MIPS;
1727 #elif  (defined M68K)
1728   static  Elf32_Half running_arch_code=EM_68K;
1729 #elif  (defined SH)
1730   static  Elf32_Half running_arch_code=EM_SH;
1731 #elif  (defined RISCV)
1732   static  Elf32_Half running_arch_code=EM_RISCV;
1733 #elif  (defined LOONGARCH64)
1734   static  Elf32_Half running_arch_code=EM_LOONGARCH;
1735 #else
1736     #error Method os::dll_load requires that one of following is defined:\
1737         AARCH64, ALPHA, ARM, AMD64, IA32, IA64, LOONGARCH64, M68K, MIPS, MIPSEL, PARISC, __powerpc__, __powerpc64__, RISCV, S390, SH, __sparc
1738 #endif
1739 
1740   // Identify compatibility class for VM's architecture and library's architecture
1741   // Obtain string descriptions for architectures
1742 
1743   arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], nullptr};
1744   int running_arch_index=-1;
1745 
1746   for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) {
1747     if (running_arch_code == arch_array[i].code) {
1748       running_arch_index    = i;
1749     }
1750     if (lib_arch.code == arch_array[i].code) {
1751       lib_arch.compat_class = arch_array[i].compat_class;
1752       lib_arch.name         = arch_array[i].name;
1753     }
1754   }
1755 
1756   assert(running_arch_index != -1,
1757          "Didn't find running architecture code (running_arch_code) in arch_array");
1758   if (running_arch_index == -1) {
1759     // Even though running architecture detection failed
1760     // we may still continue with reporting dlerror() message
1761     return nullptr;
1762   }
1763 
1764   if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
1765     if (lib_arch.name != nullptr) {
1766       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1767                  " (Possible cause: can't load %s .so on a %s platform)",
1768                  lib_arch.name, arch_array[running_arch_index].name);
1769     } else {
1770       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1771                  " (Possible cause: can't load this .so (machine code=0x%x) on a %s platform)",
1772                  lib_arch.code, arch_array[running_arch_index].name);
1773     }
1774     return nullptr;
1775   }
1776 
1777   if (lib_arch.endianness != arch_array[running_arch_index].endianness) {
1778     ::snprintf(diag_msg_buf, diag_msg_max_length-1, " (Possible cause: endianness mismatch)");
1779     return nullptr;
1780   }
1781 
1782   // ELF file class/capacity : 0 - invalid, 1 - 32bit, 2 - 64bit
1783   if (lib_arch.elf_class > 2 || lib_arch.elf_class < 1) {
1784     ::snprintf(diag_msg_buf, diag_msg_max_length-1, " (Possible cause: invalid ELF file class)");
1785     return nullptr;
1786   }
1787 
1788   if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
1789     ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1790                " (Possible cause: architecture word width mismatch, can't load %d-bit .so on a %d-bit platform)",
1791                (int) lib_arch.elf_class * 32, arch_array[running_arch_index].elf_class * 32);
1792     return nullptr;
1793   }
1794 
1795   return nullptr;
1796 }
1797 
1798 void * os::Linux::dlopen_helper(const char *filename, char *ebuf,
1799                                 int ebuflen) {
1800   void * result = ::dlopen(filename, RTLD_LAZY);
1801   if (result == nullptr) {
1802     const char* error_report = ::dlerror();
1803     if (error_report == nullptr) {
1804       error_report = "dlerror returned no error description";
1805     }
1806     if (ebuf != nullptr && ebuflen > 0) {
1807       ::strncpy(ebuf, error_report, ebuflen-1);
1808       ebuf[ebuflen-1]='\0';
1809     }
1810     Events::log_dll_message(nullptr, "Loading shared library %s failed, %s", filename, error_report);
1811     log_info(os)("shared library load of %s failed, %s", filename, error_report);
1812   } else {
1813     Events::log_dll_message(nullptr, "Loaded shared library %s", filename);
1814     log_info(os)("shared library load of %s was successful", filename);
1815   }
1816   return result;
1817 }
1818 
1819 void * os::Linux::dll_load_in_vmthread(const char *filename, char *ebuf,
1820                                        int ebuflen) {
1821   void * result = nullptr;
1822   if (LoadExecStackDllInVMThread) {
1823     result = dlopen_helper(filename, ebuf, ebuflen);
1824   }
1825 
1826   // Since 7019808, libjvm.so is linked with -noexecstack. If the VM loads a
1827   // library that requires an executable stack, or which does not have this
1828   // stack attribute set, dlopen changes the stack attribute to executable. The
1829   // read protection of the guard pages gets lost.
1830   //
1831   // Need to check _stack_is_executable again as multiple VM_LinuxDllLoad
1832   // may have been queued at the same time.
1833 
1834   if (!_stack_is_executable) {
1835     for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
1836       StackOverflow* overflow_state = jt->stack_overflow_state();
1837       if (!overflow_state->stack_guard_zone_unused() &&     // Stack not yet fully initialized
1838           overflow_state->stack_guards_enabled()) {         // No pending stack overflow exceptions
1839         if (!os::guard_memory((char *)jt->stack_end(), StackOverflow::stack_guard_zone_size())) {
1840           warning("Attempt to reguard stack yellow zone failed.");
1841         }
1842       }
1843     }
1844   }
1845 
1846   return result;
1847 }
1848 
1849 const char* os::Linux::dll_path(void* lib) {
1850   struct link_map *lmap;
1851   const char* l_path = nullptr;
1852   assert(lib != nullptr, "dll_path parameter must not be null");
1853 
1854   int res_dli = ::dlinfo(lib, RTLD_DI_LINKMAP, &lmap);
1855   if (res_dli == 0) {
1856     l_path = lmap->l_name;
1857   }
1858   return l_path;
1859 }
1860 
1861 static unsigned count_newlines(const char* s) {
1862   unsigned n = 0;
1863   for (const char* s2 = strchr(s, '\n');
1864        s2 != nullptr; s2 = strchr(s2 + 1, '\n')) {
1865     n++;
1866   }
1867   return n;
1868 }
1869 
1870 static bool _print_ascii_file(const char* filename, outputStream* st, unsigned* num_lines = nullptr, const char* hdr = nullptr) {
1871   int fd = ::open(filename, O_RDONLY);
1872   if (fd == -1) {
1873     return false;
1874   }
1875 
1876   if (hdr != nullptr) {
1877     st->print_cr("%s", hdr);
1878   }
1879 
1880   char buf[33];
1881   int bytes;
1882   buf[32] = '\0';
1883   unsigned lines = 0;
1884   while ((bytes = ::read(fd, buf, sizeof(buf)-1)) > 0) {
1885     st->print_raw(buf, bytes);
1886     // count newlines
1887     if (num_lines != nullptr) {
1888       lines += count_newlines(buf);
1889     }
1890   }
1891 
1892   if (num_lines != nullptr) {
1893     (*num_lines) = lines;
1894   }
1895 
1896   ::close(fd);
1897 
1898   return true;
1899 }
1900 
1901 static void _print_ascii_file_h(const char* header, const char* filename, outputStream* st, bool same_line = true) {
1902   st->print("%s:%c", header, same_line ? ' ' : '\n');
1903   if (!_print_ascii_file(filename, st)) {
1904     st->print_cr("<Not Available>");
1905   }
1906 }
1907 
1908 void os::print_dll_info(outputStream *st) {
1909   st->print_cr("Dynamic libraries:");
1910 
1911   char fname[32];
1912   pid_t pid = os::Linux::gettid();
1913 
1914   jio_snprintf(fname, sizeof(fname), "/proc/%d/maps", pid);
1915   unsigned num = 0;
1916   if (!_print_ascii_file(fname, st, &num)) {
1917     st->print_cr("Can not get library information for pid = %d", pid);
1918   } else {
1919     st->print_cr("Total number of mappings: %u", num);
1920   }
1921 }
1922 
1923 struct loaded_modules_info_param {
1924   os::LoadedModulesCallbackFunc callback;
1925   void *param;
1926 };
1927 
1928 static int dl_iterate_callback(struct dl_phdr_info *info, size_t size, void *data) {
1929   if ((info->dlpi_name == nullptr) || (*info->dlpi_name == '\0')) {
1930     return 0;
1931   }
1932 
1933   struct loaded_modules_info_param *callback_param = reinterpret_cast<struct loaded_modules_info_param *>(data);
1934   address base = nullptr;
1935   address top = nullptr;
1936   for (int idx = 0; idx < info->dlpi_phnum; idx++) {
1937     const ElfW(Phdr) *phdr = info->dlpi_phdr + idx;
1938     if (phdr->p_type == PT_LOAD) {
1939       address raw_phdr_base = reinterpret_cast<address>(info->dlpi_addr + phdr->p_vaddr);
1940 
1941       address phdr_base = align_down(raw_phdr_base, phdr->p_align);
1942       if ((base == nullptr) || (base > phdr_base)) {
1943         base = phdr_base;
1944       }
1945 
1946       address phdr_top = align_up(raw_phdr_base + phdr->p_memsz, phdr->p_align);
1947       if ((top == nullptr) || (top < phdr_top)) {
1948         top = phdr_top;
1949       }
1950     }
1951   }
1952 
1953   return callback_param->callback(info->dlpi_name, base, top, callback_param->param);
1954 }
1955 
1956 int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *param) {
1957   struct loaded_modules_info_param callback_param = {callback, param};
1958   return dl_iterate_phdr(&dl_iterate_callback, &callback_param);
1959 }
1960 
1961 void os::print_os_info_brief(outputStream* st) {
1962   os::Linux::print_distro_info(st);
1963 
1964   os::Posix::print_uname_info(st);
1965 
1966   os::Linux::print_libversion_info(st);
1967 
1968 }
1969 
1970 void os::print_os_info(outputStream* st) {
1971   st->print_cr("OS:");
1972 
1973   os::Linux::print_distro_info(st);
1974 
1975   os::Posix::print_uname_info(st);
1976 
1977   os::Linux::print_uptime_info(st);
1978 
1979   // Print warning if unsafe chroot environment detected
1980   if (unsafe_chroot_detected) {
1981     st->print_cr("WARNING!! %s", unstable_chroot_error);
1982   }
1983 
1984   os::Linux::print_libversion_info(st);
1985 
1986   os::Posix::print_rlimit_info(st);
1987 
1988   os::Posix::print_load_average(st);
1989   st->cr();
1990 
1991   os::Linux::print_system_memory_info(st);
1992   st->cr();
1993 
1994   os::Linux::print_process_memory_info(st);
1995   st->cr();
1996 
1997   os::Linux::print_proc_sys_info(st);
1998   st->cr();
1999 
2000   if (os::Linux::print_ld_preload_file(st)) {
2001     st->cr();
2002   }
2003 
2004   if (os::Linux::print_container_info(st)) {
2005     st->cr();
2006   }
2007 
2008   VM_Version::print_platform_virtualization_info(st);
2009 
2010   os::Linux::print_steal_info(st);
2011 }
2012 
2013 // Try to identify popular distros.
2014 // Most Linux distributions have a /etc/XXX-release file, which contains
2015 // the OS version string. Newer Linux distributions have a /etc/lsb-release
2016 // file that also contains the OS version string. Some have more than one
2017 // /etc/XXX-release file (e.g. Mandrake has both /etc/mandrake-release and
2018 // /etc/redhat-release.), so the order is important.
2019 // Any Linux that is based on Redhat (i.e. Oracle, Mandrake, Sun JDS...) have
2020 // their own specific XXX-release file as well as a redhat-release file.
2021 // Because of this the XXX-release file needs to be searched for before the
2022 // redhat-release file.
2023 // Since Red Hat and SuSE have an lsb-release file that is not very descriptive the
2024 // search for redhat-release / SuSE-release needs to be before lsb-release.
2025 // Since the lsb-release file is the new standard it needs to be searched
2026 // before the older style release files.
2027 // Searching system-release (Red Hat) and os-release (other Linuxes) are a
2028 // next to last resort.  The os-release file is a new standard that contains
2029 // distribution information and the system-release file seems to be an old
2030 // standard that has been replaced by the lsb-release and os-release files.
2031 // Searching for the debian_version file is the last resort.  It contains
2032 // an informative string like "6.0.6" or "wheezy/sid". Because of this
2033 // "Debian " is printed before the contents of the debian_version file.
2034 
2035 const char* distro_files[] = {
2036   "/etc/oracle-release",
2037   "/etc/mandriva-release",
2038   "/etc/mandrake-release",
2039   "/etc/sun-release",
2040   "/etc/redhat-release",
2041   "/etc/lsb-release",
2042   "/etc/turbolinux-release",
2043   "/etc/gentoo-release",
2044   "/etc/ltib-release",
2045   "/etc/angstrom-version",
2046   "/etc/system-release",
2047   "/etc/os-release",
2048   "/etc/SuSE-release", // Deprecated in favor of os-release since SuSE 12
2049   nullptr };
2050 
2051 void os::Linux::print_distro_info(outputStream* st) {
2052   for (int i = 0;; i++) {
2053     const char* file = distro_files[i];
2054     if (file == nullptr) {
2055       break;  // done
2056     }
2057     // If file prints, we found it.
2058     if (_print_ascii_file(file, st)) {
2059       return;
2060     }
2061   }
2062 
2063   if (file_exists("/etc/debian_version")) {
2064     st->print("Debian ");
2065     _print_ascii_file("/etc/debian_version", st);
2066   } else {
2067     st->print_cr("Linux");
2068   }
2069 }
2070 
2071 static void parse_os_info_helper(FILE* fp, char* distro, size_t length, bool get_first_line) {
2072   char buf[256];
2073   while (fgets(buf, sizeof(buf), fp)) {
2074     // Edit out extra stuff in expected format
2075     if (strstr(buf, "DISTRIB_DESCRIPTION=") != nullptr || strstr(buf, "PRETTY_NAME=") != nullptr) {
2076       char* ptr = strstr(buf, "\"");  // the name is in quotes
2077       if (ptr != nullptr) {
2078         ptr++; // go beyond first quote
2079         char* nl = strchr(ptr, '\"');
2080         if (nl != nullptr) *nl = '\0';
2081         strncpy(distro, ptr, length);
2082       } else {
2083         ptr = strstr(buf, "=");
2084         ptr++; // go beyond equals then
2085         char* nl = strchr(ptr, '\n');
2086         if (nl != nullptr) *nl = '\0';
2087         strncpy(distro, ptr, length);
2088       }
2089       return;
2090     } else if (get_first_line) {
2091       char* nl = strchr(buf, '\n');
2092       if (nl != nullptr) *nl = '\0';
2093       strncpy(distro, buf, length);
2094       return;
2095     }
2096   }
2097   // print last line and close
2098   char* nl = strchr(buf, '\n');
2099   if (nl != nullptr) *nl = '\0';
2100   strncpy(distro, buf, length);
2101 }
2102 
2103 static void parse_os_info(char* distro, size_t length, const char* file) {
2104   FILE* fp = os::fopen(file, "r");
2105   if (fp != nullptr) {
2106     // if suse format, print out first line
2107     bool get_first_line = (strcmp(file, "/etc/SuSE-release") == 0);
2108     parse_os_info_helper(fp, distro, length, get_first_line);
2109     fclose(fp);
2110   }
2111 }
2112 
2113 void os::get_summary_os_info(char* buf, size_t buflen) {
2114   for (int i = 0;; i++) {
2115     const char* file = distro_files[i];
2116     if (file == nullptr) {
2117       break; // ran out of distro_files
2118     }
2119     if (file_exists(file)) {
2120       parse_os_info(buf, buflen, file);
2121       return;
2122     }
2123   }
2124   // special case for debian
2125   if (file_exists("/etc/debian_version")) {
2126     strncpy(buf, "Debian ", buflen);
2127     if (buflen > 7) {
2128       parse_os_info(&buf[7], buflen-7, "/etc/debian_version");
2129     }
2130   } else {
2131     strncpy(buf, "Linux", buflen);
2132   }
2133 }
2134 
2135 void os::Linux::print_libversion_info(outputStream* st) {
2136   // libc, pthread
2137   st->print("libc: ");
2138   st->print("%s ", os::Linux::libc_version());
2139   st->print("%s ", os::Linux::libpthread_version());
2140   st->cr();
2141 }
2142 
2143 void os::Linux::print_proc_sys_info(outputStream* st) {
2144   _print_ascii_file_h("/proc/sys/kernel/threads-max (system-wide limit on the number of threads)",
2145                       "/proc/sys/kernel/threads-max", st);
2146   _print_ascii_file_h("/proc/sys/vm/max_map_count (maximum number of memory map areas a process may have)",
2147                       "/proc/sys/vm/max_map_count", st);
2148   _print_ascii_file_h("/proc/sys/kernel/pid_max (system-wide limit on number of process identifiers)",
2149                       "/proc/sys/kernel/pid_max", st);
2150 }
2151 
2152 void os::Linux::print_system_memory_info(outputStream* st) {
2153   _print_ascii_file_h("/proc/meminfo", "/proc/meminfo", st, false);
2154   st->cr();
2155 
2156   // some information regarding THPs; for details see
2157   // https://www.kernel.org/doc/Documentation/vm/transhuge.txt
2158   _print_ascii_file_h("/sys/kernel/mm/transparent_hugepage/enabled",
2159                       "/sys/kernel/mm/transparent_hugepage/enabled", st);
2160   _print_ascii_file_h("/sys/kernel/mm/transparent_hugepage/hpage_pmd_size",
2161                       "/sys/kernel/mm/transparent_hugepage/hpage_pmd_size", st);
2162   _print_ascii_file_h("/sys/kernel/mm/transparent_hugepage/defrag (defrag/compaction efforts parameter)",
2163                       "/sys/kernel/mm/transparent_hugepage/defrag", st);
2164 }
2165 
2166 bool os::Linux::query_process_memory_info(os::Linux::meminfo_t* info) {
2167   FILE* f = os::fopen("/proc/self/status", "r");
2168   const int num_values = sizeof(os::Linux::meminfo_t) / sizeof(size_t);
2169   int num_found = 0;
2170   char buf[256];
2171   info->vmsize = info->vmpeak = info->vmrss = info->vmhwm = info->vmswap =
2172       info->rssanon = info->rssfile = info->rssshmem = -1;
2173   if (f != nullptr) {
2174     while (::fgets(buf, sizeof(buf), f) != nullptr && num_found < num_values) {
2175       if ( (info->vmsize == -1    && sscanf(buf, "VmSize: " SSIZE_FORMAT " kB", &info->vmsize) == 1) ||
2176            (info->vmpeak == -1    && sscanf(buf, "VmPeak: " SSIZE_FORMAT " kB", &info->vmpeak) == 1) ||
2177            (info->vmswap == -1    && sscanf(buf, "VmSwap: " SSIZE_FORMAT " kB", &info->vmswap) == 1) ||
2178            (info->vmhwm == -1     && sscanf(buf, "VmHWM: " SSIZE_FORMAT " kB", &info->vmhwm) == 1) ||
2179            (info->vmrss == -1     && sscanf(buf, "VmRSS: " SSIZE_FORMAT " kB", &info->vmrss) == 1) ||
2180            (info->rssanon == -1   && sscanf(buf, "RssAnon: " SSIZE_FORMAT " kB", &info->rssanon) == 1) || // Needs Linux 4.5
2181            (info->rssfile == -1   && sscanf(buf, "RssFile: " SSIZE_FORMAT " kB", &info->rssfile) == 1) || // Needs Linux 4.5
2182            (info->rssshmem == -1  && sscanf(buf, "RssShmem: " SSIZE_FORMAT " kB", &info->rssshmem) == 1)  // Needs Linux 4.5
2183            )
2184       {
2185         num_found ++;
2186       }
2187     }
2188     fclose(f);
2189     return true;
2190   }
2191   return false;
2192 }
2193 
2194 #ifdef __GLIBC__
2195 // For Glibc, print a one-liner with the malloc tunables.
2196 // Most important and popular is MALLOC_ARENA_MAX, but we are
2197 // thorough and print them all.
2198 static void print_glibc_malloc_tunables(outputStream* st) {
2199   static const char* var[] = {
2200       // the new variant
2201       "GLIBC_TUNABLES",
2202       // legacy variants
2203       "MALLOC_CHECK_", "MALLOC_TOP_PAD_", "MALLOC_PERTURB_",
2204       "MALLOC_MMAP_THRESHOLD_", "MALLOC_TRIM_THRESHOLD_",
2205       "MALLOC_MMAP_MAX_", "MALLOC_ARENA_TEST", "MALLOC_ARENA_MAX",
2206       nullptr};
2207   st->print("glibc malloc tunables: ");
2208   bool printed = false;
2209   for (int i = 0; var[i] != nullptr; i ++) {
2210     const char* const val = ::getenv(var[i]);
2211     if (val != nullptr) {
2212       st->print("%s%s=%s", (printed ? ", " : ""), var[i], val);
2213       printed = true;
2214     }
2215   }
2216   if (!printed) {
2217     st->print("(default)");
2218   }
2219 }
2220 #endif // __GLIBC__
2221 
2222 void os::Linux::print_process_memory_info(outputStream* st) {
2223 
2224   st->print_cr("Process Memory:");
2225 
2226   // Print virtual and resident set size; peak values; swap; and for
2227   //  rss its components if the kernel is recent enough.
2228   meminfo_t info;
2229   if (query_process_memory_info(&info)) {
2230     st->print_cr("Virtual Size: " SSIZE_FORMAT "K (peak: " SSIZE_FORMAT "K)", info.vmsize, info.vmpeak);
2231     st->print("Resident Set Size: " SSIZE_FORMAT "K (peak: " SSIZE_FORMAT "K)", info.vmrss, info.vmhwm);
2232     if (info.rssanon != -1) { // requires kernel >= 4.5
2233       st->print(" (anon: " SSIZE_FORMAT "K, file: " SSIZE_FORMAT "K, shmem: " SSIZE_FORMAT "K)",
2234                 info.rssanon, info.rssfile, info.rssshmem);
2235     }
2236     st->cr();
2237     if (info.vmswap != -1) { // requires kernel >= 2.6.34
2238       st->print_cr("Swapped out: " SSIZE_FORMAT "K", info.vmswap);
2239     }
2240   } else {
2241     st->print_cr("Could not open /proc/self/status to get process memory related information");
2242   }
2243 
2244   // glibc only:
2245   // - Print outstanding allocations using mallinfo
2246   // - Print glibc tunables
2247 #ifdef __GLIBC__
2248   size_t total_allocated = 0;
2249   size_t free_retained = 0;
2250   bool might_have_wrapped = false;
2251   glibc_mallinfo mi;
2252   os::Linux::get_mallinfo(&mi, &might_have_wrapped);
2253   total_allocated = mi.uordblks + mi.hblkhd;
2254   free_retained = mi.fordblks;
2255 #ifdef _LP64
2256   // If legacy mallinfo(), we can still print the values if we are sure they cannot have wrapped.
2257   might_have_wrapped = might_have_wrapped && (info.vmsize * K) > UINT_MAX;
2258 #endif
2259   st->print_cr("C-Heap outstanding allocations: " SIZE_FORMAT "K, retained: " SIZE_FORMAT "K%s",
2260                total_allocated / K, free_retained / K,
2261                might_have_wrapped ? " (may have wrapped)" : "");
2262   // Tunables
2263   print_glibc_malloc_tunables(st);
2264   st->cr();
2265 #endif
2266 }
2267 
2268 bool os::Linux::print_ld_preload_file(outputStream* st) {
2269   return _print_ascii_file("/etc/ld.so.preload", st, nullptr, "/etc/ld.so.preload:");
2270 }
2271 
2272 void os::Linux::print_uptime_info(outputStream* st) {
2273   struct sysinfo sinfo;
2274   int ret = sysinfo(&sinfo);
2275   if (ret == 0) {
2276     os::print_dhm(st, "OS uptime:", (long) sinfo.uptime);
2277   }
2278 }
2279 
2280 bool os::Linux::print_container_info(outputStream* st) {
2281   if (!OSContainer::is_containerized()) {
2282     st->print_cr("container information not found.");
2283     return false;
2284   }
2285 
2286   st->print_cr("container (cgroup) information:");
2287 
2288   const char *p_ct = OSContainer::container_type();
2289   st->print_cr("container_type: %s", p_ct != nullptr ? p_ct : "not supported");
2290 
2291   char *p = OSContainer::cpu_cpuset_cpus();
2292   st->print_cr("cpu_cpuset_cpus: %s", p != nullptr ? p : "not supported");
2293   free(p);
2294 
2295   p = OSContainer::cpu_cpuset_memory_nodes();
2296   st->print_cr("cpu_memory_nodes: %s", p != nullptr ? p : "not supported");
2297   free(p);
2298 
2299   int i = OSContainer::active_processor_count();
2300   st->print("active_processor_count: ");
2301   if (i > 0) {
2302     if (ActiveProcessorCount > 0) {
2303       st->print_cr("%d, but overridden by -XX:ActiveProcessorCount %d", i, ActiveProcessorCount);
2304     } else {
2305       st->print_cr("%d", i);
2306     }
2307   } else {
2308     st->print_cr("not supported");
2309   }
2310 
2311   i = OSContainer::cpu_quota();
2312   st->print("cpu_quota: ");
2313   if (i > 0) {
2314     st->print_cr("%d", i);
2315   } else {
2316     st->print_cr("%s", i == OSCONTAINER_ERROR ? "not supported" : "no quota");
2317   }
2318 
2319   i = OSContainer::cpu_period();
2320   st->print("cpu_period: ");
2321   if (i > 0) {
2322     st->print_cr("%d", i);
2323   } else {
2324     st->print_cr("%s", i == OSCONTAINER_ERROR ? "not supported" : "no period");
2325   }
2326 
2327   i = OSContainer::cpu_shares();
2328   st->print("cpu_shares: ");
2329   if (i > 0) {
2330     st->print_cr("%d", i);
2331   } else {
2332     st->print_cr("%s", i == OSCONTAINER_ERROR ? "not supported" : "no shares");
2333   }
2334 
2335   OSContainer::print_container_helper(st, OSContainer::memory_limit_in_bytes(), "memory_limit_in_bytes");
2336   OSContainer::print_container_helper(st, OSContainer::memory_and_swap_limit_in_bytes(), "memory_and_swap_limit_in_bytes");
2337   OSContainer::print_container_helper(st, OSContainer::memory_soft_limit_in_bytes(), "memory_soft_limit_in_bytes");
2338   OSContainer::print_container_helper(st, OSContainer::memory_usage_in_bytes(), "memory_usage_in_bytes");
2339   OSContainer::print_container_helper(st, OSContainer::memory_max_usage_in_bytes(), "memory_max_usage_in_bytes");
2340 
2341   OSContainer::print_version_specific_info(st);
2342 
2343   jlong j = OSContainer::pids_max();
2344   st->print("maximum number of tasks: ");
2345   if (j > 0) {
2346     st->print_cr(JLONG_FORMAT, j);
2347   } else {
2348     st->print_cr("%s", j == OSCONTAINER_ERROR ? "not supported" : "unlimited");
2349   }
2350 
2351   j = OSContainer::pids_current();
2352   st->print("current number of tasks: ");
2353   if (j > 0) {
2354     st->print_cr(JLONG_FORMAT, j);
2355   } else {
2356     if (j == OSCONTAINER_ERROR) {
2357       st->print_cr("not supported");
2358     }
2359   }
2360 
2361   return true;
2362 }
2363 
2364 void os::Linux::print_steal_info(outputStream* st) {
2365   if (has_initial_tick_info) {
2366     CPUPerfTicks pticks;
2367     bool res = os::Linux::get_tick_information(&pticks, -1);
2368 
2369     if (res && pticks.has_steal_ticks) {
2370       uint64_t steal_ticks_difference = pticks.steal - initial_steal_ticks;
2371       uint64_t total_ticks_difference = pticks.total - initial_total_ticks;
2372       double steal_ticks_perc = 0.0;
2373       if (total_ticks_difference != 0) {
2374         steal_ticks_perc = (double) steal_ticks_difference / total_ticks_difference;
2375       }
2376       st->print_cr("Steal ticks since vm start: " UINT64_FORMAT, steal_ticks_difference);
2377       st->print_cr("Steal ticks percentage since vm start:%7.3f", steal_ticks_perc);
2378     }
2379   }
2380 }
2381 
2382 void os::print_memory_info(outputStream* st) {
2383 
2384   st->print("Memory:");
2385   st->print(" " SIZE_FORMAT "k page", os::vm_page_size()>>10);
2386 
2387   // values in struct sysinfo are "unsigned long"
2388   struct sysinfo si;
2389   sysinfo(&si);
2390 
2391   st->print(", physical " UINT64_FORMAT "k",
2392             os::physical_memory() >> 10);
2393   st->print("(" UINT64_FORMAT "k free)",
2394             os::available_memory() >> 10);
2395   st->print(", swap " UINT64_FORMAT "k",
2396             ((jlong)si.totalswap * si.mem_unit) >> 10);
2397   st->print("(" UINT64_FORMAT "k free)",
2398             ((jlong)si.freeswap * si.mem_unit) >> 10);
2399   st->cr();
2400   st->print("Page Sizes: ");
2401   _page_sizes.print_on(st);
2402   st->cr();
2403 }
2404 
2405 // Print the first "model name" line and the first "flags" line
2406 // that we find and nothing more. We assume "model name" comes
2407 // before "flags" so if we find a second "model name", then the
2408 // "flags" field is considered missing.
2409 static bool print_model_name_and_flags(outputStream* st, char* buf, size_t buflen) {
2410 #if defined(IA32) || defined(AMD64)
2411   // Other platforms have less repetitive cpuinfo files
2412   FILE *fp = os::fopen("/proc/cpuinfo", "r");
2413   if (fp) {
2414     bool model_name_printed = false;
2415     while (!feof(fp)) {
2416       if (fgets(buf, buflen, fp)) {
2417         // Assume model name comes before flags
2418         if (strstr(buf, "model name") != nullptr) {
2419           if (!model_name_printed) {
2420             st->print_raw("CPU Model and flags from /proc/cpuinfo:\n");
2421             st->print_raw(buf);
2422             model_name_printed = true;
2423           } else {
2424             // model name printed but not flags?  Odd, just return
2425             fclose(fp);
2426             return true;
2427           }
2428         }
2429         // print the flags line too
2430         if (strstr(buf, "flags") != nullptr) {
2431           st->print_raw(buf);
2432           fclose(fp);
2433           return true;
2434         }
2435       }
2436     }
2437     fclose(fp);
2438   }
2439 #endif // x86 platforms
2440   return false;
2441 }
2442 
2443 // additional information about CPU e.g. available frequency ranges
2444 static void print_sys_devices_cpu_info(outputStream* st) {
2445   _print_ascii_file_h("Online cpus", "/sys/devices/system/cpu/online", st);
2446   _print_ascii_file_h("Offline cpus", "/sys/devices/system/cpu/offline", st);
2447 
2448   if (ExtensiveErrorReports) {
2449     // cache related info (cpu 0, should be similar for other CPUs)
2450     for (unsigned int i=0; i < 10; i++) { // handle max. 10 cache entries
2451       char hbuf_level[60];
2452       char hbuf_type[60];
2453       char hbuf_size[60];
2454       char hbuf_coherency_line_size[80];
2455       snprintf(hbuf_level, 60, "/sys/devices/system/cpu/cpu0/cache/index%u/level", i);
2456       snprintf(hbuf_type, 60, "/sys/devices/system/cpu/cpu0/cache/index%u/type", i);
2457       snprintf(hbuf_size, 60, "/sys/devices/system/cpu/cpu0/cache/index%u/size", i);
2458       snprintf(hbuf_coherency_line_size, 80, "/sys/devices/system/cpu/cpu0/cache/index%u/coherency_line_size", i);
2459       if (os::file_exists(hbuf_level)) {
2460         _print_ascii_file_h("cache level", hbuf_level, st);
2461         _print_ascii_file_h("cache type", hbuf_type, st);
2462         _print_ascii_file_h("cache size", hbuf_size, st);
2463         _print_ascii_file_h("cache coherency line size", hbuf_coherency_line_size, st);
2464       }
2465     }
2466   }
2467 
2468   // we miss the cpufreq entries on Power and s390x
2469 #if defined(IA32) || defined(AMD64)
2470   _print_ascii_file_h("BIOS frequency limitation", "/sys/devices/system/cpu/cpu0/cpufreq/bios_limit", st);
2471   _print_ascii_file_h("Frequency switch latency (ns)", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_transition_latency", st);
2472   _print_ascii_file_h("Available cpu frequencies", "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies", st);
2473   // min and max should be in the Available range but still print them (not all info might be available for all kernels)
2474   if (ExtensiveErrorReports) {
2475     _print_ascii_file_h("Maximum cpu frequency", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", st);
2476     _print_ascii_file_h("Minimum cpu frequency", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq", st);
2477     _print_ascii_file_h("Current cpu frequency", "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq", st);
2478   }
2479   // governors are power schemes, see https://wiki.archlinux.org/index.php/CPU_frequency_scaling
2480   if (ExtensiveErrorReports) {
2481     _print_ascii_file_h("Available governors", "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors", st);
2482   }
2483   _print_ascii_file_h("Current governor", "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor", st);
2484   // Core performance boost, see https://www.kernel.org/doc/Documentation/cpu-freq/boost.txt
2485   // Raise operating frequency of some cores in a multi-core package if certain conditions apply, e.g.
2486   // whole chip is not fully utilized
2487   _print_ascii_file_h("Core performance/turbo boost", "/sys/devices/system/cpu/cpufreq/boost", st);
2488 #endif
2489 }
2490 
2491 void os::pd_print_cpu_info(outputStream* st, char* buf, size_t buflen) {
2492   // Only print the model name if the platform provides this as a summary
2493   if (!print_model_name_and_flags(st, buf, buflen)) {
2494     _print_ascii_file_h("/proc/cpuinfo", "/proc/cpuinfo", st, false);
2495   }
2496   st->cr();
2497   print_sys_devices_cpu_info(st);
2498 }
2499 
2500 #if INCLUDE_JFR
2501 
2502 void os::jfr_report_memory_info() {
2503   os::Linux::meminfo_t info;
2504   if (os::Linux::query_process_memory_info(&info)) {
2505     // Send the RSS JFR event
2506     EventResidentSetSize event;
2507     event.set_size(info.vmrss * K);
2508     event.set_peak(info.vmhwm * K);
2509     event.commit();
2510   } else {
2511     // Log a warning
2512     static bool first_warning = true;
2513     if (first_warning) {
2514       log_warning(jfr)("Error fetching RSS values: query_process_memory_info failed");
2515       first_warning = false;
2516     }
2517   }
2518 }
2519 
2520 #endif // INCLUDE_JFR
2521 
2522 #if defined(AMD64) || defined(IA32) || defined(X32)
2523 const char* search_string = "model name";
2524 #elif defined(M68K)
2525 const char* search_string = "CPU";
2526 #elif defined(PPC64)
2527 const char* search_string = "cpu";
2528 #elif defined(S390)
2529 const char* search_string = "machine =";
2530 #elif defined(SPARC)
2531 const char* search_string = "cpu";
2532 #else
2533 const char* search_string = "Processor";
2534 #endif
2535 
2536 // Parses the cpuinfo file for string representing the model name.
2537 void os::get_summary_cpu_info(char* cpuinfo, size_t length) {
2538   FILE* fp = os::fopen("/proc/cpuinfo", "r");
2539   if (fp != nullptr) {
2540     while (!feof(fp)) {
2541       char buf[256];
2542       if (fgets(buf, sizeof(buf), fp)) {
2543         char* start = strstr(buf, search_string);
2544         if (start != nullptr) {
2545           char *ptr = start + strlen(search_string);
2546           char *end = buf + strlen(buf);
2547           while (ptr != end) {
2548              // skip whitespace and colon for the rest of the name.
2549              if (*ptr != ' ' && *ptr != '\t' && *ptr != ':') {
2550                break;
2551              }
2552              ptr++;
2553           }
2554           if (ptr != end) {
2555             // reasonable string, get rid of newline and keep the rest
2556             char* nl = strchr(buf, '\n');
2557             if (nl != nullptr) *nl = '\0';
2558             strncpy(cpuinfo, ptr, length);
2559             fclose(fp);
2560             return;
2561           }
2562         }
2563       }
2564     }
2565     fclose(fp);
2566   }
2567   // cpuinfo not found or parsing failed, just print generic string.  The entire
2568   // /proc/cpuinfo file will be printed later in the file (or enough of it for x86)
2569 #if   defined(AARCH64)
2570   strncpy(cpuinfo, "AArch64", length);
2571 #elif defined(AMD64)
2572   strncpy(cpuinfo, "x86_64", length);
2573 #elif defined(ARM)  // Order wrt. AARCH64 is relevant!
2574   strncpy(cpuinfo, "ARM", length);
2575 #elif defined(IA32)
2576   strncpy(cpuinfo, "x86_32", length);
2577 #elif defined(IA64)
2578   strncpy(cpuinfo, "IA64", length);
2579 #elif defined(PPC)
2580   strncpy(cpuinfo, "PPC64", length);
2581 #elif defined(RISCV)
2582   strncpy(cpuinfo, LP64_ONLY("RISCV64") NOT_LP64("RISCV32"), length);
2583 #elif defined(S390)
2584   strncpy(cpuinfo, "S390", length);
2585 #elif defined(SPARC)
2586   strncpy(cpuinfo, "sparcv9", length);
2587 #elif defined(ZERO_LIBARCH)
2588   strncpy(cpuinfo, ZERO_LIBARCH, length);
2589 #else
2590   strncpy(cpuinfo, "unknown", length);
2591 #endif
2592 }
2593 
2594 static char saved_jvm_path[MAXPATHLEN] = {0};
2595 
2596 // Find the full path to the current module, libjvm.so
2597 void os::jvm_path(char *buf, jint buflen) {
2598   // Error checking.
2599   if (buflen < MAXPATHLEN) {
2600     assert(false, "must use a large-enough buffer");
2601     buf[0] = '\0';
2602     return;
2603   }
2604   // Lazy resolve the path to current module.
2605   if (saved_jvm_path[0] != 0) {
2606     strcpy(buf, saved_jvm_path);
2607     return;
2608   }
2609 
2610   char dli_fname[MAXPATHLEN];
2611   dli_fname[0] = '\0';
2612   bool ret = dll_address_to_library_name(
2613                                          CAST_FROM_FN_PTR(address, os::jvm_path),
2614                                          dli_fname, sizeof(dli_fname), nullptr);
2615   assert(ret, "cannot locate libjvm");
2616   char *rp = nullptr;
2617   if (ret && dli_fname[0] != '\0') {
2618     rp = os::Posix::realpath(dli_fname, buf, buflen);
2619   }
2620   if (rp == nullptr) {
2621     return;
2622   }
2623 
2624   if (Arguments::sun_java_launcher_is_altjvm()) {
2625     // Support for the java launcher's '-XXaltjvm=<path>' option. Typical
2626     // value for buf is "<JAVA_HOME>/jre/lib/<vmtype>/libjvm.so".
2627     // If "/jre/lib/" appears at the right place in the string, then
2628     // assume we are installed in a JDK and we're done. Otherwise, check
2629     // for a JAVA_HOME environment variable and fix up the path so it
2630     // looks like libjvm.so is installed there (append a fake suffix
2631     // hotspot/libjvm.so).
2632     const char *p = buf + strlen(buf) - 1;
2633     for (int count = 0; p > buf && count < 5; ++count) {
2634       for (--p; p > buf && *p != '/'; --p)
2635         /* empty */ ;
2636     }
2637 
2638     if (strncmp(p, "/jre/lib/", 9) != 0) {
2639       // Look for JAVA_HOME in the environment.
2640       char* java_home_var = ::getenv("JAVA_HOME");
2641       if (java_home_var != nullptr && java_home_var[0] != 0) {
2642         char* jrelib_p;
2643         int len;
2644 
2645         // Check the current module name "libjvm.so".
2646         p = strrchr(buf, '/');
2647         if (p == nullptr) {
2648           return;
2649         }
2650         assert(strstr(p, "/libjvm") == p, "invalid library name");
2651 
2652         rp = os::Posix::realpath(java_home_var, buf, buflen);
2653         if (rp == nullptr) {
2654           return;
2655         }
2656 
2657         // determine if this is a legacy image or modules image
2658         // modules image doesn't have "jre" subdirectory
2659         len = strlen(buf);
2660         assert(len < buflen, "Ran out of buffer room");
2661         jrelib_p = buf + len;
2662         snprintf(jrelib_p, buflen-len, "/jre/lib");
2663         if (0 != access(buf, F_OK)) {
2664           snprintf(jrelib_p, buflen-len, "/lib");
2665         }
2666 
2667         if (0 == access(buf, F_OK)) {
2668           // Use current module name "libjvm.so"
2669           len = strlen(buf);
2670           snprintf(buf + len, buflen-len, "/hotspot/libjvm.so");
2671         } else {
2672           // Go back to path of .so
2673           rp = os::Posix::realpath(dli_fname, buf, buflen);
2674           if (rp == nullptr) {
2675             return;
2676           }
2677         }
2678       }
2679     }
2680   }
2681 
2682   strncpy(saved_jvm_path, buf, MAXPATHLEN);
2683   saved_jvm_path[MAXPATHLEN - 1] = '\0';
2684 }
2685 
2686 ////////////////////////////////////////////////////////////////////////////////
2687 // Virtual Memory
2688 
2689 // Rationale behind this function:
2690 //  current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
2691 //  mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
2692 //  samples for JITted code. Here we create private executable mapping over the code cache
2693 //  and then we can use standard (well, almost, as mapping can change) way to provide
2694 //  info for the reporting script by storing timestamp and location of symbol
2695 void linux_wrap_code(char* base, size_t size) {
2696   static volatile jint cnt = 0;
2697 
2698   static_assert(sizeof(off_t) == 8, "Expected Large File Support in this file");
2699 
2700   if (!UseOprofile) {
2701     return;
2702   }
2703 
2704   char buf[PATH_MAX+1];
2705   int num = Atomic::add(&cnt, 1);
2706 
2707   snprintf(buf, sizeof(buf), "%s/hs-vm-%d-%d",
2708            os::get_temp_directory(), os::current_process_id(), num);
2709   unlink(buf);
2710 
2711   int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
2712 
2713   if (fd != -1) {
2714     off_t rv = ::lseek(fd, size-2, SEEK_SET);
2715     if (rv != (off_t)-1) {
2716       if (::write(fd, "", 1) == 1) {
2717         mmap(base, size,
2718              PROT_READ|PROT_WRITE|PROT_EXEC,
2719              MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
2720       }
2721     }
2722     ::close(fd);
2723     unlink(buf);
2724   }
2725 }
2726 
2727 static bool recoverable_mmap_error(int err) {
2728   // See if the error is one we can let the caller handle. This
2729   // list of errno values comes from JBS-6843484. I can't find a
2730   // Linux man page that documents this specific set of errno
2731   // values so while this list currently matches Solaris, it may
2732   // change as we gain experience with this failure mode.
2733   switch (err) {
2734   case EBADF:
2735   case EINVAL:
2736   case ENOTSUP:
2737     // let the caller deal with these errors
2738     return true;
2739 
2740   default:
2741     // Any remaining errors on this OS can cause our reserved mapping
2742     // to be lost. That can cause confusion where different data
2743     // structures think they have the same memory mapped. The worst
2744     // scenario is if both the VM and a library think they have the
2745     // same memory mapped.
2746     return false;
2747   }
2748 }
2749 
2750 static void warn_fail_commit_memory(char* addr, size_t size, bool exec,
2751                                     int err) {
2752   warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2753           ", %d) failed; error='%s' (errno=%d)", p2i(addr), size, exec,
2754           os::strerror(err), err);
2755 }
2756 
2757 static void warn_fail_commit_memory(char* addr, size_t size,
2758                                     size_t alignment_hint, bool exec,
2759                                     int err) {
2760   warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2761           ", " SIZE_FORMAT ", %d) failed; error='%s' (errno=%d)", p2i(addr), size,
2762           alignment_hint, exec, os::strerror(err), err);
2763 }
2764 
2765 // NOTE: Linux kernel does not really reserve the pages for us.
2766 //       All it does is to check if there are enough free pages
2767 //       left at the time of mmap(). This could be a potential
2768 //       problem.
2769 int os::Linux::commit_memory_impl(char* addr, size_t size, bool exec) {
2770   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
2771   uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
2772                                      MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
2773   if (res != (uintptr_t) MAP_FAILED) {
2774     if (UseNUMAInterleaving) {
2775       numa_make_global(addr, size);
2776     }
2777     return 0;
2778   }
2779 
2780   int err = errno;  // save errno from mmap() call above
2781 
2782   if (!recoverable_mmap_error(err)) {
2783     warn_fail_commit_memory(addr, size, exec, err);
2784     vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "committing reserved memory.");
2785   }
2786 
2787   return err;
2788 }
2789 
2790 bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
2791   return os::Linux::commit_memory_impl(addr, size, exec) == 0;
2792 }
2793 
2794 void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
2795                                   const char* mesg) {
2796   assert(mesg != nullptr, "mesg must be specified");
2797   int err = os::Linux::commit_memory_impl(addr, size, exec);
2798   if (err != 0) {
2799     // the caller wants all commit errors to exit with the specified mesg:
2800     warn_fail_commit_memory(addr, size, exec, err);
2801     vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "%s", mesg);
2802   }
2803 }
2804 
2805 // Define MAP_HUGETLB here so we can build HotSpot on old systems.
2806 #ifndef MAP_HUGETLB
2807   #define MAP_HUGETLB 0x40000
2808 #endif
2809 
2810 // If mmap flags are set with MAP_HUGETLB and the system supports multiple
2811 // huge page sizes, flag bits [26:31] can be used to encode the log2 of the
2812 // desired huge page size. Otherwise, the system's default huge page size will be used.
2813 // See mmap(2) man page for more info (since Linux 3.8).
2814 // https://lwn.net/Articles/533499/
2815 #ifndef MAP_HUGE_SHIFT
2816   #define MAP_HUGE_SHIFT 26
2817 #endif
2818 
2819 // Define MADV_HUGEPAGE here so we can build HotSpot on old systems.
2820 #ifndef MADV_HUGEPAGE
2821   #define MADV_HUGEPAGE 14
2822 #endif
2823 
2824 int os::Linux::commit_memory_impl(char* addr, size_t size,
2825                                   size_t alignment_hint, bool exec) {
2826   int err = os::Linux::commit_memory_impl(addr, size, exec);
2827   if (err == 0) {
2828     realign_memory(addr, size, alignment_hint);
2829   }
2830   return err;
2831 }
2832 
2833 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
2834                           bool exec) {
2835   return os::Linux::commit_memory_impl(addr, size, alignment_hint, exec) == 0;
2836 }
2837 
2838 void os::pd_commit_memory_or_exit(char* addr, size_t size,
2839                                   size_t alignment_hint, bool exec,
2840                                   const char* mesg) {
2841   assert(mesg != nullptr, "mesg must be specified");
2842   int err = os::Linux::commit_memory_impl(addr, size, alignment_hint, exec);
2843   if (err != 0) {
2844     // the caller wants all commit errors to exit with the specified mesg:
2845     warn_fail_commit_memory(addr, size, alignment_hint, exec, err);
2846     vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "%s", mesg);
2847   }
2848 }
2849 
2850 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
2851   if (UseTransparentHugePages && alignment_hint > vm_page_size()) {
2852     // We don't check the return value: madvise(MADV_HUGEPAGE) may not
2853     // be supported or the memory may already be backed by huge pages.
2854     ::madvise(addr, bytes, MADV_HUGEPAGE);
2855   }
2856 }
2857 
2858 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
2859   // This method works by doing an mmap over an existing mmaping and effectively discarding
2860   // the existing pages. However it won't work for SHM-based large pages that cannot be
2861   // uncommitted at all. We don't do anything in this case to avoid creating a segment with
2862   // small pages on top of the SHM segment. This method always works for small pages, so we
2863   // allow that in any case.
2864   if (alignment_hint <= os::vm_page_size() || can_commit_large_page_memory()) {
2865     commit_memory(addr, bytes, alignment_hint, !ExecMem);
2866   }
2867 }
2868 
2869 void os::numa_make_global(char *addr, size_t bytes) {
2870   Linux::numa_interleave_memory(addr, bytes);
2871 }
2872 
2873 // Define for numa_set_bind_policy(int). Setting the argument to 0 will set the
2874 // bind policy to MPOL_PREFERRED for the current thread.
2875 #define USE_MPOL_PREFERRED 0
2876 
2877 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
2878   // To make NUMA and large pages more robust when both enabled, we need to ease
2879   // the requirements on where the memory should be allocated. MPOL_BIND is the
2880   // default policy and it will force memory to be allocated on the specified
2881   // node. Changing this to MPOL_PREFERRED will prefer to allocate the memory on
2882   // the specified node, but will not force it. Using this policy will prevent
2883   // getting SIGBUS when trying to allocate large pages on NUMA nodes with no
2884   // free large pages.
2885   Linux::numa_set_bind_policy(USE_MPOL_PREFERRED);
2886   Linux::numa_tonode_memory(addr, bytes, lgrp_hint);
2887 }
2888 
2889 bool os::numa_topology_changed() { return false; }
2890 
2891 size_t os::numa_get_groups_num() {
2892   // Return just the number of nodes in which it's possible to allocate memory
2893   // (in numa terminology, configured nodes).
2894   return Linux::numa_num_configured_nodes();
2895 }
2896 
2897 int os::numa_get_group_id() {
2898   int cpu_id = Linux::sched_getcpu();
2899   if (cpu_id != -1) {
2900     int lgrp_id = Linux::get_node_by_cpu(cpu_id);
2901     if (lgrp_id != -1) {
2902       return lgrp_id;
2903     }
2904   }
2905   return 0;
2906 }
2907 
2908 int os::numa_get_group_id_for_address(const void* address) {
2909   void** pages = const_cast<void**>(&address);
2910   int id = -1;
2911 
2912   if (os::Linux::numa_move_pages(0, 1, pages, nullptr, &id, 0) == -1) {
2913     return -1;
2914   }
2915   if (id < 0) {
2916     return -1;
2917   }
2918   return id;
2919 }
2920 
2921 bool os::numa_get_group_ids_for_range(const void** addresses, int* lgrp_ids, size_t count) {
2922   void** pages = const_cast<void**>(addresses);
2923   return os::Linux::numa_move_pages(0, count, pages, nullptr, lgrp_ids, 0) == 0;
2924 }
2925 
2926 int os::Linux::get_existing_num_nodes() {
2927   int node;
2928   int highest_node_number = Linux::numa_max_node();
2929   int num_nodes = 0;
2930 
2931   // Get the total number of nodes in the system including nodes without memory.
2932   for (node = 0; node <= highest_node_number; node++) {
2933     if (is_node_in_existing_nodes(node)) {
2934       num_nodes++;
2935     }
2936   }
2937   return num_nodes;
2938 }
2939 
2940 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
2941   int highest_node_number = Linux::numa_max_node();
2942   size_t i = 0;
2943 
2944   // Map all node ids in which it is possible to allocate memory. Also nodes are
2945   // not always consecutively available, i.e. available from 0 to the highest
2946   // node number. If the nodes have been bound explicitly using numactl membind,
2947   // then allocate memory from those nodes only.
2948   for (int node = 0; node <= highest_node_number; node++) {
2949     if (Linux::is_node_in_bound_nodes((unsigned int)node)) {
2950       ids[i++] = node;
2951     }
2952   }
2953   return i;
2954 }
2955 
2956 char *os::scan_pages(char *start, char* end, page_info* page_expected,
2957                      page_info* page_found) {
2958   return end;
2959 }
2960 
2961 
2962 int os::Linux::sched_getcpu_syscall(void) {
2963   unsigned int cpu = 0;
2964   int retval = -1;
2965 
2966 #if defined(IA32)
2967   #ifndef SYS_getcpu
2968     #define SYS_getcpu 318
2969   #endif
2970   retval = syscall(SYS_getcpu, &cpu, nullptr, nullptr);
2971 #elif defined(AMD64)
2972 // Unfortunately we have to bring all these macros here from vsyscall.h
2973 // to be able to compile on old linuxes.
2974   #define __NR_vgetcpu 2
2975   #define VSYSCALL_START (-10UL << 20)
2976   #define VSYSCALL_SIZE 1024
2977   #define VSYSCALL_ADDR(vsyscall_nr) (VSYSCALL_START+VSYSCALL_SIZE*(vsyscall_nr))
2978   typedef long (*vgetcpu_t)(unsigned int *cpu, unsigned int *node, unsigned long *tcache);
2979   vgetcpu_t vgetcpu = (vgetcpu_t)VSYSCALL_ADDR(__NR_vgetcpu);
2980   retval = vgetcpu(&cpu, nullptr, nullptr);
2981 #endif
2982 
2983   return (retval == -1) ? retval : cpu;
2984 }
2985 
2986 void os::Linux::sched_getcpu_init() {
2987   // sched_getcpu() should be in libc.
2988   set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t,
2989                                   dlsym(RTLD_DEFAULT, "sched_getcpu")));
2990 
2991   // If it's not, try a direct syscall.
2992   if (sched_getcpu() == -1) {
2993     set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t,
2994                                     (void*)&sched_getcpu_syscall));
2995   }
2996 
2997   if (sched_getcpu() == -1) {
2998     vm_exit_during_initialization("getcpu(2) system call not supported by kernel");
2999   }
3000 }
3001 
3002 // Something to do with the numa-aware allocator needs these symbols
3003 extern "C" JNIEXPORT void numa_warn(int number, char *where, ...) { }
3004 extern "C" JNIEXPORT void numa_error(char *where) { }
3005 
3006 // Handle request to load libnuma symbol version 1.1 (API v1). If it fails
3007 // load symbol from base version instead.
3008 void* os::Linux::libnuma_dlsym(void* handle, const char *name) {
3009   void *f = dlvsym(handle, name, "libnuma_1.1");
3010   if (f == nullptr) {
3011     f = dlsym(handle, name);
3012   }
3013   return f;
3014 }
3015 
3016 // Handle request to load libnuma symbol version 1.2 (API v2) only.
3017 // Return null if the symbol is not defined in this particular version.
3018 void* os::Linux::libnuma_v2_dlsym(void* handle, const char* name) {
3019   return dlvsym(handle, name, "libnuma_1.2");
3020 }
3021 
3022 // Check numa dependent syscalls
3023 static bool numa_syscall_check() {
3024   // NUMA APIs depend on several syscalls. E.g., get_mempolicy is required for numa_get_membind and
3025   // numa_get_interleave_mask. But these dependent syscalls can be unsupported for various reasons.
3026   // Especially in dockers, get_mempolicy is not allowed with the default configuration. So it's necessary
3027   // to check whether the syscalls are available. Currently, only get_mempolicy is checked since checking
3028   // others like mbind would cause unexpected side effects.
3029 #ifdef SYS_get_mempolicy
3030   int dummy = 0;
3031   if (syscall(SYS_get_mempolicy, &dummy, nullptr, 0, (void*)&dummy, 3) == -1) {
3032     return false;
3033   }
3034 #endif
3035 
3036   return true;
3037 }
3038 
3039 bool os::Linux::libnuma_init() {
3040   // Requires sched_getcpu() and numa dependent syscalls support
3041   if ((sched_getcpu() != -1) && numa_syscall_check()) {
3042     void *handle = dlopen("libnuma.so.1", RTLD_LAZY);
3043     if (handle != nullptr) {
3044       set_numa_node_to_cpus(CAST_TO_FN_PTR(numa_node_to_cpus_func_t,
3045                                            libnuma_dlsym(handle, "numa_node_to_cpus")));
3046       set_numa_node_to_cpus_v2(CAST_TO_FN_PTR(numa_node_to_cpus_v2_func_t,
3047                                               libnuma_v2_dlsym(handle, "numa_node_to_cpus")));
3048       set_numa_max_node(CAST_TO_FN_PTR(numa_max_node_func_t,
3049                                        libnuma_dlsym(handle, "numa_max_node")));
3050       set_numa_num_configured_nodes(CAST_TO_FN_PTR(numa_num_configured_nodes_func_t,
3051                                                    libnuma_dlsym(handle, "numa_num_configured_nodes")));
3052       set_numa_available(CAST_TO_FN_PTR(numa_available_func_t,
3053                                         libnuma_dlsym(handle, "numa_available")));
3054       set_numa_tonode_memory(CAST_TO_FN_PTR(numa_tonode_memory_func_t,
3055                                             libnuma_dlsym(handle, "numa_tonode_memory")));
3056       set_numa_interleave_memory(CAST_TO_FN_PTR(numa_interleave_memory_func_t,
3057                                                 libnuma_dlsym(handle, "numa_interleave_memory")));
3058       set_numa_interleave_memory_v2(CAST_TO_FN_PTR(numa_interleave_memory_v2_func_t,
3059                                                 libnuma_v2_dlsym(handle, "numa_interleave_memory")));
3060       set_numa_set_bind_policy(CAST_TO_FN_PTR(numa_set_bind_policy_func_t,
3061                                               libnuma_dlsym(handle, "numa_set_bind_policy")));
3062       set_numa_bitmask_isbitset(CAST_TO_FN_PTR(numa_bitmask_isbitset_func_t,
3063                                                libnuma_dlsym(handle, "numa_bitmask_isbitset")));
3064       set_numa_distance(CAST_TO_FN_PTR(numa_distance_func_t,
3065                                        libnuma_dlsym(handle, "numa_distance")));
3066       set_numa_get_membind(CAST_TO_FN_PTR(numa_get_membind_func_t,
3067                                           libnuma_v2_dlsym(handle, "numa_get_membind")));
3068       set_numa_get_interleave_mask(CAST_TO_FN_PTR(numa_get_interleave_mask_func_t,
3069                                                   libnuma_v2_dlsym(handle, "numa_get_interleave_mask")));
3070       set_numa_move_pages(CAST_TO_FN_PTR(numa_move_pages_func_t,
3071                                          libnuma_dlsym(handle, "numa_move_pages")));
3072       set_numa_set_preferred(CAST_TO_FN_PTR(numa_set_preferred_func_t,
3073                                             libnuma_dlsym(handle, "numa_set_preferred")));
3074 
3075       if (numa_available() != -1) {
3076         set_numa_all_nodes((unsigned long*)libnuma_dlsym(handle, "numa_all_nodes"));
3077         set_numa_all_nodes_ptr((struct bitmask **)libnuma_dlsym(handle, "numa_all_nodes_ptr"));
3078         set_numa_nodes_ptr((struct bitmask **)libnuma_dlsym(handle, "numa_nodes_ptr"));
3079         set_numa_interleave_bitmask(_numa_get_interleave_mask());
3080         set_numa_membind_bitmask(_numa_get_membind());
3081         // Create an index -> node mapping, since nodes are not always consecutive
3082         _nindex_to_node = new (mtInternal) GrowableArray<int>(0, mtInternal);
3083         rebuild_nindex_to_node_map();
3084         // Create a cpu -> node mapping
3085         _cpu_to_node = new (mtInternal) GrowableArray<int>(0, mtInternal);
3086         rebuild_cpu_to_node_map();
3087         return true;
3088       }
3089     }
3090   }
3091   return false;
3092 }
3093 
3094 size_t os::Linux::default_guard_size(os::ThreadType thr_type) {
3095 
3096   if (THPStackMitigation) {
3097     // If THPs are unconditionally enabled, the following scenario can lead to huge RSS
3098     // - parent thread spawns, in quick succession, multiple child threads
3099     // - child threads are slow to start
3100     // - thread stacks of future child threads are adjacent and get merged into one large VMA
3101     //   by the kernel, and subsequently transformed into huge pages by khugepaged
3102     // - child threads come up, place JVM guard pages, thus splinter the large VMA, splinter
3103     //   the huge pages into many (still paged-in) small pages.
3104     // The result of that sequence are thread stacks that are fully paged-in even though the
3105     // threads did not even start yet.
3106     // We prevent that by letting the glibc allocate a guard page, which causes a VMA with different
3107     // permission bits to separate two ajacent thread stacks and therefore prevent merging stacks
3108     // into one VMA.
3109     //
3110     // Yes, this means we have two guard sections - the glibc and the JVM one - per thread. But the
3111     // cost for that one extra protected page is dwarfed from a large win in performance and memory
3112     // that avoiding interference by khugepaged buys us.
3113     return os::vm_page_size();
3114   }
3115 
3116   // Creating guard page is very expensive. Java thread has HotSpot
3117   // guard pages, only enable glibc guard page for non-Java threads.
3118   // (Remember: compiler thread is a Java thread, too!)
3119   return ((thr_type == java_thread || thr_type == compiler_thread) ? 0 : os::vm_page_size());
3120 }
3121 
3122 void os::Linux::rebuild_nindex_to_node_map() {
3123   int highest_node_number = Linux::numa_max_node();
3124 
3125   nindex_to_node()->clear();
3126   for (int node = 0; node <= highest_node_number; node++) {
3127     if (Linux::is_node_in_existing_nodes(node)) {
3128       nindex_to_node()->append(node);
3129     }
3130   }
3131 }
3132 
3133 // rebuild_cpu_to_node_map() constructs a table mapping cpud id to node id.
3134 // The table is later used in get_node_by_cpu().
3135 void os::Linux::rebuild_cpu_to_node_map() {
3136   const size_t NCPUS = 32768; // Since the buffer size computation is very obscure
3137                               // in libnuma (possible values are starting from 16,
3138                               // and continuing up with every other power of 2, but less
3139                               // than the maximum number of CPUs supported by kernel), and
3140                               // is a subject to change (in libnuma version 2 the requirements
3141                               // are more reasonable) we'll just hardcode the number they use
3142                               // in the library.
3143   const size_t BitsPerCLong = sizeof(long) * CHAR_BIT;
3144 
3145   size_t cpu_num = processor_count();
3146   size_t cpu_map_size = NCPUS / BitsPerCLong;
3147   size_t cpu_map_valid_size =
3148     MIN2((cpu_num + BitsPerCLong - 1) / BitsPerCLong, cpu_map_size);
3149 
3150   cpu_to_node()->clear();
3151   cpu_to_node()->at_grow(cpu_num - 1);
3152 
3153   size_t node_num = get_existing_num_nodes();
3154 
3155   int distance = 0;
3156   int closest_distance = INT_MAX;
3157   int closest_node = 0;
3158   unsigned long *cpu_map = NEW_C_HEAP_ARRAY(unsigned long, cpu_map_size, mtInternal);
3159   for (size_t i = 0; i < node_num; i++) {
3160     // Check if node is configured (not a memory-less node). If it is not, find
3161     // the closest configured node. Check also if node is bound, i.e. it's allowed
3162     // to allocate memory from the node. If it's not allowed, map cpus in that node
3163     // to the closest node from which memory allocation is allowed.
3164     if (!is_node_in_configured_nodes(nindex_to_node()->at(i)) ||
3165         !is_node_in_bound_nodes(nindex_to_node()->at(i))) {
3166       closest_distance = INT_MAX;
3167       // Check distance from all remaining nodes in the system. Ignore distance
3168       // from itself, from another non-configured node, and from another non-bound
3169       // node.
3170       for (size_t m = 0; m < node_num; m++) {
3171         if (m != i &&
3172             is_node_in_configured_nodes(nindex_to_node()->at(m)) &&
3173             is_node_in_bound_nodes(nindex_to_node()->at(m))) {
3174           distance = numa_distance(nindex_to_node()->at(i), nindex_to_node()->at(m));
3175           // If a closest node is found, update. There is always at least one
3176           // configured and bound node in the system so there is always at least
3177           // one node close.
3178           if (distance != 0 && distance < closest_distance) {
3179             closest_distance = distance;
3180             closest_node = nindex_to_node()->at(m);
3181           }
3182         }
3183       }
3184      } else {
3185        // Current node is already a configured node.
3186        closest_node = nindex_to_node()->at(i);
3187      }
3188 
3189     // Get cpus from the original node and map them to the closest node. If node
3190     // is a configured node (not a memory-less node), then original node and
3191     // closest node are the same.
3192     if (numa_node_to_cpus(nindex_to_node()->at(i), cpu_map, cpu_map_size * sizeof(unsigned long)) != -1) {
3193       for (size_t j = 0; j < cpu_map_valid_size; j++) {
3194         if (cpu_map[j] != 0) {
3195           for (size_t k = 0; k < BitsPerCLong; k++) {
3196             if (cpu_map[j] & (1UL << k)) {
3197               int cpu_index = j * BitsPerCLong + k;
3198 
3199 #ifndef PRODUCT
3200               if (UseDebuggerErgo1 && cpu_index >= (int)cpu_num) {
3201                 // Some debuggers limit the processor count without
3202                 // intercepting the NUMA APIs. Just fake the values.
3203                 cpu_index = 0;
3204               }
3205 #endif
3206 
3207               cpu_to_node()->at_put(cpu_index, closest_node);
3208             }
3209           }
3210         }
3211       }
3212     }
3213   }
3214   FREE_C_HEAP_ARRAY(unsigned long, cpu_map);
3215 }
3216 
3217 int os::Linux::numa_node_to_cpus(int node, unsigned long *buffer, int bufferlen) {
3218   // use the latest version of numa_node_to_cpus if available
3219   if (_numa_node_to_cpus_v2 != nullptr) {
3220 
3221     // libnuma bitmask struct
3222     struct bitmask {
3223       unsigned long size; /* number of bits in the map */
3224       unsigned long *maskp;
3225     };
3226 
3227     struct bitmask mask;
3228     mask.maskp = (unsigned long *)buffer;
3229     mask.size = bufferlen * 8;
3230     return _numa_node_to_cpus_v2(node, &mask);
3231   } else if (_numa_node_to_cpus != nullptr) {
3232     return _numa_node_to_cpus(node, buffer, bufferlen);
3233   }
3234   return -1;
3235 }
3236 
3237 int os::Linux::get_node_by_cpu(int cpu_id) {
3238   if (cpu_to_node() != nullptr && cpu_id >= 0 && cpu_id < cpu_to_node()->length()) {
3239     return cpu_to_node()->at(cpu_id);
3240   }
3241   return -1;
3242 }
3243 
3244 GrowableArray<int>* os::Linux::_cpu_to_node;
3245 GrowableArray<int>* os::Linux::_nindex_to_node;
3246 os::Linux::sched_getcpu_func_t os::Linux::_sched_getcpu;
3247 os::Linux::numa_node_to_cpus_func_t os::Linux::_numa_node_to_cpus;
3248 os::Linux::numa_node_to_cpus_v2_func_t os::Linux::_numa_node_to_cpus_v2;
3249 os::Linux::numa_max_node_func_t os::Linux::_numa_max_node;
3250 os::Linux::numa_num_configured_nodes_func_t os::Linux::_numa_num_configured_nodes;
3251 os::Linux::numa_available_func_t os::Linux::_numa_available;
3252 os::Linux::numa_tonode_memory_func_t os::Linux::_numa_tonode_memory;
3253 os::Linux::numa_interleave_memory_func_t os::Linux::_numa_interleave_memory;
3254 os::Linux::numa_interleave_memory_v2_func_t os::Linux::_numa_interleave_memory_v2;
3255 os::Linux::numa_set_bind_policy_func_t os::Linux::_numa_set_bind_policy;
3256 os::Linux::numa_bitmask_isbitset_func_t os::Linux::_numa_bitmask_isbitset;
3257 os::Linux::numa_distance_func_t os::Linux::_numa_distance;
3258 os::Linux::numa_get_membind_func_t os::Linux::_numa_get_membind;
3259 os::Linux::numa_get_interleave_mask_func_t os::Linux::_numa_get_interleave_mask;
3260 os::Linux::numa_move_pages_func_t os::Linux::_numa_move_pages;
3261 os::Linux::numa_set_preferred_func_t os::Linux::_numa_set_preferred;
3262 os::Linux::NumaAllocationPolicy os::Linux::_current_numa_policy;
3263 unsigned long* os::Linux::_numa_all_nodes;
3264 struct bitmask* os::Linux::_numa_all_nodes_ptr;
3265 struct bitmask* os::Linux::_numa_nodes_ptr;
3266 struct bitmask* os::Linux::_numa_interleave_bitmask;
3267 struct bitmask* os::Linux::_numa_membind_bitmask;
3268 
3269 bool os::pd_uncommit_memory(char* addr, size_t size, bool exec) {
3270   uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
3271                                      MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
3272   return res  != (uintptr_t) MAP_FAILED;
3273 }
3274 
3275 static address get_stack_commited_bottom(address bottom, size_t size) {
3276   address nbot = bottom;
3277   address ntop = bottom + size;
3278 
3279   size_t page_sz = os::vm_page_size();
3280   unsigned pages = size / page_sz;
3281 
3282   unsigned char vec[1];
3283   unsigned imin = 1, imax = pages + 1, imid;
3284   int mincore_return_value = 0;
3285 
3286   assert(imin <= imax, "Unexpected page size");
3287 
3288   while (imin < imax) {
3289     imid = (imax + imin) / 2;
3290     nbot = ntop - (imid * page_sz);
3291 
3292     // Use a trick with mincore to check whether the page is mapped or not.
3293     // mincore sets vec to 1 if page resides in memory and to 0 if page
3294     // is swapped output but if page we are asking for is unmapped
3295     // it returns -1,ENOMEM
3296     mincore_return_value = mincore(nbot, page_sz, vec);
3297 
3298     if (mincore_return_value == -1) {
3299       // Page is not mapped go up
3300       // to find first mapped page
3301       if (errno != EAGAIN) {
3302         assert(errno == ENOMEM, "Unexpected mincore errno");
3303         imax = imid;
3304       }
3305     } else {
3306       // Page is mapped go down
3307       // to find first not mapped page
3308       imin = imid + 1;
3309     }
3310   }
3311 
3312   nbot = nbot + page_sz;
3313 
3314   // Adjust stack bottom one page up if last checked page is not mapped
3315   if (mincore_return_value == -1) {
3316     nbot = nbot + page_sz;
3317   }
3318 
3319   return nbot;
3320 }
3321 
3322 bool os::committed_in_range(address start, size_t size, address& committed_start, size_t& committed_size) {
3323   int mincore_return_value;
3324   const size_t stripe = 1024;  // query this many pages each time
3325   unsigned char vec[stripe + 1];
3326   // set a guard
3327   vec[stripe] = 'X';
3328 
3329   const size_t page_sz = os::vm_page_size();
3330   size_t pages = size / page_sz;
3331 
3332   assert(is_aligned(start, page_sz), "Start address must be page aligned");
3333   assert(is_aligned(size, page_sz), "Size must be page aligned");
3334 
3335   committed_start = nullptr;
3336 
3337   int loops = (pages + stripe - 1) / stripe;
3338   int committed_pages = 0;
3339   address loop_base = start;
3340   bool found_range = false;
3341 
3342   for (int index = 0; index < loops && !found_range; index ++) {
3343     assert(pages > 0, "Nothing to do");
3344     int pages_to_query = (pages >= stripe) ? stripe : pages;
3345     pages -= pages_to_query;
3346 
3347     // Get stable read
3348     while ((mincore_return_value = mincore(loop_base, pages_to_query * page_sz, vec)) == -1 && errno == EAGAIN);
3349 
3350     // During shutdown, some memory goes away without properly notifying NMT,
3351     // E.g. ConcurrentGCThread/WatcherThread can exit without deleting thread object.
3352     // Bailout and return as not committed for now.
3353     if (mincore_return_value == -1 && errno == ENOMEM) {
3354       return false;
3355     }
3356 
3357     assert(vec[stripe] == 'X', "overflow guard");
3358     assert(mincore_return_value == 0, "Range must be valid");
3359     // Process this stripe
3360     for (int vecIdx = 0; vecIdx < pages_to_query; vecIdx ++) {
3361       if ((vec[vecIdx] & 0x01) == 0) { // not committed
3362         // End of current contiguous region
3363         if (committed_start != nullptr) {
3364           found_range = true;
3365           break;
3366         }
3367       } else { // committed
3368         // Start of region
3369         if (committed_start == nullptr) {
3370           committed_start = loop_base + page_sz * vecIdx;
3371         }
3372         committed_pages ++;
3373       }
3374     }
3375 
3376     loop_base += pages_to_query * page_sz;
3377   }
3378 
3379   if (committed_start != nullptr) {
3380     assert(committed_pages > 0, "Must have committed region");
3381     assert(committed_pages <= int(size / page_sz), "Can not commit more than it has");
3382     assert(committed_start >= start && committed_start < start + size, "Out of range");
3383     committed_size = page_sz * committed_pages;
3384     return true;
3385   } else {
3386     assert(committed_pages == 0, "Should not have committed region");
3387     return false;
3388   }
3389 }
3390 
3391 
3392 // Linux uses a growable mapping for the stack, and if the mapping for
3393 // the stack guard pages is not removed when we detach a thread the
3394 // stack cannot grow beyond the pages where the stack guard was
3395 // mapped.  If at some point later in the process the stack expands to
3396 // that point, the Linux kernel cannot expand the stack any further
3397 // because the guard pages are in the way, and a segfault occurs.
3398 //
3399 // However, it's essential not to split the stack region by unmapping
3400 // a region (leaving a hole) that's already part of the stack mapping,
3401 // so if the stack mapping has already grown beyond the guard pages at
3402 // the time we create them, we have to truncate the stack mapping.
3403 // So, we need to know the extent of the stack mapping when
3404 // create_stack_guard_pages() is called.
3405 
3406 // We only need this for stacks that are growable: at the time of
3407 // writing thread stacks don't use growable mappings (i.e. those
3408 // creeated with MAP_GROWSDOWN), and aren't marked "[stack]", so this
3409 // only applies to the main thread.
3410 
3411 // If the (growable) stack mapping already extends beyond the point
3412 // where we're going to put our guard pages, truncate the mapping at
3413 // that point by munmap()ping it.  This ensures that when we later
3414 // munmap() the guard pages we don't leave a hole in the stack
3415 // mapping. This only affects the main/primordial thread
3416 
3417 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
3418   if (os::is_primordial_thread()) {
3419     // As we manually grow stack up to bottom inside create_attached_thread(),
3420     // it's likely that os::Linux::initial_thread_stack_bottom is mapped and
3421     // we don't need to do anything special.
3422     // Check it first, before calling heavy function.
3423     uintptr_t stack_extent = (uintptr_t) os::Linux::initial_thread_stack_bottom();
3424     unsigned char vec[1];
3425 
3426     if (mincore((address)stack_extent, os::vm_page_size(), vec) == -1) {
3427       // Fallback to slow path on all errors, including EAGAIN
3428       assert((uintptr_t)addr >= stack_extent,
3429              "Sanity: addr should be larger than extent, " PTR_FORMAT " >= " PTR_FORMAT,
3430              p2i(addr), stack_extent);
3431       stack_extent = (uintptr_t) get_stack_commited_bottom(
3432                                                            os::Linux::initial_thread_stack_bottom(),
3433                                                            (size_t)addr - stack_extent);
3434     }
3435 
3436     if (stack_extent < (uintptr_t)addr) {
3437       ::munmap((void*)stack_extent, (uintptr_t)(addr - stack_extent));
3438     }
3439   }
3440 
3441   return os::commit_memory(addr, size, !ExecMem);
3442 }
3443 
3444 // If this is a growable mapping, remove the guard pages entirely by
3445 // munmap()ping them.  If not, just call uncommit_memory(). This only
3446 // affects the main/primordial thread, but guard against future OS changes.
3447 // It's safe to always unmap guard pages for primordial thread because we
3448 // always place it right after end of the mapped region.
3449 
3450 bool os::remove_stack_guard_pages(char* addr, size_t size) {
3451   uintptr_t stack_extent, stack_base;
3452 
3453   if (os::is_primordial_thread()) {
3454     return ::munmap(addr, size) == 0;
3455   }
3456 
3457   return os::uncommit_memory(addr, size);
3458 }
3459 
3460 // 'requested_addr' is only treated as a hint, the return value may or
3461 // may not start from the requested address. Unlike Linux mmap(), this
3462 // function returns null to indicate failure.
3463 static char* anon_mmap(char* requested_addr, size_t bytes) {
3464   // MAP_FIXED is intentionally left out, to leave existing mappings intact.
3465   const int flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
3466 
3467   // Map reserved/uncommitted pages PROT_NONE so we fail early if we
3468   // touch an uncommitted page. Otherwise, the read/write might
3469   // succeed if we have enough swap space to back the physical page.
3470   char* addr = (char*)::mmap(requested_addr, bytes, PROT_NONE, flags, -1, 0);
3471 
3472   return addr == MAP_FAILED ? nullptr : addr;
3473 }
3474 
3475 // Allocate (using mmap, NO_RESERVE, with small pages) at either a given request address
3476 //   (req_addr != nullptr) or with a given alignment.
3477 //  - bytes shall be a multiple of alignment.
3478 //  - req_addr can be null. If not null, it must be a multiple of alignment.
3479 //  - alignment sets the alignment at which memory shall be allocated.
3480 //     It must be a multiple of allocation granularity.
3481 // Returns address of memory or null. If req_addr was not null, will only return
3482 //  req_addr or null.
3483 static char* anon_mmap_aligned(char* req_addr, size_t bytes, size_t alignment) {
3484   size_t extra_size = bytes;
3485   if (req_addr == nullptr && alignment > 0) {
3486     extra_size += alignment;
3487   }
3488 
3489   char* start = anon_mmap(req_addr, extra_size);
3490   if (start != nullptr) {
3491     if (req_addr != nullptr) {
3492       if (start != req_addr) {
3493         ::munmap(start, extra_size);
3494         start = nullptr;
3495       }
3496     } else {
3497       char* const start_aligned = align_up(start, alignment);
3498       char* const end_aligned = start_aligned + bytes;
3499       char* const end = start + extra_size;
3500       if (start_aligned > start) {
3501         ::munmap(start, start_aligned - start);
3502       }
3503       if (end_aligned < end) {
3504         ::munmap(end_aligned, end - end_aligned);
3505       }
3506       start = start_aligned;
3507     }
3508   }
3509   return start;
3510 }
3511 
3512 static int anon_munmap(char * addr, size_t size) {
3513   return ::munmap(addr, size) == 0;
3514 }
3515 
3516 char* os::pd_reserve_memory(size_t bytes, bool exec) {
3517   return anon_mmap(nullptr, bytes);
3518 }
3519 
3520 bool os::pd_release_memory(char* addr, size_t size) {
3521   return anon_munmap(addr, size);
3522 }
3523 
3524 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
3525 extern char* g_assert_poison; // assertion poison page address
3526 #endif
3527 
3528 static bool linux_mprotect(char* addr, size_t size, int prot) {
3529   // Linux wants the mprotect address argument to be page aligned.
3530   char* bottom = (char*)align_down((intptr_t)addr, os::vm_page_size());
3531 
3532   // According to SUSv3, mprotect() should only be used with mappings
3533   // established by mmap(), and mmap() always maps whole pages. Unaligned
3534   // 'addr' likely indicates problem in the VM (e.g. trying to change
3535   // protection of malloc'ed or statically allocated memory). Check the
3536   // caller if you hit this assert.
3537   assert(addr == bottom, "sanity check");
3538 
3539   size = align_up(pointer_delta(addr, bottom, 1) + size, os::vm_page_size());
3540   // Don't log anything if we're executing in the poison page signal handling
3541   // context. It can lead to reentrant use of other parts of the VM code.
3542 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
3543   if (addr != g_assert_poison)
3544 #endif
3545   Events::log(nullptr, "Protecting memory [" INTPTR_FORMAT "," INTPTR_FORMAT "] with protection modes %x", p2i(bottom), p2i(bottom+size), prot);
3546   return ::mprotect(bottom, size, prot) == 0;
3547 }
3548 
3549 // Set protections specified
3550 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
3551                         bool is_committed) {
3552   unsigned int p = 0;
3553   switch (prot) {
3554   case MEM_PROT_NONE: p = PROT_NONE; break;
3555   case MEM_PROT_READ: p = PROT_READ; break;
3556   case MEM_PROT_RW:   p = PROT_READ|PROT_WRITE; break;
3557   case MEM_PROT_RWX:  p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
3558   default:
3559     ShouldNotReachHere();
3560   }
3561   // is_committed is unused.
3562   return linux_mprotect(addr, bytes, p);
3563 }
3564 
3565 bool os::guard_memory(char* addr, size_t size) {
3566   return linux_mprotect(addr, size, PROT_NONE);
3567 }
3568 
3569 bool os::unguard_memory(char* addr, size_t size) {
3570   return linux_mprotect(addr, size, PROT_READ|PROT_WRITE);
3571 }
3572 
3573 bool os::Linux::transparent_huge_pages_sanity_check(bool warn,
3574                                                     size_t page_size) {
3575   bool result = false;
3576   void *p = mmap(nullptr, page_size * 2, PROT_READ|PROT_WRITE,
3577                  MAP_ANONYMOUS|MAP_PRIVATE,
3578                  -1, 0);
3579   if (p != MAP_FAILED) {
3580     void *aligned_p = align_up(p, page_size);
3581 
3582     result = madvise(aligned_p, page_size, MADV_HUGEPAGE) == 0;
3583 
3584     munmap(p, page_size * 2);
3585   }
3586 
3587   if (warn && !result) {
3588     warning("TransparentHugePages is not supported by the operating system.");
3589   }
3590 
3591   return result;
3592 }
3593 
3594 int os::Linux::hugetlbfs_page_size_flag(size_t page_size) {
3595   if (page_size != HugePages::default_static_hugepage_size()) {
3596     return (exact_log2(page_size) << MAP_HUGE_SHIFT);
3597   }
3598   return 0;
3599 }
3600 
3601 bool os::Linux::hugetlbfs_sanity_check(bool warn, size_t page_size) {
3602   // Include the page size flag to ensure we sanity check the correct page size.
3603   int flags = MAP_ANONYMOUS | MAP_PRIVATE | MAP_HUGETLB | hugetlbfs_page_size_flag(page_size);
3604   void *p = mmap(nullptr, page_size, PROT_READ|PROT_WRITE, flags, -1, 0);
3605 
3606   if (p != MAP_FAILED) {
3607     // Mapping succeeded, sanity check passed.
3608     munmap(p, page_size);
3609     return true;
3610   } else {
3611       log_info(pagesize)("Large page size (" SIZE_FORMAT "%s) failed sanity check, "
3612                          "checking if smaller large page sizes are usable",
3613                          byte_size_in_exact_unit(page_size),
3614                          exact_unit_for_byte_size(page_size));
3615       for (size_t page_size_ = _page_sizes.next_smaller(page_size);
3616           page_size_ != os::vm_page_size();
3617           page_size_ = _page_sizes.next_smaller(page_size_)) {
3618         flags = MAP_ANONYMOUS | MAP_PRIVATE | MAP_HUGETLB | hugetlbfs_page_size_flag(page_size_);
3619         p = mmap(nullptr, page_size_, PROT_READ|PROT_WRITE, flags, -1, 0);
3620         if (p != MAP_FAILED) {
3621           // Mapping succeeded, sanity check passed.
3622           munmap(p, page_size_);
3623           log_info(pagesize)("Large page size (" SIZE_FORMAT "%s) passed sanity check",
3624                              byte_size_in_exact_unit(page_size_),
3625                              exact_unit_for_byte_size(page_size_));
3626           return true;
3627         }
3628       }
3629   }
3630 
3631   if (warn) {
3632     warning("HugeTLBFS is not configured or not supported by the operating system.");
3633   }
3634 
3635   return false;
3636 }
3637 
3638 bool os::Linux::shm_hugetlbfs_sanity_check(bool warn, size_t page_size) {
3639   // Try to create a large shared memory segment.
3640   int shmid = shmget(IPC_PRIVATE, page_size, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W);
3641   if (shmid == -1) {
3642     // Possible reasons for shmget failure:
3643     // 1. shmmax is too small for the request.
3644     //    > check shmmax value: cat /proc/sys/kernel/shmmax
3645     //    > increase shmmax value: echo "new_value" > /proc/sys/kernel/shmmax
3646     // 2. not enough large page memory.
3647     //    > check available large pages: cat /proc/meminfo
3648     //    > increase amount of large pages:
3649     //          sysctl -w vm.nr_hugepages=new_value
3650     //    > For more information regarding large pages please refer to:
3651     //      https://www.kernel.org/doc/Documentation/vm/hugetlbpage.txt
3652     if (warn) {
3653       warning("Large pages using UseSHM are not configured on this system.");
3654     }
3655     return false;
3656   }
3657   // Managed to create a segment, now delete it.
3658   shmctl(shmid, IPC_RMID, nullptr);
3659   return true;
3660 }
3661 
3662 // From the coredump_filter documentation:
3663 //
3664 // - (bit 0) anonymous private memory
3665 // - (bit 1) anonymous shared memory
3666 // - (bit 2) file-backed private memory
3667 // - (bit 3) file-backed shared memory
3668 // - (bit 4) ELF header pages in file-backed private memory areas (it is
3669 //           effective only if the bit 2 is cleared)
3670 // - (bit 5) hugetlb private memory
3671 // - (bit 6) hugetlb shared memory
3672 // - (bit 7) dax private memory
3673 // - (bit 8) dax shared memory
3674 //
3675 static void set_coredump_filter(CoredumpFilterBit bit) {
3676   FILE *f;
3677   long cdm;
3678 
3679   if ((f = os::fopen("/proc/self/coredump_filter", "r+")) == nullptr) {
3680     return;
3681   }
3682 
3683   if (fscanf(f, "%lx", &cdm) != 1) {
3684     fclose(f);
3685     return;
3686   }
3687 
3688   long saved_cdm = cdm;
3689   rewind(f);
3690   cdm |= bit;
3691 
3692   if (cdm != saved_cdm) {
3693     fprintf(f, "%#lx", cdm);
3694   }
3695 
3696   fclose(f);
3697 }
3698 
3699 // Large page support
3700 
3701 static size_t _large_page_size = 0;
3702 
3703 void warn_no_large_pages_configured() {
3704   if (!FLAG_IS_DEFAULT(UseLargePages)) {
3705     log_warning(pagesize)("UseLargePages disabled, no large pages configured and available on the system.");
3706   }
3707 }
3708 
3709 bool os::Linux::setup_large_page_type(size_t page_size) {
3710   if (FLAG_IS_DEFAULT(UseHugeTLBFS) &&
3711       FLAG_IS_DEFAULT(UseSHM) &&
3712       FLAG_IS_DEFAULT(UseTransparentHugePages)) {
3713 
3714     // The type of large pages has not been specified by the user.
3715 
3716     // Try UseHugeTLBFS and then UseSHM.
3717     UseHugeTLBFS = UseSHM = true;
3718 
3719     // Don't try UseTransparentHugePages since there are known
3720     // performance issues with it turned on. This might change in the future.
3721     UseTransparentHugePages = false;
3722   }
3723 
3724   if (UseTransparentHugePages) {
3725     bool warn_on_failure = !FLAG_IS_DEFAULT(UseTransparentHugePages);
3726     if (transparent_huge_pages_sanity_check(warn_on_failure, page_size)) {
3727       UseHugeTLBFS = false;
3728       UseSHM = false;
3729       return true;
3730     }
3731     UseTransparentHugePages = false;
3732   }
3733 
3734   if (UseHugeTLBFS) {
3735     bool warn_on_failure = !FLAG_IS_DEFAULT(UseHugeTLBFS);
3736     if (hugetlbfs_sanity_check(warn_on_failure, page_size)) {
3737       UseSHM = false;
3738       return true;
3739     }
3740     UseHugeTLBFS = false;
3741   }
3742 
3743   if (UseSHM) {
3744     bool warn_on_failure = !FLAG_IS_DEFAULT(UseSHM);
3745     if (shm_hugetlbfs_sanity_check(warn_on_failure, page_size)) {
3746       return true;
3747     }
3748     UseSHM = false;
3749   }
3750 
3751   warn_no_large_pages_configured();
3752   return false;
3753 }
3754 
3755 struct LargePageInitializationLoggerMark {
3756   ~LargePageInitializationLoggerMark() {
3757     LogTarget(Info, pagesize) lt;
3758     if (lt.is_enabled()) {
3759       LogStream ls(lt);
3760       if (UseLargePages) {
3761         ls.print_cr("UseLargePages=1, UseTransparentHugePages=%d, UseHugeTLBFS=%d, UseSHM=%d",
3762                     UseTransparentHugePages, UseHugeTLBFS, UseSHM);
3763         ls.print("Large page support enabled. Usable page sizes: ");
3764         os::page_sizes().print_on(&ls);
3765         ls.print_cr(". Default large page size: " EXACTFMT ".", EXACTFMTARGS(os::large_page_size()));
3766       } else {
3767         ls.print("Large page support disabled.");
3768       }
3769     }
3770   }
3771 };
3772 
3773 void os::large_page_init() {
3774   LargePageInitializationLoggerMark logger;
3775 
3776   // Query OS information first.
3777   HugePages::initialize();
3778 
3779   // If THPs are unconditionally enabled (THP mode "always"), khugepaged may attempt to
3780   // coalesce small pages in thread stacks to huge pages. That costs a lot of memory and
3781   // is usually unwanted for thread stacks. Therefore we attempt to prevent THP formation in
3782   // thread stacks unless the user explicitly allowed THP formation by manually disabling
3783   // -XX:-THPStackMitigation.
3784   if (HugePages::thp_mode() == THPMode::always) {
3785     if (THPStackMitigation) {
3786       log_info(pagesize)("JVM will attempt to prevent THPs in thread stacks.");
3787     } else {
3788       log_info(pagesize)("JVM will *not* prevent THPs in thread stacks. This may cause high RSS.");
3789     }
3790   } else {
3791     FLAG_SET_ERGO(THPStackMitigation, false); // Mitigation not needed
3792   }
3793 
3794   // 1) Handle the case where we do not want to use huge pages
3795   if (!UseLargePages &&
3796       !UseTransparentHugePages &&
3797       !UseHugeTLBFS &&
3798       !UseSHM) {
3799     // Not using large pages.
3800     return;
3801   }
3802 
3803   if (!FLAG_IS_DEFAULT(UseLargePages) && !UseLargePages) {
3804     // The user explicitly turned off large pages.
3805     // Ignore the rest of the large pages flags.
3806     UseTransparentHugePages = false;
3807     UseHugeTLBFS = false;
3808     UseSHM = false;
3809     return;
3810   }
3811 
3812   // 2) check if the OS supports THPs resp. static hugepages.
3813   if (UseTransparentHugePages && !HugePages::supports_thp()) {
3814     if (!FLAG_IS_DEFAULT(UseTransparentHugePages)) {
3815       log_warning(pagesize)("UseTransparentHugePages disabled, transparent huge pages are not supported by the operating system.");
3816     }
3817     UseLargePages = UseTransparentHugePages = UseHugeTLBFS = UseSHM = false;
3818     return;
3819   }
3820   if (!UseTransparentHugePages && !HugePages::supports_static_hugepages()) {
3821     warn_no_large_pages_configured();
3822     UseLargePages = UseTransparentHugePages = UseHugeTLBFS = UseSHM = false;
3823     return;
3824   }
3825 
3826   if (UseTransparentHugePages) {
3827     // In THP mode:
3828     // - os::large_page_size() is the *THP page size*
3829     // - os::pagesizes() has two members, the THP page size and the system page size
3830     assert(HugePages::supports_thp() && HugePages::thp_pagesize() > 0, "Missing OS info");
3831     _large_page_size = HugePages::thp_pagesize();
3832     _page_sizes.add(_large_page_size);
3833     _page_sizes.add(os::vm_page_size());
3834 
3835   } else {
3836 
3837     // In static hugepage mode:
3838     // - os::large_page_size() is the default static hugepage size (/proc/meminfo "Hugepagesize")
3839     // - os::pagesizes() contains all hugepage sizes the kernel supports, regardless whether there
3840     //   are pages configured in the pool or not (from /sys/kernel/hugepages/hugepage-xxxx ...)
3841     os::PageSizes all_large_pages = HugePages::static_info().pagesizes();
3842     const size_t default_large_page_size = HugePages::default_static_hugepage_size();
3843 
3844     // 3) Consistency check and post-processing
3845 
3846     // Check LargePageSizeInBytes matches an available page size and if so set _large_page_size
3847     // using LargePageSizeInBytes as the maximum allowed large page size. If LargePageSizeInBytes
3848     // doesn't match an available page size set _large_page_size to default_large_page_size
3849     // and use it as the maximum.
3850    if (FLAG_IS_DEFAULT(LargePageSizeInBytes) ||
3851         LargePageSizeInBytes == 0 ||
3852         LargePageSizeInBytes == default_large_page_size) {
3853       _large_page_size = default_large_page_size;
3854       log_info(pagesize)("Using the default large page size: " SIZE_FORMAT "%s",
3855                          byte_size_in_exact_unit(_large_page_size),
3856                          exact_unit_for_byte_size(_large_page_size));
3857     } else {
3858       if (all_large_pages.contains(LargePageSizeInBytes)) {
3859         _large_page_size = LargePageSizeInBytes;
3860         log_info(pagesize)("Overriding default large page size (" SIZE_FORMAT "%s) "
3861                            "using LargePageSizeInBytes: " SIZE_FORMAT "%s",
3862                            byte_size_in_exact_unit(default_large_page_size),
3863                            exact_unit_for_byte_size(default_large_page_size),
3864                            byte_size_in_exact_unit(_large_page_size),
3865                            exact_unit_for_byte_size(_large_page_size));
3866       } else {
3867         _large_page_size = default_large_page_size;
3868         log_info(pagesize)("LargePageSizeInBytes is not a valid large page size (" SIZE_FORMAT "%s) "
3869                            "using the default large page size: " SIZE_FORMAT "%s",
3870                            byte_size_in_exact_unit(LargePageSizeInBytes),
3871                            exact_unit_for_byte_size(LargePageSizeInBytes),
3872                            byte_size_in_exact_unit(_large_page_size),
3873                            exact_unit_for_byte_size(_large_page_size));
3874       }
3875     }
3876 
3877     // Populate _page_sizes with large page sizes less than or equal to
3878     // _large_page_size.
3879     for (size_t page_size = _large_page_size; page_size != 0;
3880            page_size = all_large_pages.next_smaller(page_size)) {
3881       _page_sizes.add(page_size);
3882     }
3883   }
3884 
3885   // Now determine the type of large pages to use:
3886   UseLargePages = os::Linux::setup_large_page_type(_large_page_size);
3887 
3888   set_coredump_filter(LARGEPAGES_BIT);
3889 }
3890 
3891 #ifndef SHM_HUGETLB
3892   #define SHM_HUGETLB 04000
3893 #endif
3894 
3895 #define shm_warning_format(format, ...)              \
3896   do {                                               \
3897     if (UseLargePages &&                             \
3898         (!FLAG_IS_DEFAULT(UseLargePages) ||          \
3899          !FLAG_IS_DEFAULT(UseSHM) ||                 \
3900          !FLAG_IS_DEFAULT(LargePageSizeInBytes))) {  \
3901       warning(format, __VA_ARGS__);                  \
3902     }                                                \
3903   } while (0)
3904 
3905 #define shm_warning(str) shm_warning_format("%s", str)
3906 
3907 #define shm_warning_with_errno(str)                \
3908   do {                                             \
3909     int err = errno;                               \
3910     shm_warning_format(str " (error = %d)", err);  \
3911   } while (0)
3912 
3913 static char* shmat_with_alignment(int shmid, size_t bytes, size_t alignment) {
3914   assert(is_aligned(bytes, alignment), "Must be divisible by the alignment");
3915 
3916   if (!is_aligned(alignment, SHMLBA)) {
3917     assert(false, "Code below assumes that alignment is at least SHMLBA aligned");
3918     return nullptr;
3919   }
3920 
3921   // To ensure that we get 'alignment' aligned memory from shmat,
3922   // we pre-reserve aligned virtual memory and then attach to that.
3923 
3924   char* pre_reserved_addr = anon_mmap_aligned(nullptr /* req_addr */, bytes, alignment);
3925   if (pre_reserved_addr == nullptr) {
3926     // Couldn't pre-reserve aligned memory.
3927     shm_warning("Failed to pre-reserve aligned memory for shmat.");
3928     return nullptr;
3929   }
3930 
3931   // SHM_REMAP is needed to allow shmat to map over an existing mapping.
3932   char* addr = (char*)shmat(shmid, pre_reserved_addr, SHM_REMAP);
3933 
3934   if ((intptr_t)addr == -1) {
3935     int err = errno;
3936     shm_warning_with_errno("Failed to attach shared memory.");
3937 
3938     assert(err != EACCES, "Unexpected error");
3939     assert(err != EIDRM,  "Unexpected error");
3940     assert(err != EINVAL, "Unexpected error");
3941 
3942     // Since we don't know if the kernel unmapped the pre-reserved memory area
3943     // we can't unmap it, since that would potentially unmap memory that was
3944     // mapped from other threads.
3945     return nullptr;
3946   }
3947 
3948   return addr;
3949 }
3950 
3951 static char* shmat_at_address(int shmid, char* req_addr) {
3952   if (!is_aligned(req_addr, SHMLBA)) {
3953     assert(false, "Requested address needs to be SHMLBA aligned");
3954     return nullptr;
3955   }
3956 
3957   char* addr = (char*)shmat(shmid, req_addr, 0);
3958 
3959   if ((intptr_t)addr == -1) {
3960     shm_warning_with_errno("Failed to attach shared memory.");
3961     return nullptr;
3962   }
3963 
3964   return addr;
3965 }
3966 
3967 static char* shmat_large_pages(int shmid, size_t bytes, size_t alignment, char* req_addr) {
3968   // If a req_addr has been provided, we assume that the caller has already aligned the address.
3969   if (req_addr != nullptr) {
3970     assert(is_aligned(req_addr, os::large_page_size()), "Must be divisible by the large page size");
3971     assert(is_aligned(req_addr, alignment), "Must be divisible by given alignment");
3972     return shmat_at_address(shmid, req_addr);
3973   }
3974 
3975   // Since shmid has been setup with SHM_HUGETLB, shmat will automatically
3976   // return large page size aligned memory addresses when req_addr == nullptr.
3977   // However, if the alignment is larger than the large page size, we have
3978   // to manually ensure that the memory returned is 'alignment' aligned.
3979   if (alignment > os::large_page_size()) {
3980     assert(is_aligned(alignment, os::large_page_size()), "Must be divisible by the large page size");
3981     return shmat_with_alignment(shmid, bytes, alignment);
3982   } else {
3983     return shmat_at_address(shmid, nullptr);
3984   }
3985 }
3986 
3987 char* os::Linux::reserve_memory_special_shm(size_t bytes, size_t alignment,
3988                                             char* req_addr, bool exec) {
3989   // "exec" is passed in but not used.  Creating the shared image for
3990   // the code cache doesn't have an SHM_X executable permission to check.
3991   assert(UseLargePages && UseSHM, "only for SHM large pages");
3992   assert(is_aligned(req_addr, os::large_page_size()), "Unaligned address");
3993   assert(is_aligned(req_addr, alignment), "Unaligned address");
3994 
3995   if (!is_aligned(bytes, os::large_page_size())) {
3996     return nullptr; // Fallback to small pages.
3997   }
3998 
3999   // Create a large shared memory region to attach to based on size.
4000   // Currently, size is the total size of the heap.
4001   int shmid = shmget(IPC_PRIVATE, bytes, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W);
4002   if (shmid == -1) {
4003     // Possible reasons for shmget failure:
4004     // 1. shmmax is too small for the request.
4005     //    > check shmmax value: cat /proc/sys/kernel/shmmax
4006     //    > increase shmmax value: echo "new_value" > /proc/sys/kernel/shmmax
4007     // 2. not enough large page memory.
4008     //    > check available large pages: cat /proc/meminfo
4009     //    > increase amount of large pages:
4010     //          sysctl -w vm.nr_hugepages=new_value
4011     //    > For more information regarding large pages please refer to:
4012     //      https://www.kernel.org/doc/Documentation/vm/hugetlbpage.txt
4013     //      Note 1: different Linux may use different name for this property,
4014     //            e.g. on Redhat AS-3 it is "hugetlb_pool".
4015     //      Note 2: it's possible there's enough physical memory available but
4016     //            they are so fragmented after a long run that they can't
4017     //            coalesce into large pages. Try to reserve large pages when
4018     //            the system is still "fresh".
4019     shm_warning_with_errno("Failed to reserve shared memory.");
4020     return nullptr;
4021   }
4022 
4023   // Attach to the region.
4024   char* addr = shmat_large_pages(shmid, bytes, alignment, req_addr);
4025 
4026   // Remove shmid. If shmat() is successful, the actual shared memory segment
4027   // will be deleted when it's detached by shmdt() or when the process
4028   // terminates. If shmat() is not successful this will remove the shared
4029   // segment immediately.
4030   shmctl(shmid, IPC_RMID, nullptr);
4031 
4032   return addr;
4033 }
4034 
4035 static void log_on_commit_special_failure(char* req_addr, size_t bytes,
4036                                            size_t page_size, int error) {
4037   assert(error == ENOMEM, "Only expect to fail if no memory is available");
4038 
4039   log_info(pagesize)("Failed to reserve and commit memory with given page size. req_addr: " PTR_FORMAT
4040                      " size: " SIZE_FORMAT "%s, page size: " SIZE_FORMAT "%s, (errno = %d)",
4041                      p2i(req_addr), byte_size_in_exact_unit(bytes), exact_unit_for_byte_size(bytes),
4042                      byte_size_in_exact_unit(page_size), exact_unit_for_byte_size(page_size), error);
4043 }
4044 
4045 bool os::Linux::commit_memory_special(size_t bytes,
4046                                       size_t page_size,
4047                                       char* req_addr,
4048                                       bool exec) {
4049   assert(UseLargePages && UseHugeTLBFS, "Should only get here when HugeTLBFS large pages are used");
4050   assert(is_aligned(bytes, page_size), "Unaligned size");
4051   assert(is_aligned(req_addr, page_size), "Unaligned address");
4052   assert(req_addr != nullptr, "Must have a requested address for special mappings");
4053 
4054   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
4055   int flags = MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED;
4056 
4057   // For large pages additional flags are required.
4058   if (page_size > os::vm_page_size()) {
4059     flags |= MAP_HUGETLB | hugetlbfs_page_size_flag(page_size);
4060   }
4061   char* addr = (char*)::mmap(req_addr, bytes, prot, flags, -1, 0);
4062 
4063   if (addr == MAP_FAILED) {
4064     log_on_commit_special_failure(req_addr, bytes, page_size, errno);
4065     return false;
4066   }
4067 
4068   log_debug(pagesize)("Commit special mapping: " PTR_FORMAT ", size=" SIZE_FORMAT "%s, page size="
4069                       SIZE_FORMAT "%s",
4070                       p2i(addr), byte_size_in_exact_unit(bytes),
4071                       exact_unit_for_byte_size(bytes),
4072                       byte_size_in_exact_unit(page_size),
4073                       exact_unit_for_byte_size(page_size));
4074   assert(is_aligned(addr, page_size), "Must be");
4075   return true;
4076 }
4077 
4078 char* os::Linux::reserve_memory_special_huge_tlbfs(size_t bytes,
4079                                                    size_t alignment,
4080                                                    size_t page_size,
4081                                                    char* req_addr,
4082                                                    bool exec) {
4083   assert(UseLargePages && UseHugeTLBFS, "only for Huge TLBFS large pages");
4084   assert(is_aligned(req_addr, alignment), "Must be");
4085   assert(is_aligned(req_addr, page_size), "Must be");
4086   assert(is_aligned(alignment, os::vm_allocation_granularity()), "Must be");
4087   assert(_page_sizes.contains(page_size), "Must be a valid page size");
4088   assert(page_size > os::vm_page_size(), "Must be a large page size");
4089   assert(bytes >= page_size, "Shouldn't allocate large pages for small sizes");
4090 
4091   // We only end up here when at least 1 large page can be used.
4092   // If the size is not a multiple of the large page size, we
4093   // will mix the type of pages used, but in a descending order.
4094   // Start off by reserving a range of the given size that is
4095   // properly aligned. At this point no pages are committed. If
4096   // a requested address is given it will be used and it must be
4097   // aligned to both the large page size and the given alignment.
4098   // The larger of the two will be used.
4099   size_t required_alignment = MAX(page_size, alignment);
4100   char* const aligned_start = anon_mmap_aligned(req_addr, bytes, required_alignment);
4101   if (aligned_start == nullptr) {
4102     return nullptr;
4103   }
4104 
4105   // First commit using large pages.
4106   size_t large_bytes = align_down(bytes, page_size);
4107   bool large_committed = commit_memory_special(large_bytes, page_size, aligned_start, exec);
4108 
4109   if (large_committed && bytes == large_bytes) {
4110     // The size was large page aligned so no additional work is
4111     // needed even if the commit failed.
4112     return aligned_start;
4113   }
4114 
4115   // The requested size requires some small pages as well.
4116   char* small_start = aligned_start + large_bytes;
4117   size_t small_size = bytes - large_bytes;
4118   if (!large_committed) {
4119     // Failed to commit large pages, so we need to unmap the
4120     // reminder of the orinal reservation.
4121     ::munmap(small_start, small_size);
4122     return nullptr;
4123   }
4124 
4125   // Commit the remaining bytes using small pages.
4126   bool small_committed = commit_memory_special(small_size, os::vm_page_size(), small_start, exec);
4127   if (!small_committed) {
4128     // Failed to commit the remaining size, need to unmap
4129     // the large pages part of the reservation.
4130     ::munmap(aligned_start, large_bytes);
4131     return nullptr;
4132   }
4133   return aligned_start;
4134 }
4135 
4136 char* os::pd_reserve_memory_special(size_t bytes, size_t alignment, size_t page_size,
4137                                     char* req_addr, bool exec) {
4138   assert(UseLargePages, "only for large pages");
4139 
4140   char* addr;
4141   if (UseSHM) {
4142     // No support for using specific page sizes with SHM.
4143     addr = os::Linux::reserve_memory_special_shm(bytes, alignment, req_addr, exec);
4144   } else {
4145     assert(UseHugeTLBFS, "must be");
4146     addr = os::Linux::reserve_memory_special_huge_tlbfs(bytes, alignment, page_size, req_addr, exec);
4147   }
4148 
4149   if (addr != nullptr) {
4150     if (UseNUMAInterleaving) {
4151       numa_make_global(addr, bytes);
4152     }
4153   }
4154 
4155   return addr;
4156 }
4157 
4158 bool os::Linux::release_memory_special_shm(char* base, size_t bytes) {
4159   // detaching the SHM segment will also delete it, see reserve_memory_special_shm()
4160   return shmdt(base) == 0;
4161 }
4162 
4163 bool os::Linux::release_memory_special_huge_tlbfs(char* base, size_t bytes) {
4164   return pd_release_memory(base, bytes);
4165 }
4166 
4167 bool os::pd_release_memory_special(char* base, size_t bytes) {
4168   assert(UseLargePages, "only for large pages");
4169   bool res;
4170 
4171   if (UseSHM) {
4172     res = os::Linux::release_memory_special_shm(base, bytes);
4173   } else {
4174     assert(UseHugeTLBFS, "must be");
4175     res = os::Linux::release_memory_special_huge_tlbfs(base, bytes);
4176   }
4177   return res;
4178 }
4179 
4180 size_t os::large_page_size() {
4181   return _large_page_size;
4182 }
4183 
4184 // With SysV SHM the entire memory region must be allocated as shared
4185 // memory.
4186 // HugeTLBFS allows application to commit large page memory on demand.
4187 // However, when committing memory with HugeTLBFS fails, the region
4188 // that was supposed to be committed will lose the old reservation
4189 // and allow other threads to steal that memory region. Because of this
4190 // behavior we can't commit HugeTLBFS memory.
4191 bool os::can_commit_large_page_memory() {
4192   return UseTransparentHugePages;
4193 }
4194 
4195 bool os::can_execute_large_page_memory() {
4196   return UseTransparentHugePages || UseHugeTLBFS;
4197 }
4198 
4199 char* os::pd_attempt_map_memory_to_file_at(char* requested_addr, size_t bytes, int file_desc) {
4200   assert(file_desc >= 0, "file_desc is not valid");
4201   char* result = pd_attempt_reserve_memory_at(requested_addr, bytes, !ExecMem);
4202   if (result != nullptr) {
4203     if (replace_existing_mapping_with_file_mapping(result, bytes, file_desc) == nullptr) {
4204       vm_exit_during_initialization(err_msg("Error in mapping Java heap at the given filesystem directory"));
4205     }
4206   }
4207   return result;
4208 }
4209 
4210 // Reserve memory at an arbitrary address, only if that area is
4211 // available (and not reserved for something else).
4212 
4213 char* os::pd_attempt_reserve_memory_at(char* requested_addr, size_t bytes, bool exec) {
4214   // Assert only that the size is a multiple of the page size, since
4215   // that's all that mmap requires, and since that's all we really know
4216   // about at this low abstraction level.  If we need higher alignment,
4217   // we can either pass an alignment to this method or verify alignment
4218   // in one of the methods further up the call chain.  See bug 5044738.
4219   assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
4220 
4221   // Linux mmap allows caller to pass an address as hint; give it a try first,
4222   // if kernel honors the hint then we can return immediately.
4223   char * addr = anon_mmap(requested_addr, bytes);
4224   if (addr == requested_addr) {
4225     return requested_addr;
4226   }
4227 
4228   if (addr != nullptr) {
4229     // mmap() is successful but it fails to reserve at the requested address
4230     anon_munmap(addr, bytes);
4231   }
4232 
4233   return nullptr;
4234 }
4235 
4236 // Used to convert frequent JVM_Yield() to nops
4237 bool os::dont_yield() {
4238   return DontYieldALot;
4239 }
4240 
4241 // Linux CFS scheduler (since 2.6.23) does not guarantee sched_yield(2) will
4242 // actually give up the CPU. Since skip buddy (v2.6.28):
4243 //
4244 // * Sets the yielding task as skip buddy for current CPU's run queue.
4245 // * Picks next from run queue, if empty, picks a skip buddy (can be the yielding task).
4246 // * Clears skip buddies for this run queue (yielding task no longer a skip buddy).
4247 //
4248 // An alternative is calling os::naked_short_nanosleep with a small number to avoid
4249 // getting re-scheduled immediately.
4250 //
4251 void os::naked_yield() {
4252   sched_yield();
4253 }
4254 
4255 ////////////////////////////////////////////////////////////////////////////////
4256 // thread priority support
4257 
4258 // Note: Normal Linux applications are run with SCHED_OTHER policy. SCHED_OTHER
4259 // only supports dynamic priority, static priority must be zero. For real-time
4260 // applications, Linux supports SCHED_RR which allows static priority (1-99).
4261 // However, for large multi-threaded applications, SCHED_RR is not only slower
4262 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
4263 // of 5 runs - Sep 2005).
4264 //
4265 // The following code actually changes the niceness of kernel-thread/LWP. It
4266 // has an assumption that setpriority() only modifies one kernel-thread/LWP,
4267 // not the entire user process, and user level threads are 1:1 mapped to kernel
4268 // threads. It has always been the case, but could change in the future. For
4269 // this reason, the code should not be used as default (ThreadPriorityPolicy=0).
4270 // It is only used when ThreadPriorityPolicy=1 and may require system level permission
4271 // (e.g., root privilege or CAP_SYS_NICE capability).
4272 
4273 int os::java_to_os_priority[CriticalPriority + 1] = {
4274   19,              // 0 Entry should never be used
4275 
4276    4,              // 1 MinPriority
4277    3,              // 2
4278    2,              // 3
4279 
4280    1,              // 4
4281    0,              // 5 NormPriority
4282   -1,              // 6
4283 
4284   -2,              // 7
4285   -3,              // 8
4286   -4,              // 9 NearMaxPriority
4287 
4288   -5,              // 10 MaxPriority
4289 
4290   -5               // 11 CriticalPriority
4291 };
4292 
4293 static int prio_init() {
4294   if (ThreadPriorityPolicy == 1) {
4295     if (geteuid() != 0) {
4296       if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy) && !FLAG_IS_JIMAGE_RESOURCE(ThreadPriorityPolicy)) {
4297         warning("-XX:ThreadPriorityPolicy=1 may require system level permission, " \
4298                 "e.g., being the root user. If the necessary permission is not " \
4299                 "possessed, changes to priority will be silently ignored.");
4300       }
4301     }
4302   }
4303   if (UseCriticalJavaThreadPriority) {
4304     os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
4305   }
4306   return 0;
4307 }
4308 
4309 OSReturn os::set_native_priority(Thread* thread, int newpri) {
4310   if (!UseThreadPriorities || ThreadPriorityPolicy == 0) return OS_OK;
4311 
4312   int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
4313   return (ret == 0) ? OS_OK : OS_ERR;
4314 }
4315 
4316 OSReturn os::get_native_priority(const Thread* const thread,
4317                                  int *priority_ptr) {
4318   if (!UseThreadPriorities || ThreadPriorityPolicy == 0) {
4319     *priority_ptr = java_to_os_priority[NormPriority];
4320     return OS_OK;
4321   }
4322 
4323   errno = 0;
4324   *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
4325   return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
4326 }
4327 
4328 // This is the fastest way to get thread cpu time on Linux.
4329 // Returns cpu time (user+sys) for any thread, not only for current.
4330 // POSIX compliant clocks are implemented in the kernels 2.6.16+.
4331 // It might work on 2.6.10+ with a special kernel/glibc patch.
4332 // For reference, please, see IEEE Std 1003.1-2004:
4333 //   http://www.unix.org/single_unix_specification
4334 
4335 jlong os::Linux::fast_thread_cpu_time(clockid_t clockid) {
4336   struct timespec tp;
4337   int status = clock_gettime(clockid, &tp);
4338   assert(status == 0, "clock_gettime error: %s", os::strerror(errno));
4339   return (tp.tv_sec * NANOSECS_PER_SEC) + tp.tv_nsec;
4340 }
4341 
4342 // Determine if the vmid is the parent pid for a child in a PID namespace.
4343 // Return the namespace pid if so, otherwise -1.
4344 int os::Linux::get_namespace_pid(int vmid) {
4345   char fname[24];
4346   int retpid = -1;
4347 
4348   snprintf(fname, sizeof(fname), "/proc/%d/status", vmid);
4349   FILE *fp = os::fopen(fname, "r");
4350 
4351   if (fp) {
4352     int pid, nspid;
4353     int ret;
4354     while (!feof(fp) && !ferror(fp)) {
4355       ret = fscanf(fp, "NSpid: %d %d", &pid, &nspid);
4356       if (ret == 1) {
4357         break;
4358       }
4359       if (ret == 2) {
4360         retpid = nspid;
4361         break;
4362       }
4363       for (;;) {
4364         int ch = fgetc(fp);
4365         if (ch == EOF || ch == (int)'\n') break;
4366       }
4367     }
4368     fclose(fp);
4369   }
4370   return retpid;
4371 }
4372 
4373 extern void report_error(char* file_name, int line_no, char* title,
4374                          char* format, ...);
4375 
4376 // Some linux distributions (notably: Alpine Linux) include the
4377 // grsecurity in the kernel. Of particular interest from a JVM perspective
4378 // is PaX (https://pax.grsecurity.net/), which adds some security features
4379 // related to page attributes. Specifically, the MPROTECT PaX functionality
4380 // (https://pax.grsecurity.net/docs/mprotect.txt) prevents dynamic
4381 // code generation by disallowing a (previously) writable page to be
4382 // marked as executable. This is, of course, exactly what HotSpot does
4383 // for both JIT compiled method, as well as for stubs, adapters, etc.
4384 //
4385 // Instead of crashing "lazily" when trying to make a page executable,
4386 // this code probes for the presence of PaX and reports the failure
4387 // eagerly.
4388 static void check_pax(void) {
4389   // Zero doesn't generate code dynamically, so no need to perform the PaX check
4390 #ifndef ZERO
4391   size_t size = os::vm_page_size();
4392 
4393   void* p = ::mmap(nullptr, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
4394   if (p == MAP_FAILED) {
4395     log_debug(os)("os_linux.cpp: check_pax: mmap failed (%s)" , os::strerror(errno));
4396     vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "failed to allocate memory for PaX check.");
4397   }
4398 
4399   int res = ::mprotect(p, size, PROT_READ|PROT_WRITE|PROT_EXEC);
4400   if (res == -1) {
4401     log_debug(os)("os_linux.cpp: check_pax: mprotect failed (%s)" , os::strerror(errno));
4402     vm_exit_during_initialization(
4403       "Failed to mark memory page as executable - check if grsecurity/PaX is enabled");
4404   }
4405 
4406   ::munmap(p, size);
4407 #endif
4408 }
4409 
4410 // this is called _before_ most of the global arguments have been parsed
4411 void os::init(void) {
4412   char dummy;   // used to get a guess on initial stack address
4413 
4414   clock_tics_per_sec = sysconf(_SC_CLK_TCK);
4415   int sys_pg_size = sysconf(_SC_PAGESIZE);
4416   if (sys_pg_size < 0) {
4417     fatal("os_linux.cpp: os::init: sysconf failed (%s)",
4418           os::strerror(errno));
4419   }
4420   size_t page_size = (size_t) sys_pg_size;
4421   OSInfo::set_vm_page_size(page_size);
4422   OSInfo::set_vm_allocation_granularity(page_size);
4423   if (os::vm_page_size() == 0) {
4424     fatal("os_linux.cpp: os::init: OSInfo::set_vm_page_size failed");
4425   }
4426   _page_sizes.add(os::vm_page_size());
4427 
4428   Linux::initialize_system_info();
4429 
4430 #ifdef __GLIBC__
4431   g_mallinfo = CAST_TO_FN_PTR(mallinfo_func_t, dlsym(RTLD_DEFAULT, "mallinfo"));
4432   g_mallinfo2 = CAST_TO_FN_PTR(mallinfo2_func_t, dlsym(RTLD_DEFAULT, "mallinfo2"));
4433   g_malloc_info = CAST_TO_FN_PTR(malloc_info_func_t, dlsym(RTLD_DEFAULT, "malloc_info"));
4434 #endif // __GLIBC__
4435 
4436   os::Linux::CPUPerfTicks pticks;
4437   bool res = os::Linux::get_tick_information(&pticks, -1);
4438 
4439   if (res && pticks.has_steal_ticks) {
4440     has_initial_tick_info = true;
4441     initial_total_ticks = pticks.total;
4442     initial_steal_ticks = pticks.steal;
4443   }
4444 
4445   // _main_thread points to the thread that created/loaded the JVM.
4446   Linux::_main_thread = pthread_self();
4447 
4448   // retrieve entry point for pthread_setname_np
4449   Linux::_pthread_setname_np =
4450     (int(*)(pthread_t, const char*))dlsym(RTLD_DEFAULT, "pthread_setname_np");
4451 
4452   check_pax();
4453 
4454   os::Posix::init();
4455 }
4456 
4457 // To install functions for atexit system call
4458 extern "C" {
4459   static void perfMemory_exit_helper() {
4460     perfMemory_exit();
4461   }
4462 }
4463 
4464 void os::pd_init_container_support() {
4465   OSContainer::init();
4466 }
4467 
4468 void os::Linux::numa_init() {
4469 
4470   // Java can be invoked as
4471   // 1. Without numactl and heap will be allocated/configured on all nodes as
4472   //    per the system policy.
4473   // 2. With numactl --interleave:
4474   //      Use numa_get_interleave_mask(v2) API to get nodes bitmask. The same
4475   //      API for membind case bitmask is reset.
4476   //      Interleave is only hint and Kernel can fallback to other nodes if
4477   //      no memory is available on the target nodes.
4478   // 3. With numactl --membind:
4479   //      Use numa_get_membind(v2) API to get nodes bitmask. The same API for
4480   //      interleave case returns bitmask of all nodes.
4481   // numa_all_nodes_ptr holds bitmask of all nodes.
4482   // numa_get_interleave_mask(v2) and numa_get_membind(v2) APIs returns correct
4483   // bitmask when externally configured to run on all or fewer nodes.
4484 
4485   if (!Linux::libnuma_init()) {
4486     FLAG_SET_ERGO(UseNUMA, false);
4487     FLAG_SET_ERGO(UseNUMAInterleaving, false); // Also depends on libnuma.
4488   } else {
4489     if ((Linux::numa_max_node() < 1) || Linux::is_bound_to_single_node()) {
4490       // If there's only one node (they start from 0) or if the process
4491       // is bound explicitly to a single node using membind, disable NUMA
4492       UseNUMA = false;
4493     } else {
4494       LogTarget(Info,os) log;
4495       LogStream ls(log);
4496 
4497       Linux::set_configured_numa_policy(Linux::identify_numa_policy());
4498 
4499       struct bitmask* bmp = Linux::_numa_membind_bitmask;
4500       const char* numa_mode = "membind";
4501 
4502       if (Linux::is_running_in_interleave_mode()) {
4503         bmp = Linux::_numa_interleave_bitmask;
4504         numa_mode = "interleave";
4505       }
4506 
4507       ls.print("UseNUMA is enabled and invoked in '%s' mode."
4508                " Heap will be configured using NUMA memory nodes:", numa_mode);
4509 
4510       for (int node = 0; node <= Linux::numa_max_node(); node++) {
4511         if (Linux::_numa_bitmask_isbitset(bmp, node)) {
4512           ls.print(" %d", node);
4513         }
4514       }
4515     }
4516   }
4517 
4518   // When NUMA requested, not-NUMA-aware allocations default to interleaving.
4519   if (UseNUMA && !UseNUMAInterleaving) {
4520     FLAG_SET_ERGO_IF_DEFAULT(UseNUMAInterleaving, true);
4521   }
4522 
4523   if (UseParallelGC && UseNUMA && UseLargePages && !can_commit_large_page_memory()) {
4524     // With SHM and HugeTLBFS large pages we cannot uncommit a page, so there's no way
4525     // we can make the adaptive lgrp chunk resizing work. If the user specified both
4526     // UseNUMA and UseLargePages (or UseSHM/UseHugeTLBFS) on the command line - warn
4527     // and disable adaptive resizing.
4528     if (UseAdaptiveSizePolicy || UseAdaptiveNUMAChunkSizing) {
4529       warning("UseNUMA is not fully compatible with SHM/HugeTLBFS large pages, "
4530               "disabling adaptive resizing (-XX:-UseAdaptiveSizePolicy -XX:-UseAdaptiveNUMAChunkSizing)");
4531       UseAdaptiveSizePolicy = false;
4532       UseAdaptiveNUMAChunkSizing = false;
4533     }
4534   }
4535 }
4536 
4537 #if defined(IA32) && !defined(ZERO)
4538 /*
4539  * Work-around (execute code at a high address) for broken NX emulation using CS limit,
4540  * Red Hat patch "Exec-Shield" (IA32 only).
4541  *
4542  * Map and execute at a high VA to prevent CS lazy updates race with SMP MM
4543  * invalidation.Further code generation by the JVM will no longer cause CS limit
4544  * updates.
4545  *
4546  * Affects IA32: RHEL 5 & 6, Ubuntu 10.04 (LTS), 10.10, 11.04, 11.10, 12.04.
4547  * @see JDK-8023956
4548  */
4549 static void workaround_expand_exec_shield_cs_limit() {
4550   assert(os::Linux::initial_thread_stack_bottom() != nullptr, "sanity");
4551   size_t page_size = os::vm_page_size();
4552 
4553   /*
4554    * JDK-8197429
4555    *
4556    * Expand the stack mapping to the end of the initial stack before
4557    * attempting to install the codebuf.  This is needed because newer
4558    * Linux kernels impose a distance of a megabyte between stack
4559    * memory and other memory regions.  If we try to install the
4560    * codebuf before expanding the stack the installation will appear
4561    * to succeed but we'll get a segfault later if we expand the stack
4562    * in Java code.
4563    *
4564    */
4565   if (os::is_primordial_thread()) {
4566     address limit = os::Linux::initial_thread_stack_bottom();
4567     if (! DisablePrimordialThreadGuardPages) {
4568       limit += StackOverflow::stack_red_zone_size() +
4569                StackOverflow::stack_yellow_zone_size();
4570     }
4571     os::Linux::expand_stack_to(limit);
4572   }
4573 
4574   /*
4575    * Take the highest VA the OS will give us and exec
4576    *
4577    * Although using -(pagesz) as mmap hint works on newer kernel as you would
4578    * think, older variants affected by this work-around don't (search forward only).
4579    *
4580    * On the affected distributions, we understand the memory layout to be:
4581    *
4582    *   TASK_LIMIT= 3G, main stack base close to TASK_LIMT.
4583    *
4584    * A few pages south main stack will do it.
4585    *
4586    * If we are embedded in an app other than launcher (initial != main stack),
4587    * we don't have much control or understanding of the address space, just let it slide.
4588    */
4589   char* hint = (char*)(os::Linux::initial_thread_stack_bottom() -
4590                        (StackOverflow::stack_guard_zone_size() + page_size));
4591   char* codebuf = os::attempt_reserve_memory_at(hint, page_size);
4592 
4593   if (codebuf == nullptr) {
4594     // JDK-8197429: There may be a stack gap of one megabyte between
4595     // the limit of the stack and the nearest memory region: this is a
4596     // Linux kernel workaround for CVE-2017-1000364.  If we failed to
4597     // map our codebuf, try again at an address one megabyte lower.
4598     hint -= 1 * M;
4599     codebuf = os::attempt_reserve_memory_at(hint, page_size);
4600   }
4601 
4602   if ((codebuf == nullptr) || (!os::commit_memory(codebuf, page_size, true))) {
4603     return; // No matter, we tried, best effort.
4604   }
4605 
4606   MemTracker::record_virtual_memory_type((address)codebuf, mtInternal);
4607 
4608   log_info(os)("[CS limit NX emulation work-around, exec code at: %p]", codebuf);
4609 
4610   // Some code to exec: the 'ret' instruction
4611   codebuf[0] = 0xC3;
4612 
4613   // Call the code in the codebuf
4614   __asm__ volatile("call *%0" : : "r"(codebuf));
4615 
4616   // keep the page mapped so CS limit isn't reduced.
4617 }
4618 #endif // defined(IA32) && !defined(ZERO)
4619 
4620 // this is called _after_ the global arguments have been parsed
4621 jint os::init_2(void) {
4622 
4623   // This could be set after os::Posix::init() but all platforms
4624   // have to set it the same so we have to mirror Solaris.
4625   DEBUG_ONLY(os::set_mutex_init_done();)
4626 
4627   os::Posix::init_2();
4628 
4629   Linux::fast_thread_clock_init();
4630 
4631   if (PosixSignals::init() == JNI_ERR) {
4632     return JNI_ERR;
4633   }
4634 
4635   // Check and sets minimum stack sizes against command line options
4636   if (set_minimum_stack_sizes() == JNI_ERR) {
4637     return JNI_ERR;
4638   }
4639 
4640 #if defined(IA32) && !defined(ZERO)
4641   // Need to ensure we've determined the process's initial stack to
4642   // perform the workaround
4643   Linux::capture_initial_stack(JavaThread::stack_size_at_create());
4644   workaround_expand_exec_shield_cs_limit();
4645 #else
4646   suppress_primordial_thread_resolution = Arguments::created_by_java_launcher();
4647   if (!suppress_primordial_thread_resolution) {
4648     Linux::capture_initial_stack(JavaThread::stack_size_at_create());
4649   }
4650 #endif
4651 
4652   Linux::libpthread_init();
4653   Linux::sched_getcpu_init();
4654   log_info(os)("HotSpot is running with %s, %s",
4655                Linux::libc_version(), Linux::libpthread_version());
4656 
4657 #ifdef __GLIBC__
4658   // Check if we need to adjust the stack size for glibc guard pages.
4659   init_adjust_stacksize_for_guard_pages();
4660 #endif
4661 
4662   if (UseNUMA || UseNUMAInterleaving) {
4663     Linux::numa_init();
4664   }
4665 
4666   if (MaxFDLimit) {
4667     // set the number of file descriptors to max. print out error
4668     // if getrlimit/setrlimit fails but continue regardless.
4669     struct rlimit nbr_files;
4670     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
4671     if (status != 0) {
4672       log_info(os)("os::init_2 getrlimit failed: %s", os::strerror(errno));
4673     } else {
4674       nbr_files.rlim_cur = nbr_files.rlim_max;
4675       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
4676       if (status != 0) {
4677         log_info(os)("os::init_2 setrlimit failed: %s", os::strerror(errno));
4678       }
4679     }
4680   }
4681 
4682   // at-exit methods are called in the reverse order of their registration.
4683   // atexit functions are called on return from main or as a result of a
4684   // call to exit(3C). There can be only 32 of these functions registered
4685   // and atexit() does not set errno.
4686 
4687   if (PerfAllowAtExitRegistration) {
4688     // only register atexit functions if PerfAllowAtExitRegistration is set.
4689     // atexit functions can be delayed until process exit time, which
4690     // can be problematic for embedded VM situations. Embedded VMs should
4691     // call DestroyJavaVM() to assure that VM resources are released.
4692 
4693     // note: perfMemory_exit_helper atexit function may be removed in
4694     // the future if the appropriate cleanup code can be added to the
4695     // VM_Exit VMOperation's doit method.
4696     if (atexit(perfMemory_exit_helper) != 0) {
4697       warning("os::init_2 atexit(perfMemory_exit_helper) failed");
4698     }
4699   }
4700 
4701   // initialize thread priority policy
4702   prio_init();
4703 
4704   if (!FLAG_IS_DEFAULT(AllocateHeapAt)) {
4705     set_coredump_filter(DAX_SHARED_BIT);
4706   }
4707 
4708   if (DumpPrivateMappingsInCore) {
4709     set_coredump_filter(FILE_BACKED_PVT_BIT);
4710   }
4711 
4712   if (DumpSharedMappingsInCore) {
4713     set_coredump_filter(FILE_BACKED_SHARED_BIT);
4714   }
4715 
4716   if (DumpPerfMapAtExit && FLAG_IS_DEFAULT(UseCodeCacheFlushing)) {
4717     // Disable code cache flushing to ensure the map file written at
4718     // exit contains all nmethods generated during execution.
4719     FLAG_SET_DEFAULT(UseCodeCacheFlushing, false);
4720   }
4721 
4722   // Override the timer slack value if needed. The adjustment for the main
4723   // thread will establish the setting for child threads, which would be
4724   // most threads in JDK/JVM.
4725   if (TimerSlack >= 0) {
4726     if (prctl(PR_SET_TIMERSLACK, TimerSlack) < 0) {
4727       vm_exit_during_initialization("Setting timer slack failed: %s", os::strerror(errno));
4728     }
4729   }
4730 
4731   return JNI_OK;
4732 }
4733 
4734 // older glibc versions don't have this macro (which expands to
4735 // an optimized bit-counting function) so we have to roll our own
4736 #ifndef CPU_COUNT
4737 
4738 static int _cpu_count(const cpu_set_t* cpus) {
4739   int count = 0;
4740   // only look up to the number of configured processors
4741   for (int i = 0; i < os::processor_count(); i++) {
4742     if (CPU_ISSET(i, cpus)) {
4743       count++;
4744     }
4745   }
4746   return count;
4747 }
4748 
4749 #define CPU_COUNT(cpus) _cpu_count(cpus)
4750 
4751 #endif // CPU_COUNT
4752 
4753 // Get the current number of available processors for this process.
4754 // This value can change at any time during a process's lifetime.
4755 // sched_getaffinity gives an accurate answer as it accounts for cpusets.
4756 // If it appears there may be more than 1024 processors then we do a
4757 // dynamic check - see 6515172 for details.
4758 // If anything goes wrong we fallback to returning the number of online
4759 // processors - which can be greater than the number available to the process.
4760 static int get_active_processor_count() {
4761   // Note: keep this function, with its CPU_xx macros, *outside* the os namespace (see JDK-8289477).
4762   cpu_set_t cpus;  // can represent at most 1024 (CPU_SETSIZE) processors
4763   cpu_set_t* cpus_p = &cpus;
4764   int cpus_size = sizeof(cpu_set_t);
4765 
4766   int configured_cpus = os::processor_count();  // upper bound on available cpus
4767   int cpu_count = 0;
4768 
4769 // old build platforms may not support dynamic cpu sets
4770 #ifdef CPU_ALLOC
4771 
4772   // To enable easy testing of the dynamic path on different platforms we
4773   // introduce a diagnostic flag: UseCpuAllocPath
4774   if (configured_cpus >= CPU_SETSIZE || UseCpuAllocPath) {
4775     // kernel may use a mask bigger than cpu_set_t
4776     log_trace(os)("active_processor_count: using dynamic path %s"
4777                   "- configured processors: %d",
4778                   UseCpuAllocPath ? "(forced) " : "",
4779                   configured_cpus);
4780     cpus_p = CPU_ALLOC(configured_cpus);
4781     if (cpus_p != nullptr) {
4782       cpus_size = CPU_ALLOC_SIZE(configured_cpus);
4783       // zero it just to be safe
4784       CPU_ZERO_S(cpus_size, cpus_p);
4785     }
4786     else {
4787        // failed to allocate so fallback to online cpus
4788        int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN);
4789        log_trace(os)("active_processor_count: "
4790                      "CPU_ALLOC failed (%s) - using "
4791                      "online processor count: %d",
4792                      os::strerror(errno), online_cpus);
4793        return online_cpus;
4794     }
4795   }
4796   else {
4797     log_trace(os)("active_processor_count: using static path - configured processors: %d",
4798                   configured_cpus);
4799   }
4800 #else // CPU_ALLOC
4801 // these stubs won't be executed
4802 #define CPU_COUNT_S(size, cpus) -1
4803 #define CPU_FREE(cpus)
4804 
4805   log_trace(os)("active_processor_count: only static path available - configured processors: %d",
4806                 configured_cpus);
4807 #endif // CPU_ALLOC
4808 
4809   // pid 0 means the current thread - which we have to assume represents the process
4810   if (sched_getaffinity(0, cpus_size, cpus_p) == 0) {
4811     if (cpus_p != &cpus) { // can only be true when CPU_ALLOC used
4812       cpu_count = CPU_COUNT_S(cpus_size, cpus_p);
4813     }
4814     else {
4815       cpu_count = CPU_COUNT(cpus_p);
4816     }
4817     log_trace(os)("active_processor_count: sched_getaffinity processor count: %d", cpu_count);
4818   }
4819   else {
4820     cpu_count = ::sysconf(_SC_NPROCESSORS_ONLN);
4821     warning("sched_getaffinity failed (%s)- using online processor count (%d) "
4822             "which may exceed available processors", os::strerror(errno), cpu_count);
4823   }
4824 
4825   if (cpus_p != &cpus) { // can only be true when CPU_ALLOC used
4826     CPU_FREE(cpus_p);
4827   }
4828 
4829   assert(cpu_count > 0 && cpu_count <= os::processor_count(), "sanity check");
4830   return cpu_count;
4831 }
4832 
4833 int os::Linux::active_processor_count() {
4834   return get_active_processor_count();
4835 }
4836 
4837 // Determine the active processor count from one of
4838 // three different sources:
4839 //
4840 // 1. User option -XX:ActiveProcessorCount
4841 // 2. kernel os calls (sched_getaffinity or sysconf(_SC_NPROCESSORS_ONLN)
4842 // 3. extracted from cgroup cpu subsystem (shares and quotas)
4843 //
4844 // Option 1, if specified, will always override.
4845 // If the cgroup subsystem is active and configured, we
4846 // will return the min of the cgroup and option 2 results.
4847 // This is required since tools, such as numactl, that
4848 // alter cpu affinity do not update cgroup subsystem
4849 // cpuset configuration files.
4850 int os::active_processor_count() {
4851   // User has overridden the number of active processors
4852   if (ActiveProcessorCount > 0) {
4853     log_trace(os)("active_processor_count: "
4854                   "active processor count set by user : %d",
4855                   ActiveProcessorCount);
4856     return ActiveProcessorCount;
4857   }
4858 
4859   int active_cpus;
4860   if (OSContainer::is_containerized()) {
4861     active_cpus = OSContainer::active_processor_count();
4862     log_trace(os)("active_processor_count: determined by OSContainer: %d",
4863                    active_cpus);
4864   } else {
4865     active_cpus = os::Linux::active_processor_count();
4866   }
4867 
4868   return active_cpus;
4869 }
4870 
4871 static bool should_warn_invalid_processor_id() {
4872   if (os::processor_count() == 1) {
4873     // Don't warn if we only have one processor
4874     return false;
4875   }
4876 
4877   static volatile int warn_once = 1;
4878 
4879   if (Atomic::load(&warn_once) == 0 ||
4880       Atomic::xchg(&warn_once, 0) == 0) {
4881     // Don't warn more than once
4882     return false;
4883   }
4884 
4885   return true;
4886 }
4887 
4888 uint os::processor_id() {
4889   const int id = Linux::sched_getcpu();
4890 
4891   if (id < processor_count()) {
4892     return (uint)id;
4893   }
4894 
4895   // Some environments (e.g. openvz containers and the rr debugger) incorrectly
4896   // report a processor id that is higher than the number of processors available.
4897   // This is problematic, for example, when implementing CPU-local data structures,
4898   // where the processor id is used to index into an array of length processor_count().
4899   // If this happens we return 0 here. This is is safe since we always have at least
4900   // one processor, but it's not optimal for performance if we're actually executing
4901   // in an environment with more than one processor.
4902   if (should_warn_invalid_processor_id()) {
4903     log_warning(os)("Invalid processor id reported by the operating system "
4904                     "(got processor id %d, valid processor id range is 0-%d)",
4905                     id, processor_count() - 1);
4906     log_warning(os)("Falling back to assuming processor id is 0. "
4907                     "This could have a negative impact on performance.");
4908   }
4909 
4910   return 0;
4911 }
4912 
4913 void os::set_native_thread_name(const char *name) {
4914   if (Linux::_pthread_setname_np) {
4915     char buf [16]; // according to glibc manpage, 16 chars incl. '/0'
4916     snprintf(buf, sizeof(buf), "%s", name);
4917     buf[sizeof(buf) - 1] = '\0';
4918     const int rc = Linux::_pthread_setname_np(pthread_self(), buf);
4919     // ERANGE should not happen; all other errors should just be ignored.
4920     assert(rc != ERANGE, "pthread_setname_np failed");
4921   }
4922 }
4923 
4924 ////////////////////////////////////////////////////////////////////////////////
4925 // debug support
4926 
4927 bool os::find(address addr, outputStream* st) {
4928   Dl_info dlinfo;
4929   memset(&dlinfo, 0, sizeof(dlinfo));
4930   if (dladdr(addr, &dlinfo) != 0) {
4931     st->print(PTR_FORMAT ": ", p2i(addr));
4932     if (dlinfo.dli_sname != nullptr && dlinfo.dli_saddr != nullptr) {
4933       st->print("%s+" PTR_FORMAT, dlinfo.dli_sname,
4934                 p2i(addr) - p2i(dlinfo.dli_saddr));
4935     } else if (dlinfo.dli_fbase != nullptr) {
4936       st->print("<offset " PTR_FORMAT ">", p2i(addr) - p2i(dlinfo.dli_fbase));
4937     } else {
4938       st->print("<absolute address>");
4939     }
4940     if (dlinfo.dli_fname != nullptr) {
4941       st->print(" in %s", dlinfo.dli_fname);
4942     }
4943     if (dlinfo.dli_fbase != nullptr) {
4944       st->print(" at " PTR_FORMAT, p2i(dlinfo.dli_fbase));
4945     }
4946     st->cr();
4947 
4948     if (Verbose) {
4949       // decode some bytes around the PC
4950       address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
4951       address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
4952       address       lowest = (address) dlinfo.dli_sname;
4953       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
4954       if (begin < lowest)  begin = lowest;
4955       Dl_info dlinfo2;
4956       if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
4957           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) {
4958         end = (address) dlinfo2.dli_saddr;
4959       }
4960       Disassembler::decode(begin, end, st);
4961     }
4962     return true;
4963   }
4964   return false;
4965 }
4966 
4967 ////////////////////////////////////////////////////////////////////////////////
4968 // misc
4969 
4970 // This does not do anything on Linux. This is basically a hook for being
4971 // able to use structured exception handling (thread-local exception filters)
4972 // on, e.g., Win32.
4973 void
4974 os::os_exception_wrapper(java_call_t f, JavaValue* value, const methodHandle& method,
4975                          JavaCallArguments* args, JavaThread* thread) {
4976   f(value, method, args, thread);
4977 }
4978 
4979 // This code originates from JDK's sysOpen and open64_w
4980 // from src/solaris/hpi/src/system_md.c
4981 
4982 int os::open(const char *path, int oflag, int mode) {
4983   if (strlen(path) > MAX_PATH - 1) {
4984     errno = ENAMETOOLONG;
4985     return -1;
4986   }
4987 
4988   // All file descriptors that are opened in the Java process and not
4989   // specifically destined for a subprocess should have the close-on-exec
4990   // flag set.  If we don't set it, then careless 3rd party native code
4991   // might fork and exec without closing all appropriate file descriptors
4992   // (e.g. as we do in closeDescriptors in UNIXProcess.c), and this in
4993   // turn might:
4994   //
4995   // - cause end-of-file to fail to be detected on some file
4996   //   descriptors, resulting in mysterious hangs, or
4997   //
4998   // - might cause an fopen in the subprocess to fail on a system
4999   //   suffering from bug 1085341.
5000   //
5001   // (Yes, the default setting of the close-on-exec flag is a Unix
5002   // design flaw)
5003   //
5004   // See:
5005   // 1085341: 32-bit stdio routines should support file descriptors >255
5006   // 4843136: (process) pipe file descriptor from Runtime.exec not being closed
5007   // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
5008   //
5009   // Modern Linux kernels (after 2.6.23 2007) support O_CLOEXEC with open().
5010   // O_CLOEXEC is preferable to using FD_CLOEXEC on an open file descriptor
5011   // because it saves a system call and removes a small window where the flag
5012   // is unset.  On ancient Linux kernels the O_CLOEXEC flag will be ignored
5013   // and we fall back to using FD_CLOEXEC (see below).
5014 #ifdef O_CLOEXEC
5015   oflag |= O_CLOEXEC;
5016 #endif
5017 
5018   int fd = ::open(path, oflag, mode);
5019   if (fd == -1) return -1;
5020 
5021   //If the open succeeded, the file might still be a directory
5022   {
5023     struct stat buf;
5024     int ret = ::fstat(fd, &buf);
5025     int st_mode = buf.st_mode;
5026 
5027     if (ret != -1) {
5028       if ((st_mode & S_IFMT) == S_IFDIR) {
5029         errno = EISDIR;
5030         ::close(fd);
5031         return -1;
5032       }
5033     } else {
5034       ::close(fd);
5035       return -1;
5036     }
5037   }
5038 
5039 #ifdef FD_CLOEXEC
5040   // Validate that the use of the O_CLOEXEC flag on open above worked.
5041   // With recent kernels, we will perform this check exactly once.
5042   static sig_atomic_t O_CLOEXEC_is_known_to_work = 0;
5043   if (!O_CLOEXEC_is_known_to_work) {
5044     int flags = ::fcntl(fd, F_GETFD);
5045     if (flags != -1) {
5046       if ((flags & FD_CLOEXEC) != 0)
5047         O_CLOEXEC_is_known_to_work = 1;
5048       else
5049         ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
5050     }
5051   }
5052 #endif
5053 
5054   return fd;
5055 }
5056 
5057 
5058 // create binary file, rewriting existing file if required
5059 int os::create_binary_file(const char* path, bool rewrite_existing) {
5060   int oflags = O_WRONLY | O_CREAT;
5061   oflags |= rewrite_existing ? O_TRUNC : O_EXCL;
5062   return ::open(path, oflags, S_IREAD | S_IWRITE);
5063 }
5064 
5065 // return current position of file pointer
5066 jlong os::current_file_offset(int fd) {
5067   return (jlong)::lseek(fd, (off_t)0, SEEK_CUR);
5068 }
5069 
5070 // move file pointer to the specified offset
5071 jlong os::seek_to_file_offset(int fd, jlong offset) {
5072   return (jlong)::lseek(fd, (off_t)offset, SEEK_SET);
5073 }
5074 
5075 // Map a block of memory.
5076 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
5077                         char *addr, size_t bytes, bool read_only,
5078                         bool allow_exec) {
5079   int prot;
5080   int flags = MAP_PRIVATE;
5081 
5082   if (read_only) {
5083     prot = PROT_READ;
5084   } else {
5085     prot = PROT_READ | PROT_WRITE;
5086   }
5087 
5088   if (allow_exec) {
5089     prot |= PROT_EXEC;
5090   }
5091 
5092   if (addr != nullptr) {
5093     flags |= MAP_FIXED;
5094   }
5095 
5096   char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
5097                                      fd, file_offset);
5098   if (mapped_address == MAP_FAILED) {
5099     return nullptr;
5100   }
5101   return mapped_address;
5102 }
5103 
5104 
5105 // Remap a block of memory.
5106 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
5107                           char *addr, size_t bytes, bool read_only,
5108                           bool allow_exec) {
5109   // same as map_memory() on this OS
5110   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
5111                         allow_exec);
5112 }
5113 
5114 
5115 // Unmap a block of memory.
5116 bool os::pd_unmap_memory(char* addr, size_t bytes) {
5117   return munmap(addr, bytes) == 0;
5118 }
5119 
5120 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time);
5121 
5122 static jlong fast_cpu_time(Thread *thread) {
5123     clockid_t clockid;
5124     int rc = os::Linux::pthread_getcpuclockid(thread->osthread()->pthread_id(),
5125                                               &clockid);
5126     if (rc == 0) {
5127       return os::Linux::fast_thread_cpu_time(clockid);
5128     } else {
5129       // It's possible to encounter a terminated native thread that failed
5130       // to detach itself from the VM - which should result in ESRCH.
5131       assert_status(rc == ESRCH, rc, "pthread_getcpuclockid failed");
5132       return -1;
5133     }
5134 }
5135 
5136 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
5137 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
5138 // of a thread.
5139 //
5140 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
5141 // the fast estimate available on the platform.
5142 
5143 jlong os::current_thread_cpu_time() {
5144   if (os::Linux::supports_fast_thread_cpu_time()) {
5145     return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
5146   } else {
5147     // return user + sys since the cost is the same
5148     return slow_thread_cpu_time(Thread::current(), true /* user + sys */);
5149   }
5150 }
5151 
5152 jlong os::thread_cpu_time(Thread* thread) {
5153   // consistent with what current_thread_cpu_time() returns
5154   if (os::Linux::supports_fast_thread_cpu_time()) {
5155     return fast_cpu_time(thread);
5156   } else {
5157     return slow_thread_cpu_time(thread, true /* user + sys */);
5158   }
5159 }
5160 
5161 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
5162   if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {
5163     return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
5164   } else {
5165     return slow_thread_cpu_time(Thread::current(), user_sys_cpu_time);
5166   }
5167 }
5168 
5169 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
5170   if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {
5171     return fast_cpu_time(thread);
5172   } else {
5173     return slow_thread_cpu_time(thread, user_sys_cpu_time);
5174   }
5175 }
5176 
5177 //  -1 on error.
5178 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
5179   pid_t  tid = thread->osthread()->thread_id();
5180   char *s;
5181   char stat[2048];
5182   int statlen;
5183   char proc_name[64];
5184   int count;
5185   long sys_time, user_time;
5186   char cdummy;
5187   int idummy;
5188   long ldummy;
5189   FILE *fp;
5190 
5191   snprintf(proc_name, 64, "/proc/self/task/%d/stat", tid);
5192   fp = os::fopen(proc_name, "r");
5193   if (fp == nullptr) return -1;
5194   statlen = fread(stat, 1, 2047, fp);
5195   stat[statlen] = '\0';
5196   fclose(fp);
5197 
5198   // Skip pid and the command string. Note that we could be dealing with
5199   // weird command names, e.g. user could decide to rename java launcher
5200   // to "java 1.4.2 :)", then the stat file would look like
5201   //                1234 (java 1.4.2 :)) R ... ...
5202   // We don't really need to know the command string, just find the last
5203   // occurrence of ")" and then start parsing from there. See bug 4726580.
5204   s = strrchr(stat, ')');
5205   if (s == nullptr) return -1;
5206 
5207   // Skip blank chars
5208   do { s++; } while (s && isspace(*s));
5209 
5210   count = sscanf(s,"%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu",
5211                  &cdummy, &idummy, &idummy, &idummy, &idummy, &idummy,
5212                  &ldummy, &ldummy, &ldummy, &ldummy, &ldummy,
5213                  &user_time, &sys_time);
5214   if (count != 13) return -1;
5215   if (user_sys_cpu_time) {
5216     return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec);
5217   } else {
5218     return (jlong)user_time * (1000000000 / clock_tics_per_sec);
5219   }
5220 }
5221 
5222 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5223   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
5224   info_ptr->may_skip_backward = false;     // elapsed time not wall time
5225   info_ptr->may_skip_forward = false;      // elapsed time not wall time
5226   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
5227 }
5228 
5229 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5230   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
5231   info_ptr->may_skip_backward = false;     // elapsed time not wall time
5232   info_ptr->may_skip_forward = false;      // elapsed time not wall time
5233   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
5234 }
5235 
5236 bool os::is_thread_cpu_time_supported() {
5237   return true;
5238 }
5239 
5240 // System loadavg support.  Returns -1 if load average cannot be obtained.
5241 // Linux doesn't yet have a (official) notion of processor sets,
5242 // so just return the system wide load average.
5243 int os::loadavg(double loadavg[], int nelem) {
5244   return ::getloadavg(loadavg, nelem);
5245 }
5246 
5247 // Get the default path to the core file
5248 // Returns the length of the string
5249 int os::get_core_path(char* buffer, size_t bufferSize) {
5250   /*
5251    * Max length of /proc/sys/kernel/core_pattern is 128 characters.
5252    * See https://www.kernel.org/doc/Documentation/sysctl/kernel.txt
5253    */
5254   const int core_pattern_len = 129;
5255   char core_pattern[core_pattern_len] = {0};
5256 
5257   int core_pattern_file = ::open("/proc/sys/kernel/core_pattern", O_RDONLY);
5258   if (core_pattern_file == -1) {
5259     return -1;
5260   }
5261 
5262   ssize_t ret = ::read(core_pattern_file, core_pattern, core_pattern_len);
5263   ::close(core_pattern_file);
5264   if (ret <= 0 || ret >= core_pattern_len || core_pattern[0] == '\n') {
5265     return -1;
5266   }
5267   if (core_pattern[ret-1] == '\n') {
5268     core_pattern[ret-1] = '\0';
5269   } else {
5270     core_pattern[ret] = '\0';
5271   }
5272 
5273   // Replace the %p in the core pattern with the process id. NOTE: we do this
5274   // only if the pattern doesn't start with "|", and we support only one %p in
5275   // the pattern.
5276   char *pid_pos = strstr(core_pattern, "%p");
5277   const char* tail = (pid_pos != nullptr) ? (pid_pos + 2) : "";  // skip over the "%p"
5278   int written;
5279 
5280   if (core_pattern[0] == '/') {
5281     if (pid_pos != nullptr) {
5282       *pid_pos = '\0';
5283       written = jio_snprintf(buffer, bufferSize, "%s%d%s", core_pattern,
5284                              current_process_id(), tail);
5285     } else {
5286       written = jio_snprintf(buffer, bufferSize, "%s", core_pattern);
5287     }
5288   } else {
5289     char cwd[PATH_MAX];
5290 
5291     const char* p = get_current_directory(cwd, PATH_MAX);
5292     if (p == nullptr) {
5293       return -1;
5294     }
5295 
5296     if (core_pattern[0] == '|') {
5297       written = jio_snprintf(buffer, bufferSize,
5298                              "\"%s\" (or dumping to %s/core.%d)",
5299                              &core_pattern[1], p, current_process_id());
5300     } else if (pid_pos != nullptr) {
5301       *pid_pos = '\0';
5302       written = jio_snprintf(buffer, bufferSize, "%s/%s%d%s", p, core_pattern,
5303                              current_process_id(), tail);
5304     } else {
5305       written = jio_snprintf(buffer, bufferSize, "%s/%s", p, core_pattern);
5306     }
5307   }
5308 
5309   if (written < 0) {
5310     return -1;
5311   }
5312 
5313   if (((size_t)written < bufferSize) && (pid_pos == nullptr) && (core_pattern[0] != '|')) {
5314     int core_uses_pid_file = ::open("/proc/sys/kernel/core_uses_pid", O_RDONLY);
5315 
5316     if (core_uses_pid_file != -1) {
5317       char core_uses_pid = 0;
5318       ssize_t ret = ::read(core_uses_pid_file, &core_uses_pid, 1);
5319       ::close(core_uses_pid_file);
5320 
5321       if (core_uses_pid == '1') {
5322         jio_snprintf(buffer + written, bufferSize - written,
5323                                           ".%d", current_process_id());
5324       }
5325     }
5326   }
5327 
5328   return strlen(buffer);
5329 }
5330 
5331 bool os::start_debugging(char *buf, int buflen) {
5332   int len = (int)strlen(buf);
5333   char *p = &buf[len];
5334 
5335   jio_snprintf(p, buflen-len,
5336                "\n\n"
5337                "Do you want to debug the problem?\n\n"
5338                "To debug, run 'gdb /proc/%d/exe %d'; then switch to thread " UINTX_FORMAT " (" INTPTR_FORMAT ")\n"
5339                "Enter 'yes' to launch gdb automatically (PATH must include gdb)\n"
5340                "Otherwise, press RETURN to abort...",
5341                os::current_process_id(), os::current_process_id(),
5342                os::current_thread_id(), os::current_thread_id());
5343 
5344   bool yes = os::message_box("Unexpected Error", buf);
5345 
5346   if (yes) {
5347     // yes, user asked VM to launch debugger
5348     jio_snprintf(buf, sizeof(char)*buflen, "gdb /proc/%d/exe %d",
5349                  os::current_process_id(), os::current_process_id());
5350 
5351     os::fork_and_exec(buf);
5352     yes = false;
5353   }
5354   return yes;
5355 }
5356 
5357 
5358 // Java/Compiler thread:
5359 //
5360 //   Low memory addresses
5361 // P0 +------------------------+
5362 //    |                        |\  Java thread created by VM does not have glibc
5363 //    |    glibc guard page    | - guard page, attached Java thread usually has
5364 //    |                        |/  1 glibc guard page.
5365 // P1 +------------------------+ Thread::stack_base() - Thread::stack_size()
5366 //    |                        |\
5367 //    |  HotSpot Guard Pages   | - red, yellow and reserved pages
5368 //    |                        |/
5369 //    +------------------------+ StackOverflow::stack_reserved_zone_base()
5370 //    |                        |\
5371 //    |      Normal Stack      | -
5372 //    |                        |/
5373 // P2 +------------------------+ Thread::stack_base()
5374 //
5375 // Non-Java thread:
5376 //
5377 //   Low memory addresses
5378 // P0 +------------------------+
5379 //    |                        |\
5380 //    |  glibc guard page      | - usually 1 page
5381 //    |                        |/
5382 // P1 +------------------------+ Thread::stack_base() - Thread::stack_size()
5383 //    |                        |\
5384 //    |      Normal Stack      | -
5385 //    |                        |/
5386 // P2 +------------------------+ Thread::stack_base()
5387 //
5388 // ** P1 (aka bottom) and size (P2 = P1 - size) are the address and stack size
5389 //    returned from pthread_attr_getstack().
5390 // ** If adjustStackSizeForGuardPages() is true the guard pages have been taken
5391 //    out of the stack size given in pthread_attr. We work around this for
5392 //    threads created by the VM. We adjust bottom to be P1 and size accordingly.
5393 //
5394 #ifndef ZERO
5395 static void current_stack_region(address * bottom, size_t * size) {
5396   if (os::is_primordial_thread()) {
5397     // primordial thread needs special handling because pthread_getattr_np()
5398     // may return bogus value.
5399     *bottom = os::Linux::initial_thread_stack_bottom();
5400     *size   = os::Linux::initial_thread_stack_size();
5401   } else {
5402     pthread_attr_t attr;
5403 
5404     int rslt = pthread_getattr_np(pthread_self(), &attr);
5405 
5406     // JVM needs to know exact stack location, abort if it fails
5407     if (rslt != 0) {
5408       if (rslt == ENOMEM) {
5409         vm_exit_out_of_memory(0, OOM_MMAP_ERROR, "pthread_getattr_np");
5410       } else {
5411         fatal("pthread_getattr_np failed with error = %d", rslt);
5412       }
5413     }
5414 
5415     if (pthread_attr_getstack(&attr, (void **)bottom, size) != 0) {
5416       fatal("Cannot locate current stack attributes!");
5417     }
5418 
5419     if (os::Linux::adjustStackSizeForGuardPages()) {
5420       size_t guard_size = 0;
5421       rslt = pthread_attr_getguardsize(&attr, &guard_size);
5422       if (rslt != 0) {
5423         fatal("pthread_attr_getguardsize failed with error = %d", rslt);
5424       }
5425       *bottom += guard_size;
5426       *size   -= guard_size;
5427     }
5428 
5429     pthread_attr_destroy(&attr);
5430 
5431   }
5432   assert(os::current_stack_pointer() >= *bottom &&
5433          os::current_stack_pointer() < *bottom + *size, "just checking");
5434 }
5435 
5436 address os::current_stack_base() {
5437   address bottom;
5438   size_t size;
5439   current_stack_region(&bottom, &size);
5440   return (bottom + size);
5441 }
5442 
5443 size_t os::current_stack_size() {
5444   // This stack size includes the usable stack and HotSpot guard pages
5445   // (for the threads that have Hotspot guard pages).
5446   address bottom;
5447   size_t size;
5448   current_stack_region(&bottom, &size);
5449   return size;
5450 }
5451 #endif
5452 
5453 static inline struct timespec get_mtime(const char* filename) {
5454   struct stat st;
5455   int ret = os::stat(filename, &st);
5456   assert(ret == 0, "failed to stat() file '%s': %s", filename, os::strerror(errno));
5457   return st.st_mtim;
5458 }
5459 
5460 int os::compare_file_modified_times(const char* file1, const char* file2) {
5461   struct timespec filetime1 = get_mtime(file1);
5462   struct timespec filetime2 = get_mtime(file2);
5463   int diff = filetime1.tv_sec - filetime2.tv_sec;
5464   if (diff == 0) {
5465     return filetime1.tv_nsec - filetime2.tv_nsec;
5466   }
5467   return diff;
5468 }
5469 
5470 bool os::supports_map_sync() {
5471   return true;
5472 }
5473 
5474 void os::print_memory_mappings(char* addr, size_t bytes, outputStream* st) {
5475   // Note: all ranges are "[..)"
5476   unsigned long long start = (unsigned long long)addr;
5477   unsigned long long end = start + bytes;
5478   FILE* f = os::fopen("/proc/self/maps", "r");
5479   int num_found = 0;
5480   if (f != nullptr) {
5481     st->print_cr("Range [%llx-%llx) contains: ", start, end);
5482     char line[512];
5483     while(fgets(line, sizeof(line), f) == line) {
5484       unsigned long long segment_start = 0;
5485       unsigned long long segment_end = 0;
5486       if (::sscanf(line, "%llx-%llx", &segment_start, &segment_end) == 2) {
5487         // Lets print out every range which touches ours.
5488         if (segment_start < end && segment_end > start) {
5489           num_found ++;
5490           st->print("%s", line); // line includes \n
5491         }
5492       }
5493     }
5494     ::fclose(f);
5495     if (num_found == 0) {
5496       st->print_cr("nothing.");
5497     }
5498     st->cr();
5499   }
5500 }
5501 
5502 #ifdef __GLIBC__
5503 void os::Linux::get_mallinfo(glibc_mallinfo* out, bool* might_have_wrapped) {
5504   if (g_mallinfo2) {
5505     new_mallinfo mi = g_mallinfo2();
5506     out->arena = mi.arena;
5507     out->ordblks = mi.ordblks;
5508     out->smblks = mi.smblks;
5509     out->hblks = mi.hblks;
5510     out->hblkhd = mi.hblkhd;
5511     out->usmblks = mi.usmblks;
5512     out->fsmblks = mi.fsmblks;
5513     out->uordblks = mi.uordblks;
5514     out->fordblks = mi.fordblks;
5515     out->keepcost =  mi.keepcost;
5516     *might_have_wrapped = false;
5517   } else if (g_mallinfo) {
5518     old_mallinfo mi = g_mallinfo();
5519     // glibc reports unsigned 32-bit sizes in int form. First make unsigned, then extend.
5520     out->arena = (size_t)(unsigned)mi.arena;
5521     out->ordblks = (size_t)(unsigned)mi.ordblks;
5522     out->smblks = (size_t)(unsigned)mi.smblks;
5523     out->hblks = (size_t)(unsigned)mi.hblks;
5524     out->hblkhd = (size_t)(unsigned)mi.hblkhd;
5525     out->usmblks = (size_t)(unsigned)mi.usmblks;
5526     out->fsmblks = (size_t)(unsigned)mi.fsmblks;
5527     out->uordblks = (size_t)(unsigned)mi.uordblks;
5528     out->fordblks = (size_t)(unsigned)mi.fordblks;
5529     out->keepcost = (size_t)(unsigned)mi.keepcost;
5530     *might_have_wrapped = NOT_LP64(false) LP64_ONLY(true);
5531   } else {
5532     // We should have either mallinfo or mallinfo2
5533     ShouldNotReachHere();
5534   }
5535 }
5536 
5537 int os::Linux::malloc_info(FILE* stream) {
5538   if (g_malloc_info == nullptr) {
5539     return -2;
5540   }
5541   return g_malloc_info(0, stream);
5542 }
5543 #endif // __GLIBC__
5544 
5545 bool os::trim_native_heap(os::size_change_t* rss_change) {
5546 #ifdef __GLIBC__
5547   os::Linux::meminfo_t info1;
5548   os::Linux::meminfo_t info2;
5549 
5550   bool have_info1 = rss_change != nullptr &&
5551                     os::Linux::query_process_memory_info(&info1);
5552   ::malloc_trim(0);
5553   bool have_info2 = rss_change != nullptr && have_info1 &&
5554                     os::Linux::query_process_memory_info(&info2);
5555   ssize_t delta = (ssize_t) -1;
5556   if (rss_change != nullptr) {
5557     if (have_info1 && have_info2 &&
5558         info1.vmrss != -1 && info2.vmrss != -1 &&
5559         info1.vmswap != -1 && info2.vmswap != -1) {
5560       // Note: query_process_memory_info returns values in K
5561       rss_change->before = (info1.vmrss + info1.vmswap) * K;
5562       rss_change->after = (info2.vmrss + info2.vmswap) * K;
5563     } else {
5564       rss_change->after = rss_change->before = SIZE_MAX;
5565     }
5566   }
5567 
5568   return true;
5569 #else
5570   return false; // musl
5571 #endif
5572 }
5573 
5574 bool os::pd_dll_unload(void* libhandle, char* ebuf, int ebuflen) {
5575 
5576   if (ebuf && ebuflen > 0) {
5577     ebuf[0] = '\0';
5578     ebuf[ebuflen - 1] = '\0';
5579   }
5580 
5581   bool res = (0 == ::dlclose(libhandle));
5582   if (!res) {
5583     // error analysis when dlopen fails
5584     const char* error_report = ::dlerror();
5585     if (error_report == nullptr) {
5586       error_report = "dlerror returned no error description";
5587     }
5588     if (ebuf != nullptr && ebuflen > 0) {
5589       snprintf(ebuf, ebuflen - 1, "%s", error_report);
5590     }
5591   }
5592 
5593   return res;
5594 } // end: os::pd_dll_unload()