src/os/solaris/vm/os_solaris.cpp

Thu, 05 Sep 2019 18:52:27 +0800

author
aoqi
date
Thu, 05 Sep 2019 18:52:27 +0800
changeset 9703
2fdf635bcf28
parent 9637
eef07cd490d4
parent 9677
af43bab3c5d0
child 9756
2be326848943
permissions
-rw-r--r--

Merge

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

mercurial