1 /*
  2  * Copyright (c) 1997, 2021, 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 "precompiled.hpp"
 26 #include "jvm.h"
 27 #include "classfile/systemDictionary.hpp"
 28 #include "code/codeCache.hpp"
 29 #include "code/icBuffer.hpp"
 30 #include "code/nmethod.hpp"
 31 #include "code/vtableStubs.hpp"
 32 #include "compiler/compileBroker.hpp"
 33 #include "compiler/disassembler.hpp"
 34 #include "gc/shared/collectedHeap.hpp"
 35 #include "interpreter/interpreter.hpp"
 36 #include "memory/allocation.hpp"
 37 #include "memory/resourceArea.hpp"
 38 #include "memory/universe.hpp"
 39 #include "oops/klass.inline.hpp"
 40 #include "oops/oop.inline.hpp"
 41 #include "runtime/atomic.hpp"
 42 #include "runtime/flags/flagSetting.hpp"
 43 #include "runtime/frame.inline.hpp"
 44 #include "runtime/handles.inline.hpp"
 45 #include "runtime/java.hpp"
 46 #include "runtime/os.hpp"
 47 #include "runtime/safefetch.inline.hpp"
 48 #include "runtime/sharedRuntime.hpp"
 49 #include "runtime/stubCodeGenerator.hpp"
 50 #include "runtime/stubRoutines.hpp"
 51 #include "runtime/thread.inline.hpp"
 52 #include "runtime/vframe.hpp"
 53 #include "runtime/vm_version.hpp"
 54 #include "services/heapDumper.hpp"
 55 #include "services/memTracker.hpp"
 56 #include "utilities/defaultStream.hpp"
 57 #include "utilities/events.hpp"
 58 #include "utilities/formatBuffer.hpp"
 59 #include "utilities/globalDefinitions.hpp"
 60 #include "utilities/macros.hpp"
 61 #include "utilities/vmError.hpp"
 62 
 63 #include <stdio.h>
 64 #include <stdarg.h>
 65 
 66 // Support for showing register content on asserts/guarantees.
 67 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
 68 static char g_dummy;
 69 char* g_assert_poison = &g_dummy;
 70 static intx g_asserting_thread = 0;
 71 static void* g_assertion_context = NULL;
 72 #endif // CAN_SHOW_REGISTERS_ON_ASSERT
 73 
 74 // Set to suppress secondary error reporting.
 75 bool Debugging = false;
 76 
 77 #ifndef ASSERT
 78 #  ifdef _DEBUG
 79    // NOTE: don't turn the lines below into a comment -- if you're getting
 80    // a compile error here, change the settings to define ASSERT
 81    ASSERT should be defined when _DEBUG is defined.  It is not intended to be used for debugging
 82    functions that do not slow down the system too much and thus can be left in optimized code.
 83    On the other hand, the code should not be included in a production version.
 84 #  endif // _DEBUG
 85 #endif // ASSERT
 86 
 87 
 88 #ifdef _DEBUG
 89 #  ifndef ASSERT
 90      configuration error: ASSERT must be defined in debug version
 91 #  endif // ASSERT
 92 #endif // _DEBUG
 93 
 94 
 95 #ifdef PRODUCT
 96 #  if -defined _DEBUG || -defined ASSERT
 97      configuration error: ASSERT et al. must not be defined in PRODUCT version
 98 #  endif
 99 #endif // PRODUCT
100 
101 #ifdef ASSERT
102 // This is to test that error reporting works if we assert during dynamic
103 // initialization of the hotspot. See JDK-8214975.
104 struct Crasher {
105   Crasher() {
106     // Using getenv - no other mechanism would work yet.
107     const char* s = ::getenv("HOTSPOT_FATAL_ERROR_DURING_DYNAMIC_INITIALIZATION");
108     if (s != NULL && ::strcmp(s, "1") == 0) {
109       fatal("HOTSPOT_FATAL_ERROR_DURING_DYNAMIC_INITIALIZATION");
110     }
111   }
112 };
113 static Crasher g_crasher;
114 #endif // ASSERT
115 
116 ATTRIBUTE_PRINTF(1, 2)
117 void warning(const char* format, ...) {
118   if (PrintWarnings) {
119     FILE* const err = defaultStream::error_stream();
120     jio_fprintf(err, "%s warning: ", VM_Version::vm_name());
121     va_list ap;
122     va_start(ap, format);
123     vfprintf(err, format, ap);
124     va_end(ap);
125     fputc('\n', err);
126   }
127 }
128 
129 #ifndef PRODUCT
130 
131 #define is_token_break(ch) (isspace(ch) || (ch) == ',')
132 
133 static const char* last_file_name = NULL;
134 static int         last_line_no   = -1;
135 
136 // assert/guarantee/... may happen very early during VM initialization.
137 // Don't rely on anything that is initialized by Threads::create_vm(). For
138 // example, don't use tty.
139 bool error_is_suppressed(const char* file_name, int line_no) {
140   // The following 1-element cache requires that passed-in
141   // file names are always only constant literals.
142   if (file_name == last_file_name && line_no == last_line_no)  return true;
143 
144   int file_name_len = (int)strlen(file_name);
145   char separator = os::file_separator()[0];
146   const char* base_name = strrchr(file_name, separator);
147   if (base_name == NULL)
148     base_name = file_name;
149 
150   // scan the SuppressErrorAt option
151   const char* cp = SuppressErrorAt;
152   for (;;) {
153     const char* sfile;
154     int sfile_len;
155     int sline;
156     bool noisy;
157     while ((*cp) != '\0' && is_token_break(*cp))  cp++;
158     if ((*cp) == '\0')  break;
159     sfile = cp;
160     while ((*cp) != '\0' && !is_token_break(*cp) && (*cp) != ':')  cp++;
161     sfile_len = cp - sfile;
162     if ((*cp) == ':')  cp++;
163     sline = 0;
164     while ((*cp) != '\0' && isdigit(*cp)) {
165       sline *= 10;
166       sline += (*cp) - '0';
167       cp++;
168     }
169     // "file:line!" means the assert suppression is not silent
170     noisy = ((*cp) == '!');
171     while ((*cp) != '\0' && !is_token_break(*cp))  cp++;
172     // match the line
173     if (sline != 0) {
174       if (sline != line_no)  continue;
175     }
176     // match the file
177     if (sfile_len > 0) {
178       const char* look = file_name;
179       const char* look_max = file_name + file_name_len - sfile_len;
180       const char* foundp;
181       bool match = false;
182       while (!match
183              && (foundp = strchr(look, sfile[0])) != NULL
184              && foundp <= look_max) {
185         match = true;
186         for (int i = 1; i < sfile_len; i++) {
187           if (sfile[i] != foundp[i]) {
188             match = false;
189             break;
190           }
191         }
192         look = foundp + 1;
193       }
194       if (!match)  continue;
195     }
196     // got a match!
197     if (noisy) {
198       fdStream out(defaultStream::output_fd());
199       out.print_raw("[error suppressed at ");
200       out.print_raw(base_name);
201       char buf[16];
202       jio_snprintf(buf, sizeof(buf), ":%d]", line_no);
203       out.print_raw_cr(buf);
204     } else {
205       // update 1-element cache for fast silent matches
206       last_file_name = file_name;
207       last_line_no   = line_no;
208     }
209     return true;
210   }
211 
212   if (!VMError::is_error_reported() && !SuppressFatalErrorMessage) {
213     // print a friendly hint:
214     fdStream out(defaultStream::output_fd());
215     out.print_raw_cr("# To suppress the following error report, specify this argument");
216     out.print_raw   ("# after -XX: or in .hotspotrc:  SuppressErrorAt=");
217     out.print_raw   (base_name);
218     char buf[16];
219     jio_snprintf(buf, sizeof(buf), ":%d", line_no);
220     out.print_raw_cr(buf);
221   }
222   return false;
223 }
224 
225 #undef is_token_break
226 
227 #else
228 
229 // Place-holder for non-existent suppression check:
230 #define error_is_suppressed(file_name, line_no) (false)
231 
232 #endif // !PRODUCT
233 
234 void report_vm_error(const char* file, int line, const char* error_msg)
235 {
236   report_vm_error(file, line, error_msg, "%s", "");
237 }
238 
239 
240 static void print_error_for_unit_test(const char* message, const char* detail_fmt, va_list detail_args) {
241 #ifdef ASSERT
242   if (ExecutingUnitTests) {
243     char detail_msg[256];
244     if (detail_fmt != NULL) {
245       // Special handling for the sake of gtest death tests which expect the assert
246       // message to be printed in one short line to stderr (see TEST_VM_ASSERT_MSG) and
247       // cannot be tweaked to accept our normal assert message.
248       va_list detail_args_copy;
249       va_copy(detail_args_copy, detail_args);
250       jio_vsnprintf(detail_msg, sizeof(detail_msg), detail_fmt, detail_args_copy);
251 
252       // the VM assert tests look for "assert failed: "
253       if (message == NULL) {
254         fprintf(stderr, "assert failed: %s", detail_msg);
255       } else {
256         if (strlen(detail_msg) > 0) {
257           fprintf(stderr, "assert failed: %s: %s", message, detail_msg);
258         } else {
259           fprintf(stderr, "assert failed: Error: %s", message);
260         }
261       }
262       ::fflush(stderr);
263       va_end(detail_args_copy);
264     }
265   }
266 #endif // ASSERT
267 }
268 
269 void report_vm_error(const char* file, int line, const char* error_msg, const char* detail_fmt, ...)
270 {
271   if (Debugging || error_is_suppressed(file, line)) return;
272   va_list detail_args;
273   va_start(detail_args, detail_fmt);
274   void* context = NULL;
275 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
276   if (g_assertion_context != NULL && os::current_thread_id() == g_asserting_thread) {
277     context = g_assertion_context;
278   }
279 #endif // CAN_SHOW_REGISTERS_ON_ASSERT
280 
281   print_error_for_unit_test(error_msg, detail_fmt, detail_args);
282 
283   VMError::report_and_die(Thread::current_or_null(), context, file, line, error_msg, detail_fmt, detail_args);
284   va_end(detail_args);
285 }
286 
287 void report_vm_status_error(const char* file, int line, const char* error_msg,
288                             int status, const char* detail) {
289   report_vm_error(file, line, error_msg, "error %s(%d), %s", os::errno_name(status), status, detail);
290 }
291 
292 void report_fatal(VMErrorType error_type, const char* file, int line, const char* detail_fmt, ...) {
293   if (Debugging || error_is_suppressed(file, line)) return;
294   va_list detail_args;
295   va_start(detail_args, detail_fmt);
296   void* context = NULL;
297 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
298   if (g_assertion_context != NULL && os::current_thread_id() == g_asserting_thread) {
299     context = g_assertion_context;
300   }
301 #endif // CAN_SHOW_REGISTERS_ON_ASSERT
302 
303   print_error_for_unit_test("fatal error", detail_fmt, detail_args);
304 
305   VMError::report_and_die(error_type, "fatal error", detail_fmt, detail_args,
306                           Thread::current_or_null(), NULL, NULL, context,
307                           file, line, 0);
308   va_end(detail_args);
309 }
310 
311 void report_vm_out_of_memory(const char* file, int line, size_t size,
312                              VMErrorType vm_err_type, const char* detail_fmt, ...) {
313   if (Debugging) return;
314   va_list detail_args;
315   va_start(detail_args, detail_fmt);
316 
317   print_error_for_unit_test(NULL, detail_fmt, detail_args);
318 
319   VMError::report_and_die(Thread::current_or_null(), file, line, size, vm_err_type, detail_fmt, detail_args);
320   va_end(detail_args);
321 
322   // The UseOSErrorReporting option in report_and_die() may allow a return
323   // to here. If so then we'll have to figure out how to handle it.
324   guarantee(false, "report_and_die() should not return here");
325 }
326 
327 void report_should_not_call(const char* file, int line) {
328   report_vm_error(file, line, "ShouldNotCall()");
329 }
330 
331 void report_should_not_reach_here(const char* file, int line) {
332   report_vm_error(file, line, "ShouldNotReachHere()");
333 }
334 
335 void report_unimplemented(const char* file, int line) {
336   report_vm_error(file, line, "Unimplemented()");
337 }
338 
339 void report_untested(const char* file, int line, const char* message) {
340 #ifndef PRODUCT
341   warning("Untested: %s in %s: %d\n", message, file, line);
342 #endif // !PRODUCT
343 }
344 
345 void report_java_out_of_memory(const char* message) {
346   static int out_of_memory_reported = 0;
347 
348   // A number of threads may attempt to report OutOfMemoryError at around the
349   // same time. To avoid dumping the heap or executing the data collection
350   // commands multiple times we just do it once when the first threads reports
351   // the error.
352   if (Atomic::cmpxchg(&out_of_memory_reported, 0, 1) == 0) {
353     // create heap dump before OnOutOfMemoryError commands are executed
354     if (HeapDumpOnOutOfMemoryError) {
355       tty->print_cr("java.lang.OutOfMemoryError: %s", message);
356       HeapDumper::dump_heap_from_oome();
357     }
358 
359     if (OnOutOfMemoryError && OnOutOfMemoryError[0]) {
360       VMError::report_java_out_of_memory(message);
361     }
362 
363     if (CrashOnOutOfMemoryError) {
364       tty->print_cr("Aborting due to java.lang.OutOfMemoryError: %s", message);
365       report_fatal(OOM_JAVA_HEAP_FATAL, __FILE__, __LINE__, "OutOfMemory encountered: %s", message);
366     }
367 
368     if (ExitOnOutOfMemoryError) {
369       tty->print_cr("Terminating due to java.lang.OutOfMemoryError: %s", message);
370       os::_exit(3); // quick exit with no cleanup hooks run
371     }
372   }
373 }
374 
375 // ------ helper functions for debugging go here ------------
376 
377 // All debug entries should be wrapped with a stack allocated
378 // Command object. It makes sure a resource mark is set and
379 // flushes the logfile to prevent file sharing problems.
380 
381 class Command : public StackObj {
382  private:
383   ResourceMark rm;
384   bool debug_save;
385  public:
386   static int level;
387   Command(const char* str) {
388     debug_save = Debugging;
389     Debugging = true;
390     if (level++ > 0)  return;
391     tty->cr();
392     tty->print_cr("\"Executing %s\"", str);
393   }
394 
395   ~Command() {
396     tty->flush();
397     Debugging = debug_save;
398     level--;
399   }
400 };
401 
402 int Command::level = 0;
403 
404 extern "C" JNIEXPORT void blob(CodeBlob* cb) {
405   Command c("blob");
406   cb->print();
407 }
408 
409 
410 extern "C" JNIEXPORT void dump_vtable(address p) {
411   Command c("dump_vtable");
412   Klass* k = (Klass*)p;
413   k->vtable().print();
414 }
415 
416 
417 extern "C" JNIEXPORT void nm(intptr_t p) {
418   // Actually we look through all CodeBlobs (the nm name has been kept for backwards compatability)
419   Command c("nm");
420   CodeBlob* cb = CodeCache::find_blob((address)p);
421   if (cb == NULL) {
422     tty->print_cr("NULL");
423   } else {
424     cb->print();
425   }
426 }
427 
428 
429 extern "C" JNIEXPORT void disnm(intptr_t p) {
430   Command c("disnm");
431   CodeBlob* cb = CodeCache::find_blob((address) p);
432   if (cb != NULL) {
433     nmethod* nm = cb->as_nmethod_or_null();
434     if (nm != NULL) {
435       nm->print();
436     } else {
437       cb->print();
438     }
439     Disassembler::decode(cb);
440   }
441 }
442 
443 
444 extern "C" JNIEXPORT void printnm(intptr_t p) {
445   char buffer[256];
446   sprintf(buffer, "printnm: " INTPTR_FORMAT, p);
447   Command c(buffer);
448   CodeBlob* cb = CodeCache::find_blob((address) p);
449   if (cb->is_nmethod()) {
450     nmethod* nm = (nmethod*)cb;
451     nm->print_nmethod(true);
452   }
453 }
454 
455 
456 extern "C" JNIEXPORT void universe() {
457   Command c("universe");
458   Universe::print_on(tty);
459 }
460 
461 
462 extern "C" JNIEXPORT void verify() {
463   // try to run a verify on the entire system
464   // note: this may not be safe if we're not at a safepoint; for debugging,
465   // this manipulates the safepoint settings to avoid assertion failures
466   Command c("universe verify");
467   bool safe = SafepointSynchronize::is_at_safepoint();
468   if (!safe) {
469     tty->print_cr("warning: not at safepoint -- verify may fail");
470     SafepointSynchronize::set_is_at_safepoint();
471   }
472   // Ensure Eden top is correct before verification
473   Universe::heap()->prepare_for_verify();
474   Universe::verify();
475   if (!safe) SafepointSynchronize::set_is_not_at_safepoint();
476 }
477 
478 
479 extern "C" JNIEXPORT void pp(void* p) {
480   Command c("pp");
481   FlagSetting fl(DisplayVMOutput, true);
482   if (Universe::heap()->is_in(p)) {
483     oop obj = cast_to_oop(p);
484     obj->print();
485   } else {
486     tty->print(PTR_FORMAT, p2i(p));
487   }
488 }
489 
490 
491 extern "C" JNIEXPORT void findpc(intptr_t x);
492 
493 extern "C" JNIEXPORT void ps() { // print stack
494   if (Thread::current_or_null() == NULL) return;
495   Command c("ps");
496 
497   // Prints the stack of the current Java thread
498   JavaThread* p = JavaThread::active();
499   tty->print(" for thread: ");
500   p->print();
501   tty->cr();
502 
503   if (p->has_last_Java_frame()) {
504     // If the last_Java_fp is set we are in C land and
505     // can call the standard stack_trace function.
506     p->print_stack();
507 #ifndef PRODUCT
508     if (Verbose) p->trace_stack();
509   } else {
510     frame f = os::current_frame();
511     RegisterMap reg_map(p);
512     f = f.sender(&reg_map);
513     tty->print("(guessing starting frame id=" PTR_FORMAT " based on current fp)\n", p2i(f.id()));
514     p->trace_stack_from(vframe::new_vframe(&f, &reg_map, p));
515 #endif
516   }
517 }
518 
519 extern "C" JNIEXPORT void pfl() {
520   // print frame layout
521   Command c("pfl");
522   JavaThread* p = JavaThread::active();
523   tty->print(" for thread: ");
524   p->print();
525   tty->cr();
526   if (p->has_last_Java_frame()) {
527     p->print_frame_layout();
528   }
529 }
530 
531 extern "C" JNIEXPORT void psf() { // print stack frames
532   {
533     Command c("psf");
534     JavaThread* p = JavaThread::active();
535     tty->print(" for thread: ");
536     p->print();
537     tty->cr();
538     if (p->has_last_Java_frame()) {
539       p->trace_frames();
540     }
541   }
542 }
543 
544 
545 extern "C" JNIEXPORT void threads() {
546   Command c("threads");
547   Threads::print(false, true);
548 }
549 
550 
551 extern "C" JNIEXPORT void psd() {
552   Command c("psd");
553   SystemDictionary::print();
554 }
555 
556 
557 extern "C" JNIEXPORT void pss() { // print all stacks
558   if (Thread::current_or_null() == NULL) return;
559   Command c("pss");
560   Threads::print(true, PRODUCT_ONLY(false) NOT_PRODUCT(true));
561 }
562 
563 // #ifndef PRODUCT
564 
565 extern "C" JNIEXPORT void debug() {               // to set things up for compiler debugging
566   Command c("debug");
567   NOT_PRODUCT(WizardMode = true;)
568   PrintCompilation = true;
569   PrintInlining = PrintAssembly = true;
570   tty->flush();
571 }
572 
573 
574 extern "C" JNIEXPORT void ndebug() {              // undo debug()
575   Command c("ndebug");
576   PrintCompilation = false;
577   PrintInlining = PrintAssembly = false;
578   tty->flush();
579 }
580 
581 
582 extern "C" JNIEXPORT void flush()  {
583   Command c("flush");
584   tty->flush();
585 }
586 
587 extern "C" JNIEXPORT void events() {
588   Command c("events");
589   Events::print();
590 }
591 
592 extern "C" JNIEXPORT Method* findm(intptr_t pc) {
593   Command c("findm");
594   nmethod* nm = CodeCache::find_nmethod((address)pc);
595   return (nm == NULL) ? (Method*)NULL : nm->method();
596 }
597 
598 
599 extern "C" JNIEXPORT nmethod* findnm(intptr_t addr) {
600   Command c("findnm");
601   return  CodeCache::find_nmethod((address)addr);
602 }
603 
604 extern "C" JNIEXPORT void find(intptr_t x) {
605   Command c("find");
606   os::print_location(tty, x, false);
607 }
608 
609 
610 extern "C" JNIEXPORT void findpc(intptr_t x) {
611   Command c("findpc");
612   os::print_location(tty, x, true);
613 }
614 
615 
616 // Need method pointer to find bcp, when not in permgen.
617 extern "C" JNIEXPORT void findbcp(intptr_t method, intptr_t bcp) {
618   Command c("findbcp");
619   Method* mh = (Method*)method;
620   if (!mh->is_native()) {
621     tty->print_cr("bci_from(%p) = %d; print_codes():",
622                         mh, mh->bci_from(address(bcp)));
623     mh->print_codes_on(tty);
624   }
625 }
626 
627 // int versions of all methods to avoid having to type type casts in the debugger
628 
629 void pp(intptr_t p)          { pp((void*)p); }
630 void pp(oop p)               { pp((void*)p); }
631 
632 void help() {
633   Command c("help");
634   tty->print_cr("basic");
635   tty->print_cr("  pp(void* p)   - try to make sense of p");
636   tty->print_cr("  ps()          - print current thread stack");
637   tty->print_cr("  pss()         - print all thread stacks");
638   tty->print_cr("  pm(int pc)    - print Method* given compiled PC");
639   tty->print_cr("  findm(intptr_t pc) - finds Method*");
640   tty->print_cr("  find(intptr_t x)   - finds & prints nmethod/stub/bytecode/oop based on pointer into it");
641   tty->print_cr("  pns(void* sp, void* fp, void* pc)  - print native (i.e. mixed) stack trace. E.g.");
642   tty->print_cr("                   pns($sp, $rbp, $pc) on Linux/amd64 or");
643   tty->print_cr("                   pns($sp, $ebp, $pc) on Linux/x86 or");
644   tty->print_cr("                   pns($sp, $fp, $pc)  on Linux/AArch64 or");
645   tty->print_cr("                   pns($sp, 0, $pc)    on Linux/ppc64 or");
646   tty->print_cr("                   pns($sp, $s8, $pc)  on Linux/mips or");
647   tty->print_cr("                 - in gdb do 'set overload-resolution off' before calling pns()");
648   tty->print_cr("                 - in dbx do 'frame 1' before calling pns()");
649 
650   tty->print_cr("misc.");
651   tty->print_cr("  flush()       - flushes the log file");
652   tty->print_cr("  events()      - dump events from ring buffers");
653 
654 
655   tty->print_cr("compiler debugging");
656   tty->print_cr("  debug()       - to set things up for compiler debugging");
657   tty->print_cr("  ndebug()      - undo debug");
658 }
659 
660 #ifndef PRODUCT
661 extern "C" JNIEXPORT void pns(void* sp, void* fp, void* pc) { // print native stack
662   Command c("pns");
663   static char buf[O_BUFLEN];
664   Thread* t = Thread::current_or_null();
665   // Call generic frame constructor (certain arguments may be ignored)
666   frame fr(sp, fp, pc);
667   VMError::print_native_stack(tty, fr, t, buf, sizeof(buf));
668 }
669 
670 //
671 // This version of pns() will not work when called from the debugger, but is
672 // useful when called from within hotspot code. The advantages over pns()
673 // are not having to pass in any arguments, and it will work on Windows/x64.
674 //
675 // WARNING: Only intended for use when debugging. Do not leave calls to
676 // pns2() in committed source (product or debug).
677 //
678 extern "C" JNIEXPORT void pns2() { // print native stack
679   Command c("pns2");
680   static char buf[O_BUFLEN];
681   if (os::platform_print_native_stack(tty, NULL, buf, sizeof(buf))) {
682     // We have printed the native stack in platform-specific code,
683     // so nothing else to do in this case.
684   } else {
685     Thread* t = Thread::current_or_null();
686     frame fr = os::current_frame();
687     VMError::print_native_stack(tty, fr, t, buf, sizeof(buf));
688   }
689 }
690 #endif
691 
692 
693 // Returns true iff the address p is readable and *(intptr_t*)p != errvalue
694 extern "C" bool dbg_is_safe(const void* p, intptr_t errvalue) {
695   return p != NULL && SafeFetchN((intptr_t*)const_cast<void*>(p), errvalue) != errvalue;
696 }
697 
698 //////////////////////////////////////////////////////////////////////////////
699 // Test multiple STATIC_ASSERT forms in various scopes.
700 
701 #ifndef PRODUCT
702 
703 // namespace scope
704 STATIC_ASSERT(true);
705 STATIC_ASSERT(true);
706 STATIC_ASSERT(1 == 1);
707 STATIC_ASSERT(0 == 0);
708 
709 void test_multiple_static_assert_forms_in_function_scope() {
710   STATIC_ASSERT(true);
711   STATIC_ASSERT(true);
712   STATIC_ASSERT(0 == 0);
713   STATIC_ASSERT(1 == 1);
714 }
715 
716 // class scope
717 struct TestMultipleStaticAssertFormsInClassScope {
718   STATIC_ASSERT(true);
719   STATIC_ASSERT(true);
720   STATIC_ASSERT(0 == 0);
721   STATIC_ASSERT(1 == 1);
722 };
723 
724 #endif // !PRODUCT
725 
726 // Support for showing register content on asserts/guarantees.
727 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
728 
729 static ucontext_t g_stored_assertion_context;
730 
731 void initialize_assert_poison() {
732   char* page = os::reserve_memory(os::vm_page_size());
733   if (page) {
734     MemTracker::record_virtual_memory_type(page, mtInternal);
735     if (os::commit_memory(page, os::vm_page_size(), false) &&
736         os::protect_memory(page, os::vm_page_size(), os::MEM_PROT_NONE)) {
737       g_assert_poison = page;
738     }
739   }
740 }
741 
742 void disarm_assert_poison() {
743   g_assert_poison = &g_dummy;
744 }
745 
746 static void store_context(const void* context) {
747   memcpy(&g_stored_assertion_context, context, sizeof(ucontext_t));
748 #if defined(LINUX) && defined(PPC64)
749   // on Linux ppc64, ucontext_t contains pointers into itself which have to be patched up
750   //  after copying the context (see comment in sys/ucontext.h):
751   *((void**) &g_stored_assertion_context.uc_mcontext.regs) = &(g_stored_assertion_context.uc_mcontext.gp_regs);
752 #endif
753 }
754 
755 bool handle_assert_poison_fault(const void* ucVoid, const void* faulting_address) {
756   if (faulting_address == g_assert_poison) {
757     // Disarm poison page.
758     if (os::protect_memory((char*)g_assert_poison, os::vm_page_size(), os::MEM_PROT_RWX) == false) {
759 #ifdef ASSERT
760       fprintf(stderr, "Assertion poison page cannot be unprotected - mprotect failed with %d (%s)",
761               errno, os::strerror(errno));
762       fflush(stderr);
763 #endif
764       return false; // unprotecting memory may fail in OOM situations, as surprising as this sounds.
765     }
766     // Store Context away.
767     if (ucVoid) {
768       const intx my_tid = os::current_thread_id();
769       if (Atomic::cmpxchg(&g_asserting_thread, (intx)0, my_tid) == 0) {
770         store_context(ucVoid);
771         g_assertion_context = &g_stored_assertion_context;
772       }
773     }
774     return true;
775   }
776   return false;
777 }
778 #endif // CAN_SHOW_REGISTERS_ON_ASSERT