1 /*
2 * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  *
23  */
24 
25 #include "utilities/globalDefinitions.hpp"
26 #include "prims/jvm.h"
27 #include "runtime/frame.inline.hpp"
28 #include "runtime/os.hpp"
29 #include "utilities/vmError.hpp"
30 
31 #include <signal.h>
32 #include <unistd.h>
33 #include <sys/resource.h>
34 #include <sys/utsname.h>
35 #include <pthread.h>
36 #include <signal.h>
37 
38 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
39 
40 // Todo: provide a os::get_max_process_id() or similar. Number of processes
41 // may have been configured, can be read more accurately from proc fs etc.
42 #ifndef MAX_PID
43 #define MAX_PID INT_MAX
44 #endif
45 #define IS_VALID_PID(p) (p > 0 && p < MAX_PID)
46 
47 // Check core dump limit and report possible place where core can be found
check_or_create_dump(void * exceptionRecord,void * contextRecord,char * buffer,size_t bufferSize)48 void os::check_or_create_dump(void* exceptionRecord, void* contextRecord, char* buffer, size_t bufferSize) {
49   int n;
50   struct rlimit rlim;
51   bool success;
52 
53   n = get_core_path(buffer, bufferSize);
54 
55   if (getrlimit(RLIMIT_CORE, &rlim) != 0) {
56     jio_snprintf(buffer + n, bufferSize - n, " (may not exist)");
57     success = true;
58   } else {
59     switch(rlim.rlim_cur) {
60       case RLIM_INFINITY:
61         success = true;
62         break;
63       case 0:
64         jio_snprintf(buffer, bufferSize, "Core dumps have been disabled. To enable core dumping, try \"ulimit -c unlimited\" before starting Java again");
65         success = false;
66         break;
67       default:
68         jio_snprintf(buffer + n, bufferSize - n, " (max size %lu kB). To ensure a full core dump, try \"ulimit -c unlimited\" before starting Java again", (unsigned long)(rlim.rlim_cur >> 10));
69         success = true;
70         break;
71     }
72   }
73   VMError::report_coredump_status(buffer, success);
74 }
75 
get_native_stack(address * stack,int frames,int toSkip)76 int os::get_native_stack(address* stack, int frames, int toSkip) {
77 #ifdef _NMT_NOINLINE_
78   toSkip++;
79 #endif
80 
81   int frame_idx = 0;
82   int num_of_frames;  // number of frames captured
83   frame fr = os::current_frame();
84   while (fr.pc() && frame_idx < frames) {
85     if (toSkip > 0) {
86       toSkip --;
87     } else {
88       stack[frame_idx ++] = fr.pc();
89     }
90     if (fr.fp() == NULL || os::is_first_C_frame(&fr)
91         ||fr.sender_pc() == NULL || fr.cb() != NULL) break;
92 
93     if (fr.sender_pc() && !os::is_first_C_frame(&fr)) {
94       fr = os::get_sender_for_C_frame(&fr);
95     } else {
96       break;
97     }
98   }
99   num_of_frames = frame_idx;
100   for (; frame_idx < frames; frame_idx ++) {
101     stack[frame_idx] = NULL;
102   }
103 
104   return num_of_frames;
105 }
106 
107 
unsetenv(const char * name)108 bool os::unsetenv(const char* name) {
109   assert(name != NULL, "Null pointer");
110   return (::unsetenv(name) == 0);
111 }
112 
get_last_error()113 int os::get_last_error() {
114   return errno;
115 }
116 
is_debugger_attached()117 bool os::is_debugger_attached() {
118   // not implemented
119   return false;
120 }
121 
wait_for_keypress_at_exit(void)122 void os::wait_for_keypress_at_exit(void) {
123   // don't do anything on posix platforms
124   return;
125 }
126 
127 // Multiple threads can race in this code, and can remap over each other with MAP_FIXED,
128 // so on posix, unmap the section at the start and at the end of the chunk that we mapped
129 // rather than unmapping and remapping the whole chunk to get requested alignment.
reserve_memory_aligned(size_t size,size_t alignment)130 char* os::reserve_memory_aligned(size_t size, size_t alignment) {
131   assert((alignment & (os::vm_allocation_granularity() - 1)) == 0,
132       "Alignment must be a multiple of allocation granularity (page size)");
133   assert((size & (alignment -1)) == 0, "size must be 'alignment' aligned");
134 
135   size_t extra_size = size + alignment;
136   assert(extra_size >= size, "overflow, size is too large to allow alignment");
137 
138   char* extra_base = os::reserve_memory(extra_size, NULL, alignment);
139 
140   if (extra_base == NULL) {
141     return NULL;
142   }
143 
144   // Do manual alignment
145   char* aligned_base = (char*) align_size_up((uintptr_t) extra_base, alignment);
146 
147   // [  |                                       |  ]
148   // ^ extra_base
149   //    ^ extra_base + begin_offset == aligned_base
150   //     extra_base + begin_offset + size       ^
151   //                       extra_base + extra_size ^
152   // |<>| == begin_offset
153   //                              end_offset == |<>|
154   size_t begin_offset = aligned_base - extra_base;
155   size_t end_offset = (extra_base + extra_size) - (aligned_base + size);
156 
157   if (begin_offset > 0) {
158       os::release_memory(extra_base, begin_offset);
159   }
160 
161   if (end_offset > 0) {
162       os::release_memory(extra_base + begin_offset + size, end_offset);
163   }
164 
165   return aligned_base;
166 }
167 
vsnprintf(char * buf,size_t len,const char * fmt,va_list args)168 int os::vsnprintf(char* buf, size_t len, const char* fmt, va_list args) {
169   int result = ::vsnprintf(buf, len, fmt, args);
170   // If an encoding error occurred (result < 0) then it's not clear
171   // whether the buffer is NUL terminated, so ensure it is.
172   if ((result < 0) && (len > 0)) {
173     buf[len - 1] = '\0';
174   }
175   return result;
176 }
177 
print_load_average(outputStream * st)178 void os::Posix::print_load_average(outputStream* st) {
179   st->print("load average:");
180   double loadavg[3];
181   os::loadavg(loadavg, 3);
182   st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]);
183   st->cr();
184 }
185 
print_rlimit_info(outputStream * st)186 void os::Posix::print_rlimit_info(outputStream* st) {
187   st->print("rlimit:");
188   struct rlimit rlim;
189 
190   st->print(" STACK ");
191   getrlimit(RLIMIT_STACK, &rlim);
192   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
193   else st->print("%uk", rlim.rlim_cur >> 10);
194 
195   st->print(", CORE ");
196   getrlimit(RLIMIT_CORE, &rlim);
197   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
198   else st->print("%uk", rlim.rlim_cur >> 10);
199 
200   // Isn't there on solaris
201 #if !defined(TARGET_OS_FAMILY_solaris) && !defined(TARGET_OS_FAMILY_aix)
202   st->print(", NPROC ");
203   getrlimit(RLIMIT_NPROC, &rlim);
204   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
205   else st->print("%d", rlim.rlim_cur);
206 #endif
207 
208   st->print(", NOFILE ");
209   getrlimit(RLIMIT_NOFILE, &rlim);
210   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
211   else st->print("%d", rlim.rlim_cur);
212 
213 #ifdef __OpenBSD__
214   st->print(", DATA ");
215   getrlimit(RLIMIT_DATA, &rlim);
216 #else
217   st->print(", AS ");
218   getrlimit(RLIMIT_AS, &rlim);
219 #endif
220   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
221   else st->print("%uk", rlim.rlim_cur >> 10);
222   st->cr();
223 }
224 
print_uname_info(outputStream * st)225 void os::Posix::print_uname_info(outputStream* st) {
226   // kernel
227   st->print("uname:");
228   struct utsname name;
229   uname(&name);
230   st->print("%s ", name.sysname);
231   st->print("%s ", name.release);
232   st->print("%s ", name.version);
233   st->print("%s", name.machine);
234   st->cr();
235 }
236 
has_allocatable_memory_limit(julong * limit)237 bool os::has_allocatable_memory_limit(julong* limit) {
238   struct rlimit rlim;
239 #ifdef __OpenBSD__
240   int getrlimit_res = getrlimit(RLIMIT_DATA, &rlim);
241 #else
242   int getrlimit_res = getrlimit(RLIMIT_AS, &rlim);
243 #endif
244   // if there was an error when calling getrlimit, assume that there is no limitation
245   // on virtual memory.
246   bool result;
247   if ((getrlimit_res != 0) || (rlim.rlim_cur == RLIM_INFINITY)) {
248     result = false;
249   } else {
250     *limit = (julong)rlim.rlim_cur;
251     result = true;
252   }
253 #ifdef _LP64
254   return result;
255 #else
256   // arbitrary virtual space limit for 32 bit Unices found by testing. If
257   // getrlimit above returned a limit, bound it with this limit. Otherwise
258   // directly use it.
259   const julong max_virtual_limit = (julong)3800*M;
260   if (result) {
261     *limit = MIN2(*limit, max_virtual_limit);
262   } else {
263     *limit = max_virtual_limit;
264   }
265 
266   // bound by actually allocatable memory. The algorithm uses two bounds, an
267   // upper and a lower limit. The upper limit is the current highest amount of
268   // memory that could not be allocated, the lower limit is the current highest
269   // amount of memory that could be allocated.
270   // The algorithm iteratively refines the result by halving the difference
271   // between these limits, updating either the upper limit (if that value could
272   // not be allocated) or the lower limit (if the that value could be allocated)
273   // until the difference between these limits is "small".
274 
275   // the minimum amount of memory we care about allocating.
276   const julong min_allocation_size = M;
277 
278   julong upper_limit = *limit;
279 
280   // first check a few trivial cases
281   if (is_allocatable(upper_limit) || (upper_limit <= min_allocation_size)) {
282     *limit = upper_limit;
283   } else if (!is_allocatable(min_allocation_size)) {
284     // we found that not even min_allocation_size is allocatable. Return it
285     // anyway. There is no point to search for a better value any more.
286     *limit = min_allocation_size;
287   } else {
288     // perform the binary search.
289     julong lower_limit = min_allocation_size;
290     while ((upper_limit - lower_limit) > min_allocation_size) {
291       julong temp_limit = ((upper_limit - lower_limit) / 2) + lower_limit;
292       temp_limit = align_size_down_(temp_limit, min_allocation_size);
293       if (is_allocatable(temp_limit)) {
294         lower_limit = temp_limit;
295       } else {
296         upper_limit = temp_limit;
297       }
298     }
299     *limit = lower_limit;
300   }
301   return true;
302 #endif
303 }
304 
get_current_directory(char * buf,size_t buflen)305 const char* os::get_current_directory(char *buf, size_t buflen) {
306   return getcwd(buf, buflen);
307 }
308 
open(int fd,const char * mode)309 FILE* os::open(int fd, const char* mode) {
310   return ::fdopen(fd, mode);
311 }
312 
opendir(const char * dirname)313 DIR* os::opendir(const char* dirname) {
314   assert(dirname != NULL, "just checking");
315   return ::opendir(dirname);
316 }
317 
readdir(DIR * dirp)318 struct dirent* os::readdir(DIR* dirp) {
319   assert(dirp != NULL, "just checking");
320   return ::readdir(dirp);
321 }
322 
closedir(DIR * dirp)323 int os::closedir(DIR *dirp) {
324   assert(dirp != NULL, "just checking");
325   return ::closedir(dirp);
326 }
327 
328 // Builds a platform dependent Agent_OnLoad_<lib_name> function name
329 // which is used to find statically linked in agents.
330 // Parameters:
331 //            sym_name: Symbol in library we are looking for
332 //            lib_name: Name of library to look in, NULL for shared libs.
333 //            is_absolute_path == true if lib_name is absolute path to agent
334 //                                     such as "/a/b/libL.so"
335 //            == false if only the base name of the library is passed in
336 //               such as "L"
build_agent_function_name(const char * sym_name,const char * lib_name,bool is_absolute_path)337 char* os::build_agent_function_name(const char *sym_name, const char *lib_name,
338                                     bool is_absolute_path) {
339   char *agent_entry_name;
340   size_t len;
341   size_t name_len;
342   size_t prefix_len = strlen(JNI_LIB_PREFIX);
343   size_t suffix_len = strlen(JNI_LIB_SUFFIX);
344   const char *start;
345 
346   if (lib_name != NULL) {
347     len = name_len = strlen(lib_name);
348     if (is_absolute_path) {
349       // Need to strip path, prefix and suffix
350       if ((start = strrchr(lib_name, *os::file_separator())) != NULL) {
351         lib_name = ++start;
352       }
353       if (len <= (prefix_len + suffix_len)) {
354         return NULL;
355       }
356       lib_name += prefix_len;
357       name_len = strlen(lib_name) - suffix_len;
358     }
359   }
360   len = (lib_name != NULL ? name_len : 0) + strlen(sym_name) + 2;
361   agent_entry_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, len, mtThread);
362   if (agent_entry_name == NULL) {
363     return NULL;
364   }
365   strcpy(agent_entry_name, sym_name);
366   if (lib_name != NULL) {
367     strcat(agent_entry_name, "_");
368     strncat(agent_entry_name, lib_name, name_len);
369   }
370   return agent_entry_name;
371 }
372 
373 // Returned string is a constant. For unknown signals "UNKNOWN" is returned.
get_signal_name(int sig,char * out,size_t outlen)374 const char* os::Posix::get_signal_name(int sig, char* out, size_t outlen) {
375 
376   static const struct {
377     int sig; const char* name;
378   }
379   info[] =
380   {
381     {  SIGABRT,     "SIGABRT" },
382 #ifdef SIGAIO
383     {  SIGAIO,      "SIGAIO" },
384 #endif
385     {  SIGALRM,     "SIGALRM" },
386 #ifdef SIGALRM1
387     {  SIGALRM1,    "SIGALRM1" },
388 #endif
389     {  SIGBUS,      "SIGBUS" },
390 #ifdef SIGCANCEL
391     {  SIGCANCEL,   "SIGCANCEL" },
392 #endif
393     {  SIGCHLD,     "SIGCHLD" },
394 #ifdef SIGCLD
395     {  SIGCLD,      "SIGCLD" },
396 #endif
397     {  SIGCONT,     "SIGCONT" },
398 #ifdef SIGCPUFAIL
399     {  SIGCPUFAIL,  "SIGCPUFAIL" },
400 #endif
401 #ifdef SIGDANGER
402     {  SIGDANGER,   "SIGDANGER" },
403 #endif
404 #ifdef SIGDIL
405     {  SIGDIL,      "SIGDIL" },
406 #endif
407 #ifdef SIGEMT
408     {  SIGEMT,      "SIGEMT" },
409 #endif
410     {  SIGFPE,      "SIGFPE" },
411 #ifdef SIGFREEZE
412     {  SIGFREEZE,   "SIGFREEZE" },
413 #endif
414 #ifdef SIGGFAULT
415     {  SIGGFAULT,   "SIGGFAULT" },
416 #endif
417 #ifdef SIGGRANT
418     {  SIGGRANT,    "SIGGRANT" },
419 #endif
420     {  SIGHUP,      "SIGHUP" },
421     {  SIGILL,      "SIGILL" },
422     {  SIGINT,      "SIGINT" },
423 #ifdef SIGIO
424     {  SIGIO,       "SIGIO" },
425 #endif
426 #ifdef SIGIOINT
427     {  SIGIOINT,    "SIGIOINT" },
428 #endif
429 #ifdef SIGIOT
430   // SIGIOT is there for BSD compatibility, but on most Unices just a
431   // synonym for SIGABRT. The result should be "SIGABRT", not
432   // "SIGIOT".
433   #if (SIGIOT != SIGABRT )
434     {  SIGIOT,      "SIGIOT" },
435   #endif
436 #endif
437 #ifdef SIGKAP
438     {  SIGKAP,      "SIGKAP" },
439 #endif
440     {  SIGKILL,     "SIGKILL" },
441 #ifdef SIGLOST
442     {  SIGLOST,     "SIGLOST" },
443 #endif
444 #ifdef SIGLWP
445     {  SIGLWP,      "SIGLWP" },
446 #endif
447 #ifdef SIGLWPTIMER
448     {  SIGLWPTIMER, "SIGLWPTIMER" },
449 #endif
450 #ifdef SIGMIGRATE
451     {  SIGMIGRATE,  "SIGMIGRATE" },
452 #endif
453 #ifdef SIGMSG
454     {  SIGMSG,      "SIGMSG" },
455 #endif
456     {  SIGPIPE,     "SIGPIPE" },
457 #ifdef SIGPOLL
458     {  SIGPOLL,     "SIGPOLL" },
459 #endif
460 #ifdef SIGPRE
461     {  SIGPRE,      "SIGPRE" },
462 #endif
463     {  SIGPROF,     "SIGPROF" },
464 #ifdef SIGPTY
465     {  SIGPTY,      "SIGPTY" },
466 #endif
467 #ifdef SIGPWR
468     {  SIGPWR,      "SIGPWR" },
469 #endif
470     {  SIGQUIT,     "SIGQUIT" },
471 #ifdef SIGRECONFIG
472     {  SIGRECONFIG, "SIGRECONFIG" },
473 #endif
474 #ifdef SIGRECOVERY
475     {  SIGRECOVERY, "SIGRECOVERY" },
476 #endif
477 #ifdef SIGRESERVE
478     {  SIGRESERVE,  "SIGRESERVE" },
479 #endif
480 #ifdef SIGRETRACT
481     {  SIGRETRACT,  "SIGRETRACT" },
482 #endif
483 #ifdef SIGSAK
484     {  SIGSAK,      "SIGSAK" },
485 #endif
486     {  SIGSEGV,     "SIGSEGV" },
487 #ifdef SIGSOUND
488     {  SIGSOUND,    "SIGSOUND" },
489 #endif
490     {  SIGSTOP,     "SIGSTOP" },
491     {  SIGSYS,      "SIGSYS" },
492 #ifdef SIGSYSERROR
493     {  SIGSYSERROR, "SIGSYSERROR" },
494 #endif
495 #ifdef SIGTALRM
496     {  SIGTALRM,    "SIGTALRM" },
497 #endif
498     {  SIGTERM,     "SIGTERM" },
499 #ifdef SIGTHAW
500     {  SIGTHAW,     "SIGTHAW" },
501 #endif
502     {  SIGTRAP,     "SIGTRAP" },
503 #ifdef SIGTSTP
504     {  SIGTSTP,     "SIGTSTP" },
505 #endif
506     {  SIGTTIN,     "SIGTTIN" },
507     {  SIGTTOU,     "SIGTTOU" },
508 #ifdef SIGURG
509     {  SIGURG,      "SIGURG" },
510 #endif
511     {  SIGUSR1,     "SIGUSR1" },
512     {  SIGUSR2,     "SIGUSR2" },
513 #ifdef SIGVIRT
514     {  SIGVIRT,     "SIGVIRT" },
515 #endif
516     {  SIGVTALRM,   "SIGVTALRM" },
517 #ifdef SIGWAITING
518     {  SIGWAITING,  "SIGWAITING" },
519 #endif
520 #ifdef SIGWINCH
521     {  SIGWINCH,    "SIGWINCH" },
522 #endif
523 #ifdef SIGWINDOW
524     {  SIGWINDOW,   "SIGWINDOW" },
525 #endif
526     {  SIGXCPU,     "SIGXCPU" },
527     {  SIGXFSZ,     "SIGXFSZ" },
528 #ifdef SIGXRES
529     {  SIGXRES,     "SIGXRES" },
530 #endif
531     { -1, NULL }
532   };
533 
534   const char* ret = NULL;
535 
536 #ifdef SIGRTMIN
537   if (sig >= SIGRTMIN && sig <= SIGRTMAX) {
538     if (sig == SIGRTMIN) {
539       ret = "SIGRTMIN";
540     } else if (sig == SIGRTMAX) {
541       ret = "SIGRTMAX";
542     } else {
543       jio_snprintf(out, outlen, "SIGRTMIN+%d", sig - SIGRTMIN);
544       return out;
545     }
546   }
547 #endif
548 
549   if (sig > 0) {
550     for (int idx = 0; info[idx].sig != -1; idx ++) {
551       if (info[idx].sig == sig) {
552         ret = info[idx].name;
553         break;
554       }
555     }
556   }
557 
558   if (!ret) {
559     if (!is_valid_signal(sig)) {
560       ret = "INVALID";
561     } else {
562       ret = "UNKNOWN";
563     }
564   }
565 
566   jio_snprintf(out, outlen, ret);
567   return out;
568 }
569 
570 // Returns true if signal number is valid.
is_valid_signal(int sig)571 bool os::Posix::is_valid_signal(int sig) {
572   // MacOS not really POSIX compliant: sigaddset does not return
573   // an error for invalid signal numbers. However, MacOS does not
574   // support real time signals and simply seems to have just 33
575   // signals with no holes in the signal range.
576 #ifdef __APPLE__
577   return sig >= 1 && sig < NSIG;
578 #else
579   // Use sigaddset to check for signal validity.
580   sigset_t set;
581   if (sigaddset(&set, sig) == -1 && errno == EINVAL) {
582     return false;
583   }
584   return true;
585 #endif
586 }
587 
588 #define NUM_IMPORTANT_SIGS 32
589 // Returns one-line short description of a signal set in a user provided buffer.
describe_signal_set_short(const sigset_t * set,char * buffer,size_t buf_size)590 const char* os::Posix::describe_signal_set_short(const sigset_t* set, char* buffer, size_t buf_size) {
591   assert(buf_size == (NUM_IMPORTANT_SIGS + 1), "wrong buffer size");
592   // Note: for shortness, just print out the first 32. That should
593   // cover most of the useful ones, apart from realtime signals.
594   for (int sig = 1; sig <= NUM_IMPORTANT_SIGS; sig++) {
595     const int rc = sigismember(set, sig);
596     if (rc == -1 && errno == EINVAL) {
597       buffer[sig-1] = '?';
598     } else {
599       buffer[sig-1] = rc == 0 ? '0' : '1';
600     }
601   }
602   buffer[NUM_IMPORTANT_SIGS] = 0;
603   return buffer;
604 }
605 
606 // Prints one-line description of a signal set.
print_signal_set_short(outputStream * st,const sigset_t * set)607 void os::Posix::print_signal_set_short(outputStream* st, const sigset_t* set) {
608   char buf[NUM_IMPORTANT_SIGS + 1];
609   os::Posix::describe_signal_set_short(set, buf, sizeof(buf));
610   st->print("%s", buf);
611 }
612 
613 // Writes one-line description of a combination of sigaction.sa_flags into a user
614 // provided buffer. Returns that buffer.
describe_sa_flags(int flags,char * buffer,size_t size)615 const char* os::Posix::describe_sa_flags(int flags, char* buffer, size_t size) {
616   char* p = buffer;
617   size_t remaining = size;
618   bool first = true;
619   int idx = 0;
620 
621   assert(buffer, "invalid argument");
622 
623   if (size == 0) {
624     return buffer;
625   }
626 
627   strncpy(buffer, "none", size);
628 
629   const struct {
630     // NB: i is an unsigned int here because SA_RESETHAND is on some
631     // systems 0x80000000, which is implicitly unsigned.  Assignining
632     // it to an int field would be an overflow in unsigned-to-signed
633     // conversion.
634     unsigned int i;
635     const char* s;
636   } flaginfo [] = {
637     { SA_NOCLDSTOP, "SA_NOCLDSTOP" },
638     { SA_ONSTACK,   "SA_ONSTACK"   },
639     { SA_RESETHAND, "SA_RESETHAND" },
640     { SA_RESTART,   "SA_RESTART"   },
641     { SA_SIGINFO,   "SA_SIGINFO"   },
642     { SA_NOCLDWAIT, "SA_NOCLDWAIT" },
643     { SA_NODEFER,   "SA_NODEFER"   },
644 #ifdef AIX
645     { SA_ONSTACK,   "SA_ONSTACK"   },
646     { SA_OLDSTYLE,  "SA_OLDSTYLE"  },
647 #endif
648     { 0, NULL }
649   };
650 
651   for (idx = 0; flaginfo[idx].s && remaining > 1; idx++) {
652     if (flags & flaginfo[idx].i) {
653       if (first) {
654         jio_snprintf(p, remaining, "%s", flaginfo[idx].s);
655         first = false;
656       } else {
657         jio_snprintf(p, remaining, "|%s", flaginfo[idx].s);
658       }
659       const size_t len = strlen(p);
660       p += len;
661       remaining -= len;
662     }
663   }
664 
665   buffer[size - 1] = '\0';
666 
667   return buffer;
668 }
669 
670 // Prints one-line description of a combination of sigaction.sa_flags.
print_sa_flags(outputStream * st,int flags)671 void os::Posix::print_sa_flags(outputStream* st, int flags) {
672   char buffer[0x100];
673   os::Posix::describe_sa_flags(flags, buffer, sizeof(buffer));
674   st->print("%s", buffer);
675 }
676 
677 // Helper function for os::Posix::print_siginfo_...():
678 // return a textual description for signal code.
679 struct enum_sigcode_desc_t {
680   const char* s_name;
681   const char* s_desc;
682 };
683 
get_signal_code_description(const siginfo_t * si,enum_sigcode_desc_t * out)684 static bool get_signal_code_description(const siginfo_t* si, enum_sigcode_desc_t* out) {
685 
686   const struct {
687     int sig; int code; const char* s_code; const char* s_desc;
688   } t1 [] = {
689     { SIGILL,  ILL_ILLOPC,   "ILL_ILLOPC",   "Illegal opcode." },
690     { SIGILL,  ILL_ILLOPN,   "ILL_ILLOPN",   "Illegal operand." },
691     { SIGILL,  ILL_ILLADR,   "ILL_ILLADR",   "Illegal addressing mode." },
692     { SIGILL,  ILL_ILLTRP,   "ILL_ILLTRP",   "Illegal trap." },
693     { SIGILL,  ILL_PRVOPC,   "ILL_PRVOPC",   "Privileged opcode." },
694     { SIGILL,  ILL_PRVREG,   "ILL_PRVREG",   "Privileged register." },
695     { SIGILL,  ILL_COPROC,   "ILL_COPROC",   "Coprocessor error." },
696     { SIGILL,  ILL_BADSTK,   "ILL_BADSTK",   "Internal stack error." },
697 #if defined(IA64) && defined(LINUX)
698     { SIGILL,  ILL_BADIADDR, "ILL_BADIADDR", "Unimplemented instruction address" },
699     { SIGILL,  ILL_BREAK,    "ILL_BREAK",    "Application Break instruction" },
700 #endif
701     { SIGFPE,  FPE_INTDIV,   "FPE_INTDIV",   "Integer divide by zero." },
702     { SIGFPE,  FPE_INTOVF,   "FPE_INTOVF",   "Integer overflow." },
703     { SIGFPE,  FPE_FLTDIV,   "FPE_FLTDIV",   "Floating-point divide by zero." },
704     { SIGFPE,  FPE_FLTOVF,   "FPE_FLTOVF",   "Floating-point overflow." },
705     { SIGFPE,  FPE_FLTUND,   "FPE_FLTUND",   "Floating-point underflow." },
706     { SIGFPE,  FPE_FLTRES,   "FPE_FLTRES",   "Floating-point inexact result." },
707     { SIGFPE,  FPE_FLTINV,   "FPE_FLTINV",   "Invalid floating-point operation." },
708     { SIGFPE,  FPE_FLTSUB,   "FPE_FLTSUB",   "Subscript out of range." },
709     { SIGSEGV, SEGV_MAPERR,  "SEGV_MAPERR",  "Address not mapped to object." },
710     { SIGSEGV, SEGV_ACCERR,  "SEGV_ACCERR",  "Invalid permissions for mapped object." },
711 #ifdef AIX
712     // no explanation found what keyerr would be
713     { SIGSEGV, SEGV_KEYERR,  "SEGV_KEYERR",  "key error" },
714 #endif
715 #if defined(IA64) && !defined(AIX)
716     { SIGSEGV, SEGV_PSTKOVF, "SEGV_PSTKOVF", "Paragraph stack overflow" },
717 #endif
718 #if defined(__sparc) && defined(SOLARIS)
719 // define Solaris Sparc M7 ADI SEGV signals
720 #if !defined(SEGV_ACCADI)
721 #define SEGV_ACCADI 3
722 #endif
723     { SIGSEGV, SEGV_ACCADI,  "SEGV_ACCADI",  "ADI not enabled for mapped object." },
724 #if !defined(SEGV_ACCDERR)
725 #define SEGV_ACCDERR 4
726 #endif
727     { SIGSEGV, SEGV_ACCDERR, "SEGV_ACCDERR", "ADI disrupting exception." },
728 #if !defined(SEGV_ACCPERR)
729 #define SEGV_ACCPERR 5
730 #endif
731     { SIGSEGV, SEGV_ACCPERR, "SEGV_ACCPERR", "ADI precise exception." },
732 #endif // defined(__sparc) && defined(SOLARIS)
733     { SIGBUS,  BUS_ADRALN,   "BUS_ADRALN",   "Invalid address alignment." },
734     { SIGBUS,  BUS_ADRERR,   "BUS_ADRERR",   "Nonexistent physical address." },
735     { SIGBUS,  BUS_OBJERR,   "BUS_OBJERR",   "Object-specific hardware error." },
736     { SIGTRAP, TRAP_BRKPT,   "TRAP_BRKPT",   "Process breakpoint." },
737     { SIGTRAP, TRAP_TRACE,   "TRAP_TRACE",   "Process trace trap." },
738     { SIGCHLD, CLD_EXITED,   "CLD_EXITED",   "Child has exited." },
739     { SIGCHLD, CLD_KILLED,   "CLD_KILLED",   "Child has terminated abnormally and did not create a core file." },
740     { SIGCHLD, CLD_DUMPED,   "CLD_DUMPED",   "Child has terminated abnormally and created a core file." },
741     { SIGCHLD, CLD_TRAPPED,  "CLD_TRAPPED",  "Traced child has trapped." },
742     { SIGCHLD, CLD_STOPPED,  "CLD_STOPPED",  "Child has stopped." },
743     { SIGCHLD, CLD_CONTINUED,"CLD_CONTINUED","Stopped child has continued." },
744 #ifdef SIGPOLL
745     { SIGPOLL, POLL_OUT,     "POLL_OUT",     "Output buffers available." },
746     { SIGPOLL, POLL_MSG,     "POLL_MSG",     "Input message available." },
747     { SIGPOLL, POLL_ERR,     "POLL_ERR",     "I/O error." },
748     { SIGPOLL, POLL_PRI,     "POLL_PRI",     "High priority input available." },
749     { SIGPOLL, POLL_HUP,     "POLL_HUP",     "Device disconnected. [Option End]" },
750 #endif
751     { -1, -1, NULL, NULL }
752   };
753 
754   // Codes valid in any signal context.
755   const struct {
756     int code; const char* s_code; const char* s_desc;
757   } t2 [] = {
758     { SI_USER,      "SI_USER",     "Signal sent by kill()." },
759     { SI_QUEUE,     "SI_QUEUE",    "Signal sent by the sigqueue()." },
760     { SI_TIMER,     "SI_TIMER",    "Signal generated by expiration of a timer set by timer_settime()." },
761 #ifdef SI_ASYNCIO
762     { SI_ASYNCIO,   "SI_ASYNCIO",  "Signal generated by completion of an asynchronous I/O request." },
763 #endif
764 #ifdef SI_MESGQ
765     { SI_MESGQ,     "SI_MESGQ",    "Signal generated by arrival of a message on an empty message queue." },
766 #endif
767     // Linux specific
768 #ifdef SI_TKILL
769     { SI_TKILL,     "SI_TKILL",    "Signal sent by tkill (pthread_kill)" },
770 #endif
771 #ifdef SI_DETHREAD
772     { SI_DETHREAD,  "SI_DETHREAD", "Signal sent by execve() killing subsidiary threads" },
773 #endif
774 #ifdef SI_KERNEL
775     { SI_KERNEL,    "SI_KERNEL",   "Signal sent by kernel." },
776 #endif
777 #ifdef SI_SIGIO
778     { SI_SIGIO,     "SI_SIGIO",    "Signal sent by queued SIGIO" },
779 #endif
780 
781 #ifdef AIX
782     { SI_UNDEFINED, "SI_UNDEFINED","siginfo contains partial information" },
783     { SI_EMPTY,     "SI_EMPTY",    "siginfo contains no useful information" },
784 #endif
785 
786 #ifdef __sun
787     { SI_NOINFO,    "SI_NOINFO",   "No signal information" },
788     { SI_RCTL,      "SI_RCTL",     "kernel generated signal via rctl action" },
789     { SI_LWP,       "SI_LWP",      "Signal sent via lwp_kill" },
790 #endif
791 
792     { -1, NULL, NULL }
793   };
794 
795   const char* s_code = NULL;
796   const char* s_desc = NULL;
797 
798   for (int i = 0; t1[i].sig != -1; i ++) {
799     if (t1[i].sig == si->si_signo && t1[i].code == si->si_code) {
800       s_code = t1[i].s_code;
801       s_desc = t1[i].s_desc;
802       break;
803     }
804   }
805 
806   if (s_code == NULL) {
807     for (int i = 0; t2[i].s_code != NULL; i ++) {
808       if (t2[i].code == si->si_code) {
809         s_code = t2[i].s_code;
810         s_desc = t2[i].s_desc;
811       }
812     }
813   }
814 
815   if (s_code == NULL) {
816     out->s_name = "unknown";
817     out->s_desc = "unknown";
818     return false;
819   }
820 
821   out->s_name = s_code;
822   out->s_desc = s_desc;
823 
824   return true;
825 }
826 
827 // A POSIX conform, platform-independend siginfo print routine.
828 // Short print out on one line.
print_siginfo_brief(outputStream * os,const siginfo_t * si)829 void os::Posix::print_siginfo_brief(outputStream* os, const siginfo_t* si) {
830   char buf[20];
831   os->print("siginfo: ");
832 
833   if (!si) {
834     os->print("<null>");
835     return;
836   }
837 
838   // See print_siginfo_full() for details.
839   const int sig = si->si_signo;
840 
841   os->print("si_signo: %d (%s)", sig, os::Posix::get_signal_name(sig, buf, sizeof(buf)));
842 
843   enum_sigcode_desc_t ed;
844   if (get_signal_code_description(si, &ed)) {
845     os->print(", si_code: %d (%s)", si->si_code, ed.s_name);
846   } else {
847     os->print(", si_code: %d (unknown)", si->si_code);
848   }
849 
850   if (si->si_errno) {
851     os->print(", si_errno: %d", si->si_errno);
852   }
853 
854   const int me = (int) ::getpid();
855   const int pid = (int) si->si_pid;
856 
857   if (si->si_code == SI_USER || si->si_code == SI_QUEUE) {
858     if (IS_VALID_PID(pid) && pid != me) {
859       os->print(", sent from pid: %d (uid: %d)", pid, (int) si->si_uid);
860     }
861   } else if (sig == SIGSEGV || sig == SIGBUS || sig == SIGILL ||
862              sig == SIGTRAP || sig == SIGFPE) {
863     os->print(", si_addr: " PTR_FORMAT, si->si_addr);
864 #ifdef SIGPOLL
865   } else if (sig == SIGPOLL) {
866     os->print(", si_band: " PTR64_FORMAT, (uint64_t)si->si_band);
867 #endif
868   } else if (sig == SIGCHLD) {
869     os->print_cr(", si_pid: %d, si_uid: %d, si_status: %d", (int) si->si_pid, si->si_uid, si->si_status);
870   }
871 }
872 
873 Thread* os::ThreadCrashProtection::_protected_thread = NULL;
874 os::ThreadCrashProtection* os::ThreadCrashProtection::_crash_protection = NULL;
875 volatile intptr_t os::ThreadCrashProtection::_crash_mux = 0;
876 
ThreadCrashProtection()877 os::ThreadCrashProtection::ThreadCrashProtection() {
878 }
879 
880 /*
881  * See the caveats for this class in os_posix.hpp
882  * Protects the callback call so that SIGSEGV / SIGBUS jumps back into this
883  * method and returns false. If none of the signals are raised, returns true.
884  * The callback is supposed to provide the method that should be protected.
885  */
call(os::CrashProtectionCallback & cb)886 bool os::ThreadCrashProtection::call(os::CrashProtectionCallback& cb) {
887   sigset_t saved_sig_mask;
888 
889   Thread::muxAcquire(&_crash_mux, "CrashProtection");
890 
891   _protected_thread = ThreadLocalStorage::thread();
892   assert(_protected_thread != NULL, "Cannot crash protect a NULL thread");
893 
894   // we cannot rely on sigsetjmp/siglongjmp to save/restore the signal mask
895   // since on at least some systems (OS X) siglongjmp will restore the mask
896   // for the process, not the thread
897   pthread_sigmask(0, NULL, &saved_sig_mask);
898   if (sigsetjmp(_jmpbuf, 0) == 0) {
899     // make sure we can see in the signal handler that we have crash protection
900     // installed
901     _crash_protection = this;
902     cb.call();
903     // and clear the crash protection
904     _crash_protection = NULL;
905     _protected_thread = NULL;
906     Thread::muxRelease(&_crash_mux);
907     return true;
908   }
909   // this happens when we siglongjmp() back
910   pthread_sigmask(SIG_SETMASK, &saved_sig_mask, NULL);
911   _crash_protection = NULL;
912   _protected_thread = NULL;
913   Thread::muxRelease(&_crash_mux);
914   return false;
915 }
916 
restore()917 void os::ThreadCrashProtection::restore() {
918   assert(_crash_protection != NULL, "must have crash protection");
919   siglongjmp(_jmpbuf, 1);
920 }
921 
check_crash_protection(int sig,Thread * thread)922 void os::ThreadCrashProtection::check_crash_protection(int sig,
923     Thread* thread) {
924 
925   if (thread != NULL &&
926       thread == _protected_thread &&
927       _crash_protection != NULL) {
928 
929     if (sig == SIGSEGV || sig == SIGBUS) {
930       _crash_protection->restore();
931     }
932   }
933 }
934