1 /*
   2  * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 // no precompiled headers
  26 #include "classfile/classLoader.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "classfile/vmSymbols.hpp"
  29 #include "code/icBuffer.hpp"
  30 #include "code/vtableStubs.hpp"
  31 #include "compiler/compileBroker.hpp"
  32 #include "compiler/disassembler.hpp"
  33 #include "interpreter/interpreter.hpp"
  34 #include "jvm_solaris.h"
  35 #include "memory/allocation.inline.hpp"
  36 #include "memory/filemap.hpp"
  37 #include "mutex_solaris.inline.hpp"
  38 #include "oops/oop.inline.hpp"
  39 #include "os_share_solaris.hpp"
  40 #include "os_solaris.inline.hpp"
  41 #include "prims/jniFastGetField.hpp"
  42 #include "prims/jvm.h"
  43 #include "prims/jvm_misc.hpp"
  44 #include "runtime/arguments.hpp"
  45 #include "runtime/atomic.inline.hpp"
  46 #include "runtime/extendedPC.hpp"
  47 #include "runtime/globals.hpp"
  48 #include "runtime/interfaceSupport.hpp"
  49 #include "runtime/java.hpp"
  50 #include "runtime/javaCalls.hpp"
  51 #include "runtime/mutexLocker.hpp"
  52 #include "runtime/objectMonitor.hpp"
  53 #include "runtime/orderAccess.inline.hpp"
  54 #include "runtime/osThread.hpp"
  55 #include "runtime/perfMemory.hpp"
  56 #include "runtime/sharedRuntime.hpp"
  57 #include "runtime/statSampler.hpp"
  58 #include "runtime/stubRoutines.hpp"
  59 #include "runtime/thread.inline.hpp"
  60 #include "runtime/threadCritical.hpp"
  61 #include "runtime/timer.hpp"
  62 #include "runtime/vm_version.hpp"
  63 #include "semaphore_posix.hpp"
  64 #include "services/attachListener.hpp"
  65 #include "services/memTracker.hpp"
  66 #include "services/runtimeService.hpp"
  67 #include "utilities/decoder.hpp"
  68 #include "utilities/defaultStream.hpp"
  69 #include "utilities/events.hpp"
  70 #include "utilities/growableArray.hpp"
  71 #include "utilities/vmError.hpp"
  72 
  73 // put OS-includes here
  74 # include <dlfcn.h>
  75 # include <errno.h>
  76 # include <exception>
  77 # include <link.h>
  78 # include <poll.h>
  79 # include <pthread.h>
  80 # include <pwd.h>
  81 # include <schedctl.h>
  82 # include <setjmp.h>
  83 # include <signal.h>
  84 # include <stdio.h>
  85 # include <alloca.h>
  86 # include <sys/filio.h>
  87 # include <sys/ipc.h>
  88 # include <sys/lwp.h>
  89 # include <sys/machelf.h>     // for elf Sym structure used by dladdr1
  90 # include <sys/mman.h>
  91 # include <sys/processor.h>
  92 # include <sys/procset.h>
  93 # include <sys/pset.h>
  94 # include <sys/resource.h>
  95 # include <sys/shm.h>
  96 # include <sys/socket.h>
  97 # include <sys/stat.h>
  98 # include <sys/systeminfo.h>
  99 # include <sys/time.h>
 100 # include <sys/times.h>
 101 # include <sys/types.h>
 102 # include <sys/wait.h>
 103 # include <sys/utsname.h>
 104 # include <thread.h>
 105 # include <unistd.h>
 106 # include <sys/priocntl.h>
 107 # include <sys/rtpriocntl.h>
 108 # include <sys/tspriocntl.h>
 109 # include <sys/iapriocntl.h>
 110 # include <sys/fxpriocntl.h>
 111 # include <sys/loadavg.h>
 112 # include <string.h>
 113 # include <stdio.h>
 114 
 115 # define _STRUCTURED_PROC 1  //  this gets us the new structured proc interfaces of 5.6 & later
 116 # include <sys/procfs.h>     //  see comment in <sys/procfs.h>
 117 
 118 #define MAX_PATH (2 * K)
 119 
 120 // for timer info max values which include all bits
 121 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
 122 
 123 
 124 // Here are some liblgrp types from sys/lgrp_user.h to be able to
 125 // compile on older systems without this header file.
 126 
 127 #ifndef MADV_ACCESS_LWP
 128   #define  MADV_ACCESS_LWP   7       /* next LWP to access heavily */
 129 #endif
 130 #ifndef MADV_ACCESS_MANY
 131   #define  MADV_ACCESS_MANY  8       /* many processes to access heavily */
 132 #endif
 133 
 134 #ifndef LGRP_RSRC_CPU
 135   #define LGRP_RSRC_CPU      0       /* CPU resources */
 136 #endif
 137 #ifndef LGRP_RSRC_MEM
 138   #define LGRP_RSRC_MEM      1       /* memory resources */
 139 #endif
 140 
 141 // see thr_setprio(3T) for the basis of these numbers
 142 #define MinimumPriority 0
 143 #define NormalPriority  64
 144 #define MaximumPriority 127
 145 
 146 // Values for ThreadPriorityPolicy == 1
 147 int prio_policy1[CriticalPriority+1] = {
 148   -99999,  0, 16,  32,  48,  64,
 149           80, 96, 112, 124, 127, 127 };
 150 
 151 // System parameters used internally
 152 static clock_t clock_tics_per_sec = 100;
 153 
 154 // Track if we have called enable_extended_FILE_stdio (on Solaris 10u4+)
 155 static bool enabled_extended_FILE_stdio = false;
 156 
 157 // For diagnostics to print a message once. see run_periodic_checks
 158 static bool check_addr0_done = false;
 159 static sigset_t check_signal_done;
 160 static bool check_signals = true;
 161 
 162 address os::Solaris::handler_start;  // start pc of thr_sighndlrinfo
 163 address os::Solaris::handler_end;    // end pc of thr_sighndlrinfo
 164 
 165 address os::Solaris::_main_stack_base = NULL;  // 4352906 workaround
 166 
 167 
 168 // "default" initializers for missing libc APIs
 169 extern "C" {
 170   static int lwp_mutex_init(mutex_t *mx, int scope, void *arg) { memset(mx, 0, sizeof(mutex_t)); return 0; }
 171   static int lwp_mutex_destroy(mutex_t *mx)                 { return 0; }
 172 
 173   static int lwp_cond_init(cond_t *cv, int scope, void *arg){ memset(cv, 0, sizeof(cond_t)); return 0; }
 174   static int lwp_cond_destroy(cond_t *cv)                   { return 0; }
 175 }
 176 
 177 // "default" initializers for pthread-based synchronization
 178 extern "C" {
 179   static int pthread_mutex_default_init(mutex_t *mx, int scope, void *arg) { memset(mx, 0, sizeof(mutex_t)); return 0; }
 180   static int pthread_cond_default_init(cond_t *cv, int scope, void *arg){ memset(cv, 0, sizeof(cond_t)); return 0; }
 181 }
 182 
 183 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time);
 184 
 185 static inline size_t adjust_stack_size(address base, size_t size) {
 186   if ((ssize_t)size < 0) {
 187     // 4759953: Compensate for ridiculous stack size.
 188     size = max_intx;
 189   }
 190   if (size > (size_t)base) {
 191     // 4812466: Make sure size doesn't allow the stack to wrap the address space.
 192     size = (size_t)base;
 193   }
 194   return size;
 195 }
 196 
 197 static inline stack_t get_stack_info() {
 198   stack_t st;
 199   int retval = thr_stksegment(&st);
 200   st.ss_size = adjust_stack_size((address)st.ss_sp, st.ss_size);
 201   assert(retval == 0, "incorrect return value from thr_stksegment");
 202   assert((address)&st < (address)st.ss_sp, "Invalid stack base returned");
 203   assert((address)&st > (address)st.ss_sp-st.ss_size, "Invalid stack size returned");
 204   return st;
 205 }
 206 
 207 address os::current_stack_base() {
 208   int r = thr_main();
 209   guarantee(r == 0 || r == 1, "CR6501650 or CR6493689");
 210   bool is_primordial_thread = r;
 211 
 212   // Workaround 4352906, avoid calls to thr_stksegment by
 213   // thr_main after the first one (it looks like we trash
 214   // some data, causing the value for ss_sp to be incorrect).
 215   if (!is_primordial_thread || os::Solaris::_main_stack_base == NULL) {
 216     stack_t st = get_stack_info();
 217     if (is_primordial_thread) {
 218       // cache initial value of stack base
 219       os::Solaris::_main_stack_base = (address)st.ss_sp;
 220     }
 221     return (address)st.ss_sp;
 222   } else {
 223     guarantee(os::Solaris::_main_stack_base != NULL, "Attempt to use null cached stack base");
 224     return os::Solaris::_main_stack_base;
 225   }
 226 }
 227 
 228 size_t os::current_stack_size() {
 229   size_t size;
 230 
 231   int r = thr_main();
 232   guarantee(r == 0 || r == 1, "CR6501650 or CR6493689");
 233   if (!r) {
 234     size = get_stack_info().ss_size;
 235   } else {
 236     struct rlimit limits;
 237     getrlimit(RLIMIT_STACK, &limits);
 238     size = adjust_stack_size(os::Solaris::_main_stack_base, (size_t)limits.rlim_cur);
 239   }
 240   // base may not be page aligned
 241   address base = current_stack_base();
 242   address bottom = (address)align_size_up((intptr_t)(base - size), os::vm_page_size());;
 243   return (size_t)(base - bottom);
 244 }
 245 
 246 struct tm* os::localtime_pd(const time_t* clock, struct tm*  res) {
 247   return localtime_r(clock, res);
 248 }
 249 
 250 void os::Solaris::try_enable_extended_io() {
 251   typedef int (*enable_extended_FILE_stdio_t)(int, int);
 252 
 253   if (!UseExtendedFileIO) {
 254     return;
 255   }
 256 
 257   enable_extended_FILE_stdio_t enabler =
 258     (enable_extended_FILE_stdio_t) dlsym(RTLD_DEFAULT,
 259                                          "enable_extended_FILE_stdio");
 260   if (enabler) {
 261     enabler(-1, -1);
 262   }
 263 }
 264 
 265 static int _processors_online = 0;
 266 
 267 jint os::Solaris::_os_thread_limit = 0;
 268 volatile jint os::Solaris::_os_thread_count = 0;
 269 
 270 julong os::available_memory() {
 271   return Solaris::available_memory();
 272 }
 273 
 274 julong os::Solaris::available_memory() {
 275   return (julong)sysconf(_SC_AVPHYS_PAGES) * os::vm_page_size();
 276 }
 277 
 278 julong os::Solaris::_physical_memory = 0;
 279 
 280 julong os::physical_memory() {
 281   return Solaris::physical_memory();
 282 }
 283 
 284 static hrtime_t first_hrtime = 0;
 285 static const hrtime_t hrtime_hz = 1000*1000*1000;
 286 static volatile hrtime_t max_hrtime = 0;
 287 
 288 
 289 void os::Solaris::initialize_system_info() {
 290   set_processor_count(sysconf(_SC_NPROCESSORS_CONF));
 291   _processors_online = sysconf(_SC_NPROCESSORS_ONLN);
 292   _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) *
 293                                      (julong)sysconf(_SC_PAGESIZE);
 294 }
 295 
 296 int os::active_processor_count() {
 297   int online_cpus = sysconf(_SC_NPROCESSORS_ONLN);
 298   pid_t pid = getpid();
 299   psetid_t pset = PS_NONE;
 300   // Are we running in a processor set or is there any processor set around?
 301   if (pset_bind(PS_QUERY, P_PID, pid, &pset) == 0) {
 302     uint_t pset_cpus;
 303     // Query the number of cpus available to us.
 304     if (pset_info(pset, NULL, &pset_cpus, NULL) == 0) {
 305       assert(pset_cpus > 0 && pset_cpus <= online_cpus, "sanity check");
 306       _processors_online = pset_cpus;
 307       return pset_cpus;
 308     }
 309   }
 310   // Otherwise return number of online cpus
 311   return online_cpus;
 312 }
 313 
 314 static bool find_processors_in_pset(psetid_t        pset,
 315                                     processorid_t** id_array,
 316                                     uint_t*         id_length) {
 317   bool result = false;
 318   // Find the number of processors in the processor set.
 319   if (pset_info(pset, NULL, id_length, NULL) == 0) {
 320     // Make up an array to hold their ids.
 321     *id_array = NEW_C_HEAP_ARRAY(processorid_t, *id_length, mtInternal);
 322     // Fill in the array with their processor ids.
 323     if (pset_info(pset, NULL, id_length, *id_array) == 0) {
 324       result = true;
 325     }
 326   }
 327   return result;
 328 }
 329 
 330 // Callers of find_processors_online() must tolerate imprecise results --
 331 // the system configuration can change asynchronously because of DR
 332 // or explicit psradm operations.
 333 //
 334 // We also need to take care that the loop (below) terminates as the
 335 // number of processors online can change between the _SC_NPROCESSORS_ONLN
 336 // request and the loop that builds the list of processor ids.   Unfortunately
 337 // there's no reliable way to determine the maximum valid processor id,
 338 // so we use a manifest constant, MAX_PROCESSOR_ID, instead.  See p_online
 339 // man pages, which claim the processor id set is "sparse, but
 340 // not too sparse".  MAX_PROCESSOR_ID is used to ensure that we eventually
 341 // exit the loop.
 342 //
 343 // In the future we'll be able to use sysconf(_SC_CPUID_MAX), but that's
 344 // not available on S8.0.
 345 
 346 static bool find_processors_online(processorid_t** id_array,
 347                                    uint*           id_length) {
 348   const processorid_t MAX_PROCESSOR_ID = 100000;
 349   // Find the number of processors online.
 350   *id_length = sysconf(_SC_NPROCESSORS_ONLN);
 351   // Make up an array to hold their ids.
 352   *id_array = NEW_C_HEAP_ARRAY(processorid_t, *id_length, mtInternal);
 353   // Processors need not be numbered consecutively.
 354   long found = 0;
 355   processorid_t next = 0;
 356   while (found < *id_length && next < MAX_PROCESSOR_ID) {
 357     processor_info_t info;
 358     if (processor_info(next, &info) == 0) {
 359       // NB, PI_NOINTR processors are effectively online ...
 360       if (info.pi_state == P_ONLINE || info.pi_state == P_NOINTR) {
 361         (*id_array)[found] = next;
 362         found += 1;
 363       }
 364     }
 365     next += 1;
 366   }
 367   if (found < *id_length) {
 368     // The loop above didn't identify the expected number of processors.
 369     // We could always retry the operation, calling sysconf(_SC_NPROCESSORS_ONLN)
 370     // and re-running the loop, above, but there's no guarantee of progress
 371     // if the system configuration is in flux.  Instead, we just return what
 372     // we've got.  Note that in the worst case find_processors_online() could
 373     // return an empty set.  (As a fall-back in the case of the empty set we
 374     // could just return the ID of the current processor).
 375     *id_length = found;
 376   }
 377 
 378   return true;
 379 }
 380 
 381 static bool assign_distribution(processorid_t* id_array,
 382                                 uint           id_length,
 383                                 uint*          distribution,
 384                                 uint           distribution_length) {
 385   // We assume we can assign processorid_t's to uint's.
 386   assert(sizeof(processorid_t) == sizeof(uint),
 387          "can't convert processorid_t to uint");
 388   // Quick check to see if we won't succeed.
 389   if (id_length < distribution_length) {
 390     return false;
 391   }
 392   // Assign processor ids to the distribution.
 393   // Try to shuffle processors to distribute work across boards,
 394   // assuming 4 processors per board.
 395   const uint processors_per_board = ProcessDistributionStride;
 396   // Find the maximum processor id.
 397   processorid_t max_id = 0;
 398   for (uint m = 0; m < id_length; m += 1) {
 399     max_id = MAX2(max_id, id_array[m]);
 400   }
 401   // The next id, to limit loops.
 402   const processorid_t limit_id = max_id + 1;
 403   // Make up markers for available processors.
 404   bool* available_id = NEW_C_HEAP_ARRAY(bool, limit_id, mtInternal);
 405   for (uint c = 0; c < limit_id; c += 1) {
 406     available_id[c] = false;
 407   }
 408   for (uint a = 0; a < id_length; a += 1) {
 409     available_id[id_array[a]] = true;
 410   }
 411   // Step by "boards", then by "slot", copying to "assigned".
 412   // NEEDS_CLEANUP: The assignment of processors should be stateful,
 413   //                remembering which processors have been assigned by
 414   //                previous calls, etc., so as to distribute several
 415   //                independent calls of this method.  What we'd like is
 416   //                It would be nice to have an API that let us ask
 417   //                how many processes are bound to a processor,
 418   //                but we don't have that, either.
 419   //                In the short term, "board" is static so that
 420   //                subsequent distributions don't all start at board 0.
 421   static uint board = 0;
 422   uint assigned = 0;
 423   // Until we've found enough processors ....
 424   while (assigned < distribution_length) {
 425     // ... find the next available processor in the board.
 426     for (uint slot = 0; slot < processors_per_board; slot += 1) {
 427       uint try_id = board * processors_per_board + slot;
 428       if ((try_id < limit_id) && (available_id[try_id] == true)) {
 429         distribution[assigned] = try_id;
 430         available_id[try_id] = false;
 431         assigned += 1;
 432         break;
 433       }
 434     }
 435     board += 1;
 436     if (board * processors_per_board + 0 >= limit_id) {
 437       board = 0;
 438     }
 439   }
 440   if (available_id != NULL) {
 441     FREE_C_HEAP_ARRAY(bool, available_id);
 442   }
 443   return true;
 444 }
 445 
 446 void os::set_native_thread_name(const char *name) {
 447   // Not yet implemented.
 448   return;
 449 }
 450 
 451 bool os::distribute_processes(uint length, uint* distribution) {
 452   bool result = false;
 453   // Find the processor id's of all the available CPUs.
 454   processorid_t* id_array  = NULL;
 455   uint           id_length = 0;
 456   // There are some races between querying information and using it,
 457   // since processor sets can change dynamically.
 458   psetid_t pset = PS_NONE;
 459   // Are we running in a processor set?
 460   if ((pset_bind(PS_QUERY, P_PID, P_MYID, &pset) == 0) && pset != PS_NONE) {
 461     result = find_processors_in_pset(pset, &id_array, &id_length);
 462   } else {
 463     result = find_processors_online(&id_array, &id_length);
 464   }
 465   if (result == true) {
 466     if (id_length >= length) {
 467       result = assign_distribution(id_array, id_length, distribution, length);
 468     } else {
 469       result = false;
 470     }
 471   }
 472   if (id_array != NULL) {
 473     FREE_C_HEAP_ARRAY(processorid_t, id_array);
 474   }
 475   return result;
 476 }
 477 
 478 bool os::bind_to_processor(uint processor_id) {
 479   // We assume that a processorid_t can be stored in a uint.
 480   assert(sizeof(uint) == sizeof(processorid_t),
 481          "can't convert uint to processorid_t");
 482   int bind_result =
 483     processor_bind(P_LWPID,                       // bind LWP.
 484                    P_MYID,                        // bind current LWP.
 485                    (processorid_t) processor_id,  // id.
 486                    NULL);                         // don't return old binding.
 487   return (bind_result == 0);
 488 }
 489 
 490 // Return true if user is running as root.
 491 
 492 bool os::have_special_privileges() {
 493   static bool init = false;
 494   static bool privileges = false;
 495   if (!init) {
 496     privileges = (getuid() != geteuid()) || (getgid() != getegid());
 497     init = true;
 498   }
 499   return privileges;
 500 }
 501 
 502 
 503 void os::init_system_properties_values() {
 504   // The next steps are taken in the product version:
 505   //
 506   // Obtain the JAVA_HOME value from the location of libjvm.so.
 507   // This library should be located at:
 508   // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.
 509   //
 510   // If "/jre/lib/" appears at the right place in the path, then we
 511   // assume libjvm.so is installed in a JDK and we use this path.
 512   //
 513   // Otherwise exit with message: "Could not create the Java virtual machine."
 514   //
 515   // The following extra steps are taken in the debugging version:
 516   //
 517   // If "/jre/lib/" does NOT appear at the right place in the path
 518   // instead of exit check for $JAVA_HOME environment variable.
 519   //
 520   // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
 521   // then we append a fake suffix "hotspot/libjvm.so" to this path so
 522   // it looks like libjvm.so is installed there
 523   // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.
 524   //
 525   // Otherwise exit.
 526   //
 527   // Important note: if the location of libjvm.so changes this
 528   // code needs to be changed accordingly.
 529 
 530 // Base path of extensions installed on the system.
 531 #define SYS_EXT_DIR     "/usr/jdk/packages"
 532 #define EXTENSIONS_DIR  "/lib/ext"
 533 
 534   char cpu_arch[12];
 535   // Buffer that fits several sprintfs.
 536   // Note that the space for the colon and the trailing null are provided
 537   // by the nulls included by the sizeof operator.
 538   const size_t bufsize =
 539     MAX3((size_t)MAXPATHLEN,  // For dll_dir & friends.
 540          sizeof(SYS_EXT_DIR) + sizeof("/lib/") + strlen(cpu_arch), // invariant ld_library_path
 541          (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR)); // extensions dir
 542   char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
 543 
 544   // sysclasspath, java_home, dll_dir
 545   {
 546     char *pslash;
 547     os::jvm_path(buf, bufsize);
 548 
 549     // Found the full path to libjvm.so.
 550     // Now cut the path to <java_home>/jre if we can.
 551     *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.
 552     pslash = strrchr(buf, '/');
 553     if (pslash != NULL) {
 554       *pslash = '\0';            // Get rid of /{client|server|hotspot}.
 555     }
 556     Arguments::set_dll_dir(buf);
 557 
 558     if (pslash != NULL) {
 559       pslash = strrchr(buf, '/');
 560       if (pslash != NULL) {
 561         *pslash = '\0';          // Get rid of /<arch>.
 562         pslash = strrchr(buf, '/');
 563         if (pslash != NULL) {
 564           *pslash = '\0';        // Get rid of /lib.
 565         }
 566       }
 567     }
 568     Arguments::set_java_home(buf);
 569     set_boot_path('/', ':');
 570   }
 571 
 572   // Where to look for native libraries.
 573   {
 574     // Use dlinfo() to determine the correct java.library.path.
 575     //
 576     // If we're launched by the Java launcher, and the user
 577     // does not set java.library.path explicitly on the commandline,
 578     // the Java launcher sets LD_LIBRARY_PATH for us and unsets
 579     // LD_LIBRARY_PATH_32 and LD_LIBRARY_PATH_64.  In this case
 580     // dlinfo returns LD_LIBRARY_PATH + crle settings (including
 581     // /usr/lib), which is exactly what we want.
 582     //
 583     // If the user does set java.library.path, it completely
 584     // overwrites this setting, and always has.
 585     //
 586     // If we're not launched by the Java launcher, we may
 587     // get here with any/all of the LD_LIBRARY_PATH[_32|64]
 588     // settings.  Again, dlinfo does exactly what we want.
 589 
 590     Dl_serinfo     info_sz, *info = &info_sz;
 591     Dl_serpath     *path;
 592     char           *library_path;
 593     char           *common_path = buf;
 594 
 595     // Determine search path count and required buffer size.
 596     if (dlinfo(RTLD_SELF, RTLD_DI_SERINFOSIZE, (void *)info) == -1) {
 597       FREE_C_HEAP_ARRAY(char, buf);
 598       vm_exit_during_initialization("dlinfo SERINFOSIZE request", dlerror());
 599     }
 600 
 601     // Allocate new buffer and initialize.
 602     info = (Dl_serinfo*)NEW_C_HEAP_ARRAY(char, info_sz.dls_size, mtInternal);
 603     info->dls_size = info_sz.dls_size;
 604     info->dls_cnt = info_sz.dls_cnt;
 605 
 606     // Obtain search path information.
 607     if (dlinfo(RTLD_SELF, RTLD_DI_SERINFO, (void *)info) == -1) {
 608       FREE_C_HEAP_ARRAY(char, buf);
 609       FREE_C_HEAP_ARRAY(char, info);
 610       vm_exit_during_initialization("dlinfo SERINFO request", dlerror());
 611     }
 612 
 613     path = &info->dls_serpath[0];
 614 
 615     // Note: Due to a legacy implementation, most of the library path
 616     // is set in the launcher. This was to accomodate linking restrictions
 617     // on legacy Solaris implementations (which are no longer supported).
 618     // Eventually, all the library path setting will be done here.
 619     //
 620     // However, to prevent the proliferation of improperly built native
 621     // libraries, the new path component /usr/jdk/packages is added here.
 622 
 623     // Determine the actual CPU architecture.
 624     sysinfo(SI_ARCHITECTURE, cpu_arch, sizeof(cpu_arch));
 625 #ifdef _LP64
 626     // If we are a 64-bit vm, perform the following translations:
 627     //   sparc   -> sparcv9
 628     //   i386    -> amd64
 629     if (strcmp(cpu_arch, "sparc") == 0) {
 630       strcat(cpu_arch, "v9");
 631     } else if (strcmp(cpu_arch, "i386") == 0) {
 632       strcpy(cpu_arch, "amd64");
 633     }
 634 #endif
 635 
 636     // Construct the invariant part of ld_library_path.
 637     sprintf(common_path, SYS_EXT_DIR "/lib/%s", cpu_arch);
 638 
 639     // Struct size is more than sufficient for the path components obtained
 640     // through the dlinfo() call, so only add additional space for the path
 641     // components explicitly added here.
 642     size_t library_path_size = info->dls_size + strlen(common_path);
 643     library_path = (char *)NEW_C_HEAP_ARRAY(char, library_path_size, mtInternal);
 644     library_path[0] = '\0';
 645 
 646     // Construct the desired Java library path from the linker's library
 647     // search path.
 648     //
 649     // For compatibility, it is optimal that we insert the additional path
 650     // components specific to the Java VM after those components specified
 651     // in LD_LIBRARY_PATH (if any) but before those added by the ld.so
 652     // infrastructure.
 653     if (info->dls_cnt == 0) { // Not sure this can happen, but allow for it.
 654       strcpy(library_path, common_path);
 655     } else {
 656       int inserted = 0;
 657       int i;
 658       for (i = 0; i < info->dls_cnt; i++, path++) {
 659         uint_t flags = path->dls_flags & LA_SER_MASK;
 660         if (((flags & LA_SER_LIBPATH) == 0) && !inserted) {
 661           strcat(library_path, common_path);
 662           strcat(library_path, os::path_separator());
 663           inserted = 1;
 664         }
 665         strcat(library_path, path->dls_name);
 666         strcat(library_path, os::path_separator());
 667       }
 668       // Eliminate trailing path separator.
 669       library_path[strlen(library_path)-1] = '\0';
 670     }
 671 
 672     // happens before argument parsing - can't use a trace flag
 673     // tty->print_raw("init_system_properties_values: native lib path: ");
 674     // tty->print_raw_cr(library_path);
 675 
 676     // Callee copies into its own buffer.
 677     Arguments::set_library_path(library_path);
 678 
 679     FREE_C_HEAP_ARRAY(char, library_path);
 680     FREE_C_HEAP_ARRAY(char, info);
 681   }
 682 
 683   // Extensions directories.
 684   sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home());
 685   Arguments::set_ext_dirs(buf);
 686 
 687   FREE_C_HEAP_ARRAY(char, buf);
 688 
 689 #undef SYS_EXT_DIR
 690 #undef EXTENSIONS_DIR
 691 }
 692 
 693 void os::breakpoint() {
 694   BREAKPOINT;
 695 }
 696 
 697 bool os::obsolete_option(const JavaVMOption *option) {
 698   if (!strncmp(option->optionString, "-Xt", 3)) {
 699     return true;
 700   } else if (!strncmp(option->optionString, "-Xtm", 4)) {
 701     return true;
 702   } else if (!strncmp(option->optionString, "-Xverifyheap", 12)) {
 703     return true;
 704   } else if (!strncmp(option->optionString, "-Xmaxjitcodesize", 16)) {
 705     return true;
 706   }
 707   return false;
 708 }
 709 
 710 bool os::Solaris::valid_stack_address(Thread* thread, address sp) {
 711   address  stackStart  = (address)thread->stack_base();
 712   address  stackEnd    = (address)(stackStart - (address)thread->stack_size());
 713   if (sp < stackStart && sp >= stackEnd) return true;
 714   return false;
 715 }
 716 
 717 extern "C" void breakpoint() {
 718   // use debugger to set breakpoint here
 719 }
 720 
 721 static thread_t main_thread;
 722 
 723 // Thread start routine for all new Java threads
 724 extern "C" void* java_start(void* thread_addr) {
 725   // Try to randomize the cache line index of hot stack frames.
 726   // This helps when threads of the same stack traces evict each other's
 727   // cache lines. The threads can be either from the same JVM instance, or
 728   // from different JVM instances. The benefit is especially true for
 729   // processors with hyperthreading technology.
 730   static int counter = 0;
 731   int pid = os::current_process_id();
 732   alloca(((pid ^ counter++) & 7) * 128);
 733 
 734   int prio;
 735   Thread* thread = (Thread*)thread_addr;
 736 
 737   thread->initialize_thread_current();
 738 
 739   OSThread* osthr = thread->osthread();
 740 
 741   osthr->set_lwp_id(_lwp_self());  // Store lwp in case we are bound
 742   thread->_schedctl = (void *) schedctl_init();
 743 
 744   if (UseNUMA) {
 745     int lgrp_id = os::numa_get_group_id();
 746     if (lgrp_id != -1) {
 747       thread->set_lgrp_id(lgrp_id);
 748     }
 749   }
 750 
 751   // If the creator called set priority before we started,
 752   // we need to call set_native_priority now that we have an lwp.
 753   // We used to get the priority from thr_getprio (we called
 754   // thr_setprio way back in create_thread) and pass it to
 755   // set_native_priority, but Solaris scales the priority
 756   // in java_to_os_priority, so when we read it back here,
 757   // we pass trash to set_native_priority instead of what's
 758   // in java_to_os_priority. So we save the native priority
 759   // in the osThread and recall it here.
 760 
 761   if (osthr->thread_id() != -1) {
 762     if (UseThreadPriorities) {
 763       int prio = osthr->native_priority();
 764       if (ThreadPriorityVerbose) {
 765         tty->print_cr("Starting Thread " INTPTR_FORMAT ", LWP is "
 766                       INTPTR_FORMAT ", setting priority: %d\n",
 767                       osthr->thread_id(), osthr->lwp_id(), prio);
 768       }
 769       os::set_native_priority(thread, prio);
 770     }
 771   } else if (ThreadPriorityVerbose) {
 772     warning("Can't set priority in _start routine, thread id hasn't been set\n");
 773   }
 774 
 775   assert(osthr->get_state() == RUNNABLE, "invalid os thread state");
 776 
 777   // initialize signal mask for this thread
 778   os::Solaris::hotspot_sigmask(thread);
 779 
 780   thread->run();
 781 
 782   // One less thread is executing
 783   // When the VMThread gets here, the main thread may have already exited
 784   // which frees the CodeHeap containing the Atomic::dec code
 785   if (thread != VMThread::vm_thread() && VMThread::vm_thread() != NULL) {
 786     Atomic::dec(&os::Solaris::_os_thread_count);
 787   }
 788 
 789   if (UseDetachedThreads) {
 790     thr_exit(NULL);
 791     ShouldNotReachHere();
 792   }
 793   return NULL;
 794 }
 795 
 796 static OSThread* create_os_thread(Thread* thread, thread_t thread_id) {
 797   // Allocate the OSThread object
 798   OSThread* osthread = new OSThread(NULL, NULL);
 799   if (osthread == NULL) return NULL;
 800 
 801   // Store info on the Solaris thread into the OSThread
 802   osthread->set_thread_id(thread_id);
 803   osthread->set_lwp_id(_lwp_self());
 804   thread->_schedctl = (void *) schedctl_init();
 805 
 806   if (UseNUMA) {
 807     int lgrp_id = os::numa_get_group_id();
 808     if (lgrp_id != -1) {
 809       thread->set_lgrp_id(lgrp_id);
 810     }
 811   }
 812 
 813   if (ThreadPriorityVerbose) {
 814     tty->print_cr("In create_os_thread, Thread " INTPTR_FORMAT ", LWP is " INTPTR_FORMAT "\n",
 815                   osthread->thread_id(), osthread->lwp_id());
 816   }
 817 
 818   // Initial thread state is INITIALIZED, not SUSPENDED
 819   osthread->set_state(INITIALIZED);
 820 
 821   return osthread;
 822 }
 823 
 824 void os::Solaris::hotspot_sigmask(Thread* thread) {
 825   //Save caller's signal mask
 826   sigset_t sigmask;
 827   thr_sigsetmask(SIG_SETMASK, NULL, &sigmask);
 828   OSThread *osthread = thread->osthread();
 829   osthread->set_caller_sigmask(sigmask);
 830 
 831   thr_sigsetmask(SIG_UNBLOCK, os::Solaris::unblocked_signals(), NULL);
 832   if (!ReduceSignalUsage) {
 833     if (thread->is_VM_thread()) {
 834       // Only the VM thread handles BREAK_SIGNAL ...
 835       thr_sigsetmask(SIG_UNBLOCK, vm_signals(), NULL);
 836     } else {
 837       // ... all other threads block BREAK_SIGNAL
 838       assert(!sigismember(vm_signals(), SIGINT), "SIGINT should not be blocked");
 839       thr_sigsetmask(SIG_BLOCK, vm_signals(), NULL);
 840     }
 841   }
 842 }
 843 
 844 bool os::create_attached_thread(JavaThread* thread) {
 845 #ifdef ASSERT
 846   thread->verify_not_published();
 847 #endif
 848   OSThread* osthread = create_os_thread(thread, thr_self());
 849   if (osthread == NULL) {
 850     return false;
 851   }
 852 
 853   // Initial thread state is RUNNABLE
 854   osthread->set_state(RUNNABLE);
 855   thread->set_osthread(osthread);
 856 
 857   // initialize signal mask for this thread
 858   // and save the caller's signal mask
 859   os::Solaris::hotspot_sigmask(thread);
 860 
 861   return true;
 862 }
 863 
 864 bool os::create_main_thread(JavaThread* thread) {
 865 #ifdef ASSERT
 866   thread->verify_not_published();
 867 #endif
 868   if (_starting_thread == NULL) {
 869     _starting_thread = create_os_thread(thread, main_thread);
 870     if (_starting_thread == NULL) {
 871       return false;
 872     }
 873   }
 874 
 875   // The primodial thread is runnable from the start
 876   _starting_thread->set_state(RUNNABLE);
 877 
 878   thread->set_osthread(_starting_thread);
 879 
 880   // initialize signal mask for this thread
 881   // and save the caller's signal mask
 882   os::Solaris::hotspot_sigmask(thread);
 883 
 884   return true;
 885 }
 886 
 887 
 888 bool os::create_thread(Thread* thread, ThreadType thr_type,
 889                        size_t stack_size) {
 890   // Allocate the OSThread object
 891   OSThread* osthread = new OSThread(NULL, NULL);
 892   if (osthread == NULL) {
 893     return false;
 894   }
 895 
 896   if (ThreadPriorityVerbose) {
 897     char *thrtyp;
 898     switch (thr_type) {
 899     case vm_thread:
 900       thrtyp = (char *)"vm";
 901       break;
 902     case cgc_thread:
 903       thrtyp = (char *)"cgc";
 904       break;
 905     case pgc_thread:
 906       thrtyp = (char *)"pgc";
 907       break;
 908     case java_thread:
 909       thrtyp = (char *)"java";
 910       break;
 911     case compiler_thread:
 912       thrtyp = (char *)"compiler";
 913       break;
 914     case watcher_thread:
 915       thrtyp = (char *)"watcher";
 916       break;
 917     default:
 918       thrtyp = (char *)"unknown";
 919       break;
 920     }
 921     tty->print_cr("In create_thread, creating a %s thread\n", thrtyp);
 922   }
 923 
 924   // Calculate stack size if it's not specified by caller.
 925   if (stack_size == 0) {
 926     // The default stack size 1M (2M for LP64).
 927     stack_size = (BytesPerWord >> 2) * K * K;
 928 
 929     switch (thr_type) {
 930     case os::java_thread:
 931       // Java threads use ThreadStackSize which default value can be changed with the flag -Xss
 932       if (JavaThread::stack_size_at_create() > 0) stack_size = JavaThread::stack_size_at_create();
 933       break;
 934     case os::compiler_thread:
 935       if (CompilerThreadStackSize > 0) {
 936         stack_size = (size_t)(CompilerThreadStackSize * K);
 937         break;
 938       } // else fall through:
 939         // use VMThreadStackSize if CompilerThreadStackSize is not defined
 940     case os::vm_thread:
 941     case os::pgc_thread:
 942     case os::cgc_thread:
 943     case os::watcher_thread:
 944       if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
 945       break;
 946     }
 947   }
 948   stack_size = MAX2(stack_size, os::Solaris::min_stack_allowed);
 949 
 950   // Initial state is ALLOCATED but not INITIALIZED
 951   osthread->set_state(ALLOCATED);
 952 
 953   if (os::Solaris::_os_thread_count > os::Solaris::_os_thread_limit) {
 954     // We got lots of threads. Check if we still have some address space left.
 955     // Need to be at least 5Mb of unreserved address space. We do check by
 956     // trying to reserve some.
 957     const size_t VirtualMemoryBangSize = 20*K*K;
 958     char* mem = os::reserve_memory(VirtualMemoryBangSize);
 959     if (mem == NULL) {
 960       delete osthread;
 961       return false;
 962     } else {
 963       // Release the memory again
 964       os::release_memory(mem, VirtualMemoryBangSize);
 965     }
 966   }
 967 
 968   // Setup osthread because the child thread may need it.
 969   thread->set_osthread(osthread);
 970 
 971   // Create the Solaris thread
 972   thread_t tid = 0;
 973   long     flags = (UseDetachedThreads ? THR_DETACHED : 0) | THR_SUSPENDED;
 974   int      status;
 975 
 976   // Mark that we don't have an lwp or thread id yet.
 977   // In case we attempt to set the priority before the thread starts.
 978   osthread->set_lwp_id(-1);
 979   osthread->set_thread_id(-1);
 980 
 981   status = thr_create(NULL, stack_size, java_start, thread, flags, &tid);
 982   if (status != 0) {
 983     if (PrintMiscellaneous && (Verbose || WizardMode)) {
 984       perror("os::create_thread");
 985     }
 986     thread->set_osthread(NULL);
 987     // Need to clean up stuff we've allocated so far
 988     delete osthread;
 989     return false;
 990   }
 991 
 992   Atomic::inc(&os::Solaris::_os_thread_count);
 993 
 994   // Store info on the Solaris thread into the OSThread
 995   osthread->set_thread_id(tid);
 996 
 997   // Remember that we created this thread so we can set priority on it
 998   osthread->set_vm_created();
 999 
1000   // Initial thread state is INITIALIZED, not SUSPENDED
1001   osthread->set_state(INITIALIZED);
1002 
1003   // The thread is returned suspended (in state INITIALIZED), and is started higher up in the call chain
1004   return true;
1005 }
1006 
1007 // defined for >= Solaris 10. This allows builds on earlier versions
1008 // of Solaris to take advantage of the newly reserved Solaris JVM signals
1009 // With SIGJVM1, SIGJVM2, ASYNC_SIGNAL is SIGJVM2 and -XX:+UseAltSigs does
1010 // nothing since these should have no conflict. Previously INTERRUPT_SIGNAL
1011 // was SIGJVM1.
1012 //
1013 #if !defined(SIGJVM1)
1014   #define SIGJVM1 39
1015   #define SIGJVM2 40
1016 #endif
1017 
1018 debug_only(static bool signal_sets_initialized = false);
1019 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
1020 
1021 int os::Solaris::_SIGasync = ASYNC_SIGNAL;
1022 
1023 bool os::Solaris::is_sig_ignored(int sig) {
1024   struct sigaction oact;
1025   sigaction(sig, (struct sigaction*)NULL, &oact);
1026   void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oact.sa_sigaction)
1027                                  : CAST_FROM_FN_PTR(void*,  oact.sa_handler);
1028   if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN)) {
1029     return true;
1030   } else {
1031     return false;
1032   }
1033 }
1034 
1035 // Note: SIGRTMIN is a macro that calls sysconf() so it will
1036 // dynamically detect SIGRTMIN value for the system at runtime, not buildtime
1037 static bool isJVM1available() {
1038   return SIGJVM1 < SIGRTMIN;
1039 }
1040 
1041 void os::Solaris::signal_sets_init() {
1042   // Should also have an assertion stating we are still single-threaded.
1043   assert(!signal_sets_initialized, "Already initialized");
1044   // Fill in signals that are necessarily unblocked for all threads in
1045   // the VM. Currently, we unblock the following signals:
1046   // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
1047   //                         by -Xrs (=ReduceSignalUsage));
1048   // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
1049   // other threads. The "ReduceSignalUsage" boolean tells us not to alter
1050   // the dispositions or masks wrt these signals.
1051   // Programs embedding the VM that want to use the above signals for their
1052   // own purposes must, at this time, use the "-Xrs" option to prevent
1053   // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
1054   // (See bug 4345157, and other related bugs).
1055   // In reality, though, unblocking these signals is really a nop, since
1056   // these signals are not blocked by default.
1057   sigemptyset(&unblocked_sigs);
1058   sigemptyset(&allowdebug_blocked_sigs);
1059   sigaddset(&unblocked_sigs, SIGILL);
1060   sigaddset(&unblocked_sigs, SIGSEGV);
1061   sigaddset(&unblocked_sigs, SIGBUS);
1062   sigaddset(&unblocked_sigs, SIGFPE);
1063 
1064   if (isJVM1available) {
1065     os::Solaris::set_SIGasync(SIGJVM2);
1066   } else if (UseAltSigs) {
1067     os::Solaris::set_SIGasync(ALT_ASYNC_SIGNAL);
1068   } else {
1069     os::Solaris::set_SIGasync(ASYNC_SIGNAL);
1070   }
1071 
1072   sigaddset(&unblocked_sigs, os::Solaris::SIGasync());
1073 
1074   if (!ReduceSignalUsage) {
1075     if (!os::Solaris::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
1076       sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
1077       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
1078     }
1079     if (!os::Solaris::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
1080       sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
1081       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
1082     }
1083     if (!os::Solaris::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
1084       sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
1085       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
1086     }
1087   }
1088   // Fill in signals that are blocked by all but the VM thread.
1089   sigemptyset(&vm_sigs);
1090   if (!ReduceSignalUsage) {
1091     sigaddset(&vm_sigs, BREAK_SIGNAL);
1092   }
1093   debug_only(signal_sets_initialized = true);
1094 
1095   // For diagnostics only used in run_periodic_checks
1096   sigemptyset(&check_signal_done);
1097 }
1098 
1099 // These are signals that are unblocked while a thread is running Java.
1100 // (For some reason, they get blocked by default.)
1101 sigset_t* os::Solaris::unblocked_signals() {
1102   assert(signal_sets_initialized, "Not initialized");
1103   return &unblocked_sigs;
1104 }
1105 
1106 // These are the signals that are blocked while a (non-VM) thread is
1107 // running Java. Only the VM thread handles these signals.
1108 sigset_t* os::Solaris::vm_signals() {
1109   assert(signal_sets_initialized, "Not initialized");
1110   return &vm_sigs;
1111 }
1112 
1113 // These are signals that are blocked during cond_wait to allow debugger in
1114 sigset_t* os::Solaris::allowdebug_blocked_signals() {
1115   assert(signal_sets_initialized, "Not initialized");
1116   return &allowdebug_blocked_sigs;
1117 }
1118 
1119 
1120 void _handle_uncaught_cxx_exception() {
1121   VMError::report_and_die("An uncaught C++ exception");
1122 }
1123 
1124 
1125 // First crack at OS-specific initialization, from inside the new thread.
1126 void os::initialize_thread(Thread* thr) {
1127   int r = thr_main();
1128   guarantee(r == 0 || r == 1, "CR6501650 or CR6493689");
1129   if (r) {
1130     JavaThread* jt = (JavaThread *)thr;
1131     assert(jt != NULL, "Sanity check");
1132     size_t stack_size;
1133     address base = jt->stack_base();
1134     if (Arguments::created_by_java_launcher()) {
1135       // Use 2MB to allow for Solaris 7 64 bit mode.
1136       stack_size = JavaThread::stack_size_at_create() == 0
1137         ? 2048*K : JavaThread::stack_size_at_create();
1138 
1139       // There are rare cases when we may have already used more than
1140       // the basic stack size allotment before this method is invoked.
1141       // Attempt to allow for a normally sized java_stack.
1142       size_t current_stack_offset = (size_t)(base - (address)&stack_size);
1143       stack_size += ReservedSpace::page_align_size_down(current_stack_offset);
1144     } else {
1145       // 6269555: If we were not created by a Java launcher, i.e. if we are
1146       // running embedded in a native application, treat the primordial thread
1147       // as much like a native attached thread as possible.  This means using
1148       // the current stack size from thr_stksegment(), unless it is too large
1149       // to reliably setup guard pages.  A reasonable max size is 8MB.
1150       size_t current_size = current_stack_size();
1151       // This should never happen, but just in case....
1152       if (current_size == 0) current_size = 2 * K * K;
1153       stack_size = current_size > (8 * K * K) ? (8 * K * K) : current_size;
1154     }
1155     address bottom = (address)align_size_up((intptr_t)(base - stack_size), os::vm_page_size());;
1156     stack_size = (size_t)(base - bottom);
1157 
1158     assert(stack_size > 0, "Stack size calculation problem");
1159 
1160     if (stack_size > jt->stack_size()) {
1161 #ifndef PRODUCT
1162       struct rlimit limits;
1163       getrlimit(RLIMIT_STACK, &limits);
1164       size_t size = adjust_stack_size(base, (size_t)limits.rlim_cur);
1165       assert(size >= jt->stack_size(), "Stack size problem in main thread");
1166 #endif
1167       tty->print_cr("Stack size of %d Kb exceeds current limit of %d Kb.\n"
1168                     "(Stack sizes are rounded up to a multiple of the system page size.)\n"
1169                     "See limit(1) to increase the stack size limit.",
1170                     stack_size / K, jt->stack_size() / K);
1171       vm_exit(1);
1172     }
1173     assert(jt->stack_size() >= stack_size,
1174            "Attempt to map more stack than was allocated");
1175     jt->set_stack_size(stack_size);
1176   }
1177 
1178   // With the T2 libthread (T1 is no longer supported) threads are always bound
1179   // and we use stackbanging in all cases.
1180 
1181   os::Solaris::init_thread_fpu_state();
1182   std::set_terminate(_handle_uncaught_cxx_exception);
1183 }
1184 
1185 
1186 
1187 // Free Solaris resources related to the OSThread
1188 void os::free_thread(OSThread* osthread) {
1189   assert(osthread != NULL, "os::free_thread but osthread not set");
1190 
1191 
1192   // We are told to free resources of the argument thread,
1193   // but we can only really operate on the current thread.
1194   // The main thread must take the VMThread down synchronously
1195   // before the main thread exits and frees up CodeHeap
1196   guarantee((Thread::current()->osthread() == osthread
1197              || (osthread == VMThread::vm_thread()->osthread())), "os::free_thread but not current thread");
1198   if (Thread::current()->osthread() == osthread) {
1199     // Restore caller's signal mask
1200     sigset_t sigmask = osthread->caller_sigmask();
1201     thr_sigsetmask(SIG_SETMASK, &sigmask, NULL);
1202   }
1203   delete osthread;
1204 }
1205 
1206 void os::pd_start_thread(Thread* thread) {
1207   int status = thr_continue(thread->osthread()->thread_id());
1208   assert_status(status == 0, status, "thr_continue failed");
1209 }
1210 
1211 
1212 intx os::current_thread_id() {
1213   return (intx)thr_self();
1214 }
1215 
1216 static pid_t _initial_pid = 0;
1217 
1218 int os::current_process_id() {
1219   return (int)(_initial_pid ? _initial_pid : getpid());
1220 }
1221 
1222 // gethrtime() should be monotonic according to the documentation,
1223 // but some virtualized platforms are known to break this guarantee.
1224 // getTimeNanos() must be guaranteed not to move backwards, so we
1225 // are forced to add a check here.
1226 inline hrtime_t getTimeNanos() {
1227   const hrtime_t now = gethrtime();
1228   const hrtime_t prev = max_hrtime;
1229   if (now <= prev) {
1230     return prev;   // same or retrograde time;
1231   }
1232   const hrtime_t obsv = Atomic::cmpxchg(now, (volatile jlong*)&max_hrtime, prev);
1233   assert(obsv >= prev, "invariant");   // Monotonicity
1234   // If the CAS succeeded then we're done and return "now".
1235   // If the CAS failed and the observed value "obsv" is >= now then
1236   // we should return "obsv".  If the CAS failed and now > obsv > prv then
1237   // some other thread raced this thread and installed a new value, in which case
1238   // we could either (a) retry the entire operation, (b) retry trying to install now
1239   // or (c) just return obsv.  We use (c).   No loop is required although in some cases
1240   // we might discard a higher "now" value in deference to a slightly lower but freshly
1241   // installed obsv value.   That's entirely benign -- it admits no new orderings compared
1242   // to (a) or (b) -- and greatly reduces coherence traffic.
1243   // We might also condition (c) on the magnitude of the delta between obsv and now.
1244   // Avoiding excessive CAS operations to hot RW locations is critical.
1245   // See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate
1246   return (prev == obsv) ? now : obsv;
1247 }
1248 
1249 // Time since start-up in seconds to a fine granularity.
1250 // Used by VMSelfDestructTimer and the MemProfiler.
1251 double os::elapsedTime() {
1252   return (double)(getTimeNanos() - first_hrtime) / (double)hrtime_hz;
1253 }
1254 
1255 jlong os::elapsed_counter() {
1256   return (jlong)(getTimeNanos() - first_hrtime);
1257 }
1258 
1259 jlong os::elapsed_frequency() {
1260   return hrtime_hz;
1261 }
1262 
1263 // Return the real, user, and system times in seconds from an
1264 // arbitrary fixed point in the past.
1265 bool os::getTimesSecs(double* process_real_time,
1266                       double* process_user_time,
1267                       double* process_system_time) {
1268   struct tms ticks;
1269   clock_t real_ticks = times(&ticks);
1270 
1271   if (real_ticks == (clock_t) (-1)) {
1272     return false;
1273   } else {
1274     double ticks_per_second = (double) clock_tics_per_sec;
1275     *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
1276     *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
1277     // For consistency return the real time from getTimeNanos()
1278     // converted to seconds.
1279     *process_real_time = ((double) getTimeNanos()) / ((double) NANOUNITS);
1280 
1281     return true;
1282   }
1283 }
1284 
1285 bool os::supports_vtime() { return true; }
1286 
1287 bool os::enable_vtime() {
1288   int fd = ::open("/proc/self/ctl", O_WRONLY);
1289   if (fd == -1) {
1290     return false;
1291   }
1292 
1293   long cmd[] = { PCSET, PR_MSACCT };
1294   int res = ::write(fd, cmd, sizeof(long) * 2);
1295   ::close(fd);
1296   if (res != sizeof(long) * 2) {
1297     return false;
1298   }
1299   return true;
1300 }
1301 
1302 bool os::vtime_enabled() {
1303   int fd = ::open("/proc/self/status", O_RDONLY);
1304   if (fd == -1) {
1305     return false;
1306   }
1307 
1308   pstatus_t status;
1309   int res = os::read(fd, (void*) &status, sizeof(pstatus_t));
1310   ::close(fd);
1311   if (res != sizeof(pstatus_t)) {
1312     return false;
1313   }
1314   return status.pr_flags & PR_MSACCT;
1315 }
1316 
1317 double os::elapsedVTime() {
1318   return (double)gethrvtime() / (double)hrtime_hz;
1319 }
1320 
1321 // Used internally for comparisons only
1322 // getTimeMillis guaranteed to not move backwards on Solaris
1323 jlong getTimeMillis() {
1324   jlong nanotime = getTimeNanos();
1325   return (jlong)(nanotime / NANOSECS_PER_MILLISEC);
1326 }
1327 
1328 // Must return millis since Jan 1 1970 for JVM_CurrentTimeMillis
1329 jlong os::javaTimeMillis() {
1330   timeval t;
1331   if (gettimeofday(&t, NULL) == -1) {
1332     fatal("os::javaTimeMillis: gettimeofday (%s)", strerror(errno));
1333   }
1334   return jlong(t.tv_sec) * 1000  +  jlong(t.tv_usec) / 1000;
1335 }
1336 
1337 void os::javaTimeSystemUTC(jlong &seconds, jlong &nanos) {
1338   timeval t;
1339   if (gettimeofday(&t, NULL) == -1) {
1340     fatal("os::javaTimeSystemUTC: gettimeofday (%s)", strerror(errno));
1341   }
1342   seconds = jlong(t.tv_sec);
1343   nanos = jlong(t.tv_usec) * 1000;
1344 }
1345 
1346 
1347 jlong os::javaTimeNanos() {
1348   return (jlong)getTimeNanos();
1349 }
1350 
1351 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
1352   info_ptr->max_value = ALL_64_BITS;      // gethrtime() uses all 64 bits
1353   info_ptr->may_skip_backward = false;    // not subject to resetting or drifting
1354   info_ptr->may_skip_forward = false;     // not subject to resetting or drifting
1355   info_ptr->kind = JVMTI_TIMER_ELAPSED;   // elapsed not CPU time
1356 }
1357 
1358 char * os::local_time_string(char *buf, size_t buflen) {
1359   struct tm t;
1360   time_t long_time;
1361   time(&long_time);
1362   localtime_r(&long_time, &t);
1363   jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
1364                t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
1365                t.tm_hour, t.tm_min, t.tm_sec);
1366   return buf;
1367 }
1368 
1369 // Note: os::shutdown() might be called very early during initialization, or
1370 // called from signal handler. Before adding something to os::shutdown(), make
1371 // sure it is async-safe and can handle partially initialized VM.
1372 void os::shutdown() {
1373 
1374   // allow PerfMemory to attempt cleanup of any persistent resources
1375   perfMemory_exit();
1376 
1377   // needs to remove object in file system
1378   AttachListener::abort();
1379 
1380   // flush buffered output, finish log files
1381   ostream_abort();
1382 
1383   // Check for abort hook
1384   abort_hook_t abort_hook = Arguments::abort_hook();
1385   if (abort_hook != NULL) {
1386     abort_hook();
1387   }
1388 }
1389 
1390 // Note: os::abort() might be called very early during initialization, or
1391 // called from signal handler. Before adding something to os::abort(), make
1392 // sure it is async-safe and can handle partially initialized VM.
1393 void os::abort(bool dump_core, void* siginfo, void* context) {
1394   os::shutdown();
1395   if (dump_core) {
1396 #ifndef PRODUCT
1397     fdStream out(defaultStream::output_fd());
1398     out.print_raw("Current thread is ");
1399     char buf[16];
1400     jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
1401     out.print_raw_cr(buf);
1402     out.print_raw_cr("Dumping core ...");
1403 #endif
1404     ::abort(); // dump core (for debugging)
1405   }
1406 
1407   ::exit(1);
1408 }
1409 
1410 // Die immediately, no exit hook, no abort hook, no cleanup.
1411 void os::die() {
1412   ::abort(); // dump core (for debugging)
1413 }
1414 
1415 // DLL functions
1416 
1417 const char* os::dll_file_extension() { return ".so"; }
1418 
1419 // This must be hard coded because it's the system's temporary
1420 // directory not the java application's temp directory, ala java.io.tmpdir.
1421 const char* os::get_temp_directory() { return "/tmp"; }
1422 
1423 static bool file_exists(const char* filename) {
1424   struct stat statbuf;
1425   if (filename == NULL || strlen(filename) == 0) {
1426     return false;
1427   }
1428   return os::stat(filename, &statbuf) == 0;
1429 }
1430 
1431 bool os::dll_build_name(char* buffer, size_t buflen,
1432                         const char* pname, const char* fname) {
1433   bool retval = false;
1434   const size_t pnamelen = pname ? strlen(pname) : 0;
1435 
1436   // Return error on buffer overflow.
1437   if (pnamelen + strlen(fname) + 10 > (size_t) buflen) {
1438     return retval;
1439   }
1440 
1441   if (pnamelen == 0) {
1442     snprintf(buffer, buflen, "lib%s.so", fname);
1443     retval = true;
1444   } else if (strchr(pname, *os::path_separator()) != NULL) {
1445     int n;
1446     char** pelements = split_path(pname, &n);
1447     if (pelements == NULL) {
1448       return false;
1449     }
1450     for (int i = 0; i < n; i++) {
1451       // really shouldn't be NULL but what the heck, check can't hurt
1452       if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
1453         continue; // skip the empty path values
1454       }
1455       snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname);
1456       if (file_exists(buffer)) {
1457         retval = true;
1458         break;
1459       }
1460     }
1461     // release the storage
1462     for (int i = 0; i < n; i++) {
1463       if (pelements[i] != NULL) {
1464         FREE_C_HEAP_ARRAY(char, pelements[i]);
1465       }
1466     }
1467     if (pelements != NULL) {
1468       FREE_C_HEAP_ARRAY(char*, pelements);
1469     }
1470   } else {
1471     snprintf(buffer, buflen, "%s/lib%s.so", pname, fname);
1472     retval = true;
1473   }
1474   return retval;
1475 }
1476 
1477 // check if addr is inside libjvm.so
1478 bool os::address_is_in_vm(address addr) {
1479   static address libjvm_base_addr;
1480   Dl_info dlinfo;
1481 
1482   if (libjvm_base_addr == NULL) {
1483     if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {
1484       libjvm_base_addr = (address)dlinfo.dli_fbase;
1485     }
1486     assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
1487   }
1488 
1489   if (dladdr((void *)addr, &dlinfo) != 0) {
1490     if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
1491   }
1492 
1493   return false;
1494 }
1495 
1496 typedef int (*dladdr1_func_type)(void *, Dl_info *, void **, int);
1497 static dladdr1_func_type dladdr1_func = NULL;
1498 
1499 bool os::dll_address_to_function_name(address addr, char *buf,
1500                                       int buflen, int * offset,
1501                                       bool demangle) {
1502   // buf is not optional, but offset is optional
1503   assert(buf != NULL, "sanity check");
1504 
1505   Dl_info dlinfo;
1506 
1507   // dladdr1_func was initialized in os::init()
1508   if (dladdr1_func != NULL) {
1509     // yes, we have dladdr1
1510 
1511     // Support for dladdr1 is checked at runtime; it may be
1512     // available even if the vm is built on a machine that does
1513     // not have dladdr1 support.  Make sure there is a value for
1514     // RTLD_DL_SYMENT.
1515 #ifndef RTLD_DL_SYMENT
1516   #define RTLD_DL_SYMENT 1
1517 #endif
1518 #ifdef _LP64
1519     Elf64_Sym * info;
1520 #else
1521     Elf32_Sym * info;
1522 #endif
1523     if (dladdr1_func((void *)addr, &dlinfo, (void **)&info,
1524                      RTLD_DL_SYMENT) != 0) {
1525       // see if we have a matching symbol that covers our address
1526       if (dlinfo.dli_saddr != NULL &&
1527           (char *)dlinfo.dli_saddr + info->st_size > (char *)addr) {
1528         if (dlinfo.dli_sname != NULL) {
1529           if (!(demangle && Decoder::demangle(dlinfo.dli_sname, buf, buflen))) {
1530             jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
1531           }
1532           if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1533           return true;
1534         }
1535       }
1536       // no matching symbol so try for just file info
1537       if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
1538         if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1539                             buf, buflen, offset, dlinfo.dli_fname, demangle)) {
1540           return true;
1541         }
1542       }
1543     }
1544     buf[0] = '\0';
1545     if (offset != NULL) *offset  = -1;
1546     return false;
1547   }
1548 
1549   // no, only dladdr is available
1550   if (dladdr((void *)addr, &dlinfo) != 0) {
1551     // see if we have a matching symbol
1552     if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {
1553       if (!(demangle && Decoder::demangle(dlinfo.dli_sname, buf, buflen))) {
1554         jio_snprintf(buf, buflen, dlinfo.dli_sname);
1555       }
1556       if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1557       return true;
1558     }
1559     // no matching symbol so try for just file info
1560     if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
1561       if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1562                           buf, buflen, offset, dlinfo.dli_fname, demangle)) {
1563         return true;
1564       }
1565     }
1566   }
1567   buf[0] = '\0';
1568   if (offset != NULL) *offset  = -1;
1569   return false;
1570 }
1571 
1572 bool os::dll_address_to_library_name(address addr, char* buf,
1573                                      int buflen, int* offset) {
1574   // buf is not optional, but offset is optional
1575   assert(buf != NULL, "sanity check");
1576 
1577   Dl_info dlinfo;
1578 
1579   if (dladdr((void*)addr, &dlinfo) != 0) {
1580     if (dlinfo.dli_fname != NULL) {
1581       jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
1582     }
1583     if (dlinfo.dli_fbase != NULL && offset != NULL) {
1584       *offset = addr - (address)dlinfo.dli_fbase;
1585     }
1586     return true;
1587   }
1588 
1589   buf[0] = '\0';
1590   if (offset) *offset = -1;
1591   return false;
1592 }
1593 
1594 int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *param) {
1595   Dl_info dli;
1596   // Sanity check?
1597   if (dladdr(CAST_FROM_FN_PTR(void *, os::get_loaded_modules_info), &dli) == 0 ||
1598       dli.dli_fname == NULL) {
1599     return 1;
1600   }
1601 
1602   void * handle = dlopen(dli.dli_fname, RTLD_LAZY);
1603   if (handle == NULL) {
1604     return 1;
1605   }
1606 
1607   Link_map *map;
1608   dlinfo(handle, RTLD_DI_LINKMAP, &map);
1609   if (map == NULL) {
1610     dlclose(handle);
1611     return 1;
1612   }
1613 
1614   while (map->l_prev != NULL) {
1615     map = map->l_prev;
1616   }
1617 
1618   while (map != NULL) {
1619     // Iterate through all map entries and call callback with fields of interest
1620     if(callback(map->l_name, (address)map->l_addr, (address)0, param)) {
1621       dlclose(handle);
1622       return 1;
1623     }
1624     map = map->l_next;
1625   }
1626 
1627   dlclose(handle);
1628   return 0;
1629 }
1630 
1631 int _print_dll_info_cb(const char * name, address base_address, address top_address, void * param) {
1632   outputStream * out = (outputStream *) param;
1633   out->print_cr(PTR_FORMAT " \t%s", base_address, name);
1634   return 0;
1635 }
1636 
1637 void os::print_dll_info(outputStream * st) {
1638   st->print_cr("Dynamic libraries:"); st->flush();
1639   if (get_loaded_modules_info(_print_dll_info_cb, (void *)st)) {
1640     st->print_cr("Error: Cannot print dynamic libraries.");
1641   }
1642 }
1643 
1644 // Loads .dll/.so and
1645 // in case of error it checks if .dll/.so was built for the
1646 // same architecture as Hotspot is running on
1647 
1648 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
1649   void * result= ::dlopen(filename, RTLD_LAZY);
1650   if (result != NULL) {
1651     // Successful loading
1652     return result;
1653   }
1654 
1655   Elf32_Ehdr elf_head;
1656 
1657   // Read system error message into ebuf
1658   // It may or may not be overwritten below
1659   ::strncpy(ebuf, ::dlerror(), ebuflen-1);
1660   ebuf[ebuflen-1]='\0';
1661   int diag_msg_max_length=ebuflen-strlen(ebuf);
1662   char* diag_msg_buf=ebuf+strlen(ebuf);
1663 
1664   if (diag_msg_max_length==0) {
1665     // No more space in ebuf for additional diagnostics message
1666     return NULL;
1667   }
1668 
1669 
1670   int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
1671 
1672   if (file_descriptor < 0) {
1673     // Can't open library, report dlerror() message
1674     return NULL;
1675   }
1676 
1677   bool failed_to_read_elf_head=
1678     (sizeof(elf_head)!=
1679      (::read(file_descriptor, &elf_head,sizeof(elf_head))));
1680 
1681   ::close(file_descriptor);
1682   if (failed_to_read_elf_head) {
1683     // file i/o error - report dlerror() msg
1684     return NULL;
1685   }
1686 
1687   typedef struct {
1688     Elf32_Half  code;         // Actual value as defined in elf.h
1689     Elf32_Half  compat_class; // Compatibility of archs at VM's sense
1690     char        elf_class;    // 32 or 64 bit
1691     char        endianess;    // MSB or LSB
1692     char*       name;         // String representation
1693   } arch_t;
1694 
1695   static const arch_t arch_array[]={
1696     {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1697     {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1698     {EM_IA_64,       EM_IA_64,   ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
1699     {EM_X86_64,      EM_X86_64,  ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
1700     {EM_SPARC,       EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1701     {EM_SPARC32PLUS, EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1702     {EM_SPARCV9,     EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
1703     {EM_PPC,         EM_PPC,     ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
1704     {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1705     {EM_ARM,         EM_ARM,     ELFCLASS32, ELFDATA2LSB, (char*)"ARM 32"}
1706   };
1707 
1708 #if  (defined IA32)
1709   static  Elf32_Half running_arch_code=EM_386;
1710 #elif   (defined AMD64)
1711   static  Elf32_Half running_arch_code=EM_X86_64;
1712 #elif  (defined IA64)
1713   static  Elf32_Half running_arch_code=EM_IA_64;
1714 #elif  (defined __sparc) && (defined _LP64)
1715   static  Elf32_Half running_arch_code=EM_SPARCV9;
1716 #elif  (defined __sparc) && (!defined _LP64)
1717   static  Elf32_Half running_arch_code=EM_SPARC;
1718 #elif  (defined __powerpc64__)
1719   static  Elf32_Half running_arch_code=EM_PPC64;
1720 #elif  (defined __powerpc__)
1721   static  Elf32_Half running_arch_code=EM_PPC;
1722 #elif (defined ARM)
1723   static  Elf32_Half running_arch_code=EM_ARM;
1724 #else
1725   #error Method os::dll_load requires that one of following is defined:\
1726        IA32, AMD64, IA64, __sparc, __powerpc__, ARM, ARM
1727 #endif
1728 
1729   // Identify compatability class for VM's architecture and library's architecture
1730   // Obtain string descriptions for architectures
1731 
1732   arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
1733   int running_arch_index=-1;
1734 
1735   for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) {
1736     if (running_arch_code == arch_array[i].code) {
1737       running_arch_index    = i;
1738     }
1739     if (lib_arch.code == arch_array[i].code) {
1740       lib_arch.compat_class = arch_array[i].compat_class;
1741       lib_arch.name         = arch_array[i].name;
1742     }
1743   }
1744 
1745   assert(running_arch_index != -1,
1746          "Didn't find running architecture code (running_arch_code) in arch_array");
1747   if (running_arch_index == -1) {
1748     // Even though running architecture detection failed
1749     // we may still continue with reporting dlerror() message
1750     return NULL;
1751   }
1752 
1753   if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
1754     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
1755     return NULL;
1756   }
1757 
1758   if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
1759     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
1760     return NULL;
1761   }
1762 
1763   if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
1764     if (lib_arch.name!=NULL) {
1765       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1766                  " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
1767                  lib_arch.name, arch_array[running_arch_index].name);
1768     } else {
1769       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1770                  " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
1771                  lib_arch.code,
1772                  arch_array[running_arch_index].name);
1773     }
1774   }
1775 
1776   return NULL;
1777 }
1778 
1779 void* os::dll_lookup(void* handle, const char* name) {
1780   return dlsym(handle, name);
1781 }
1782 
1783 void* os::get_default_process_handle() {
1784   return (void*)::dlopen(NULL, RTLD_LAZY);
1785 }
1786 
1787 int os::stat(const char *path, struct stat *sbuf) {
1788   char pathbuf[MAX_PATH];
1789   if (strlen(path) > MAX_PATH - 1) {
1790     errno = ENAMETOOLONG;
1791     return -1;
1792   }
1793   os::native_path(strcpy(pathbuf, path));
1794   return ::stat(pathbuf, sbuf);
1795 }
1796 
1797 static bool _print_ascii_file(const char* filename, outputStream* st) {
1798   int fd = ::open(filename, O_RDONLY);
1799   if (fd == -1) {
1800     return false;
1801   }
1802 
1803   char buf[32];
1804   int bytes;
1805   while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
1806     st->print_raw(buf, bytes);
1807   }
1808 
1809   ::close(fd);
1810 
1811   return true;
1812 }
1813 
1814 void os::print_os_info_brief(outputStream* st) {
1815   os::Solaris::print_distro_info(st);
1816 
1817   os::Posix::print_uname_info(st);
1818 
1819   os::Solaris::print_libversion_info(st);
1820 }
1821 
1822 void os::print_os_info(outputStream* st) {
1823   st->print("OS:");
1824 
1825   os::Solaris::print_distro_info(st);
1826 
1827   os::Posix::print_uname_info(st);
1828 
1829   os::Solaris::print_libversion_info(st);
1830 
1831   os::Posix::print_rlimit_info(st);
1832 
1833   os::Posix::print_load_average(st);
1834 }
1835 
1836 void os::Solaris::print_distro_info(outputStream* st) {
1837   if (!_print_ascii_file("/etc/release", st)) {
1838     st->print("Solaris");
1839   }
1840   st->cr();
1841 }
1842 
1843 void os::get_summary_os_info(char* buf, size_t buflen) {
1844   strncpy(buf, "Solaris", buflen);  // default to plain solaris
1845   FILE* fp = fopen("/etc/release", "r");
1846   if (fp != NULL) {
1847     char tmp[256];
1848     // Only get the first line and chop out everything but the os name.
1849     if (fgets(tmp, sizeof(tmp), fp)) {
1850       char* ptr = tmp;
1851       // skip past whitespace characters
1852       while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\t' || *ptr == '\n')) ptr++;
1853       if (*ptr != '\0') {
1854         char* nl = strchr(ptr, '\n');
1855         if (nl != NULL) *nl = '\0';
1856         strncpy(buf, ptr, buflen);
1857       }
1858     }
1859     fclose(fp);
1860   }
1861 }
1862 
1863 void os::Solaris::print_libversion_info(outputStream* st) {
1864   st->print("  (T2 libthread)");
1865   st->cr();
1866 }
1867 
1868 static bool check_addr0(outputStream* st) {
1869   jboolean status = false;
1870   int fd = ::open("/proc/self/map",O_RDONLY);
1871   if (fd >= 0) {
1872     prmap_t p;
1873     while (::read(fd, &p, sizeof(p)) > 0) {
1874       if (p.pr_vaddr == 0x0) {
1875         st->print("Warning: Address: 0x%x, Size: %dK, ",p.pr_vaddr, p.pr_size/1024, p.pr_mapname);
1876         st->print("Mapped file: %s, ", p.pr_mapname[0] == '\0' ? "None" : p.pr_mapname);
1877         st->print("Access:");
1878         st->print("%s",(p.pr_mflags & MA_READ)  ? "r" : "-");
1879         st->print("%s",(p.pr_mflags & MA_WRITE) ? "w" : "-");
1880         st->print("%s",(p.pr_mflags & MA_EXEC)  ? "x" : "-");
1881         st->cr();
1882         status = true;
1883       }
1884     }
1885     ::close(fd);
1886   }
1887   return status;
1888 }
1889 
1890 void os::get_summary_cpu_info(char* buf, size_t buflen) {
1891   // Get MHz with system call. We don't seem to already have this.
1892   processor_info_t stats;
1893   processorid_t id = getcpuid();
1894   int clock = 0;
1895   if (processor_info(id, &stats) != -1) {
1896     clock = stats.pi_clock;  // pi_processor_type isn't more informative than below
1897   }
1898 #ifdef AMD64
1899   snprintf(buf, buflen, "x86 64 bit %d MHz", clock);
1900 #else
1901   // must be sparc
1902   snprintf(buf, buflen, "Sparcv9 64 bit %d MHz", clock);
1903 #endif
1904 }
1905 
1906 void os::pd_print_cpu_info(outputStream* st, char* buf, size_t buflen) {
1907   // Nothing to do for now.
1908 }
1909 
1910 void os::print_memory_info(outputStream* st) {
1911   st->print("Memory:");
1912   st->print(" %dk page", os::vm_page_size()>>10);
1913   st->print(", physical " UINT64_FORMAT "k", os::physical_memory()>>10);
1914   st->print("(" UINT64_FORMAT "k free)", os::available_memory() >> 10);
1915   st->cr();
1916   (void) check_addr0(st);
1917 }
1918 
1919 void os::print_siginfo(outputStream* st, void* siginfo) {
1920   const siginfo_t* si = (const siginfo_t*)siginfo;
1921 
1922   os::Posix::print_siginfo_brief(st, si);
1923 
1924   if (si && (si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&
1925       UseSharedSpaces) {
1926     FileMapInfo* mapinfo = FileMapInfo::current_info();
1927     if (mapinfo->is_in_shared_space(si->si_addr)) {
1928       st->print("\n\nError accessing class data sharing archive."   \
1929                 " Mapped file inaccessible during execution, "      \
1930                 " possible disk/network problem.");
1931     }
1932   }
1933   st->cr();
1934 }
1935 
1936 // Moved from whole group, because we need them here for diagnostic
1937 // prints.
1938 #define OLDMAXSIGNUM 32
1939 static int Maxsignum = 0;
1940 static int *ourSigFlags = NULL;
1941 
1942 int os::Solaris::get_our_sigflags(int sig) {
1943   assert(ourSigFlags!=NULL, "signal data structure not initialized");
1944   assert(sig > 0 && sig < Maxsignum, "vm signal out of expected range");
1945   return ourSigFlags[sig];
1946 }
1947 
1948 void os::Solaris::set_our_sigflags(int sig, int flags) {
1949   assert(ourSigFlags!=NULL, "signal data structure not initialized");
1950   assert(sig > 0 && sig < Maxsignum, "vm signal out of expected range");
1951   ourSigFlags[sig] = flags;
1952 }
1953 
1954 
1955 static const char* get_signal_handler_name(address handler,
1956                                            char* buf, int buflen) {
1957   int offset;
1958   bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
1959   if (found) {
1960     // skip directory names
1961     const char *p1, *p2;
1962     p1 = buf;
1963     size_t len = strlen(os::file_separator());
1964     while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
1965     jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
1966   } else {
1967     jio_snprintf(buf, buflen, PTR_FORMAT, handler);
1968   }
1969   return buf;
1970 }
1971 
1972 static void print_signal_handler(outputStream* st, int sig,
1973                                  char* buf, size_t buflen) {
1974   struct sigaction sa;
1975 
1976   sigaction(sig, NULL, &sa);
1977 
1978   st->print("%s: ", os::exception_name(sig, buf, buflen));
1979 
1980   address handler = (sa.sa_flags & SA_SIGINFO)
1981                   ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
1982                   : CAST_FROM_FN_PTR(address, sa.sa_handler);
1983 
1984   if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
1985     st->print("SIG_DFL");
1986   } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
1987     st->print("SIG_IGN");
1988   } else {
1989     st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
1990   }
1991 
1992   st->print(", sa_mask[0]=");
1993   os::Posix::print_signal_set_short(st, &sa.sa_mask);
1994 
1995   address rh = VMError::get_resetted_sighandler(sig);
1996   // May be, handler was resetted by VMError?
1997   if (rh != NULL) {
1998     handler = rh;
1999     sa.sa_flags = VMError::get_resetted_sigflags(sig);
2000   }
2001 
2002   st->print(", sa_flags=");
2003   os::Posix::print_sa_flags(st, sa.sa_flags);
2004 
2005   // Check: is it our handler?
2006   if (handler == CAST_FROM_FN_PTR(address, signalHandler)) {
2007     // It is our signal handler
2008     // check for flags
2009     if (sa.sa_flags != os::Solaris::get_our_sigflags(sig)) {
2010       st->print(
2011                 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
2012                 os::Solaris::get_our_sigflags(sig));
2013     }
2014   }
2015   st->cr();
2016 }
2017 
2018 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
2019   st->print_cr("Signal Handlers:");
2020   print_signal_handler(st, SIGSEGV, buf, buflen);
2021   print_signal_handler(st, SIGBUS , buf, buflen);
2022   print_signal_handler(st, SIGFPE , buf, buflen);
2023   print_signal_handler(st, SIGPIPE, buf, buflen);
2024   print_signal_handler(st, SIGXFSZ, buf, buflen);
2025   print_signal_handler(st, SIGILL , buf, buflen);
2026   print_signal_handler(st, ASYNC_SIGNAL, buf, buflen);
2027   print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
2028   print_signal_handler(st, SHUTDOWN1_SIGNAL , buf, buflen);
2029   print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
2030   print_signal_handler(st, SHUTDOWN3_SIGNAL, buf, buflen);
2031   print_signal_handler(st, os::Solaris::SIGasync(), buf, buflen);
2032 }
2033 
2034 static char saved_jvm_path[MAXPATHLEN] = { 0 };
2035 
2036 // Find the full path to the current module, libjvm.so
2037 void os::jvm_path(char *buf, jint buflen) {
2038   // Error checking.
2039   if (buflen < MAXPATHLEN) {
2040     assert(false, "must use a large-enough buffer");
2041     buf[0] = '\0';
2042     return;
2043   }
2044   // Lazy resolve the path to current module.
2045   if (saved_jvm_path[0] != 0) {
2046     strcpy(buf, saved_jvm_path);
2047     return;
2048   }
2049 
2050   Dl_info dlinfo;
2051   int ret = dladdr(CAST_FROM_FN_PTR(void *, os::jvm_path), &dlinfo);
2052   assert(ret != 0, "cannot locate libjvm");
2053   if (ret != 0 && dlinfo.dli_fname != NULL) {
2054     realpath((char *)dlinfo.dli_fname, buf);
2055   } else {
2056     buf[0] = '\0';
2057     return;
2058   }
2059 
2060   if (Arguments::sun_java_launcher_is_altjvm()) {
2061     // Support for the java launcher's '-XXaltjvm=<path>' option. Typical
2062     // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so".
2063     // If "/jre/lib/" appears at the right place in the string, then
2064     // assume we are installed in a JDK and we're done.  Otherwise, check
2065     // for a JAVA_HOME environment variable and fix up the path so it
2066     // looks like libjvm.so is installed there (append a fake suffix
2067     // hotspot/libjvm.so).
2068     const char *p = buf + strlen(buf) - 1;
2069     for (int count = 0; p > buf && count < 5; ++count) {
2070       for (--p; p > buf && *p != '/'; --p)
2071         /* empty */ ;
2072     }
2073 
2074     if (strncmp(p, "/jre/lib/", 9) != 0) {
2075       // Look for JAVA_HOME in the environment.
2076       char* java_home_var = ::getenv("JAVA_HOME");
2077       if (java_home_var != NULL && java_home_var[0] != 0) {
2078         char cpu_arch[12];
2079         char* jrelib_p;
2080         int   len;
2081         sysinfo(SI_ARCHITECTURE, cpu_arch, sizeof(cpu_arch));
2082 #ifdef _LP64
2083         // If we are on sparc running a 64-bit vm, look in jre/lib/sparcv9.
2084         if (strcmp(cpu_arch, "sparc") == 0) {
2085           strcat(cpu_arch, "v9");
2086         } else if (strcmp(cpu_arch, "i386") == 0) {
2087           strcpy(cpu_arch, "amd64");
2088         }
2089 #endif
2090         // Check the current module name "libjvm.so".
2091         p = strrchr(buf, '/');
2092         assert(strstr(p, "/libjvm") == p, "invalid library name");
2093 
2094         realpath(java_home_var, buf);
2095         // determine if this is a legacy image or modules image
2096         // modules image doesn't have "jre" subdirectory
2097         len = strlen(buf);
2098         assert(len < buflen, "Ran out of buffer space");
2099         jrelib_p = buf + len;
2100         snprintf(jrelib_p, buflen-len, "/jre/lib/%s", cpu_arch);
2101         if (0 != access(buf, F_OK)) {
2102           snprintf(jrelib_p, buflen-len, "/lib/%s", cpu_arch);
2103         }
2104 
2105         if (0 == access(buf, F_OK)) {
2106           // Use current module name "libjvm.so"
2107           len = strlen(buf);
2108           snprintf(buf + len, buflen-len, "/hotspot/libjvm.so");
2109         } else {
2110           // Go back to path of .so
2111           realpath((char *)dlinfo.dli_fname, buf);
2112         }
2113       }
2114     }
2115   }
2116 
2117   strncpy(saved_jvm_path, buf, MAXPATHLEN);
2118   saved_jvm_path[MAXPATHLEN - 1] = '\0';
2119 }
2120 
2121 
2122 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
2123   // no prefix required, not even "_"
2124 }
2125 
2126 
2127 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
2128   // no suffix required
2129 }
2130 
2131 // This method is a copy of JDK's sysGetLastErrorString
2132 // from src/solaris/hpi/src/system_md.c
2133 
2134 size_t os::lasterror(char *buf, size_t len) {
2135   if (errno == 0)  return 0;
2136 
2137   const char *s = ::strerror(errno);
2138   size_t n = ::strlen(s);
2139   if (n >= len) {
2140     n = len - 1;
2141   }
2142   ::strncpy(buf, s, n);
2143   buf[n] = '\0';
2144   return n;
2145 }
2146 
2147 
2148 // sun.misc.Signal
2149 
2150 extern "C" {
2151   static void UserHandler(int sig, void *siginfo, void *context) {
2152     // Ctrl-C is pressed during error reporting, likely because the error
2153     // handler fails to abort. Let VM die immediately.
2154     if (sig == SIGINT && is_error_reported()) {
2155       os::die();
2156     }
2157 
2158     os::signal_notify(sig);
2159     // We do not need to reinstate the signal handler each time...
2160   }
2161 }
2162 
2163 void* os::user_handler() {
2164   return CAST_FROM_FN_PTR(void*, UserHandler);
2165 }
2166 
2167 struct timespec PosixSemaphore::create_timespec(unsigned int sec, int nsec) {
2168   struct timespec ts;
2169   unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);
2170 
2171   return ts;
2172 }
2173 
2174 extern "C" {
2175   typedef void (*sa_handler_t)(int);
2176   typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
2177 }
2178 
2179 void* os::signal(int signal_number, void* handler) {
2180   struct sigaction sigAct, oldSigAct;
2181   sigfillset(&(sigAct.sa_mask));
2182   sigAct.sa_flags = SA_RESTART & ~SA_RESETHAND;
2183   sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
2184 
2185   if (sigaction(signal_number, &sigAct, &oldSigAct)) {
2186     // -1 means registration failed
2187     return (void *)-1;
2188   }
2189 
2190   return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
2191 }
2192 
2193 void os::signal_raise(int signal_number) {
2194   raise(signal_number);
2195 }
2196 
2197 // The following code is moved from os.cpp for making this
2198 // code platform specific, which it is by its very nature.
2199 
2200 // a counter for each possible signal value
2201 static int Sigexit = 0;
2202 static int Maxlibjsigsigs;
2203 static jint *pending_signals = NULL;
2204 static int *preinstalled_sigs = NULL;
2205 static struct sigaction *chainedsigactions = NULL;
2206 static sema_t sig_sem;
2207 typedef int (*version_getting_t)();
2208 version_getting_t os::Solaris::get_libjsig_version = NULL;
2209 static int libjsigversion = NULL;
2210 
2211 int os::sigexitnum_pd() {
2212   assert(Sigexit > 0, "signal memory not yet initialized");
2213   return Sigexit;
2214 }
2215 
2216 void os::Solaris::init_signal_mem() {
2217   // Initialize signal structures
2218   Maxsignum = SIGRTMAX;
2219   Sigexit = Maxsignum+1;
2220   assert(Maxsignum >0, "Unable to obtain max signal number");
2221 
2222   Maxlibjsigsigs = Maxsignum;
2223 
2224   // pending_signals has one int per signal
2225   // The additional signal is for SIGEXIT - exit signal to signal_thread
2226   pending_signals = (jint *)os::malloc(sizeof(jint) * (Sigexit+1), mtInternal);
2227   memset(pending_signals, 0, (sizeof(jint) * (Sigexit+1)));
2228 
2229   if (UseSignalChaining) {
2230     chainedsigactions = (struct sigaction *)malloc(sizeof(struct sigaction)
2231                                                    * (Maxsignum + 1), mtInternal);
2232     memset(chainedsigactions, 0, (sizeof(struct sigaction) * (Maxsignum + 1)));
2233     preinstalled_sigs = (int *)os::malloc(sizeof(int) * (Maxsignum + 1), mtInternal);
2234     memset(preinstalled_sigs, 0, (sizeof(int) * (Maxsignum + 1)));
2235   }
2236   ourSigFlags = (int*)malloc(sizeof(int) * (Maxsignum + 1), mtInternal);
2237   memset(ourSigFlags, 0, sizeof(int) * (Maxsignum + 1));
2238 }
2239 
2240 void os::signal_init_pd() {
2241   int ret;
2242 
2243   ret = ::sema_init(&sig_sem, 0, NULL, NULL);
2244   assert(ret == 0, "sema_init() failed");
2245 }
2246 
2247 void os::signal_notify(int signal_number) {
2248   int ret;
2249 
2250   Atomic::inc(&pending_signals[signal_number]);
2251   ret = ::sema_post(&sig_sem);
2252   assert(ret == 0, "sema_post() failed");
2253 }
2254 
2255 static int check_pending_signals(bool wait_for_signal) {
2256   int ret;
2257   while (true) {
2258     for (int i = 0; i < Sigexit + 1; i++) {
2259       jint n = pending_signals[i];
2260       if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
2261         return i;
2262       }
2263     }
2264     if (!wait_for_signal) {
2265       return -1;
2266     }
2267     JavaThread *thread = JavaThread::current();
2268     ThreadBlockInVM tbivm(thread);
2269 
2270     bool threadIsSuspended;
2271     do {
2272       thread->set_suspend_equivalent();
2273       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
2274       while ((ret = ::sema_wait(&sig_sem)) == EINTR)
2275         ;
2276       assert(ret == 0, "sema_wait() failed");
2277 
2278       // were we externally suspended while we were waiting?
2279       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
2280       if (threadIsSuspended) {
2281         // The semaphore has been incremented, but while we were waiting
2282         // another thread suspended us. We don't want to continue running
2283         // while suspended because that would surprise the thread that
2284         // suspended us.
2285         ret = ::sema_post(&sig_sem);
2286         assert(ret == 0, "sema_post() failed");
2287 
2288         thread->java_suspend_self();
2289       }
2290     } while (threadIsSuspended);
2291   }
2292 }
2293 
2294 int os::signal_lookup() {
2295   return check_pending_signals(false);
2296 }
2297 
2298 int os::signal_wait() {
2299   return check_pending_signals(true);
2300 }
2301 
2302 ////////////////////////////////////////////////////////////////////////////////
2303 // Virtual Memory
2304 
2305 static int page_size = -1;
2306 
2307 // The mmap MAP_ALIGN flag is supported on Solaris 9 and later.  init_2() will
2308 // clear this var if support is not available.
2309 static bool has_map_align = true;
2310 
2311 int os::vm_page_size() {
2312   assert(page_size != -1, "must call os::init");
2313   return page_size;
2314 }
2315 
2316 // Solaris allocates memory by pages.
2317 int os::vm_allocation_granularity() {
2318   assert(page_size != -1, "must call os::init");
2319   return page_size;
2320 }
2321 
2322 static bool recoverable_mmap_error(int err) {
2323   // See if the error is one we can let the caller handle. This
2324   // list of errno values comes from the Solaris mmap(2) man page.
2325   switch (err) {
2326   case EBADF:
2327   case EINVAL:
2328   case ENOTSUP:
2329     // let the caller deal with these errors
2330     return true;
2331 
2332   default:
2333     // Any remaining errors on this OS can cause our reserved mapping
2334     // to be lost. That can cause confusion where different data
2335     // structures think they have the same memory mapped. The worst
2336     // scenario is if both the VM and a library think they have the
2337     // same memory mapped.
2338     return false;
2339   }
2340 }
2341 
2342 static void warn_fail_commit_memory(char* addr, size_t bytes, bool exec,
2343                                     int err) {
2344   warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2345           ", %d) failed; error='%s' (errno=%d)", addr, bytes, exec,
2346           strerror(err), err);
2347 }
2348 
2349 static void warn_fail_commit_memory(char* addr, size_t bytes,
2350                                     size_t alignment_hint, bool exec,
2351                                     int err) {
2352   warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2353           ", " SIZE_FORMAT ", %d) failed; error='%s' (errno=%d)", addr, bytes,
2354           alignment_hint, exec, strerror(err), err);
2355 }
2356 
2357 int os::Solaris::commit_memory_impl(char* addr, size_t bytes, bool exec) {
2358   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
2359   size_t size = bytes;
2360   char *res = Solaris::mmap_chunk(addr, size, MAP_PRIVATE|MAP_FIXED, prot);
2361   if (res != NULL) {
2362     if (UseNUMAInterleaving) {
2363       numa_make_global(addr, bytes);
2364     }
2365     return 0;
2366   }
2367 
2368   int err = errno;  // save errno from mmap() call in mmap_chunk()
2369 
2370   if (!recoverable_mmap_error(err)) {
2371     warn_fail_commit_memory(addr, bytes, exec, err);
2372     vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, "committing reserved memory.");
2373   }
2374 
2375   return err;
2376 }
2377 
2378 bool os::pd_commit_memory(char* addr, size_t bytes, bool exec) {
2379   return Solaris::commit_memory_impl(addr, bytes, exec) == 0;
2380 }
2381 
2382 void os::pd_commit_memory_or_exit(char* addr, size_t bytes, bool exec,
2383                                   const char* mesg) {
2384   assert(mesg != NULL, "mesg must be specified");
2385   int err = os::Solaris::commit_memory_impl(addr, bytes, exec);
2386   if (err != 0) {
2387     // the caller wants all commit errors to exit with the specified mesg:
2388     warn_fail_commit_memory(addr, bytes, exec, err);
2389     vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, "%s", mesg);
2390   }
2391 }
2392 
2393 size_t os::Solaris::page_size_for_alignment(size_t alignment) {
2394   assert(is_size_aligned(alignment, (size_t) vm_page_size()),
2395          SIZE_FORMAT " is not aligned to " SIZE_FORMAT,
2396          alignment, (size_t) vm_page_size());
2397 
2398   for (int i = 0; _page_sizes[i] != 0; i++) {
2399     if (is_size_aligned(alignment, _page_sizes[i])) {
2400       return _page_sizes[i];
2401     }
2402   }
2403 
2404   return (size_t) vm_page_size();
2405 }
2406 
2407 int os::Solaris::commit_memory_impl(char* addr, size_t bytes,
2408                                     size_t alignment_hint, bool exec) {
2409   int err = Solaris::commit_memory_impl(addr, bytes, exec);
2410   if (err == 0 && UseLargePages && alignment_hint > 0) {
2411     assert(is_size_aligned(bytes, alignment_hint),
2412            SIZE_FORMAT " is not aligned to " SIZE_FORMAT, bytes, alignment_hint);
2413 
2414     // The syscall memcntl requires an exact page size (see man memcntl for details).
2415     size_t page_size = page_size_for_alignment(alignment_hint);
2416     if (page_size > (size_t) vm_page_size()) {
2417       (void)Solaris::setup_large_pages(addr, bytes, page_size);
2418     }
2419   }
2420   return err;
2421 }
2422 
2423 bool os::pd_commit_memory(char* addr, size_t bytes, size_t alignment_hint,
2424                           bool exec) {
2425   return Solaris::commit_memory_impl(addr, bytes, alignment_hint, exec) == 0;
2426 }
2427 
2428 void os::pd_commit_memory_or_exit(char* addr, size_t bytes,
2429                                   size_t alignment_hint, bool exec,
2430                                   const char* mesg) {
2431   assert(mesg != NULL, "mesg must be specified");
2432   int err = os::Solaris::commit_memory_impl(addr, bytes, alignment_hint, exec);
2433   if (err != 0) {
2434     // the caller wants all commit errors to exit with the specified mesg:
2435     warn_fail_commit_memory(addr, bytes, alignment_hint, exec, err);
2436     vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, "%s", mesg);
2437   }
2438 }
2439 
2440 // Uncommit the pages in a specified region.
2441 void os::pd_free_memory(char* addr, size_t bytes, size_t alignment_hint) {
2442   if (madvise(addr, bytes, MADV_FREE) < 0) {
2443     debug_only(warning("MADV_FREE failed."));
2444     return;
2445   }
2446 }
2447 
2448 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
2449   return os::commit_memory(addr, size, !ExecMem);
2450 }
2451 
2452 bool os::remove_stack_guard_pages(char* addr, size_t size) {
2453   return os::uncommit_memory(addr, size);
2454 }
2455 
2456 // Change the page size in a given range.
2457 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
2458   assert((intptr_t)addr % alignment_hint == 0, "Address should be aligned.");
2459   assert((intptr_t)(addr + bytes) % alignment_hint == 0, "End should be aligned.");
2460   if (UseLargePages) {
2461     size_t page_size = Solaris::page_size_for_alignment(alignment_hint);
2462     if (page_size > (size_t) vm_page_size()) {
2463       Solaris::setup_large_pages(addr, bytes, page_size);
2464     }
2465   }
2466 }
2467 
2468 // Tell the OS to make the range local to the first-touching LWP
2469 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
2470   assert((intptr_t)addr % os::vm_page_size() == 0, "Address should be page-aligned.");
2471   if (madvise(addr, bytes, MADV_ACCESS_LWP) < 0) {
2472     debug_only(warning("MADV_ACCESS_LWP failed."));
2473   }
2474 }
2475 
2476 // Tell the OS that this range would be accessed from different LWPs.
2477 void os::numa_make_global(char *addr, size_t bytes) {
2478   assert((intptr_t)addr % os::vm_page_size() == 0, "Address should be page-aligned.");
2479   if (madvise(addr, bytes, MADV_ACCESS_MANY) < 0) {
2480     debug_only(warning("MADV_ACCESS_MANY failed."));
2481   }
2482 }
2483 
2484 // Get the number of the locality groups.
2485 size_t os::numa_get_groups_num() {
2486   size_t n = Solaris::lgrp_nlgrps(Solaris::lgrp_cookie());
2487   return n != -1 ? n : 1;
2488 }
2489 
2490 // Get a list of leaf locality groups. A leaf lgroup is group that
2491 // doesn't have any children. Typical leaf group is a CPU or a CPU/memory
2492 // board. An LWP is assigned to one of these groups upon creation.
2493 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
2494   if ((ids[0] = Solaris::lgrp_root(Solaris::lgrp_cookie())) == -1) {
2495     ids[0] = 0;
2496     return 1;
2497   }
2498   int result_size = 0, top = 1, bottom = 0, cur = 0;
2499   for (int k = 0; k < size; k++) {
2500     int r = Solaris::lgrp_children(Solaris::lgrp_cookie(), ids[cur],
2501                                    (Solaris::lgrp_id_t*)&ids[top], size - top);
2502     if (r == -1) {
2503       ids[0] = 0;
2504       return 1;
2505     }
2506     if (!r) {
2507       // That's a leaf node.
2508       assert(bottom <= cur, "Sanity check");
2509       // Check if the node has memory
2510       if (Solaris::lgrp_resources(Solaris::lgrp_cookie(), ids[cur],
2511                                   NULL, 0, LGRP_RSRC_MEM) > 0) {
2512         ids[bottom++] = ids[cur];
2513       }
2514     }
2515     top += r;
2516     cur++;
2517   }
2518   if (bottom == 0) {
2519     // Handle a situation, when the OS reports no memory available.
2520     // Assume UMA architecture.
2521     ids[0] = 0;
2522     return 1;
2523   }
2524   return bottom;
2525 }
2526 
2527 // Detect the topology change. Typically happens during CPU plugging-unplugging.
2528 bool os::numa_topology_changed() {
2529   int is_stale = Solaris::lgrp_cookie_stale(Solaris::lgrp_cookie());
2530   if (is_stale != -1 && is_stale) {
2531     Solaris::lgrp_fini(Solaris::lgrp_cookie());
2532     Solaris::lgrp_cookie_t c = Solaris::lgrp_init(Solaris::LGRP_VIEW_CALLER);
2533     assert(c != 0, "Failure to initialize LGRP API");
2534     Solaris::set_lgrp_cookie(c);
2535     return true;
2536   }
2537   return false;
2538 }
2539 
2540 // Get the group id of the current LWP.
2541 int os::numa_get_group_id() {
2542   int lgrp_id = Solaris::lgrp_home(P_LWPID, P_MYID);
2543   if (lgrp_id == -1) {
2544     return 0;
2545   }
2546   const int size = os::numa_get_groups_num();
2547   int *ids = (int*)alloca(size * sizeof(int));
2548 
2549   // Get the ids of all lgroups with memory; r is the count.
2550   int r = Solaris::lgrp_resources(Solaris::lgrp_cookie(), lgrp_id,
2551                                   (Solaris::lgrp_id_t*)ids, size, LGRP_RSRC_MEM);
2552   if (r <= 0) {
2553     return 0;
2554   }
2555   return ids[os::random() % r];
2556 }
2557 
2558 // Request information about the page.
2559 bool os::get_page_info(char *start, page_info* info) {
2560   const uint_t info_types[] = { MEMINFO_VLGRP, MEMINFO_VPAGESIZE };
2561   uint64_t addr = (uintptr_t)start;
2562   uint64_t outdata[2];
2563   uint_t validity = 0;
2564 
2565   if (os::Solaris::meminfo(&addr, 1, info_types, 2, outdata, &validity) < 0) {
2566     return false;
2567   }
2568 
2569   info->size = 0;
2570   info->lgrp_id = -1;
2571 
2572   if ((validity & 1) != 0) {
2573     if ((validity & 2) != 0) {
2574       info->lgrp_id = outdata[0];
2575     }
2576     if ((validity & 4) != 0) {
2577       info->size = outdata[1];
2578     }
2579     return true;
2580   }
2581   return false;
2582 }
2583 
2584 // Scan the pages from start to end until a page different than
2585 // the one described in the info parameter is encountered.
2586 char *os::scan_pages(char *start, char* end, page_info* page_expected,
2587                      page_info* page_found) {
2588   const uint_t info_types[] = { MEMINFO_VLGRP, MEMINFO_VPAGESIZE };
2589   const size_t types = sizeof(info_types) / sizeof(info_types[0]);
2590   uint64_t addrs[MAX_MEMINFO_CNT], outdata[types * MAX_MEMINFO_CNT + 1];
2591   uint_t validity[MAX_MEMINFO_CNT];
2592 
2593   size_t page_size = MAX2((size_t)os::vm_page_size(), page_expected->size);
2594   uint64_t p = (uint64_t)start;
2595   while (p < (uint64_t)end) {
2596     addrs[0] = p;
2597     size_t addrs_count = 1;
2598     while (addrs_count < MAX_MEMINFO_CNT && addrs[addrs_count - 1] + page_size < (uint64_t)end) {
2599       addrs[addrs_count] = addrs[addrs_count - 1] + page_size;
2600       addrs_count++;
2601     }
2602 
2603     if (os::Solaris::meminfo(addrs, addrs_count, info_types, types, outdata, validity) < 0) {
2604       return NULL;
2605     }
2606 
2607     size_t i = 0;
2608     for (; i < addrs_count; i++) {
2609       if ((validity[i] & 1) != 0) {
2610         if ((validity[i] & 4) != 0) {
2611           if (outdata[types * i + 1] != page_expected->size) {
2612             break;
2613           }
2614         } else if (page_expected->size != 0) {
2615           break;
2616         }
2617 
2618         if ((validity[i] & 2) != 0 && page_expected->lgrp_id > 0) {
2619           if (outdata[types * i] != page_expected->lgrp_id) {
2620             break;
2621           }
2622         }
2623       } else {
2624         return NULL;
2625       }
2626     }
2627 
2628     if (i < addrs_count) {
2629       if ((validity[i] & 2) != 0) {
2630         page_found->lgrp_id = outdata[types * i];
2631       } else {
2632         page_found->lgrp_id = -1;
2633       }
2634       if ((validity[i] & 4) != 0) {
2635         page_found->size = outdata[types * i + 1];
2636       } else {
2637         page_found->size = 0;
2638       }
2639       return (char*)addrs[i];
2640     }
2641 
2642     p = addrs[addrs_count - 1] + page_size;
2643   }
2644   return end;
2645 }
2646 
2647 bool os::pd_uncommit_memory(char* addr, size_t bytes) {
2648   size_t size = bytes;
2649   // Map uncommitted pages PROT_NONE so we fail early if we touch an
2650   // uncommitted page. Otherwise, the read/write might succeed if we
2651   // have enough swap space to back the physical page.
2652   return
2653     NULL != Solaris::mmap_chunk(addr, size,
2654                                 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE,
2655                                 PROT_NONE);
2656 }
2657 
2658 char* os::Solaris::mmap_chunk(char *addr, size_t size, int flags, int prot) {
2659   char *b = (char *)mmap(addr, size, prot, flags, os::Solaris::_dev_zero_fd, 0);
2660 
2661   if (b == MAP_FAILED) {
2662     return NULL;
2663   }
2664   return b;
2665 }
2666 
2667 char* os::Solaris::anon_mmap(char* requested_addr, size_t bytes,
2668                              size_t alignment_hint, bool fixed) {
2669   char* addr = requested_addr;
2670   int flags = MAP_PRIVATE | MAP_NORESERVE;
2671 
2672   assert(!(fixed && (alignment_hint > 0)),
2673          "alignment hint meaningless with fixed mmap");
2674 
2675   if (fixed) {
2676     flags |= MAP_FIXED;
2677   } else if (has_map_align && (alignment_hint > (size_t) vm_page_size())) {
2678     flags |= MAP_ALIGN;
2679     addr = (char*) alignment_hint;
2680   }
2681 
2682   // Map uncommitted pages PROT_NONE so we fail early if we touch an
2683   // uncommitted page. Otherwise, the read/write might succeed if we
2684   // have enough swap space to back the physical page.
2685   return mmap_chunk(addr, bytes, flags, PROT_NONE);
2686 }
2687 
2688 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
2689                             size_t alignment_hint) {
2690   char* addr = Solaris::anon_mmap(requested_addr, bytes, alignment_hint,
2691                                   (requested_addr != NULL));
2692 
2693   guarantee(requested_addr == NULL || requested_addr == addr,
2694             "OS failed to return requested mmap address.");
2695   return addr;
2696 }
2697 
2698 // Reserve memory at an arbitrary address, only if that area is
2699 // available (and not reserved for something else).
2700 
2701 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
2702   const int max_tries = 10;
2703   char* base[max_tries];
2704   size_t size[max_tries];
2705 
2706   // Solaris adds a gap between mmap'ed regions.  The size of the gap
2707   // is dependent on the requested size and the MMU.  Our initial gap
2708   // value here is just a guess and will be corrected later.
2709   bool had_top_overlap = false;
2710   bool have_adjusted_gap = false;
2711   size_t gap = 0x400000;
2712 
2713   // Assert only that the size is a multiple of the page size, since
2714   // that's all that mmap requires, and since that's all we really know
2715   // about at this low abstraction level.  If we need higher alignment,
2716   // we can either pass an alignment to this method or verify alignment
2717   // in one of the methods further up the call chain.  See bug 5044738.
2718   assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
2719 
2720   // Since snv_84, Solaris attempts to honor the address hint - see 5003415.
2721   // Give it a try, if the kernel honors the hint we can return immediately.
2722   char* addr = Solaris::anon_mmap(requested_addr, bytes, 0, false);
2723 
2724   volatile int err = errno;
2725   if (addr == requested_addr) {
2726     return addr;
2727   } else if (addr != NULL) {
2728     pd_unmap_memory(addr, bytes);
2729   }
2730 
2731   if (PrintMiscellaneous && Verbose) {
2732     char buf[256];
2733     buf[0] = '\0';
2734     if (addr == NULL) {
2735       jio_snprintf(buf, sizeof(buf), ": %s", strerror(err));
2736     }
2737     warning("attempt_reserve_memory_at: couldn't reserve " SIZE_FORMAT " bytes at "
2738             PTR_FORMAT ": reserve_memory_helper returned " PTR_FORMAT
2739             "%s", bytes, requested_addr, addr, buf);
2740   }
2741 
2742   // Address hint method didn't work.  Fall back to the old method.
2743   // In theory, once SNV becomes our oldest supported platform, this
2744   // code will no longer be needed.
2745   //
2746   // Repeatedly allocate blocks until the block is allocated at the
2747   // right spot. Give up after max_tries.
2748   int i;
2749   for (i = 0; i < max_tries; ++i) {
2750     base[i] = reserve_memory(bytes);
2751 
2752     if (base[i] != NULL) {
2753       // Is this the block we wanted?
2754       if (base[i] == requested_addr) {
2755         size[i] = bytes;
2756         break;
2757       }
2758 
2759       // check that the gap value is right
2760       if (had_top_overlap && !have_adjusted_gap) {
2761         size_t actual_gap = base[i-1] - base[i] - bytes;
2762         if (gap != actual_gap) {
2763           // adjust the gap value and retry the last 2 allocations
2764           assert(i > 0, "gap adjustment code problem");
2765           have_adjusted_gap = true;  // adjust the gap only once, just in case
2766           gap = actual_gap;
2767           if (PrintMiscellaneous && Verbose) {
2768             warning("attempt_reserve_memory_at: adjusted gap to 0x%lx", gap);
2769           }
2770           unmap_memory(base[i], bytes);
2771           unmap_memory(base[i-1], size[i-1]);
2772           i-=2;
2773           continue;
2774         }
2775       }
2776 
2777       // Does this overlap the block we wanted? Give back the overlapped
2778       // parts and try again.
2779       //
2780       // There is still a bug in this code: if top_overlap == bytes,
2781       // the overlap is offset from requested region by the value of gap.
2782       // In this case giving back the overlapped part will not work,
2783       // because we'll give back the entire block at base[i] and
2784       // therefore the subsequent allocation will not generate a new gap.
2785       // This could be fixed with a new algorithm that used larger
2786       // or variable size chunks to find the requested region -
2787       // but such a change would introduce additional complications.
2788       // It's rare enough that the planets align for this bug,
2789       // so we'll just wait for a fix for 6204603/5003415 which
2790       // will provide a mmap flag to allow us to avoid this business.
2791 
2792       size_t top_overlap = requested_addr + (bytes + gap) - base[i];
2793       if (top_overlap >= 0 && top_overlap < bytes) {
2794         had_top_overlap = true;
2795         unmap_memory(base[i], top_overlap);
2796         base[i] += top_overlap;
2797         size[i] = bytes - top_overlap;
2798       } else {
2799         size_t bottom_overlap = base[i] + bytes - requested_addr;
2800         if (bottom_overlap >= 0 && bottom_overlap < bytes) {
2801           if (PrintMiscellaneous && Verbose && bottom_overlap == 0) {
2802             warning("attempt_reserve_memory_at: possible alignment bug");
2803           }
2804           unmap_memory(requested_addr, bottom_overlap);
2805           size[i] = bytes - bottom_overlap;
2806         } else {
2807           size[i] = bytes;
2808         }
2809       }
2810     }
2811   }
2812 
2813   // Give back the unused reserved pieces.
2814 
2815   for (int j = 0; j < i; ++j) {
2816     if (base[j] != NULL) {
2817       unmap_memory(base[j], size[j]);
2818     }
2819   }
2820 
2821   return (i < max_tries) ? requested_addr : NULL;
2822 }
2823 
2824 bool os::pd_release_memory(char* addr, size_t bytes) {
2825   size_t size = bytes;
2826   return munmap(addr, size) == 0;
2827 }
2828 
2829 static bool solaris_mprotect(char* addr, size_t bytes, int prot) {
2830   assert(addr == (char*)align_size_down((uintptr_t)addr, os::vm_page_size()),
2831          "addr must be page aligned");
2832   int retVal = mprotect(addr, bytes, prot);
2833   return retVal == 0;
2834 }
2835 
2836 // Protect memory (Used to pass readonly pages through
2837 // JNI GetArray<type>Elements with empty arrays.)
2838 // Also, used for serialization page and for compressed oops null pointer
2839 // checking.
2840 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
2841                         bool is_committed) {
2842   unsigned int p = 0;
2843   switch (prot) {
2844   case MEM_PROT_NONE: p = PROT_NONE; break;
2845   case MEM_PROT_READ: p = PROT_READ; break;
2846   case MEM_PROT_RW:   p = PROT_READ|PROT_WRITE; break;
2847   case MEM_PROT_RWX:  p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
2848   default:
2849     ShouldNotReachHere();
2850   }
2851   // is_committed is unused.
2852   return solaris_mprotect(addr, bytes, p);
2853 }
2854 
2855 // guard_memory and unguard_memory only happens within stack guard pages.
2856 // Since ISM pertains only to the heap, guard and unguard memory should not
2857 /// happen with an ISM region.
2858 bool os::guard_memory(char* addr, size_t bytes) {
2859   return solaris_mprotect(addr, bytes, PROT_NONE);
2860 }
2861 
2862 bool os::unguard_memory(char* addr, size_t bytes) {
2863   return solaris_mprotect(addr, bytes, PROT_READ|PROT_WRITE);
2864 }
2865 
2866 // Large page support
2867 static size_t _large_page_size = 0;
2868 
2869 // Insertion sort for small arrays (descending order).
2870 static void insertion_sort_descending(size_t* array, int len) {
2871   for (int i = 0; i < len; i++) {
2872     size_t val = array[i];
2873     for (size_t key = i; key > 0 && array[key - 1] < val; --key) {
2874       size_t tmp = array[key];
2875       array[key] = array[key - 1];
2876       array[key - 1] = tmp;
2877     }
2878   }
2879 }
2880 
2881 bool os::Solaris::mpss_sanity_check(bool warn, size_t* page_size) {
2882   const unsigned int usable_count = VM_Version::page_size_count();
2883   if (usable_count == 1) {
2884     return false;
2885   }
2886 
2887   // Find the right getpagesizes interface.  When solaris 11 is the minimum
2888   // build platform, getpagesizes() (without the '2') can be called directly.
2889   typedef int (*gps_t)(size_t[], int);
2890   gps_t gps_func = CAST_TO_FN_PTR(gps_t, dlsym(RTLD_DEFAULT, "getpagesizes2"));
2891   if (gps_func == NULL) {
2892     gps_func = CAST_TO_FN_PTR(gps_t, dlsym(RTLD_DEFAULT, "getpagesizes"));
2893     if (gps_func == NULL) {
2894       if (warn) {
2895         warning("MPSS is not supported by the operating system.");
2896       }
2897       return false;
2898     }
2899   }
2900 
2901   // Fill the array of page sizes.
2902   int n = (*gps_func)(_page_sizes, page_sizes_max);
2903   assert(n > 0, "Solaris bug?");
2904 
2905   if (n == page_sizes_max) {
2906     // Add a sentinel value (necessary only if the array was completely filled
2907     // since it is static (zeroed at initialization)).
2908     _page_sizes[--n] = 0;
2909     DEBUG_ONLY(warning("increase the size of the os::_page_sizes array.");)
2910   }
2911   assert(_page_sizes[n] == 0, "missing sentinel");
2912   trace_page_sizes("available page sizes", _page_sizes, n);
2913 
2914   if (n == 1) return false;     // Only one page size available.
2915 
2916   // Skip sizes larger than 4M (or LargePageSizeInBytes if it was set) and
2917   // select up to usable_count elements.  First sort the array, find the first
2918   // acceptable value, then copy the usable sizes to the top of the array and
2919   // trim the rest.  Make sure to include the default page size :-).
2920   //
2921   // A better policy could get rid of the 4M limit by taking the sizes of the
2922   // important VM memory regions (java heap and possibly the code cache) into
2923   // account.
2924   insertion_sort_descending(_page_sizes, n);
2925   const size_t size_limit =
2926     FLAG_IS_DEFAULT(LargePageSizeInBytes) ? 4 * M : LargePageSizeInBytes;
2927   int beg;
2928   for (beg = 0; beg < n && _page_sizes[beg] > size_limit; ++beg) /* empty */;
2929   const int end = MIN2((int)usable_count, n) - 1;
2930   for (int cur = 0; cur < end; ++cur, ++beg) {
2931     _page_sizes[cur] = _page_sizes[beg];
2932   }
2933   _page_sizes[end] = vm_page_size();
2934   _page_sizes[end + 1] = 0;
2935 
2936   if (_page_sizes[end] > _page_sizes[end - 1]) {
2937     // Default page size is not the smallest; sort again.
2938     insertion_sort_descending(_page_sizes, end + 1);
2939   }
2940   *page_size = _page_sizes[0];
2941 
2942   trace_page_sizes("usable page sizes", _page_sizes, end + 1);
2943   return true;
2944 }
2945 
2946 void os::large_page_init() {
2947   if (UseLargePages) {
2948     // print a warning if any large page related flag is specified on command line
2949     bool warn_on_failure = !FLAG_IS_DEFAULT(UseLargePages)        ||
2950                            !FLAG_IS_DEFAULT(LargePageSizeInBytes);
2951 
2952     UseLargePages = Solaris::mpss_sanity_check(warn_on_failure, &_large_page_size);
2953   }
2954 }
2955 
2956 bool os::Solaris::is_valid_page_size(size_t bytes) {
2957   for (int i = 0; _page_sizes[i] != 0; i++) {
2958     if (_page_sizes[i] == bytes) {
2959       return true;
2960     }
2961   }
2962   return false;
2963 }
2964 
2965 bool os::Solaris::setup_large_pages(caddr_t start, size_t bytes, size_t align) {
2966   assert(is_valid_page_size(align), SIZE_FORMAT " is not a valid page size", align);
2967   assert(is_ptr_aligned((void*) start, align),
2968          PTR_FORMAT " is not aligned to " SIZE_FORMAT, p2i((void*) start), align);
2969   assert(is_size_aligned(bytes, align),
2970          SIZE_FORMAT " is not aligned to " SIZE_FORMAT, bytes, align);
2971 
2972   // Signal to OS that we want large pages for addresses
2973   // from addr, addr + bytes
2974   struct memcntl_mha mpss_struct;
2975   mpss_struct.mha_cmd = MHA_MAPSIZE_VA;
2976   mpss_struct.mha_pagesize = align;
2977   mpss_struct.mha_flags = 0;
2978   // Upon successful completion, memcntl() returns 0
2979   if (memcntl(start, bytes, MC_HAT_ADVISE, (caddr_t) &mpss_struct, 0, 0)) {
2980     debug_only(warning("Attempt to use MPSS failed."));
2981     return false;
2982   }
2983   return true;
2984 }
2985 
2986 char* os::reserve_memory_special(size_t size, size_t alignment, char* addr, bool exec) {
2987   fatal("os::reserve_memory_special should not be called on Solaris.");
2988   return NULL;
2989 }
2990 
2991 bool os::release_memory_special(char* base, size_t bytes) {
2992   fatal("os::release_memory_special should not be called on Solaris.");
2993   return false;
2994 }
2995 
2996 size_t os::large_page_size() {
2997   return _large_page_size;
2998 }
2999 
3000 // MPSS allows application to commit large page memory on demand; with ISM
3001 // the entire memory region must be allocated as shared memory.
3002 bool os::can_commit_large_page_memory() {
3003   return true;
3004 }
3005 
3006 bool os::can_execute_large_page_memory() {
3007   return true;
3008 }
3009 
3010 // Read calls from inside the vm need to perform state transitions
3011 size_t os::read(int fd, void *buf, unsigned int nBytes) {
3012   size_t res;
3013   JavaThread* thread = (JavaThread*)Thread::current();
3014   assert(thread->thread_state() == _thread_in_vm, "Assumed _thread_in_vm");
3015   ThreadBlockInVM tbiv(thread);
3016   RESTARTABLE(::read(fd, buf, (size_t) nBytes), res);
3017   return res;
3018 }
3019 
3020 size_t os::read_at(int fd, void *buf, unsigned int nBytes, jlong offset) {
3021   size_t res;
3022   JavaThread* thread = (JavaThread*)Thread::current();
3023   assert(thread->thread_state() == _thread_in_vm, "Assumed _thread_in_vm");
3024   ThreadBlockInVM tbiv(thread);
3025   RESTARTABLE(::pread(fd, buf, (size_t) nBytes, offset), res);
3026   return res;
3027 }
3028 
3029 size_t os::restartable_read(int fd, void *buf, unsigned int nBytes) {
3030   size_t res;
3031   assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
3032          "Assumed _thread_in_native");
3033   RESTARTABLE(::read(fd, buf, (size_t) nBytes), res);
3034   return res;
3035 }
3036 
3037 void os::naked_short_sleep(jlong ms) {
3038   assert(ms < 1000, "Un-interruptable sleep, short time use only");
3039 
3040   // usleep is deprecated and removed from POSIX, in favour of nanosleep, but
3041   // Solaris requires -lrt for this.
3042   usleep((ms * 1000));
3043 
3044   return;
3045 }
3046 
3047 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
3048 void os::infinite_sleep() {
3049   while (true) {    // sleep forever ...
3050     ::sleep(100);   // ... 100 seconds at a time
3051   }
3052 }
3053 
3054 // Used to convert frequent JVM_Yield() to nops
3055 bool os::dont_yield() {
3056   if (DontYieldALot) {
3057     static hrtime_t last_time = 0;
3058     hrtime_t diff = getTimeNanos() - last_time;
3059 
3060     if (diff < DontYieldALotInterval * 1000000) {
3061       return true;
3062     }
3063 
3064     last_time += diff;
3065 
3066     return false;
3067   } else {
3068     return false;
3069   }
3070 }
3071 
3072 // Note that yield semantics are defined by the scheduling class to which
3073 // the thread currently belongs.  Typically, yield will _not yield to
3074 // other equal or higher priority threads that reside on the dispatch queues
3075 // of other CPUs.
3076 
3077 void os::naked_yield() {
3078   thr_yield();
3079 }
3080 
3081 // Interface for setting lwp priorities.  If we are using T2 libthread,
3082 // which forces the use of BoundThreads or we manually set UseBoundThreads,
3083 // all of our threads will be assigned to real lwp's.  Using the thr_setprio
3084 // function is meaningless in this mode so we must adjust the real lwp's priority
3085 // The routines below implement the getting and setting of lwp priorities.
3086 //
3087 // Note: T2 is now the only supported libthread. UseBoundThreads flag is
3088 //       being deprecated and all threads are now BoundThreads
3089 //
3090 // Note: There are three priority scales used on Solaris.  Java priotities
3091 //       which range from 1 to 10, libthread "thr_setprio" scale which range
3092 //       from 0 to 127, and the current scheduling class of the process we
3093 //       are running in.  This is typically from -60 to +60.
3094 //       The setting of the lwp priorities in done after a call to thr_setprio
3095 //       so Java priorities are mapped to libthread priorities and we map from
3096 //       the latter to lwp priorities.  We don't keep priorities stored in
3097 //       Java priorities since some of our worker threads want to set priorities
3098 //       higher than all Java threads.
3099 //
3100 // For related information:
3101 // (1)  man -s 2 priocntl
3102 // (2)  man -s 4 priocntl
3103 // (3)  man dispadmin
3104 // =    librt.so
3105 // =    libthread/common/rtsched.c - thrp_setlwpprio().
3106 // =    ps -cL <pid> ... to validate priority.
3107 // =    sched_get_priority_min and _max
3108 //              pthread_create
3109 //              sched_setparam
3110 //              pthread_setschedparam
3111 //
3112 // Assumptions:
3113 // +    We assume that all threads in the process belong to the same
3114 //              scheduling class.   IE. an homogenous process.
3115 // +    Must be root or in IA group to change change "interactive" attribute.
3116 //              Priocntl() will fail silently.  The only indication of failure is when
3117 //              we read-back the value and notice that it hasn't changed.
3118 // +    Interactive threads enter the runq at the head, non-interactive at the tail.
3119 // +    For RT, change timeslice as well.  Invariant:
3120 //              constant "priority integral"
3121 //              Konst == TimeSlice * (60-Priority)
3122 //              Given a priority, compute appropriate timeslice.
3123 // +    Higher numerical values have higher priority.
3124 
3125 // sched class attributes
3126 typedef struct {
3127   int   schedPolicy;              // classID
3128   int   maxPrio;
3129   int   minPrio;
3130 } SchedInfo;
3131 
3132 
3133 static SchedInfo tsLimits, iaLimits, rtLimits, fxLimits;
3134 
3135 #ifdef ASSERT
3136 static int  ReadBackValidate = 1;
3137 #endif
3138 static int  myClass     = 0;
3139 static int  myMin       = 0;
3140 static int  myMax       = 0;
3141 static int  myCur       = 0;
3142 static bool priocntl_enable = false;
3143 
3144 static const int criticalPrio = 60; // FX/60 is critical thread class/priority on T4
3145 static int java_MaxPriority_to_os_priority = 0; // Saved mapping
3146 
3147 
3148 // lwp_priocntl_init
3149 //
3150 // Try to determine the priority scale for our process.
3151 //
3152 // Return errno or 0 if OK.
3153 //
3154 static int lwp_priocntl_init() {
3155   int rslt;
3156   pcinfo_t ClassInfo;
3157   pcparms_t ParmInfo;
3158   int i;
3159 
3160   if (!UseThreadPriorities) return 0;
3161 
3162   // If ThreadPriorityPolicy is 1, switch tables
3163   if (ThreadPriorityPolicy == 1) {
3164     for (i = 0; i < CriticalPriority+1; i++)
3165       os::java_to_os_priority[i] = prio_policy1[i];
3166   }
3167   if (UseCriticalJavaThreadPriority) {
3168     // MaxPriority always maps to the FX scheduling class and criticalPrio.
3169     // See set_native_priority() and set_lwp_class_and_priority().
3170     // Save original MaxPriority mapping in case attempt to
3171     // use critical priority fails.
3172     java_MaxPriority_to_os_priority = os::java_to_os_priority[MaxPriority];
3173     // Set negative to distinguish from other priorities
3174     os::java_to_os_priority[MaxPriority] = -criticalPrio;
3175   }
3176 
3177   // Get IDs for a set of well-known scheduling classes.
3178   // TODO-FIXME: GETCLINFO returns the current # of classes in the
3179   // the system.  We should have a loop that iterates over the
3180   // classID values, which are known to be "small" integers.
3181 
3182   strcpy(ClassInfo.pc_clname, "TS");
3183   ClassInfo.pc_cid = -1;
3184   rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
3185   if (rslt < 0) return errno;
3186   assert(ClassInfo.pc_cid != -1, "cid for TS class is -1");
3187   tsLimits.schedPolicy = ClassInfo.pc_cid;
3188   tsLimits.maxPrio = ((tsinfo_t*)ClassInfo.pc_clinfo)->ts_maxupri;
3189   tsLimits.minPrio = -tsLimits.maxPrio;
3190 
3191   strcpy(ClassInfo.pc_clname, "IA");
3192   ClassInfo.pc_cid = -1;
3193   rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
3194   if (rslt < 0) return errno;
3195   assert(ClassInfo.pc_cid != -1, "cid for IA class is -1");
3196   iaLimits.schedPolicy = ClassInfo.pc_cid;
3197   iaLimits.maxPrio = ((iainfo_t*)ClassInfo.pc_clinfo)->ia_maxupri;
3198   iaLimits.minPrio = -iaLimits.maxPrio;
3199 
3200   strcpy(ClassInfo.pc_clname, "RT");
3201   ClassInfo.pc_cid = -1;
3202   rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
3203   if (rslt < 0) return errno;
3204   assert(ClassInfo.pc_cid != -1, "cid for RT class is -1");
3205   rtLimits.schedPolicy = ClassInfo.pc_cid;
3206   rtLimits.maxPrio = ((rtinfo_t*)ClassInfo.pc_clinfo)->rt_maxpri;
3207   rtLimits.minPrio = 0;
3208 
3209   strcpy(ClassInfo.pc_clname, "FX");
3210   ClassInfo.pc_cid = -1;
3211   rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
3212   if (rslt < 0) return errno;
3213   assert(ClassInfo.pc_cid != -1, "cid for FX class is -1");
3214   fxLimits.schedPolicy = ClassInfo.pc_cid;
3215   fxLimits.maxPrio = ((fxinfo_t*)ClassInfo.pc_clinfo)->fx_maxupri;
3216   fxLimits.minPrio = 0;
3217 
3218   // Query our "current" scheduling class.
3219   // This will normally be IA, TS or, rarely, FX or RT.
3220   memset(&ParmInfo, 0, sizeof(ParmInfo));
3221   ParmInfo.pc_cid = PC_CLNULL;
3222   rslt = priocntl(P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo);
3223   if (rslt < 0) return errno;
3224   myClass = ParmInfo.pc_cid;
3225 
3226   // We now know our scheduling classId, get specific information
3227   // about the class.
3228   ClassInfo.pc_cid = myClass;
3229   ClassInfo.pc_clname[0] = 0;
3230   rslt = priocntl((idtype)0, 0, PC_GETCLINFO, (caddr_t)&ClassInfo);
3231   if (rslt < 0) return errno;
3232 
3233   if (ThreadPriorityVerbose) {
3234     tty->print_cr("lwp_priocntl_init: Class=%d(%s)...", myClass, ClassInfo.pc_clname);
3235   }
3236 
3237   memset(&ParmInfo, 0, sizeof(pcparms_t));
3238   ParmInfo.pc_cid = PC_CLNULL;
3239   rslt = priocntl(P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo);
3240   if (rslt < 0) return errno;
3241 
3242   if (ParmInfo.pc_cid == rtLimits.schedPolicy) {
3243     myMin = rtLimits.minPrio;
3244     myMax = rtLimits.maxPrio;
3245   } else if (ParmInfo.pc_cid == iaLimits.schedPolicy) {
3246     iaparms_t *iaInfo  = (iaparms_t*)ParmInfo.pc_clparms;
3247     myMin = iaLimits.minPrio;
3248     myMax = iaLimits.maxPrio;
3249     myMax = MIN2(myMax, (int)iaInfo->ia_uprilim);       // clamp - restrict
3250   } else if (ParmInfo.pc_cid == tsLimits.schedPolicy) {
3251     tsparms_t *tsInfo  = (tsparms_t*)ParmInfo.pc_clparms;
3252     myMin = tsLimits.minPrio;
3253     myMax = tsLimits.maxPrio;
3254     myMax = MIN2(myMax, (int)tsInfo->ts_uprilim);       // clamp - restrict
3255   } else if (ParmInfo.pc_cid == fxLimits.schedPolicy) {
3256     fxparms_t *fxInfo = (fxparms_t*)ParmInfo.pc_clparms;
3257     myMin = fxLimits.minPrio;
3258     myMax = fxLimits.maxPrio;
3259     myMax = MIN2(myMax, (int)fxInfo->fx_uprilim);       // clamp - restrict
3260   } else {
3261     // No clue - punt
3262     if (ThreadPriorityVerbose) {
3263       tty->print_cr("Unknown scheduling class: %s ... \n",
3264                     ClassInfo.pc_clname);
3265     }
3266     return EINVAL;      // no clue, punt
3267   }
3268 
3269   if (ThreadPriorityVerbose) {
3270     tty->print_cr("Thread priority Range: [%d..%d]\n", myMin, myMax);
3271   }
3272 
3273   priocntl_enable = true;  // Enable changing priorities
3274   return 0;
3275 }
3276 
3277 #define IAPRI(x)        ((iaparms_t *)((x).pc_clparms))
3278 #define RTPRI(x)        ((rtparms_t *)((x).pc_clparms))
3279 #define TSPRI(x)        ((tsparms_t *)((x).pc_clparms))
3280 #define FXPRI(x)        ((fxparms_t *)((x).pc_clparms))
3281 
3282 
3283 // scale_to_lwp_priority
3284 //
3285 // Convert from the libthread "thr_setprio" scale to our current
3286 // lwp scheduling class scale.
3287 //
3288 static int scale_to_lwp_priority(int rMin, int rMax, int x) {
3289   int v;
3290 
3291   if (x == 127) return rMax;            // avoid round-down
3292   v = (((x*(rMax-rMin)))/128)+rMin;
3293   return v;
3294 }
3295 
3296 
3297 // set_lwp_class_and_priority
3298 int set_lwp_class_and_priority(int ThreadID, int lwpid,
3299                                int newPrio, int new_class, bool scale) {
3300   int rslt;
3301   int Actual, Expected, prv;
3302   pcparms_t ParmInfo;                   // for GET-SET
3303 #ifdef ASSERT
3304   pcparms_t ReadBack;                   // for readback
3305 #endif
3306 
3307   // Set priority via PC_GETPARMS, update, PC_SETPARMS
3308   // Query current values.
3309   // TODO: accelerate this by eliminating the PC_GETPARMS call.
3310   // Cache "pcparms_t" in global ParmCache.
3311   // TODO: elide set-to-same-value
3312 
3313   // If something went wrong on init, don't change priorities.
3314   if (!priocntl_enable) {
3315     if (ThreadPriorityVerbose) {
3316       tty->print_cr("Trying to set priority but init failed, ignoring");
3317     }
3318     return EINVAL;
3319   }
3320 
3321   // If lwp hasn't started yet, just return
3322   // the _start routine will call us again.
3323   if (lwpid <= 0) {
3324     if (ThreadPriorityVerbose) {
3325       tty->print_cr("deferring the set_lwp_class_and_priority of thread "
3326                     INTPTR_FORMAT " to %d, lwpid not set",
3327                     ThreadID, newPrio);
3328     }
3329     return 0;
3330   }
3331 
3332   if (ThreadPriorityVerbose) {
3333     tty->print_cr ("set_lwp_class_and_priority("
3334                    INTPTR_FORMAT "@" INTPTR_FORMAT " %d) ",
3335                    ThreadID, lwpid, newPrio);
3336   }
3337 
3338   memset(&ParmInfo, 0, sizeof(pcparms_t));
3339   ParmInfo.pc_cid = PC_CLNULL;
3340   rslt = priocntl(P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ParmInfo);
3341   if (rslt < 0) return errno;
3342 
3343   int cur_class = ParmInfo.pc_cid;
3344   ParmInfo.pc_cid = (id_t)new_class;
3345 
3346   if (new_class == rtLimits.schedPolicy) {
3347     rtparms_t *rtInfo  = (rtparms_t*)ParmInfo.pc_clparms;
3348     rtInfo->rt_pri     = scale ? scale_to_lwp_priority(rtLimits.minPrio,
3349                                                        rtLimits.maxPrio, newPrio)
3350                                : newPrio;
3351     rtInfo->rt_tqsecs  = RT_NOCHANGE;
3352     rtInfo->rt_tqnsecs = RT_NOCHANGE;
3353     if (ThreadPriorityVerbose) {
3354       tty->print_cr("RT: %d->%d\n", newPrio, rtInfo->rt_pri);
3355     }
3356   } else if (new_class == iaLimits.schedPolicy) {
3357     iaparms_t* iaInfo  = (iaparms_t*)ParmInfo.pc_clparms;
3358     int maxClamped     = MIN2(iaLimits.maxPrio,
3359                               cur_class == new_class
3360                               ? (int)iaInfo->ia_uprilim : iaLimits.maxPrio);
3361     iaInfo->ia_upri    = scale ? scale_to_lwp_priority(iaLimits.minPrio,
3362                                                        maxClamped, newPrio)
3363                                : newPrio;
3364     iaInfo->ia_uprilim = cur_class == new_class
3365                            ? IA_NOCHANGE : (pri_t)iaLimits.maxPrio;
3366     iaInfo->ia_mode    = IA_NOCHANGE;
3367     if (ThreadPriorityVerbose) {
3368       tty->print_cr("IA: [%d...%d] %d->%d\n",
3369                     iaLimits.minPrio, maxClamped, newPrio, iaInfo->ia_upri);
3370     }
3371   } else if (new_class == tsLimits.schedPolicy) {
3372     tsparms_t* tsInfo  = (tsparms_t*)ParmInfo.pc_clparms;
3373     int maxClamped     = MIN2(tsLimits.maxPrio,
3374                               cur_class == new_class
3375                               ? (int)tsInfo->ts_uprilim : tsLimits.maxPrio);
3376     tsInfo->ts_upri    = scale ? scale_to_lwp_priority(tsLimits.minPrio,
3377                                                        maxClamped, newPrio)
3378                                : newPrio;
3379     tsInfo->ts_uprilim = cur_class == new_class
3380                            ? TS_NOCHANGE : (pri_t)tsLimits.maxPrio;
3381     if (ThreadPriorityVerbose) {
3382       tty->print_cr("TS: [%d...%d] %d->%d\n",
3383                     tsLimits.minPrio, maxClamped, newPrio, tsInfo->ts_upri);
3384     }
3385   } else if (new_class == fxLimits.schedPolicy) {
3386     fxparms_t* fxInfo  = (fxparms_t*)ParmInfo.pc_clparms;
3387     int maxClamped     = MIN2(fxLimits.maxPrio,
3388                               cur_class == new_class
3389                               ? (int)fxInfo->fx_uprilim : fxLimits.maxPrio);
3390     fxInfo->fx_upri    = scale ? scale_to_lwp_priority(fxLimits.minPrio,
3391                                                        maxClamped, newPrio)
3392                                : newPrio;
3393     fxInfo->fx_uprilim = cur_class == new_class
3394                            ? FX_NOCHANGE : (pri_t)fxLimits.maxPrio;
3395     fxInfo->fx_tqsecs  = FX_NOCHANGE;
3396     fxInfo->fx_tqnsecs = FX_NOCHANGE;
3397     if (ThreadPriorityVerbose) {
3398       tty->print_cr("FX: [%d...%d] %d->%d\n",
3399                     fxLimits.minPrio, maxClamped, newPrio, fxInfo->fx_upri);
3400     }
3401   } else {
3402     if (ThreadPriorityVerbose) {
3403       tty->print_cr("Unknown new scheduling class %d\n", new_class);
3404     }
3405     return EINVAL;    // no clue, punt
3406   }
3407 
3408   rslt = priocntl(P_LWPID, lwpid, PC_SETPARMS, (caddr_t)&ParmInfo);
3409   if (ThreadPriorityVerbose && rslt) {
3410     tty->print_cr ("PC_SETPARMS ->%d %d\n", rslt, errno);
3411   }
3412   if (rslt < 0) return errno;
3413 
3414 #ifdef ASSERT
3415   // Sanity check: read back what we just attempted to set.
3416   // In theory it could have changed in the interim ...
3417   //
3418   // The priocntl system call is tricky.
3419   // Sometimes it'll validate the priority value argument and
3420   // return EINVAL if unhappy.  At other times it fails silently.
3421   // Readbacks are prudent.
3422 
3423   if (!ReadBackValidate) return 0;
3424 
3425   memset(&ReadBack, 0, sizeof(pcparms_t));
3426   ReadBack.pc_cid = PC_CLNULL;
3427   rslt = priocntl(P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ReadBack);
3428   assert(rslt >= 0, "priocntl failed");
3429   Actual = Expected = 0xBAD;
3430   assert(ParmInfo.pc_cid == ReadBack.pc_cid, "cid's don't match");
3431   if (ParmInfo.pc_cid == rtLimits.schedPolicy) {
3432     Actual   = RTPRI(ReadBack)->rt_pri;
3433     Expected = RTPRI(ParmInfo)->rt_pri;
3434   } else if (ParmInfo.pc_cid == iaLimits.schedPolicy) {
3435     Actual   = IAPRI(ReadBack)->ia_upri;
3436     Expected = IAPRI(ParmInfo)->ia_upri;
3437   } else if (ParmInfo.pc_cid == tsLimits.schedPolicy) {
3438     Actual   = TSPRI(ReadBack)->ts_upri;
3439     Expected = TSPRI(ParmInfo)->ts_upri;
3440   } else if (ParmInfo.pc_cid == fxLimits.schedPolicy) {
3441     Actual   = FXPRI(ReadBack)->fx_upri;
3442     Expected = FXPRI(ParmInfo)->fx_upri;
3443   } else {
3444     if (ThreadPriorityVerbose) {
3445       tty->print_cr("set_lwp_class_and_priority: unexpected class in readback: %d\n",
3446                     ParmInfo.pc_cid);
3447     }
3448   }
3449 
3450   if (Actual != Expected) {
3451     if (ThreadPriorityVerbose) {
3452       tty->print_cr ("set_lwp_class_and_priority(%d %d) Class=%d: actual=%d vs expected=%d\n",
3453                      lwpid, newPrio, ReadBack.pc_cid, Actual, Expected);
3454     }
3455   }
3456 #endif
3457 
3458   return 0;
3459 }
3460 
3461 // Solaris only gives access to 128 real priorities at a time,
3462 // so we expand Java's ten to fill this range.  This would be better
3463 // if we dynamically adjusted relative priorities.
3464 //
3465 // The ThreadPriorityPolicy option allows us to select 2 different
3466 // priority scales.
3467 //
3468 // ThreadPriorityPolicy=0
3469 // Since the Solaris' default priority is MaximumPriority, we do not
3470 // set a priority lower than Max unless a priority lower than
3471 // NormPriority is requested.
3472 //
3473 // ThreadPriorityPolicy=1
3474 // This mode causes the priority table to get filled with
3475 // linear values.  NormPriority get's mapped to 50% of the
3476 // Maximum priority an so on.  This will cause VM threads
3477 // to get unfair treatment against other Solaris processes
3478 // which do not explicitly alter their thread priorities.
3479 
3480 int os::java_to_os_priority[CriticalPriority + 1] = {
3481   -99999,         // 0 Entry should never be used
3482 
3483   0,              // 1 MinPriority
3484   32,             // 2
3485   64,             // 3
3486 
3487   96,             // 4
3488   127,            // 5 NormPriority
3489   127,            // 6
3490 
3491   127,            // 7
3492   127,            // 8
3493   127,            // 9 NearMaxPriority
3494 
3495   127,            // 10 MaxPriority
3496 
3497   -criticalPrio   // 11 CriticalPriority
3498 };
3499 
3500 OSReturn os::set_native_priority(Thread* thread, int newpri) {
3501   OSThread* osthread = thread->osthread();
3502 
3503   // Save requested priority in case the thread hasn't been started
3504   osthread->set_native_priority(newpri);
3505 
3506   // Check for critical priority request
3507   bool fxcritical = false;
3508   if (newpri == -criticalPrio) {
3509     fxcritical = true;
3510     newpri = criticalPrio;
3511   }
3512 
3513   assert(newpri >= MinimumPriority && newpri <= MaximumPriority, "bad priority mapping");
3514   if (!UseThreadPriorities) return OS_OK;
3515 
3516   int status = 0;
3517 
3518   if (!fxcritical) {
3519     // Use thr_setprio only if we have a priority that thr_setprio understands
3520     status = thr_setprio(thread->osthread()->thread_id(), newpri);
3521   }
3522 
3523   int lwp_status =
3524           set_lwp_class_and_priority(osthread->thread_id(),
3525                                      osthread->lwp_id(),
3526                                      newpri,
3527                                      fxcritical ? fxLimits.schedPolicy : myClass,
3528                                      !fxcritical);
3529   if (lwp_status != 0 && fxcritical) {
3530     // Try again, this time without changing the scheduling class
3531     newpri = java_MaxPriority_to_os_priority;
3532     lwp_status = set_lwp_class_and_priority(osthread->thread_id(),
3533                                             osthread->lwp_id(),
3534                                             newpri, myClass, false);
3535   }
3536   status |= lwp_status;
3537   return (status == 0) ? OS_OK : OS_ERR;
3538 }
3539 
3540 
3541 OSReturn os::get_native_priority(const Thread* const thread,
3542                                  int *priority_ptr) {
3543   int p;
3544   if (!UseThreadPriorities) {
3545     *priority_ptr = NormalPriority;
3546     return OS_OK;
3547   }
3548   int status = thr_getprio(thread->osthread()->thread_id(), &p);
3549   if (status != 0) {
3550     return OS_ERR;
3551   }
3552   *priority_ptr = p;
3553   return OS_OK;
3554 }
3555 
3556 
3557 // Hint to the underlying OS that a task switch would not be good.
3558 // Void return because it's a hint and can fail.
3559 void os::hint_no_preempt() {
3560   schedctl_start(schedctl_init());
3561 }
3562 
3563 static void resume_clear_context(OSThread *osthread) {
3564   osthread->set_ucontext(NULL);
3565 }
3566 
3567 static void suspend_save_context(OSThread *osthread, ucontext_t* context) {
3568   osthread->set_ucontext(context);
3569 }
3570 
3571 static PosixSemaphore sr_semaphore;
3572 
3573 void os::Solaris::SR_handler(Thread* thread, ucontext_t* uc) {
3574   // Save and restore errno to avoid confusing native code with EINTR
3575   // after sigsuspend.
3576   int old_errno = errno;
3577 
3578   OSThread* osthread = thread->osthread();
3579   assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
3580 
3581   os::SuspendResume::State current = osthread->sr.state();
3582   if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
3583     suspend_save_context(osthread, uc);
3584 
3585     // attempt to switch the state, we assume we had a SUSPEND_REQUEST
3586     os::SuspendResume::State state = osthread->sr.suspended();
3587     if (state == os::SuspendResume::SR_SUSPENDED) {
3588       sigset_t suspend_set;  // signals for sigsuspend()
3589 
3590       // get current set of blocked signals and unblock resume signal
3591       thr_sigsetmask(SIG_BLOCK, NULL, &suspend_set);
3592       sigdelset(&suspend_set, os::Solaris::SIGasync());
3593 
3594       sr_semaphore.signal();
3595       // wait here until we are resumed
3596       while (1) {
3597         sigsuspend(&suspend_set);
3598 
3599         os::SuspendResume::State result = osthread->sr.running();
3600         if (result == os::SuspendResume::SR_RUNNING) {
3601           sr_semaphore.signal();
3602           break;
3603         }
3604       }
3605 
3606     } else if (state == os::SuspendResume::SR_RUNNING) {
3607       // request was cancelled, continue
3608     } else {
3609       ShouldNotReachHere();
3610     }
3611 
3612     resume_clear_context(osthread);
3613   } else if (current == os::SuspendResume::SR_RUNNING) {
3614     // request was cancelled, continue
3615   } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
3616     // ignore
3617   } else {
3618     // ignore
3619   }
3620 
3621   errno = old_errno;
3622 }
3623 
3624 void os::print_statistics() {
3625 }
3626 
3627 int os::message_box(const char* title, const char* message) {
3628   int i;
3629   fdStream err(defaultStream::error_fd());
3630   for (i = 0; i < 78; i++) err.print_raw("=");
3631   err.cr();
3632   err.print_raw_cr(title);
3633   for (i = 0; i < 78; i++) err.print_raw("-");
3634   err.cr();
3635   err.print_raw_cr(message);
3636   for (i = 0; i < 78; i++) err.print_raw("=");
3637   err.cr();
3638 
3639   char buf[16];
3640   // Prevent process from exiting upon "read error" without consuming all CPU
3641   while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
3642 
3643   return buf[0] == 'y' || buf[0] == 'Y';
3644 }
3645 
3646 static int sr_notify(OSThread* osthread) {
3647   int status = thr_kill(osthread->thread_id(), os::Solaris::SIGasync());
3648   assert_status(status == 0, status, "thr_kill");
3649   return status;
3650 }
3651 
3652 // "Randomly" selected value for how long we want to spin
3653 // before bailing out on suspending a thread, also how often
3654 // we send a signal to a thread we want to resume
3655 static const int RANDOMLY_LARGE_INTEGER = 1000000;
3656 static const int RANDOMLY_LARGE_INTEGER2 = 100;
3657 
3658 static bool do_suspend(OSThread* osthread) {
3659   assert(osthread->sr.is_running(), "thread should be running");
3660   assert(!sr_semaphore.trywait(), "semaphore has invalid state");
3661 
3662   // mark as suspended and send signal
3663   if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
3664     // failed to switch, state wasn't running?
3665     ShouldNotReachHere();
3666     return false;
3667   }
3668 
3669   if (sr_notify(osthread) != 0) {
3670     ShouldNotReachHere();
3671   }
3672 
3673   // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
3674   while (true) {
3675     if (sr_semaphore.timedwait(0, 2000 * NANOSECS_PER_MILLISEC)) {
3676       break;
3677     } else {
3678       // timeout
3679       os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
3680       if (cancelled == os::SuspendResume::SR_RUNNING) {
3681         return false;
3682       } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
3683         // make sure that we consume the signal on the semaphore as well
3684         sr_semaphore.wait();
3685         break;
3686       } else {
3687         ShouldNotReachHere();
3688         return false;
3689       }
3690     }
3691   }
3692 
3693   guarantee(osthread->sr.is_suspended(), "Must be suspended");
3694   return true;
3695 }
3696 
3697 static void do_resume(OSThread* osthread) {
3698   assert(osthread->sr.is_suspended(), "thread should be suspended");
3699   assert(!sr_semaphore.trywait(), "invalid semaphore state");
3700 
3701   if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
3702     // failed to switch to WAKEUP_REQUEST
3703     ShouldNotReachHere();
3704     return;
3705   }
3706 
3707   while (true) {
3708     if (sr_notify(osthread) == 0) {
3709       if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
3710         if (osthread->sr.is_running()) {
3711           return;
3712         }
3713       }
3714     } else {
3715       ShouldNotReachHere();
3716     }
3717   }
3718 
3719   guarantee(osthread->sr.is_running(), "Must be running!");
3720 }
3721 
3722 void os::SuspendedThreadTask::internal_do_task() {
3723   if (do_suspend(_thread->osthread())) {
3724     SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
3725     do_task(context);
3726     do_resume(_thread->osthread());
3727   }
3728 }
3729 
3730 class PcFetcher : public os::SuspendedThreadTask {
3731  public:
3732   PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
3733   ExtendedPC result();
3734  protected:
3735   void do_task(const os::SuspendedThreadTaskContext& context);
3736  private:
3737   ExtendedPC _epc;
3738 };
3739 
3740 ExtendedPC PcFetcher::result() {
3741   guarantee(is_done(), "task is not done yet.");
3742   return _epc;
3743 }
3744 
3745 void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {
3746   Thread* thread = context.thread();
3747   OSThread* osthread = thread->osthread();
3748   if (osthread->ucontext() != NULL) {
3749     _epc = os::Solaris::ucontext_get_pc((ucontext_t *) context.ucontext());
3750   } else {
3751     // NULL context is unexpected, double-check this is the VMThread
3752     guarantee(thread->is_VM_thread(), "can only be called for VMThread");
3753   }
3754 }
3755 
3756 // A lightweight implementation that does not suspend the target thread and
3757 // thus returns only a hint. Used for profiling only!
3758 ExtendedPC os::get_thread_pc(Thread* thread) {
3759   // Make sure that it is called by the watcher and the Threads lock is owned.
3760   assert(Thread::current()->is_Watcher_thread(), "Must be watcher and own Threads_lock");
3761   // For now, is only used to profile the VM Thread
3762   assert(thread->is_VM_thread(), "Can only be called for VMThread");
3763   PcFetcher fetcher(thread);
3764   fetcher.run();
3765   return fetcher.result();
3766 }
3767 
3768 
3769 // This does not do anything on Solaris. This is basically a hook for being
3770 // able to use structured exception handling (thread-local exception filters) on, e.g., Win32.
3771 void os::os_exception_wrapper(java_call_t f, JavaValue* value,
3772                               const methodHandle& method, JavaCallArguments* args,
3773                               Thread* thread) {
3774   f(value, method, args, thread);
3775 }
3776 
3777 // This routine may be used by user applications as a "hook" to catch signals.
3778 // The user-defined signal handler must pass unrecognized signals to this
3779 // routine, and if it returns true (non-zero), then the signal handler must
3780 // return immediately.  If the flag "abort_if_unrecognized" is true, then this
3781 // routine will never retun false (zero), but instead will execute a VM panic
3782 // routine kill the process.
3783 //
3784 // If this routine returns false, it is OK to call it again.  This allows
3785 // the user-defined signal handler to perform checks either before or after
3786 // the VM performs its own checks.  Naturally, the user code would be making
3787 // a serious error if it tried to handle an exception (such as a null check
3788 // or breakpoint) that the VM was generating for its own correct operation.
3789 //
3790 // This routine may recognize any of the following kinds of signals:
3791 // SIGBUS, SIGSEGV, SIGILL, SIGFPE, BREAK_SIGNAL, SIGPIPE, SIGXFSZ,
3792 // os::Solaris::SIGasync
3793 // It should be consulted by handlers for any of those signals.
3794 //
3795 // The caller of this routine must pass in the three arguments supplied
3796 // to the function referred to in the "sa_sigaction" (not the "sa_handler")
3797 // field of the structure passed to sigaction().  This routine assumes that
3798 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
3799 //
3800 // Note that the VM will print warnings if it detects conflicting signal
3801 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
3802 //
3803 extern "C" JNIEXPORT int JVM_handle_solaris_signal(int signo,
3804                                                    siginfo_t* siginfo,
3805                                                    void* ucontext,
3806                                                    int abort_if_unrecognized);
3807 
3808 
3809 void signalHandler(int sig, siginfo_t* info, void* ucVoid) {
3810   int orig_errno = errno;  // Preserve errno value over signal handler.
3811   JVM_handle_solaris_signal(sig, info, ucVoid, true);
3812   errno = orig_errno;
3813 }
3814 
3815 // This boolean allows users to forward their own non-matching signals
3816 // to JVM_handle_solaris_signal, harmlessly.
3817 bool os::Solaris::signal_handlers_are_installed = false;
3818 
3819 // For signal-chaining
3820 bool os::Solaris::libjsig_is_loaded = false;
3821 typedef struct sigaction *(*get_signal_t)(int);
3822 get_signal_t os::Solaris::get_signal_action = NULL;
3823 
3824 struct sigaction* os::Solaris::get_chained_signal_action(int sig) {
3825   struct sigaction *actp = NULL;
3826 
3827   if ((libjsig_is_loaded)  && (sig <= Maxlibjsigsigs)) {
3828     // Retrieve the old signal handler from libjsig
3829     actp = (*get_signal_action)(sig);
3830   }
3831   if (actp == NULL) {
3832     // Retrieve the preinstalled signal handler from jvm
3833     actp = get_preinstalled_handler(sig);
3834   }
3835 
3836   return actp;
3837 }
3838 
3839 static bool call_chained_handler(struct sigaction *actp, int sig,
3840                                  siginfo_t *siginfo, void *context) {
3841   // Call the old signal handler
3842   if (actp->sa_handler == SIG_DFL) {
3843     // It's more reasonable to let jvm treat it as an unexpected exception
3844     // instead of taking the default action.
3845     return false;
3846   } else if (actp->sa_handler != SIG_IGN) {
3847     if ((actp->sa_flags & SA_NODEFER) == 0) {
3848       // automaticlly block the signal
3849       sigaddset(&(actp->sa_mask), sig);
3850     }
3851 
3852     sa_handler_t hand;
3853     sa_sigaction_t sa;
3854     bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
3855     // retrieve the chained handler
3856     if (siginfo_flag_set) {
3857       sa = actp->sa_sigaction;
3858     } else {
3859       hand = actp->sa_handler;
3860     }
3861 
3862     if ((actp->sa_flags & SA_RESETHAND) != 0) {
3863       actp->sa_handler = SIG_DFL;
3864     }
3865 
3866     // try to honor the signal mask
3867     sigset_t oset;
3868     thr_sigsetmask(SIG_SETMASK, &(actp->sa_mask), &oset);
3869 
3870     // call into the chained handler
3871     if (siginfo_flag_set) {
3872       (*sa)(sig, siginfo, context);
3873     } else {
3874       (*hand)(sig);
3875     }
3876 
3877     // restore the signal mask
3878     thr_sigsetmask(SIG_SETMASK, &oset, 0);
3879   }
3880   // Tell jvm's signal handler the signal is taken care of.
3881   return true;
3882 }
3883 
3884 bool os::Solaris::chained_handler(int sig, siginfo_t* siginfo, void* context) {
3885   bool chained = false;
3886   // signal-chaining
3887   if (UseSignalChaining) {
3888     struct sigaction *actp = get_chained_signal_action(sig);
3889     if (actp != NULL) {
3890       chained = call_chained_handler(actp, sig, siginfo, context);
3891     }
3892   }
3893   return chained;
3894 }
3895 
3896 struct sigaction* os::Solaris::get_preinstalled_handler(int sig) {
3897   assert((chainedsigactions != (struct sigaction *)NULL) &&
3898          (preinstalled_sigs != (int *)NULL), "signals not yet initialized");
3899   if (preinstalled_sigs[sig] != 0) {
3900     return &chainedsigactions[sig];
3901   }
3902   return NULL;
3903 }
3904 
3905 void os::Solaris::save_preinstalled_handler(int sig,
3906                                             struct sigaction& oldAct) {
3907   assert(sig > 0 && sig <= Maxsignum, "vm signal out of expected range");
3908   assert((chainedsigactions != (struct sigaction *)NULL) &&
3909          (preinstalled_sigs != (int *)NULL), "signals not yet initialized");
3910   chainedsigactions[sig] = oldAct;
3911   preinstalled_sigs[sig] = 1;
3912 }
3913 
3914 void os::Solaris::set_signal_handler(int sig, bool set_installed,
3915                                      bool oktochain) {
3916   // Check for overwrite.
3917   struct sigaction oldAct;
3918   sigaction(sig, (struct sigaction*)NULL, &oldAct);
3919   void* oldhand =
3920       oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
3921                           : CAST_FROM_FN_PTR(void*,  oldAct.sa_handler);
3922   if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
3923       oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
3924       oldhand != CAST_FROM_FN_PTR(void*, signalHandler)) {
3925     if (AllowUserSignalHandlers || !set_installed) {
3926       // Do not overwrite; user takes responsibility to forward to us.
3927       return;
3928     } else if (UseSignalChaining) {
3929       if (oktochain) {
3930         // save the old handler in jvm
3931         save_preinstalled_handler(sig, oldAct);
3932       } else {
3933         vm_exit_during_initialization("Signal chaining not allowed for VM interrupt signal, try -XX:+UseAltSigs.");
3934       }
3935       // libjsig also interposes the sigaction() call below and saves the
3936       // old sigaction on it own.
3937     } else {
3938       fatal("Encountered unexpected pre-existing sigaction handler "
3939             "%#lx for signal %d.", (long)oldhand, sig);
3940     }
3941   }
3942 
3943   struct sigaction sigAct;
3944   sigfillset(&(sigAct.sa_mask));
3945   sigAct.sa_handler = SIG_DFL;
3946 
3947   sigAct.sa_sigaction = signalHandler;
3948   // Handle SIGSEGV on alternate signal stack if
3949   // not using stack banging
3950   if (!UseStackBanging && sig == SIGSEGV) {
3951     sigAct.sa_flags = SA_SIGINFO | SA_RESTART | SA_ONSTACK;
3952   } else {
3953     sigAct.sa_flags = SA_SIGINFO | SA_RESTART;
3954   }
3955   os::Solaris::set_our_sigflags(sig, sigAct.sa_flags);
3956 
3957   sigaction(sig, &sigAct, &oldAct);
3958 
3959   void* oldhand2 = oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
3960                                        : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
3961   assert(oldhand2 == oldhand, "no concurrent signal handler installation");
3962 }
3963 
3964 
3965 #define DO_SIGNAL_CHECK(sig)                      \
3966   do {                                            \
3967     if (!sigismember(&check_signal_done, sig)) {  \
3968       os::Solaris::check_signal_handler(sig);     \
3969     }                                             \
3970   } while (0)
3971 
3972 // This method is a periodic task to check for misbehaving JNI applications
3973 // under CheckJNI, we can add any periodic checks here
3974 
3975 void os::run_periodic_checks() {
3976   // A big source of grief is hijacking virt. addr 0x0 on Solaris,
3977   // thereby preventing a NULL checks.
3978   if (!check_addr0_done) check_addr0_done = check_addr0(tty);
3979 
3980   if (check_signals == false) return;
3981 
3982   // SEGV and BUS if overridden could potentially prevent
3983   // generation of hs*.log in the event of a crash, debugging
3984   // such a case can be very challenging, so we absolutely
3985   // check for the following for a good measure:
3986   DO_SIGNAL_CHECK(SIGSEGV);
3987   DO_SIGNAL_CHECK(SIGILL);
3988   DO_SIGNAL_CHECK(SIGFPE);
3989   DO_SIGNAL_CHECK(SIGBUS);
3990   DO_SIGNAL_CHECK(SIGPIPE);
3991   DO_SIGNAL_CHECK(SIGXFSZ);
3992 
3993   // ReduceSignalUsage allows the user to override these handlers
3994   // see comments at the very top and jvm_solaris.h
3995   if (!ReduceSignalUsage) {
3996     DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
3997     DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
3998     DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
3999     DO_SIGNAL_CHECK(BREAK_SIGNAL);
4000   }
4001 
4002   // See comments above for using JVM1/JVM2 and UseAltSigs
4003   DO_SIGNAL_CHECK(os::Solaris::SIGasync());
4004 
4005 }
4006 
4007 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
4008 
4009 static os_sigaction_t os_sigaction = NULL;
4010 
4011 void os::Solaris::check_signal_handler(int sig) {
4012   char buf[O_BUFLEN];
4013   address jvmHandler = NULL;
4014 
4015   struct sigaction act;
4016   if (os_sigaction == NULL) {
4017     // only trust the default sigaction, in case it has been interposed
4018     os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
4019     if (os_sigaction == NULL) return;
4020   }
4021 
4022   os_sigaction(sig, (struct sigaction*)NULL, &act);
4023 
4024   address thisHandler = (act.sa_flags & SA_SIGINFO)
4025     ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
4026     : CAST_FROM_FN_PTR(address, act.sa_handler);
4027 
4028 
4029   switch (sig) {
4030   case SIGSEGV:
4031   case SIGBUS:
4032   case SIGFPE:
4033   case SIGPIPE:
4034   case SIGXFSZ:
4035   case SIGILL:
4036     jvmHandler = CAST_FROM_FN_PTR(address, signalHandler);
4037     break;
4038 
4039   case SHUTDOWN1_SIGNAL:
4040   case SHUTDOWN2_SIGNAL:
4041   case SHUTDOWN3_SIGNAL:
4042   case BREAK_SIGNAL:
4043     jvmHandler = (address)user_handler();
4044     break;
4045 
4046   default:
4047     int asynsig = os::Solaris::SIGasync();
4048 
4049     if (sig == asynsig) {
4050       jvmHandler = CAST_FROM_FN_PTR(address, signalHandler);
4051     } else {
4052       return;
4053     }
4054     break;
4055   }
4056 
4057 
4058   if (thisHandler != jvmHandler) {
4059     tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
4060     tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
4061     tty->print_cr("  found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
4062     // No need to check this sig any longer
4063     sigaddset(&check_signal_done, sig);
4064     // Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN
4065     if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) {
4066       tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell",
4067                     exception_name(sig, buf, O_BUFLEN));
4068     }
4069   } else if(os::Solaris::get_our_sigflags(sig) != 0 && act.sa_flags != os::Solaris::get_our_sigflags(sig)) {
4070     tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
4071     tty->print("expected:" PTR32_FORMAT, os::Solaris::get_our_sigflags(sig));
4072     tty->print_cr("  found:" PTR32_FORMAT, act.sa_flags);
4073     // No need to check this sig any longer
4074     sigaddset(&check_signal_done, sig);
4075   }
4076 
4077   // Print all the signal handler state
4078   if (sigismember(&check_signal_done, sig)) {
4079     print_signal_handlers(tty, buf, O_BUFLEN);
4080   }
4081 
4082 }
4083 
4084 void os::Solaris::install_signal_handlers() {
4085   bool libjsigdone = false;
4086   signal_handlers_are_installed = true;
4087 
4088   // signal-chaining
4089   typedef void (*signal_setting_t)();
4090   signal_setting_t begin_signal_setting = NULL;
4091   signal_setting_t end_signal_setting = NULL;
4092   begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
4093                                         dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
4094   if (begin_signal_setting != NULL) {
4095     end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
4096                                         dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
4097     get_signal_action = CAST_TO_FN_PTR(get_signal_t,
4098                                        dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
4099     get_libjsig_version = CAST_TO_FN_PTR(version_getting_t,
4100                                          dlsym(RTLD_DEFAULT, "JVM_get_libjsig_version"));
4101     libjsig_is_loaded = true;
4102     if (os::Solaris::get_libjsig_version != NULL) {
4103       libjsigversion =  (*os::Solaris::get_libjsig_version)();
4104     }
4105     assert(UseSignalChaining, "should enable signal-chaining");
4106   }
4107   if (libjsig_is_loaded) {
4108     // Tell libjsig jvm is setting signal handlers
4109     (*begin_signal_setting)();
4110   }
4111 
4112   set_signal_handler(SIGSEGV, true, true);
4113   set_signal_handler(SIGPIPE, true, true);
4114   set_signal_handler(SIGXFSZ, true, true);
4115   set_signal_handler(SIGBUS, true, true);
4116   set_signal_handler(SIGILL, true, true);
4117   set_signal_handler(SIGFPE, true, true);
4118 
4119 
4120   if (os::Solaris::SIGasync() > OLDMAXSIGNUM) {
4121     // Pre-1.4.1 Libjsig limited to signal chaining signals <= 32 so
4122     // can not register overridable signals which might be > 32
4123     if (libjsig_is_loaded && libjsigversion <= JSIG_VERSION_1_4_1) {
4124       // Tell libjsig jvm has finished setting signal handlers
4125       (*end_signal_setting)();
4126       libjsigdone = true;
4127     }
4128   }
4129 
4130   set_signal_handler(os::Solaris::SIGasync(), true, true);
4131 
4132   if (libjsig_is_loaded && !libjsigdone) {
4133     // Tell libjsig jvm finishes setting signal handlers
4134     (*end_signal_setting)();
4135   }
4136 
4137   // We don't activate signal checker if libjsig is in place, we trust ourselves
4138   // and if UserSignalHandler is installed all bets are off.
4139   // Log that signal checking is off only if -verbose:jni is specified.
4140   if (CheckJNICalls) {
4141     if (libjsig_is_loaded) {
4142       if (PrintJNIResolving) {
4143         tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
4144       }
4145       check_signals = false;
4146     }
4147     if (AllowUserSignalHandlers) {
4148       if (PrintJNIResolving) {
4149         tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
4150       }
4151       check_signals = false;
4152     }
4153   }
4154 }
4155 
4156 
4157 void report_error(const char* file_name, int line_no, const char* title,
4158                   const char* format, ...);
4159 
4160 const char * signames[] = {
4161   "SIG0",
4162   "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", "SIGTRAP",
4163   "SIGABRT", "SIGEMT", "SIGFPE", "SIGKILL", "SIGBUS",
4164   "SIGSEGV", "SIGSYS", "SIGPIPE", "SIGALRM", "SIGTERM",
4165   "SIGUSR1", "SIGUSR2", "SIGCLD", "SIGPWR", "SIGWINCH",
4166   "SIGURG", "SIGPOLL", "SIGSTOP", "SIGTSTP", "SIGCONT",
4167   "SIGTTIN", "SIGTTOU", "SIGVTALRM", "SIGPROF", "SIGXCPU",
4168   "SIGXFSZ", "SIGWAITING", "SIGLWP", "SIGFREEZE", "SIGTHAW",
4169   "SIGCANCEL", "SIGLOST"
4170 };
4171 
4172 const char* os::exception_name(int exception_code, char* buf, size_t size) {
4173   if (0 < exception_code && exception_code <= SIGRTMAX) {
4174     // signal
4175     if (exception_code < sizeof(signames)/sizeof(const char*)) {
4176       jio_snprintf(buf, size, "%s", signames[exception_code]);
4177     } else {
4178       jio_snprintf(buf, size, "SIG%d", exception_code);
4179     }
4180     return buf;
4181   } else {
4182     return NULL;
4183   }
4184 }
4185 
4186 // (Static) wrapper for getisax(2) call.
4187 os::Solaris::getisax_func_t os::Solaris::_getisax = 0;
4188 
4189 // (Static) wrappers for the liblgrp API
4190 os::Solaris::lgrp_home_func_t os::Solaris::_lgrp_home;
4191 os::Solaris::lgrp_init_func_t os::Solaris::_lgrp_init;
4192 os::Solaris::lgrp_fini_func_t os::Solaris::_lgrp_fini;
4193 os::Solaris::lgrp_root_func_t os::Solaris::_lgrp_root;
4194 os::Solaris::lgrp_children_func_t os::Solaris::_lgrp_children;
4195 os::Solaris::lgrp_resources_func_t os::Solaris::_lgrp_resources;
4196 os::Solaris::lgrp_nlgrps_func_t os::Solaris::_lgrp_nlgrps;
4197 os::Solaris::lgrp_cookie_stale_func_t os::Solaris::_lgrp_cookie_stale;
4198 os::Solaris::lgrp_cookie_t os::Solaris::_lgrp_cookie = 0;
4199 
4200 // (Static) wrapper for meminfo() call.
4201 os::Solaris::meminfo_func_t os::Solaris::_meminfo = 0;
4202 
4203 static address resolve_symbol_lazy(const char* name) {
4204   address addr = (address) dlsym(RTLD_DEFAULT, name);
4205   if (addr == NULL) {
4206     // RTLD_DEFAULT was not defined on some early versions of 2.5.1
4207     addr = (address) dlsym(RTLD_NEXT, name);
4208   }
4209   return addr;
4210 }
4211 
4212 static address resolve_symbol(const char* name) {
4213   address addr = resolve_symbol_lazy(name);
4214   if (addr == NULL) {
4215     fatal(dlerror());
4216   }
4217   return addr;
4218 }
4219 
4220 void os::Solaris::libthread_init() {
4221   address func = (address)dlsym(RTLD_DEFAULT, "_thr_suspend_allmutators");
4222 
4223   lwp_priocntl_init();
4224 
4225   // RTLD_DEFAULT was not defined on some early versions of 5.5.1
4226   if (func == NULL) {
4227     func = (address) dlsym(RTLD_NEXT, "_thr_suspend_allmutators");
4228     // Guarantee that this VM is running on an new enough OS (5.6 or
4229     // later) that it will have a new enough libthread.so.
4230     guarantee(func != NULL, "libthread.so is too old.");
4231   }
4232 
4233   int size;
4234   void (*handler_info_func)(address *, int *);
4235   handler_info_func = CAST_TO_FN_PTR(void (*)(address *, int *), resolve_symbol("thr_sighndlrinfo"));
4236   handler_info_func(&handler_start, &size);
4237   handler_end = handler_start + size;
4238 }
4239 
4240 
4241 int_fnP_mutex_tP os::Solaris::_mutex_lock;
4242 int_fnP_mutex_tP os::Solaris::_mutex_trylock;
4243 int_fnP_mutex_tP os::Solaris::_mutex_unlock;
4244 int_fnP_mutex_tP_i_vP os::Solaris::_mutex_init;
4245 int_fnP_mutex_tP os::Solaris::_mutex_destroy;
4246 int os::Solaris::_mutex_scope = USYNC_THREAD;
4247 
4248 int_fnP_cond_tP_mutex_tP_timestruc_tP os::Solaris::_cond_timedwait;
4249 int_fnP_cond_tP_mutex_tP os::Solaris::_cond_wait;
4250 int_fnP_cond_tP os::Solaris::_cond_signal;
4251 int_fnP_cond_tP os::Solaris::_cond_broadcast;
4252 int_fnP_cond_tP_i_vP os::Solaris::_cond_init;
4253 int_fnP_cond_tP os::Solaris::_cond_destroy;
4254 int os::Solaris::_cond_scope = USYNC_THREAD;
4255 
4256 void os::Solaris::synchronization_init() {
4257   if (UseLWPSynchronization) {
4258     os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_lock")));
4259     os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_trylock")));
4260     os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_unlock")));
4261     os::Solaris::set_mutex_init(lwp_mutex_init);
4262     os::Solaris::set_mutex_destroy(lwp_mutex_destroy);
4263     os::Solaris::set_mutex_scope(USYNC_THREAD);
4264 
4265     os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("_lwp_cond_timedwait")));
4266     os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("_lwp_cond_wait")));
4267     os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("_lwp_cond_signal")));
4268     os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("_lwp_cond_broadcast")));
4269     os::Solaris::set_cond_init(lwp_cond_init);
4270     os::Solaris::set_cond_destroy(lwp_cond_destroy);
4271     os::Solaris::set_cond_scope(USYNC_THREAD);
4272   } else {
4273     os::Solaris::set_mutex_scope(USYNC_THREAD);
4274     os::Solaris::set_cond_scope(USYNC_THREAD);
4275 
4276     if (UsePthreads) {
4277       os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_lock")));
4278       os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_trylock")));
4279       os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_unlock")));
4280       os::Solaris::set_mutex_init(pthread_mutex_default_init);
4281       os::Solaris::set_mutex_destroy(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_destroy")));
4282 
4283       os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("pthread_cond_timedwait")));
4284       os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("pthread_cond_wait")));
4285       os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_signal")));
4286       os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_broadcast")));
4287       os::Solaris::set_cond_init(pthread_cond_default_init);
4288       os::Solaris::set_cond_destroy(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_destroy")));
4289     } else {
4290       os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_lock")));
4291       os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_trylock")));
4292       os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_unlock")));
4293       os::Solaris::set_mutex_init(::mutex_init);
4294       os::Solaris::set_mutex_destroy(::mutex_destroy);
4295 
4296       os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("cond_timedwait")));
4297       os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("cond_wait")));
4298       os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("cond_signal")));
4299       os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("cond_broadcast")));
4300       os::Solaris::set_cond_init(::cond_init);
4301       os::Solaris::set_cond_destroy(::cond_destroy);
4302     }
4303   }
4304 }
4305 
4306 bool os::Solaris::liblgrp_init() {
4307   void *handle = dlopen("liblgrp.so.1", RTLD_LAZY);
4308   if (handle != NULL) {
4309     os::Solaris::set_lgrp_home(CAST_TO_FN_PTR(lgrp_home_func_t, dlsym(handle, "lgrp_home")));
4310     os::Solaris::set_lgrp_init(CAST_TO_FN_PTR(lgrp_init_func_t, dlsym(handle, "lgrp_init")));
4311     os::Solaris::set_lgrp_fini(CAST_TO_FN_PTR(lgrp_fini_func_t, dlsym(handle, "lgrp_fini")));
4312     os::Solaris::set_lgrp_root(CAST_TO_FN_PTR(lgrp_root_func_t, dlsym(handle, "lgrp_root")));
4313     os::Solaris::set_lgrp_children(CAST_TO_FN_PTR(lgrp_children_func_t, dlsym(handle, "lgrp_children")));
4314     os::Solaris::set_lgrp_resources(CAST_TO_FN_PTR(lgrp_resources_func_t, dlsym(handle, "lgrp_resources")));
4315     os::Solaris::set_lgrp_nlgrps(CAST_TO_FN_PTR(lgrp_nlgrps_func_t, dlsym(handle, "lgrp_nlgrps")));
4316     os::Solaris::set_lgrp_cookie_stale(CAST_TO_FN_PTR(lgrp_cookie_stale_func_t,
4317                                                       dlsym(handle, "lgrp_cookie_stale")));
4318 
4319     lgrp_cookie_t c = lgrp_init(LGRP_VIEW_CALLER);
4320     set_lgrp_cookie(c);
4321     return true;
4322   }
4323   return false;
4324 }
4325 
4326 void os::Solaris::misc_sym_init() {
4327   address func;
4328 
4329   // getisax
4330   func = resolve_symbol_lazy("getisax");
4331   if (func != NULL) {
4332     os::Solaris::_getisax = CAST_TO_FN_PTR(getisax_func_t, func);
4333   }
4334 
4335   // meminfo
4336   func = resolve_symbol_lazy("meminfo");
4337   if (func != NULL) {
4338     os::Solaris::set_meminfo(CAST_TO_FN_PTR(meminfo_func_t, func));
4339   }
4340 }
4341 
4342 uint_t os::Solaris::getisax(uint32_t* array, uint_t n) {
4343   assert(_getisax != NULL, "_getisax not set");
4344   return _getisax(array, n);
4345 }
4346 
4347 // int pset_getloadavg(psetid_t pset, double loadavg[], int nelem);
4348 typedef long (*pset_getloadavg_type)(psetid_t pset, double loadavg[], int nelem);
4349 static pset_getloadavg_type pset_getloadavg_ptr = NULL;
4350 
4351 void init_pset_getloadavg_ptr(void) {
4352   pset_getloadavg_ptr =
4353     (pset_getloadavg_type)dlsym(RTLD_DEFAULT, "pset_getloadavg");
4354   if (PrintMiscellaneous && Verbose && pset_getloadavg_ptr == NULL) {
4355     warning("pset_getloadavg function not found");
4356   }
4357 }
4358 
4359 int os::Solaris::_dev_zero_fd = -1;
4360 
4361 // this is called _before_ the global arguments have been parsed
4362 void os::init(void) {
4363   _initial_pid = getpid();
4364 
4365   max_hrtime = first_hrtime = gethrtime();
4366 
4367   init_random(1234567);
4368 
4369   page_size = sysconf(_SC_PAGESIZE);
4370   if (page_size == -1) {
4371     fatal("os_solaris.cpp: os::init: sysconf failed (%s)", strerror(errno));
4372   }
4373   init_page_sizes((size_t) page_size);
4374 
4375   Solaris::initialize_system_info();
4376 
4377   // Initialize misc. symbols as soon as possible, so we can use them
4378   // if we need them.
4379   Solaris::misc_sym_init();
4380 
4381   int fd = ::open("/dev/zero", O_RDWR);
4382   if (fd < 0) {
4383     fatal("os::init: cannot open /dev/zero (%s)", strerror(errno));
4384   } else {
4385     Solaris::set_dev_zero_fd(fd);
4386 
4387     // Close on exec, child won't inherit.
4388     fcntl(fd, F_SETFD, FD_CLOEXEC);
4389   }
4390 
4391   clock_tics_per_sec = CLK_TCK;
4392 
4393   // check if dladdr1() exists; dladdr1 can provide more information than
4394   // dladdr for os::dll_address_to_function_name. It comes with SunOS 5.9
4395   // and is available on linker patches for 5.7 and 5.8.
4396   // libdl.so must have been loaded, this call is just an entry lookup
4397   void * hdl = dlopen("libdl.so", RTLD_NOW);
4398   if (hdl) {
4399     dladdr1_func = CAST_TO_FN_PTR(dladdr1_func_type, dlsym(hdl, "dladdr1"));
4400   }
4401 
4402   // (Solaris only) this switches to calls that actually do locking.
4403   ThreadCritical::initialize();
4404 
4405   main_thread = thr_self();
4406 
4407   // Constant minimum stack size allowed. It must be at least
4408   // the minimum of what the OS supports (thr_min_stack()), and
4409   // enough to allow the thread to get to user bytecode execution.
4410   Solaris::min_stack_allowed = MAX2(thr_min_stack(), Solaris::min_stack_allowed);
4411   // If the pagesize of the VM is greater than 8K determine the appropriate
4412   // number of initial guard pages.  The user can change this with the
4413   // command line arguments, if needed.
4414   if (vm_page_size() > 8*K) {
4415     StackYellowPages = 1;
4416     StackRedPages = 1;
4417     StackShadowPages = round_to((StackShadowPages*8*K), vm_page_size()) / vm_page_size();
4418   }
4419 }
4420 
4421 // To install functions for atexit system call
4422 extern "C" {
4423   static void perfMemory_exit_helper() {
4424     perfMemory_exit();
4425   }
4426 }
4427 
4428 // this is called _after_ the global arguments have been parsed
4429 jint os::init_2(void) {
4430   // try to enable extended file IO ASAP, see 6431278
4431   os::Solaris::try_enable_extended_io();
4432 
4433   // Allocate a single page and mark it as readable for safepoint polling.  Also
4434   // use this first mmap call to check support for MAP_ALIGN.
4435   address polling_page = (address)Solaris::mmap_chunk((char*)page_size,
4436                                                       page_size,
4437                                                       MAP_PRIVATE | MAP_ALIGN,
4438                                                       PROT_READ);
4439   if (polling_page == NULL) {
4440     has_map_align = false;
4441     polling_page = (address)Solaris::mmap_chunk(NULL, page_size, MAP_PRIVATE,
4442                                                 PROT_READ);
4443   }
4444 
4445   os::set_polling_page(polling_page);
4446 
4447 #ifndef PRODUCT
4448   if (Verbose && PrintMiscellaneous) {
4449     tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n",
4450                (intptr_t)polling_page);
4451   }
4452 #endif
4453 
4454   if (!UseMembar) {
4455     address mem_serialize_page = (address)Solaris::mmap_chunk(NULL, page_size, MAP_PRIVATE, PROT_READ | PROT_WRITE);
4456     guarantee(mem_serialize_page != NULL, "mmap Failed for memory serialize page");
4457     os::set_memory_serialize_page(mem_serialize_page);
4458 
4459 #ifndef PRODUCT
4460     if (Verbose && PrintMiscellaneous) {
4461       tty->print("[Memory Serialize  Page address: " INTPTR_FORMAT "]\n",
4462                  (intptr_t)mem_serialize_page);
4463     }
4464 #endif
4465   }
4466 
4467   // Check minimum allowable stack size for thread creation and to initialize
4468   // the java system classes, including StackOverflowError - depends on page
4469   // size.  Add a page for compiler2 recursion in main thread.
4470   // Add in 2*BytesPerWord times page size to account for VM stack during
4471   // class initialization depending on 32 or 64 bit VM.
4472   os::Solaris::min_stack_allowed = MAX2(os::Solaris::min_stack_allowed,
4473                                         (size_t)(StackYellowPages+StackRedPages+StackShadowPages+
4474                                         2*BytesPerWord COMPILER2_PRESENT(+1)) * page_size);
4475 
4476   size_t threadStackSizeInBytes = ThreadStackSize * K;
4477   if (threadStackSizeInBytes != 0 &&
4478       threadStackSizeInBytes < os::Solaris::min_stack_allowed) {
4479     tty->print_cr("\nThe stack size specified is too small, Specify at least %dk",
4480                   os::Solaris::min_stack_allowed/K);
4481     return JNI_ERR;
4482   }
4483 
4484   // For 64kbps there will be a 64kb page size, which makes
4485   // the usable default stack size quite a bit less.  Increase the
4486   // stack for 64kb (or any > than 8kb) pages, this increases
4487   // virtual memory fragmentation (since we're not creating the
4488   // stack on a power of 2 boundary.  The real fix for this
4489   // should be to fix the guard page mechanism.
4490 
4491   if (vm_page_size() > 8*K) {
4492     threadStackSizeInBytes = (threadStackSizeInBytes != 0)
4493        ? threadStackSizeInBytes +
4494          ((StackYellowPages + StackRedPages) * vm_page_size())
4495        : 0;
4496     ThreadStackSize = threadStackSizeInBytes/K;
4497   }
4498 
4499   // Make the stack size a multiple of the page size so that
4500   // the yellow/red zones can be guarded.
4501   JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
4502                                                 vm_page_size()));
4503 
4504   Solaris::libthread_init();
4505 
4506   if (UseNUMA) {
4507     if (!Solaris::liblgrp_init()) {
4508       UseNUMA = false;
4509     } else {
4510       size_t lgrp_limit = os::numa_get_groups_num();
4511       int *lgrp_ids = NEW_C_HEAP_ARRAY(int, lgrp_limit, mtInternal);
4512       size_t lgrp_num = os::numa_get_leaf_groups(lgrp_ids, lgrp_limit);
4513       FREE_C_HEAP_ARRAY(int, lgrp_ids);
4514       if (lgrp_num < 2) {
4515         // There's only one locality group, disable NUMA.
4516         UseNUMA = false;
4517       }
4518     }
4519     if (!UseNUMA && ForceNUMA) {
4520       UseNUMA = true;
4521     }
4522   }
4523 
4524   Solaris::signal_sets_init();
4525   Solaris::init_signal_mem();
4526   Solaris::install_signal_handlers();
4527 
4528   if (libjsigversion < JSIG_VERSION_1_4_1) {
4529     Maxlibjsigsigs = OLDMAXSIGNUM;
4530   }
4531 
4532   // initialize synchronization primitives to use either thread or
4533   // lwp synchronization (controlled by UseLWPSynchronization)
4534   Solaris::synchronization_init();
4535 
4536   if (MaxFDLimit) {
4537     // set the number of file descriptors to max. print out error
4538     // if getrlimit/setrlimit fails but continue regardless.
4539     struct rlimit nbr_files;
4540     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
4541     if (status != 0) {
4542       if (PrintMiscellaneous && (Verbose || WizardMode)) {
4543         perror("os::init_2 getrlimit failed");
4544       }
4545     } else {
4546       nbr_files.rlim_cur = nbr_files.rlim_max;
4547       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
4548       if (status != 0) {
4549         if (PrintMiscellaneous && (Verbose || WizardMode)) {
4550           perror("os::init_2 setrlimit failed");
4551         }
4552       }
4553     }
4554   }
4555 
4556   // Calculate theoretical max. size of Threads to guard gainst
4557   // artifical out-of-memory situations, where all available address-
4558   // space has been reserved by thread stacks. Default stack size is 1Mb.
4559   size_t pre_thread_stack_size = (JavaThread::stack_size_at_create()) ?
4560     JavaThread::stack_size_at_create() : (1*K*K);
4561   assert(pre_thread_stack_size != 0, "Must have a stack");
4562   // Solaris has a maximum of 4Gb of user programs. Calculate the thread limit when
4563   // we should start doing Virtual Memory banging. Currently when the threads will
4564   // have used all but 200Mb of space.
4565   size_t max_address_space = ((unsigned int)4 * K * K * K) - (200 * K * K);
4566   Solaris::_os_thread_limit = max_address_space / pre_thread_stack_size;
4567 
4568   // at-exit methods are called in the reverse order of their registration.
4569   // In Solaris 7 and earlier, atexit functions are called on return from
4570   // main or as a result of a call to exit(3C). There can be only 32 of
4571   // these functions registered and atexit() does not set errno. In Solaris
4572   // 8 and later, there is no limit to the number of functions registered
4573   // and atexit() sets errno. In addition, in Solaris 8 and later, atexit
4574   // functions are called upon dlclose(3DL) in addition to return from main
4575   // and exit(3C).
4576 
4577   if (PerfAllowAtExitRegistration) {
4578     // only register atexit functions if PerfAllowAtExitRegistration is set.
4579     // atexit functions can be delayed until process exit time, which
4580     // can be problematic for embedded VM situations. Embedded VMs should
4581     // call DestroyJavaVM() to assure that VM resources are released.
4582 
4583     // note: perfMemory_exit_helper atexit function may be removed in
4584     // the future if the appropriate cleanup code can be added to the
4585     // VM_Exit VMOperation's doit method.
4586     if (atexit(perfMemory_exit_helper) != 0) {
4587       warning("os::init2 atexit(perfMemory_exit_helper) failed");
4588     }
4589   }
4590 
4591   // Init pset_loadavg function pointer
4592   init_pset_getloadavg_ptr();
4593 
4594   return JNI_OK;
4595 }
4596 
4597 // Mark the polling page as unreadable
4598 void os::make_polling_page_unreadable(void) {
4599   if (mprotect((char *)_polling_page, page_size, PROT_NONE) != 0) {
4600     fatal("Could not disable polling page");
4601   }
4602 }
4603 
4604 // Mark the polling page as readable
4605 void os::make_polling_page_readable(void) {
4606   if (mprotect((char *)_polling_page, page_size, PROT_READ) != 0) {
4607     fatal("Could not enable polling page");
4608   }
4609 }
4610 
4611 // OS interface.
4612 
4613 bool os::check_heap(bool force) { return true; }
4614 
4615 // Is a (classpath) directory empty?
4616 bool os::dir_is_empty(const char* path) {
4617   DIR *dir = NULL;
4618   struct dirent *ptr;
4619 
4620   dir = opendir(path);
4621   if (dir == NULL) return true;
4622 
4623   // Scan the directory
4624   bool result = true;
4625   char buf[sizeof(struct dirent) + MAX_PATH];
4626   struct dirent *dbuf = (struct dirent *) buf;
4627   while (result && (ptr = readdir(dir, dbuf)) != NULL) {
4628     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
4629       result = false;
4630     }
4631   }
4632   closedir(dir);
4633   return result;
4634 }
4635 
4636 // This code originates from JDK's sysOpen and open64_w
4637 // from src/solaris/hpi/src/system_md.c
4638 
4639 int os::open(const char *path, int oflag, int mode) {
4640   if (strlen(path) > MAX_PATH - 1) {
4641     errno = ENAMETOOLONG;
4642     return -1;
4643   }
4644   int fd;
4645 
4646   fd = ::open64(path, oflag, mode);
4647   if (fd == -1) return -1;
4648 
4649   // If the open succeeded, the file might still be a directory
4650   {
4651     struct stat64 buf64;
4652     int ret = ::fstat64(fd, &buf64);
4653     int st_mode = buf64.st_mode;
4654 
4655     if (ret != -1) {
4656       if ((st_mode & S_IFMT) == S_IFDIR) {
4657         errno = EISDIR;
4658         ::close(fd);
4659         return -1;
4660       }
4661     } else {
4662       ::close(fd);
4663       return -1;
4664     }
4665   }
4666 
4667   // 32-bit Solaris systems suffer from:
4668   //
4669   // - an historical default soft limit of 256 per-process file
4670   //   descriptors that is too low for many Java programs.
4671   //
4672   // - a design flaw where file descriptors created using stdio
4673   //   fopen must be less than 256, _even_ when the first limit above
4674   //   has been raised.  This can cause calls to fopen (but not calls to
4675   //   open, for example) to fail mysteriously, perhaps in 3rd party
4676   //   native code (although the JDK itself uses fopen).  One can hardly
4677   //   criticize them for using this most standard of all functions.
4678   //
4679   // We attempt to make everything work anyways by:
4680   //
4681   // - raising the soft limit on per-process file descriptors beyond
4682   //   256
4683   //
4684   // - As of Solaris 10u4, we can request that Solaris raise the 256
4685   //   stdio fopen limit by calling function enable_extended_FILE_stdio.
4686   //   This is done in init_2 and recorded in enabled_extended_FILE_stdio
4687   //
4688   // - If we are stuck on an old (pre 10u4) Solaris system, we can
4689   //   workaround the bug by remapping non-stdio file descriptors below
4690   //   256 to ones beyond 256, which is done below.
4691   //
4692   // See:
4693   // 1085341: 32-bit stdio routines should support file descriptors >255
4694   // 6533291: Work around 32-bit Solaris stdio limit of 256 open files
4695   // 6431278: Netbeans crash on 32 bit Solaris: need to call
4696   //          enable_extended_FILE_stdio() in VM initialisation
4697   // Giri Mandalika's blog
4698   // http://technopark02.blogspot.com/2005_05_01_archive.html
4699   //
4700 #ifndef  _LP64
4701   if ((!enabled_extended_FILE_stdio) && fd < 256) {
4702     int newfd = ::fcntl(fd, F_DUPFD, 256);
4703     if (newfd != -1) {
4704       ::close(fd);
4705       fd = newfd;
4706     }
4707   }
4708 #endif // 32-bit Solaris
4709 
4710   // All file descriptors that are opened in the JVM and not
4711   // specifically destined for a subprocess should have the
4712   // close-on-exec flag set.  If we don't set it, then careless 3rd
4713   // party native code might fork and exec without closing all
4714   // appropriate file descriptors (e.g. as we do in closeDescriptors in
4715   // UNIXProcess.c), and this in turn might:
4716   //
4717   // - cause end-of-file to fail to be detected on some file
4718   //   descriptors, resulting in mysterious hangs, or
4719   //
4720   // - might cause an fopen in the subprocess to fail on a system
4721   //   suffering from bug 1085341.
4722   //
4723   // (Yes, the default setting of the close-on-exec flag is a Unix
4724   // design flaw)
4725   //
4726   // See:
4727   // 1085341: 32-bit stdio routines should support file descriptors >255
4728   // 4843136: (process) pipe file descriptor from Runtime.exec not being closed
4729   // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
4730   //
4731 #ifdef FD_CLOEXEC
4732   {
4733     int flags = ::fcntl(fd, F_GETFD);
4734     if (flags != -1) {
4735       ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
4736     }
4737   }
4738 #endif
4739 
4740   return fd;
4741 }
4742 
4743 // create binary file, rewriting existing file if required
4744 int os::create_binary_file(const char* path, bool rewrite_existing) {
4745   int oflags = O_WRONLY | O_CREAT;
4746   if (!rewrite_existing) {
4747     oflags |= O_EXCL;
4748   }
4749   return ::open64(path, oflags, S_IREAD | S_IWRITE);
4750 }
4751 
4752 // return current position of file pointer
4753 jlong os::current_file_offset(int fd) {
4754   return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR);
4755 }
4756 
4757 // move file pointer to the specified offset
4758 jlong os::seek_to_file_offset(int fd, jlong offset) {
4759   return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET);
4760 }
4761 
4762 jlong os::lseek(int fd, jlong offset, int whence) {
4763   return (jlong) ::lseek64(fd, offset, whence);
4764 }
4765 
4766 char * os::native_path(char *path) {
4767   return path;
4768 }
4769 
4770 int os::ftruncate(int fd, jlong length) {
4771   return ::ftruncate64(fd, length);
4772 }
4773 
4774 int os::fsync(int fd)  {
4775   RESTARTABLE_RETURN_INT(::fsync(fd));
4776 }
4777 
4778 int os::available(int fd, jlong *bytes) {
4779   assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
4780          "Assumed _thread_in_native");
4781   jlong cur, end;
4782   int mode;
4783   struct stat64 buf64;
4784 
4785   if (::fstat64(fd, &buf64) >= 0) {
4786     mode = buf64.st_mode;
4787     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
4788       int n,ioctl_return;
4789 
4790       RESTARTABLE(::ioctl(fd, FIONREAD, &n), ioctl_return);
4791       if (ioctl_return>= 0) {
4792         *bytes = n;
4793         return 1;
4794       }
4795     }
4796   }
4797   if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) {
4798     return 0;
4799   } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) {
4800     return 0;
4801   } else if (::lseek64(fd, cur, SEEK_SET) == -1) {
4802     return 0;
4803   }
4804   *bytes = end - cur;
4805   return 1;
4806 }
4807 
4808 // Map a block of memory.
4809 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
4810                         char *addr, size_t bytes, bool read_only,
4811                         bool allow_exec) {
4812   int prot;
4813   int flags;
4814 
4815   if (read_only) {
4816     prot = PROT_READ;
4817     flags = MAP_SHARED;
4818   } else {
4819     prot = PROT_READ | PROT_WRITE;
4820     flags = MAP_PRIVATE;
4821   }
4822 
4823   if (allow_exec) {
4824     prot |= PROT_EXEC;
4825   }
4826 
4827   if (addr != NULL) {
4828     flags |= MAP_FIXED;
4829   }
4830 
4831   char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
4832                                      fd, file_offset);
4833   if (mapped_address == MAP_FAILED) {
4834     return NULL;
4835   }
4836   return mapped_address;
4837 }
4838 
4839 
4840 // Remap a block of memory.
4841 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
4842                           char *addr, size_t bytes, bool read_only,
4843                           bool allow_exec) {
4844   // same as map_memory() on this OS
4845   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
4846                         allow_exec);
4847 }
4848 
4849 
4850 // Unmap a block of memory.
4851 bool os::pd_unmap_memory(char* addr, size_t bytes) {
4852   return munmap(addr, bytes) == 0;
4853 }
4854 
4855 void os::pause() {
4856   char filename[MAX_PATH];
4857   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
4858     jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
4859   } else {
4860     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
4861   }
4862 
4863   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
4864   if (fd != -1) {
4865     struct stat buf;
4866     ::close(fd);
4867     while (::stat(filename, &buf) == 0) {
4868       (void)::poll(NULL, 0, 100);
4869     }
4870   } else {
4871     jio_fprintf(stderr,
4872                 "Could not open pause file '%s', continuing immediately.\n", filename);
4873   }
4874 }
4875 
4876 #ifndef PRODUCT
4877 #ifdef INTERPOSE_ON_SYSTEM_SYNCH_FUNCTIONS
4878 // Turn this on if you need to trace synch operations.
4879 // Set RECORD_SYNCH_LIMIT to a large-enough value,
4880 // and call record_synch_enable and record_synch_disable
4881 // around the computation of interest.
4882 
4883 void record_synch(char* name, bool returning);  // defined below
4884 
4885 class RecordSynch {
4886   char* _name;
4887  public:
4888   RecordSynch(char* name) :_name(name) { record_synch(_name, false); }
4889   ~RecordSynch()                       { record_synch(_name, true); }
4890 };
4891 
4892 #define CHECK_SYNCH_OP(ret, name, params, args, inner)          \
4893 extern "C" ret name params {                                    \
4894   typedef ret name##_t params;                                  \
4895   static name##_t* implem = NULL;                               \
4896   static int callcount = 0;                                     \
4897   if (implem == NULL) {                                         \
4898     implem = (name##_t*) dlsym(RTLD_NEXT, #name);               \
4899     if (implem == NULL)  fatal(dlerror());                      \
4900   }                                                             \
4901   ++callcount;                                                  \
4902   RecordSynch _rs(#name);                                       \
4903   inner;                                                        \
4904   return implem args;                                           \
4905 }
4906 // in dbx, examine callcounts this way:
4907 // for n in $(eval whereis callcount | awk '{print $2}'); do print $n; done
4908 
4909 #define CHECK_POINTER_OK(p) \
4910   (!Universe::is_fully_initialized() || !Universe::is_reserved_heap((oop)(p)))
4911 #define CHECK_MU \
4912   if (!CHECK_POINTER_OK(mu)) fatal("Mutex must be in C heap only.");
4913 #define CHECK_CV \
4914   if (!CHECK_POINTER_OK(cv)) fatal("Condvar must be in C heap only.");
4915 #define CHECK_P(p) \
4916   if (!CHECK_POINTER_OK(p))  fatal(false,  "Pointer must be in C heap only.");
4917 
4918 #define CHECK_MUTEX(mutex_op) \
4919   CHECK_SYNCH_OP(int, mutex_op, (mutex_t *mu), (mu), CHECK_MU);
4920 
4921 CHECK_MUTEX(   mutex_lock)
4922 CHECK_MUTEX(  _mutex_lock)
4923 CHECK_MUTEX( mutex_unlock)
4924 CHECK_MUTEX(_mutex_unlock)
4925 CHECK_MUTEX( mutex_trylock)
4926 CHECK_MUTEX(_mutex_trylock)
4927 
4928 #define CHECK_COND(cond_op) \
4929   CHECK_SYNCH_OP(int, cond_op, (cond_t *cv, mutex_t *mu), (cv, mu), CHECK_MU; CHECK_CV);
4930 
4931 CHECK_COND( cond_wait);
4932 CHECK_COND(_cond_wait);
4933 CHECK_COND(_cond_wait_cancel);
4934 
4935 #define CHECK_COND2(cond_op) \
4936   CHECK_SYNCH_OP(int, cond_op, (cond_t *cv, mutex_t *mu, timestruc_t* ts), (cv, mu, ts), CHECK_MU; CHECK_CV);
4937 
4938 CHECK_COND2( cond_timedwait);
4939 CHECK_COND2(_cond_timedwait);
4940 CHECK_COND2(_cond_timedwait_cancel);
4941 
4942 // do the _lwp_* versions too
4943 #define mutex_t lwp_mutex_t
4944 #define cond_t  lwp_cond_t
4945 CHECK_MUTEX(  _lwp_mutex_lock)
4946 CHECK_MUTEX(  _lwp_mutex_unlock)
4947 CHECK_MUTEX(  _lwp_mutex_trylock)
4948 CHECK_MUTEX( __lwp_mutex_lock)
4949 CHECK_MUTEX( __lwp_mutex_unlock)
4950 CHECK_MUTEX( __lwp_mutex_trylock)
4951 CHECK_MUTEX(___lwp_mutex_lock)
4952 CHECK_MUTEX(___lwp_mutex_unlock)
4953 
4954 CHECK_COND(  _lwp_cond_wait);
4955 CHECK_COND( __lwp_cond_wait);
4956 CHECK_COND(___lwp_cond_wait);
4957 
4958 CHECK_COND2(  _lwp_cond_timedwait);
4959 CHECK_COND2( __lwp_cond_timedwait);
4960 #undef mutex_t
4961 #undef cond_t
4962 
4963 CHECK_SYNCH_OP(int, _lwp_suspend2,       (int lwp, int *n), (lwp, n), 0);
4964 CHECK_SYNCH_OP(int,__lwp_suspend2,       (int lwp, int *n), (lwp, n), 0);
4965 CHECK_SYNCH_OP(int, _lwp_kill,           (int lwp, int n),  (lwp, n), 0);
4966 CHECK_SYNCH_OP(int,__lwp_kill,           (int lwp, int n),  (lwp, n), 0);
4967 CHECK_SYNCH_OP(int, _lwp_sema_wait,      (lwp_sema_t* p),   (p),  CHECK_P(p));
4968 CHECK_SYNCH_OP(int,__lwp_sema_wait,      (lwp_sema_t* p),   (p),  CHECK_P(p));
4969 CHECK_SYNCH_OP(int, _lwp_cond_broadcast, (lwp_cond_t* cv),  (cv), CHECK_CV);
4970 CHECK_SYNCH_OP(int,__lwp_cond_broadcast, (lwp_cond_t* cv),  (cv), CHECK_CV);
4971 
4972 
4973 // recording machinery:
4974 
4975 enum { RECORD_SYNCH_LIMIT = 200 };
4976 char* record_synch_name[RECORD_SYNCH_LIMIT];
4977 void* record_synch_arg0ptr[RECORD_SYNCH_LIMIT];
4978 bool record_synch_returning[RECORD_SYNCH_LIMIT];
4979 thread_t record_synch_thread[RECORD_SYNCH_LIMIT];
4980 int record_synch_count = 0;
4981 bool record_synch_enabled = false;
4982 
4983 // in dbx, examine recorded data this way:
4984 // for n in name arg0ptr returning thread; do print record_synch_$n[0..record_synch_count-1]; done
4985 
4986 void record_synch(char* name, bool returning) {
4987   if (record_synch_enabled) {
4988     if (record_synch_count < RECORD_SYNCH_LIMIT) {
4989       record_synch_name[record_synch_count] = name;
4990       record_synch_returning[record_synch_count] = returning;
4991       record_synch_thread[record_synch_count] = thr_self();
4992       record_synch_arg0ptr[record_synch_count] = &name;
4993       record_synch_count++;
4994     }
4995     // put more checking code here:
4996     // ...
4997   }
4998 }
4999 
5000 void record_synch_enable() {
5001   // start collecting trace data, if not already doing so
5002   if (!record_synch_enabled)  record_synch_count = 0;
5003   record_synch_enabled = true;
5004 }
5005 
5006 void record_synch_disable() {
5007   // stop collecting trace data
5008   record_synch_enabled = false;
5009 }
5010 
5011 #endif // INTERPOSE_ON_SYSTEM_SYNCH_FUNCTIONS
5012 #endif // PRODUCT
5013 
5014 const intptr_t thr_time_off  = (intptr_t)(&((prusage_t *)(NULL))->pr_utime);
5015 const intptr_t thr_time_size = (intptr_t)(&((prusage_t *)(NULL))->pr_ttime) -
5016                                (intptr_t)(&((prusage_t *)(NULL))->pr_utime);
5017 
5018 
5019 // JVMTI & JVM monitoring and management support
5020 // The thread_cpu_time() and current_thread_cpu_time() are only
5021 // supported if is_thread_cpu_time_supported() returns true.
5022 // They are not supported on Solaris T1.
5023 
5024 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
5025 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
5026 // of a thread.
5027 //
5028 // current_thread_cpu_time() and thread_cpu_time(Thread *)
5029 // returns the fast estimate available on the platform.
5030 
5031 // hrtime_t gethrvtime() return value includes
5032 // user time but does not include system time
5033 jlong os::current_thread_cpu_time() {
5034   return (jlong) gethrvtime();
5035 }
5036 
5037 jlong os::thread_cpu_time(Thread *thread) {
5038   // return user level CPU time only to be consistent with
5039   // what current_thread_cpu_time returns.
5040   // thread_cpu_time_info() must be changed if this changes
5041   return os::thread_cpu_time(thread, false /* user time only */);
5042 }
5043 
5044 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
5045   if (user_sys_cpu_time) {
5046     return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
5047   } else {
5048     return os::current_thread_cpu_time();
5049   }
5050 }
5051 
5052 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
5053   char proc_name[64];
5054   int count;
5055   prusage_t prusage;
5056   jlong lwp_time;
5057   int fd;
5058 
5059   sprintf(proc_name, "/proc/%d/lwp/%d/lwpusage",
5060           getpid(),
5061           thread->osthread()->lwp_id());
5062   fd = ::open(proc_name, O_RDONLY);
5063   if (fd == -1) return -1;
5064 
5065   do {
5066     count = ::pread(fd,
5067                     (void *)&prusage.pr_utime,
5068                     thr_time_size,
5069                     thr_time_off);
5070   } while (count < 0 && errno == EINTR);
5071   ::close(fd);
5072   if (count < 0) return -1;
5073 
5074   if (user_sys_cpu_time) {
5075     // user + system CPU time
5076     lwp_time = (((jlong)prusage.pr_stime.tv_sec +
5077                  (jlong)prusage.pr_utime.tv_sec) * (jlong)1000000000) +
5078                  (jlong)prusage.pr_stime.tv_nsec +
5079                  (jlong)prusage.pr_utime.tv_nsec;
5080   } else {
5081     // user level CPU time only
5082     lwp_time = ((jlong)prusage.pr_utime.tv_sec * (jlong)1000000000) +
5083                 (jlong)prusage.pr_utime.tv_nsec;
5084   }
5085 
5086   return (lwp_time);
5087 }
5088 
5089 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5090   info_ptr->max_value = ALL_64_BITS;      // will not wrap in less than 64 bits
5091   info_ptr->may_skip_backward = false;    // elapsed time not wall time
5092   info_ptr->may_skip_forward = false;     // elapsed time not wall time
5093   info_ptr->kind = JVMTI_TIMER_USER_CPU;  // only user time is returned
5094 }
5095 
5096 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5097   info_ptr->max_value = ALL_64_BITS;      // will not wrap in less than 64 bits
5098   info_ptr->may_skip_backward = false;    // elapsed time not wall time
5099   info_ptr->may_skip_forward = false;     // elapsed time not wall time
5100   info_ptr->kind = JVMTI_TIMER_USER_CPU;  // only user time is returned
5101 }
5102 
5103 bool os::is_thread_cpu_time_supported() {
5104   return true;
5105 }
5106 
5107 // System loadavg support.  Returns -1 if load average cannot be obtained.
5108 // Return the load average for our processor set if the primitive exists
5109 // (Solaris 9 and later).  Otherwise just return system wide loadavg.
5110 int os::loadavg(double loadavg[], int nelem) {
5111   if (pset_getloadavg_ptr != NULL) {
5112     return (*pset_getloadavg_ptr)(PS_MYID, loadavg, nelem);
5113   } else {
5114     return ::getloadavg(loadavg, nelem);
5115   }
5116 }
5117 
5118 //---------------------------------------------------------------------------------
5119 
5120 bool os::find(address addr, outputStream* st) {
5121   Dl_info dlinfo;
5122   memset(&dlinfo, 0, sizeof(dlinfo));
5123   if (dladdr(addr, &dlinfo) != 0) {
5124     st->print(PTR_FORMAT ": ", addr);
5125     if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
5126       st->print("%s+%#lx", dlinfo.dli_sname, addr-(intptr_t)dlinfo.dli_saddr);
5127     } else if (dlinfo.dli_fbase != NULL) {
5128       st->print("<offset %#lx>", addr-(intptr_t)dlinfo.dli_fbase);
5129     } else {
5130       st->print("<absolute address>");
5131     }
5132     if (dlinfo.dli_fname != NULL) {
5133       st->print(" in %s", dlinfo.dli_fname);
5134     }
5135     if (dlinfo.dli_fbase != NULL) {
5136       st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
5137     }
5138     st->cr();
5139 
5140     if (Verbose) {
5141       // decode some bytes around the PC
5142       address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
5143       address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
5144       address       lowest = (address) dlinfo.dli_sname;
5145       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
5146       if (begin < lowest)  begin = lowest;
5147       Dl_info dlinfo2;
5148       if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
5149           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) {
5150         end = (address) dlinfo2.dli_saddr;
5151       }
5152       Disassembler::decode(begin, end, st);
5153     }
5154     return true;
5155   }
5156   return false;
5157 }
5158 
5159 // Following function has been added to support HotSparc's libjvm.so running
5160 // under Solaris production JDK 1.2.2 / 1.3.0.  These came from
5161 // src/solaris/hpi/native_threads in the EVM codebase.
5162 //
5163 // NOTE: This is no longer needed in the 1.3.1 and 1.4 production release
5164 // libraries and should thus be removed. We will leave it behind for a while
5165 // until we no longer want to able to run on top of 1.3.0 Solaris production
5166 // JDK. See 4341971.
5167 
5168 #define STACK_SLACK 0x800
5169 
5170 extern "C" {
5171   intptr_t sysThreadAvailableStackWithSlack() {
5172     stack_t st;
5173     intptr_t retval, stack_top;
5174     retval = thr_stksegment(&st);
5175     assert(retval == 0, "incorrect return value from thr_stksegment");
5176     assert((address)&st < (address)st.ss_sp, "Invalid stack base returned");
5177     assert((address)&st > (address)st.ss_sp-st.ss_size, "Invalid stack size returned");
5178     stack_top=(intptr_t)st.ss_sp-st.ss_size;
5179     return ((intptr_t)&stack_top - stack_top - STACK_SLACK);
5180   }
5181 }
5182 
5183 // ObjectMonitor park-unpark infrastructure ...
5184 //
5185 // We implement Solaris and Linux PlatformEvents with the
5186 // obvious condvar-mutex-flag triple.
5187 // Another alternative that works quite well is pipes:
5188 // Each PlatformEvent consists of a pipe-pair.
5189 // The thread associated with the PlatformEvent
5190 // calls park(), which reads from the input end of the pipe.
5191 // Unpark() writes into the other end of the pipe.
5192 // The write-side of the pipe must be set NDELAY.
5193 // Unfortunately pipes consume a large # of handles.
5194 // Native solaris lwp_park() and lwp_unpark() work nicely, too.
5195 // Using pipes for the 1st few threads might be workable, however.
5196 //
5197 // park() is permitted to return spuriously.
5198 // Callers of park() should wrap the call to park() in
5199 // an appropriate loop.  A litmus test for the correct
5200 // usage of park is the following: if park() were modified
5201 // to immediately return 0 your code should still work,
5202 // albeit degenerating to a spin loop.
5203 //
5204 // In a sense, park()-unpark() just provides more polite spinning
5205 // and polling with the key difference over naive spinning being
5206 // that a parked thread needs to be explicitly unparked() in order
5207 // to wake up and to poll the underlying condition.
5208 //
5209 // Assumption:
5210 //    Only one parker can exist on an event, which is why we allocate
5211 //    them per-thread. Multiple unparkers can coexist.
5212 //
5213 // _Event transitions in park()
5214 //   -1 => -1 : illegal
5215 //    1 =>  0 : pass - return immediately
5216 //    0 => -1 : block; then set _Event to 0 before returning
5217 //
5218 // _Event transitions in unpark()
5219 //    0 => 1 : just return
5220 //    1 => 1 : just return
5221 //   -1 => either 0 or 1; must signal target thread
5222 //         That is, we can safely transition _Event from -1 to either
5223 //         0 or 1.
5224 //
5225 // _Event serves as a restricted-range semaphore.
5226 //   -1 : thread is blocked, i.e. there is a waiter
5227 //    0 : neutral: thread is running or ready,
5228 //        could have been signaled after a wait started
5229 //    1 : signaled - thread is running or ready
5230 //
5231 // Another possible encoding of _Event would be with
5232 // explicit "PARKED" == 01b and "SIGNALED" == 10b bits.
5233 //
5234 // TODO-FIXME: add DTRACE probes for:
5235 // 1.   Tx parks
5236 // 2.   Ty unparks Tx
5237 // 3.   Tx resumes from park
5238 
5239 
5240 // value determined through experimentation
5241 #define ROUNDINGFIX 11
5242 
5243 // utility to compute the abstime argument to timedwait.
5244 // TODO-FIXME: switch from compute_abstime() to unpackTime().
5245 
5246 static timestruc_t* compute_abstime(timestruc_t* abstime, jlong millis) {
5247   // millis is the relative timeout time
5248   // abstime will be the absolute timeout time
5249   if (millis < 0)  millis = 0;
5250   struct timeval now;
5251   int status = gettimeofday(&now, NULL);
5252   assert(status == 0, "gettimeofday");
5253   jlong seconds = millis / 1000;
5254   jlong max_wait_period;
5255 
5256   if (UseLWPSynchronization) {
5257     // forward port of fix for 4275818 (not sleeping long enough)
5258     // There was a bug in Solaris 6, 7 and pre-patch 5 of 8 where
5259     // _lwp_cond_timedwait() used a round_down algorithm rather
5260     // than a round_up. For millis less than our roundfactor
5261     // it rounded down to 0 which doesn't meet the spec.
5262     // For millis > roundfactor we may return a bit sooner, but
5263     // since we can not accurately identify the patch level and
5264     // this has already been fixed in Solaris 9 and 8 we will
5265     // leave it alone rather than always rounding down.
5266 
5267     if (millis > 0 && millis < ROUNDINGFIX) millis = ROUNDINGFIX;
5268     // It appears that when we go directly through Solaris _lwp_cond_timedwait()
5269     // the acceptable max time threshold is smaller than for libthread on 2.5.1 and 2.6
5270     max_wait_period = 21000000;
5271   } else {
5272     max_wait_period = 50000000;
5273   }
5274   millis %= 1000;
5275   if (seconds > max_wait_period) {      // see man cond_timedwait(3T)
5276     seconds = max_wait_period;
5277   }
5278   abstime->tv_sec = now.tv_sec  + seconds;
5279   long       usec = now.tv_usec + millis * 1000;
5280   if (usec >= 1000000) {
5281     abstime->tv_sec += 1;
5282     usec -= 1000000;
5283   }
5284   abstime->tv_nsec = usec * 1000;
5285   return abstime;
5286 }
5287 
5288 void os::PlatformEvent::park() {           // AKA: down()
5289   // Transitions for _Event:
5290   //   -1 => -1 : illegal
5291   //    1 =>  0 : pass - return immediately
5292   //    0 => -1 : block; then set _Event to 0 before returning
5293 
5294   // Invariant: Only the thread associated with the Event/PlatformEvent
5295   // may call park().
5296   assert(_nParked == 0, "invariant");
5297 
5298   int v;
5299   for (;;) {
5300     v = _Event;
5301     if (Atomic::cmpxchg(v-1, &_Event, v) == v) break;
5302   }
5303   guarantee(v >= 0, "invariant");
5304   if (v == 0) {
5305     // Do this the hard way by blocking ...
5306     // See http://monaco.sfbay/detail.jsf?cr=5094058.
5307     // TODO-FIXME: for Solaris SPARC set fprs.FEF=0 prior to parking.
5308     // Only for SPARC >= V8PlusA
5309 #if defined(__sparc) && defined(COMPILER2)
5310     if (ClearFPUAtPark) { _mark_fpu_nosave(); }
5311 #endif
5312     int status = os::Solaris::mutex_lock(_mutex);
5313     assert_status(status == 0, status, "mutex_lock");
5314     guarantee(_nParked == 0, "invariant");
5315     ++_nParked;
5316     while (_Event < 0) {
5317       // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
5318       // Treat this the same as if the wait was interrupted
5319       // With usr/lib/lwp going to kernel, always handle ETIME
5320       status = os::Solaris::cond_wait(_cond, _mutex);
5321       if (status == ETIME) status = EINTR;
5322       assert_status(status == 0 || status == EINTR, status, "cond_wait");
5323     }
5324     --_nParked;
5325     _Event = 0;
5326     status = os::Solaris::mutex_unlock(_mutex);
5327     assert_status(status == 0, status, "mutex_unlock");
5328     // Paranoia to ensure our locked and lock-free paths interact
5329     // correctly with each other.
5330     OrderAccess::fence();
5331   }
5332 }
5333 
5334 int os::PlatformEvent::park(jlong millis) {
5335   // Transitions for _Event:
5336   //   -1 => -1 : illegal
5337   //    1 =>  0 : pass - return immediately
5338   //    0 => -1 : block; then set _Event to 0 before returning
5339 
5340   guarantee(_nParked == 0, "invariant");
5341   int v;
5342   for (;;) {
5343     v = _Event;
5344     if (Atomic::cmpxchg(v-1, &_Event, v) == v) break;
5345   }
5346   guarantee(v >= 0, "invariant");
5347   if (v != 0) return OS_OK;
5348 
5349   int ret = OS_TIMEOUT;
5350   timestruc_t abst;
5351   compute_abstime(&abst, millis);
5352 
5353   // See http://monaco.sfbay/detail.jsf?cr=5094058.
5354   // For Solaris SPARC set fprs.FEF=0 prior to parking.
5355   // Only for SPARC >= V8PlusA
5356 #if defined(__sparc) && defined(COMPILER2)
5357   if (ClearFPUAtPark) { _mark_fpu_nosave(); }
5358 #endif
5359   int status = os::Solaris::mutex_lock(_mutex);
5360   assert_status(status == 0, status, "mutex_lock");
5361   guarantee(_nParked == 0, "invariant");
5362   ++_nParked;
5363   while (_Event < 0) {
5364     int status = os::Solaris::cond_timedwait(_cond, _mutex, &abst);
5365     assert_status(status == 0 || status == EINTR ||
5366                   status == ETIME || status == ETIMEDOUT,
5367                   status, "cond_timedwait");
5368     if (!FilterSpuriousWakeups) break;                // previous semantics
5369     if (status == ETIME || status == ETIMEDOUT) break;
5370     // We consume and ignore EINTR and spurious wakeups.
5371   }
5372   --_nParked;
5373   if (_Event >= 0) ret = OS_OK;
5374   _Event = 0;
5375   status = os::Solaris::mutex_unlock(_mutex);
5376   assert_status(status == 0, status, "mutex_unlock");
5377   // Paranoia to ensure our locked and lock-free paths interact
5378   // correctly with each other.
5379   OrderAccess::fence();
5380   return ret;
5381 }
5382 
5383 void os::PlatformEvent::unpark() {
5384   // Transitions for _Event:
5385   //    0 => 1 : just return
5386   //    1 => 1 : just return
5387   //   -1 => either 0 or 1; must signal target thread
5388   //         That is, we can safely transition _Event from -1 to either
5389   //         0 or 1.
5390   // See also: "Semaphores in Plan 9" by Mullender & Cox
5391   //
5392   // Note: Forcing a transition from "-1" to "1" on an unpark() means
5393   // that it will take two back-to-back park() calls for the owning
5394   // thread to block. This has the benefit of forcing a spurious return
5395   // from the first park() call after an unpark() call which will help
5396   // shake out uses of park() and unpark() without condition variables.
5397 
5398   if (Atomic::xchg(1, &_Event) >= 0) return;
5399 
5400   // If the thread associated with the event was parked, wake it.
5401   // Wait for the thread assoc with the PlatformEvent to vacate.
5402   int status = os::Solaris::mutex_lock(_mutex);
5403   assert_status(status == 0, status, "mutex_lock");
5404   int AnyWaiters = _nParked;
5405   status = os::Solaris::mutex_unlock(_mutex);
5406   assert_status(status == 0, status, "mutex_unlock");
5407   guarantee(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
5408   if (AnyWaiters != 0) {
5409     // Note that we signal() *after* dropping the lock for "immortal" Events.
5410     // This is safe and avoids a common class of  futile wakeups.  In rare
5411     // circumstances this can cause a thread to return prematurely from
5412     // cond_{timed}wait() but the spurious wakeup is benign and the victim
5413     // will simply re-test the condition and re-park itself.
5414     // This provides particular benefit if the underlying platform does not
5415     // provide wait morphing.
5416     status = os::Solaris::cond_signal(_cond);
5417     assert_status(status == 0, status, "cond_signal");
5418   }
5419 }
5420 
5421 // JSR166
5422 // -------------------------------------------------------
5423 
5424 // The solaris and linux implementations of park/unpark are fairly
5425 // conservative for now, but can be improved. They currently use a
5426 // mutex/condvar pair, plus _counter.
5427 // Park decrements _counter if > 0, else does a condvar wait.  Unpark
5428 // sets count to 1 and signals condvar.  Only one thread ever waits
5429 // on the condvar. Contention seen when trying to park implies that someone
5430 // is unparking you, so don't wait. And spurious returns are fine, so there
5431 // is no need to track notifications.
5432 
5433 #define MAX_SECS 100000000
5434 
5435 // This code is common to linux and solaris and will be moved to a
5436 // common place in dolphin.
5437 //
5438 // The passed in time value is either a relative time in nanoseconds
5439 // or an absolute time in milliseconds. Either way it has to be unpacked
5440 // into suitable seconds and nanoseconds components and stored in the
5441 // given timespec structure.
5442 // Given time is a 64-bit value and the time_t used in the timespec is only
5443 // a signed-32-bit value (except on 64-bit Linux) we have to watch for
5444 // overflow if times way in the future are given. Further on Solaris versions
5445 // prior to 10 there is a restriction (see cond_timedwait) that the specified
5446 // number of seconds, in abstime, is less than current_time  + 100,000,000.
5447 // As it will be 28 years before "now + 100000000" will overflow we can
5448 // ignore overflow and just impose a hard-limit on seconds using the value
5449 // of "now + 100,000,000". This places a limit on the timeout of about 3.17
5450 // years from "now".
5451 //
5452 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) {
5453   assert(time > 0, "convertTime");
5454 
5455   struct timeval now;
5456   int status = gettimeofday(&now, NULL);
5457   assert(status == 0, "gettimeofday");
5458 
5459   time_t max_secs = now.tv_sec + MAX_SECS;
5460 
5461   if (isAbsolute) {
5462     jlong secs = time / 1000;
5463     if (secs > max_secs) {
5464       absTime->tv_sec = max_secs;
5465     } else {
5466       absTime->tv_sec = secs;
5467     }
5468     absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
5469   } else {
5470     jlong secs = time / NANOSECS_PER_SEC;
5471     if (secs >= MAX_SECS) {
5472       absTime->tv_sec = max_secs;
5473       absTime->tv_nsec = 0;
5474     } else {
5475       absTime->tv_sec = now.tv_sec + secs;
5476       absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
5477       if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
5478         absTime->tv_nsec -= NANOSECS_PER_SEC;
5479         ++absTime->tv_sec; // note: this must be <= max_secs
5480       }
5481     }
5482   }
5483   assert(absTime->tv_sec >= 0, "tv_sec < 0");
5484   assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
5485   assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
5486   assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
5487 }
5488 
5489 void Parker::park(bool isAbsolute, jlong time) {
5490   // Ideally we'd do something useful while spinning, such
5491   // as calling unpackTime().
5492 
5493   // Optional fast-path check:
5494   // Return immediately if a permit is available.
5495   // We depend on Atomic::xchg() having full barrier semantics
5496   // since we are doing a lock-free update to _counter.
5497   if (Atomic::xchg(0, &_counter) > 0) return;
5498 
5499   // Optional fast-exit: Check interrupt before trying to wait
5500   Thread* thread = Thread::current();
5501   assert(thread->is_Java_thread(), "Must be JavaThread");
5502   JavaThread *jt = (JavaThread *)thread;
5503   if (Thread::is_interrupted(thread, false)) {
5504     return;
5505   }
5506 
5507   // First, demultiplex/decode time arguments
5508   timespec absTime;
5509   if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all
5510     return;
5511   }
5512   if (time > 0) {
5513     // Warning: this code might be exposed to the old Solaris time
5514     // round-down bugs.  Grep "roundingFix" for details.
5515     unpackTime(&absTime, isAbsolute, time);
5516   }
5517 
5518   // Enter safepoint region
5519   // Beware of deadlocks such as 6317397.
5520   // The per-thread Parker:: _mutex is a classic leaf-lock.
5521   // In particular a thread must never block on the Threads_lock while
5522   // holding the Parker:: mutex.  If safepoints are pending both the
5523   // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
5524   ThreadBlockInVM tbivm(jt);
5525 
5526   // Don't wait if cannot get lock since interference arises from
5527   // unblocking.  Also. check interrupt before trying wait
5528   if (Thread::is_interrupted(thread, false) ||
5529       os::Solaris::mutex_trylock(_mutex) != 0) {
5530     return;
5531   }
5532 
5533   int status;
5534 
5535   if (_counter > 0)  { // no wait needed
5536     _counter = 0;
5537     status = os::Solaris::mutex_unlock(_mutex);
5538     assert(status == 0, "invariant");
5539     // Paranoia to ensure our locked and lock-free paths interact
5540     // correctly with each other and Java-level accesses.
5541     OrderAccess::fence();
5542     return;
5543   }
5544 
5545 #ifdef ASSERT
5546   // Don't catch signals while blocked; let the running threads have the signals.
5547   // (This allows a debugger to break into the running thread.)
5548   sigset_t oldsigs;
5549   sigset_t* allowdebug_blocked = os::Solaris::allowdebug_blocked_signals();
5550   thr_sigsetmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
5551 #endif
5552 
5553   OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
5554   jt->set_suspend_equivalent();
5555   // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
5556 
5557   // Do this the hard way by blocking ...
5558   // See http://monaco.sfbay/detail.jsf?cr=5094058.
5559   // TODO-FIXME: for Solaris SPARC set fprs.FEF=0 prior to parking.
5560   // Only for SPARC >= V8PlusA
5561 #if defined(__sparc) && defined(COMPILER2)
5562   if (ClearFPUAtPark) { _mark_fpu_nosave(); }
5563 #endif
5564 
5565   if (time == 0) {
5566     status = os::Solaris::cond_wait(_cond, _mutex);
5567   } else {
5568     status = os::Solaris::cond_timedwait (_cond, _mutex, &absTime);
5569   }
5570   // Note that an untimed cond_wait() can sometimes return ETIME on older
5571   // versions of the Solaris.
5572   assert_status(status == 0 || status == EINTR ||
5573                 status == ETIME || status == ETIMEDOUT,
5574                 status, "cond_timedwait");
5575 
5576 #ifdef ASSERT
5577   thr_sigsetmask(SIG_SETMASK, &oldsigs, NULL);
5578 #endif
5579   _counter = 0;
5580   status = os::Solaris::mutex_unlock(_mutex);
5581   assert_status(status == 0, status, "mutex_unlock");
5582   // Paranoia to ensure our locked and lock-free paths interact
5583   // correctly with each other and Java-level accesses.
5584   OrderAccess::fence();
5585 
5586   // If externally suspended while waiting, re-suspend
5587   if (jt->handle_special_suspend_equivalent_condition()) {
5588     jt->java_suspend_self();
5589   }
5590 }
5591 
5592 void Parker::unpark() {
5593   int status = os::Solaris::mutex_lock(_mutex);
5594   assert(status == 0, "invariant");
5595   const int s = _counter;
5596   _counter = 1;
5597   status = os::Solaris::mutex_unlock(_mutex);
5598   assert(status == 0, "invariant");
5599 
5600   if (s < 1) {
5601     status = os::Solaris::cond_signal(_cond);
5602     assert(status == 0, "invariant");
5603   }
5604 }
5605 
5606 extern char** environ;
5607 
5608 // Run the specified command in a separate process. Return its exit value,
5609 // or -1 on failure (e.g. can't fork a new process).
5610 // Unlike system(), this function can be called from signal handler. It
5611 // doesn't block SIGINT et al.
5612 int os::fork_and_exec(char* cmd) {
5613   char * argv[4];
5614   argv[0] = (char *)"sh";
5615   argv[1] = (char *)"-c";
5616   argv[2] = cmd;
5617   argv[3] = NULL;
5618 
5619   // fork is async-safe, fork1 is not so can't use in signal handler
5620   pid_t pid;
5621   Thread* t = Thread::current();
5622   if (t != NULL && t->is_inside_signal_handler()) {
5623     pid = fork();
5624   } else {
5625     pid = fork1();
5626   }
5627 
5628   if (pid < 0) {
5629     // fork failed
5630     warning("fork failed: %s", strerror(errno));
5631     return -1;
5632 
5633   } else if (pid == 0) {
5634     // child process
5635 
5636     // try to be consistent with system(), which uses "/usr/bin/sh" on Solaris
5637     execve("/usr/bin/sh", argv, environ);
5638 
5639     // execve failed
5640     _exit(-1);
5641 
5642   } else  {
5643     // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
5644     // care about the actual exit code, for now.
5645 
5646     int status;
5647 
5648     // Wait for the child process to exit.  This returns immediately if
5649     // the child has already exited. */
5650     while (waitpid(pid, &status, 0) < 0) {
5651       switch (errno) {
5652       case ECHILD: return 0;
5653       case EINTR: break;
5654       default: return -1;
5655       }
5656     }
5657 
5658     if (WIFEXITED(status)) {
5659       // The child exited normally; get its exit code.
5660       return WEXITSTATUS(status);
5661     } else if (WIFSIGNALED(status)) {
5662       // The child exited because of a signal
5663       // The best value to return is 0x80 + signal number,
5664       // because that is what all Unix shells do, and because
5665       // it allows callers to distinguish between process exit and
5666       // process death by signal.
5667       return 0x80 + WTERMSIG(status);
5668     } else {
5669       // Unknown exit code; pass it through
5670       return status;
5671     }
5672   }
5673 }
5674 
5675 // is_headless_jre()
5676 //
5677 // Test for the existence of xawt/libmawt.so or libawt_xawt.so
5678 // in order to report if we are running in a headless jre
5679 //
5680 // Since JDK8 xawt/libmawt.so was moved into the same directory
5681 // as libawt.so, and renamed libawt_xawt.so
5682 //
5683 bool os::is_headless_jre() {
5684   struct stat statbuf;
5685   char buf[MAXPATHLEN];
5686   char libmawtpath[MAXPATHLEN];
5687   const char *xawtstr  = "/xawt/libmawt.so";
5688   const char *new_xawtstr = "/libawt_xawt.so";
5689   char *p;
5690 
5691   // Get path to libjvm.so
5692   os::jvm_path(buf, sizeof(buf));
5693 
5694   // Get rid of libjvm.so
5695   p = strrchr(buf, '/');
5696   if (p == NULL) {
5697     return false;
5698   } else {
5699     *p = '\0';
5700   }
5701 
5702   // Get rid of client or server
5703   p = strrchr(buf, '/');
5704   if (p == NULL) {
5705     return false;
5706   } else {
5707     *p = '\0';
5708   }
5709 
5710   // check xawt/libmawt.so
5711   strcpy(libmawtpath, buf);
5712   strcat(libmawtpath, xawtstr);
5713   if (::stat(libmawtpath, &statbuf) == 0) return false;
5714 
5715   // check libawt_xawt.so
5716   strcpy(libmawtpath, buf);
5717   strcat(libmawtpath, new_xawtstr);
5718   if (::stat(libmawtpath, &statbuf) == 0) return false;
5719 
5720   return true;
5721 }
5722 
5723 size_t os::write(int fd, const void *buf, unsigned int nBytes) {
5724   size_t res;
5725   assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
5726          "Assumed _thread_in_native");
5727   RESTARTABLE((size_t) ::write(fd, buf, (size_t) nBytes), res);
5728   return res;
5729 }
5730 
5731 int os::close(int fd) {
5732   return ::close(fd);
5733 }
5734 
5735 int os::socket_close(int fd) {
5736   return ::close(fd);
5737 }
5738 
5739 int os::recv(int fd, char* buf, size_t nBytes, uint flags) {
5740   assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
5741          "Assumed _thread_in_native");
5742   RESTARTABLE_RETURN_INT((int)::recv(fd, buf, nBytes, flags));
5743 }
5744 
5745 int os::send(int fd, char* buf, size_t nBytes, uint flags) {
5746   assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
5747          "Assumed _thread_in_native");
5748   RESTARTABLE_RETURN_INT((int)::send(fd, buf, nBytes, flags));
5749 }
5750 
5751 int os::raw_send(int fd, char* buf, size_t nBytes, uint flags) {
5752   RESTARTABLE_RETURN_INT((int)::send(fd, buf, nBytes, flags));
5753 }
5754 
5755 // As both poll and select can be interrupted by signals, we have to be
5756 // prepared to restart the system call after updating the timeout, unless
5757 // a poll() is done with timeout == -1, in which case we repeat with this
5758 // "wait forever" value.
5759 
5760 int os::connect(int fd, struct sockaddr *him, socklen_t len) {
5761   int _result;
5762   _result = ::connect(fd, him, len);
5763 
5764   // On Solaris, when a connect() call is interrupted, the connection
5765   // can be established asynchronously (see 6343810). Subsequent calls
5766   // to connect() must check the errno value which has the semantic
5767   // described below (copied from the connect() man page). Handling
5768   // of asynchronously established connections is required for both
5769   // blocking and non-blocking sockets.
5770   //     EINTR            The  connection  attempt  was   interrupted
5771   //                      before  any data arrived by the delivery of
5772   //                      a signal. The connection, however, will  be
5773   //                      established asynchronously.
5774   //
5775   //     EINPROGRESS      The socket is non-blocking, and the connec-
5776   //                      tion  cannot  be completed immediately.
5777   //
5778   //     EALREADY         The socket is non-blocking,  and a previous
5779   //                      connection  attempt  has  not yet been com-
5780   //                      pleted.
5781   //
5782   //     EISCONN          The socket is already connected.
5783   if (_result == OS_ERR && errno == EINTR) {
5784     // restarting a connect() changes its errno semantics
5785     RESTARTABLE(::connect(fd, him, len), _result);
5786     // undo these changes
5787     if (_result == OS_ERR) {
5788       if (errno == EALREADY) {
5789         errno = EINPROGRESS; // fall through
5790       } else if (errno == EISCONN) {
5791         errno = 0;
5792         return OS_OK;
5793       }
5794     }
5795   }
5796   return _result;
5797 }
5798 
5799 // Get the default path to the core file
5800 // Returns the length of the string
5801 int os::get_core_path(char* buffer, size_t bufferSize) {
5802   const char* p = get_current_directory(buffer, bufferSize);
5803 
5804   if (p == NULL) {
5805     assert(p != NULL, "failed to get current directory");
5806     return 0;
5807   }
5808 
5809   jio_snprintf(buffer, bufferSize, "%s/core or core.%d",
5810                                               p, current_process_id());
5811 
5812   return strlen(buffer);
5813 }
5814 
5815 #ifndef PRODUCT
5816 void TestReserveMemorySpecial_test() {
5817   // No tests available for this platform
5818 }
5819 #endif