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