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