1 /*
  2  * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
  3  * Copyright (c) 2016, 2019 SAP SE. All rights reserved.
  4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  5  *
  6  * This code is free software; you can redistribute it and/or modify it
  7  * under the terms of the GNU General Public License version 2 only, as
  8  * published by the Free Software Foundation.
  9  *
 10  * This code is distributed in the hope that it will be useful, but WITHOUT
 11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 13  * version 2 for more details (a copy is included in the LICENSE file that
 14  * accompanied this code).
 15  *
 16  * You should have received a copy of the GNU General Public License version
 17  * 2 along with this work; if not, write to the Free Software Foundation,
 18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 19  *
 20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 21  * or visit www.oracle.com if you need additional information or have any
 22  * questions.
 23  *
 24  */
 25 
 26 #include "precompiled.hpp"
 27 #include "compiler/oopMap.hpp"
 28 #include "interpreter/interpreter.hpp"
 29 #include "memory/resourceArea.hpp"
 30 #include "memory/universe.hpp"
 31 #include "oops/markWord.hpp"
 32 #include "oops/oop.inline.hpp"
 33 #include "runtime/frame.inline.hpp"
 34 #include "runtime/handles.inline.hpp"
 35 #include "runtime/javaCalls.hpp"
 36 #include "runtime/monitorChunk.hpp"
 37 #include "runtime/os.inline.hpp"
 38 #include "runtime/signature.hpp"
 39 #include "runtime/stubCodeGenerator.hpp"
 40 #include "runtime/stubRoutines.hpp"
 41 #include "vmreg_s390.inline.hpp"
 42 #ifdef COMPILER1
 43 #include "c1/c1_Runtime1.hpp"
 44 #include "runtime/vframeArray.hpp"
 45 #endif
 46 
 47 // Major contributions by Aha, AS.
 48 
 49 #ifdef ASSERT
 50 void RegisterMap::check_location_valid() {
 51 }
 52 #endif // ASSERT
 53 
 54 
 55 // Profiling/safepoint support
 56 
 57 bool frame::safe_for_sender(JavaThread *thread) {
 58   address sp = (address)_sp;
 59   address fp = (address)_fp;
 60   address unextended_sp = (address)_unextended_sp;
 61 
 62   // consider stack guards when trying to determine "safe" stack pointers
 63   // sp must be within the usable part of the stack (not in guards)
 64   if (!thread->is_in_usable_stack(sp)) {
 65     return false;
 66   }
 67 
 68   // Unextended sp must be within the stack
 69   if (!thread->is_in_full_stack_checked(unextended_sp)) {
 70     return false;
 71   }
 72 
 73   // An fp must be within the stack and above (but not equal) sp.
 74   bool fp_safe = thread->is_in_stack_range_excl(fp, sp);
 75   // An interpreter fp must be fp_safe.
 76   // Moreover, it must be at a distance at least the size of the z_ijava_state structure.
 77   bool fp_interp_safe = fp_safe && ((fp - sp) >= z_ijava_state_size);
 78 
 79   // We know sp/unextended_sp are safe, only fp is questionable here
 80 
 81   // If the current frame is known to the code cache then we can attempt to
 82   // construct the sender and do some validation of it. This goes a long way
 83   // toward eliminating issues when we get in frame construction code
 84 
 85   if (_cb != NULL ) {
 86 
 87     // First check if the frame is complete and the test is reliable.
 88     // Unfortunately we can only check frame completeness for runtime stubs.
 89     // Other generic buffer blobs are more problematic so we just assume they are OK.
 90     // Adapter blobs never have a complete frame and are never OK.
 91     // nmethods should be OK on s390.
 92     if (!_cb->is_frame_complete_at(_pc)) {
 93       if (_cb->is_adapter_blob() || _cb->is_runtime_stub()) {
 94         return false;
 95       }
 96     }
 97 
 98     // Could just be some random pointer within the codeBlob.
 99     if (!_cb->code_contains(_pc)) {
100       return false;
101     }
102 
103     // Entry frame checks
104     if (is_entry_frame()) {
105       // An entry frame must have a valid fp.
106       return fp_safe && is_entry_frame_valid(thread);
107     }
108 
109     if (is_interpreted_frame() && !fp_interp_safe) {
110       return false;
111     }
112 
113     // At this point, there still is a chance that fp_safe is false.
114     // In particular, (fp == NULL) might be true. So let's check and
115     // bail out before we actually dereference from fp.
116     if (!fp_safe) {
117       return false;
118     }
119 
120     z_abi_160* sender_abi = (z_abi_160*) fp;
121     intptr_t* sender_sp = (intptr_t*) sender_abi->callers_sp;
122     address   sender_pc = (address)   sender_abi->return_pc;
123 
124     // We must always be able to find a recognizable pc.
125     CodeBlob* sender_blob = CodeCache::find_blob_unsafe(sender_pc);
126     if (sender_blob == NULL) {
127       return false;
128     }
129 
130     // Could be a zombie method
131     if (sender_blob->is_zombie() || sender_blob->is_unloaded()) {
132       return false;
133     }
134 
135     // It should be safe to construct the sender though it might not be valid.
136 
137     frame sender(sender_sp, sender_pc);
138 
139     // Do we have a valid fp?
140     address sender_fp = (address) sender.fp();
141 
142     // sender_fp must be within the stack and above (but not
143     // equal) current frame's fp.
144     if (!thread->is_in_stack_range_excl(sender_fp, fp)) {
145         return false;
146     }
147 
148     // If the potential sender is the interpreter then we can do some more checking.
149     if (Interpreter::contains(sender_pc)) {
150       return sender.is_interpreted_frame_valid(thread);
151     }
152 
153     // Could just be some random pointer within the codeBlob.
154     if (!sender.cb()->code_contains(sender_pc)) {
155       return false;
156     }
157 
158     // We should never be able to see an adapter if the current frame is something from code cache.
159     if (sender_blob->is_adapter_blob()) {
160       return false;
161     }
162 
163     if (sender.is_entry_frame()) {
164       return sender.is_entry_frame_valid(thread);
165     }
166 
167     // Frame size is always greater than zero. If the sender frame size is zero or less,
168     // something is really weird and we better give up.
169     if (sender_blob->frame_size() <= 0) {
170       return false;
171     }
172 
173     return true;
174   }
175 
176   // Must be native-compiled frame. Since sender will try and use fp to find
177   // linkages it must be safe
178 
179   if (!fp_safe) {
180     return false;
181   }
182 
183   return true;
184 }
185 
186 bool frame::is_interpreted_frame() const {
187   return Interpreter::contains(pc());
188 }
189 
190 // sender_sp
191 
192 intptr_t* frame::interpreter_frame_sender_sp() const {
193   return sender_sp();
194 }
195 
196 frame frame::sender_for_entry_frame(RegisterMap *map) const {
197   assert(map != NULL, "map must be set");
198   // Java frame called from C. Skip all C frames and return top C
199   // frame of that chunk as the sender.
200   JavaFrameAnchor* jfa = entry_frame_call_wrapper()->anchor();
201 
202   assert(!entry_frame_is_first(), "next Java sp must be non zero");
203   assert(jfa->last_Java_sp() > _sp, "must be above this frame on stack");
204 
205   map->clear();
206 
207   assert(map->include_argument_oops(), "should be set by clear");
208 
209   if (jfa->last_Java_pc() != NULL) {
210     frame fr(jfa->last_Java_sp(), jfa->last_Java_pc());
211     return fr;
212   }
213   // Last_java_pc is not set if we come here from compiled code.
214   frame fr(jfa->last_Java_sp());
215   return fr;
216 }
217 
218 OptimizedEntryBlob::FrameData* OptimizedEntryBlob::frame_data_for_frame(const frame& frame) const {
219   ShouldNotCallThis();
220   return nullptr;
221 }
222 
223 bool frame::optimized_entry_frame_is_first() const {
224   ShouldNotCallThis();
225   return false;
226 }
227 
228 frame frame::sender_for_interpreter_frame(RegisterMap *map) const {
229   // Pass callers sender_sp as unextended_sp.
230   return frame(sender_sp(), sender_pc(), (intptr_t*)(ijava_state()->sender_sp));
231 }
232 
233 frame frame::sender_for_compiled_frame(RegisterMap *map) const {
234   assert(map != NULL, "map must be set");
235   // Frame owned by compiler.
236 
237   address pc = *compiled_sender_pc_addr(_cb);
238   frame caller(compiled_sender_sp(_cb), pc);
239 
240   // Now adjust the map.
241 
242   // Get the rest.
243   if (map->update_map()) {
244     // Tell GC to use argument oopmaps for some runtime stubs that need it.
245     map->set_include_argument_oops(_cb->caller_must_gc_arguments(map->thread()));
246     if (_cb->oop_maps() != NULL) {
247       OopMapSet::update_register_map(this, map);
248     }
249   }
250 
251   return caller;
252 }
253 
254 intptr_t* frame::compiled_sender_sp(CodeBlob* cb) const {
255   return sender_sp();
256 }
257 
258 address* frame::compiled_sender_pc_addr(CodeBlob* cb) const {
259   return sender_pc_addr();
260 }
261 
262 frame frame::sender(RegisterMap* map) const {
263   // Default is we don't have to follow them. The sender_for_xxx will
264   // update it accordingly.
265   map->set_include_argument_oops(false);
266 
267   if (is_entry_frame()) {
268     return sender_for_entry_frame(map);
269   }
270   if (is_interpreted_frame()) {
271     return sender_for_interpreter_frame(map);
272   }
273   assert(_cb == CodeCache::find_blob(pc()),"Must be the same");
274   if (_cb != NULL) {
275     return sender_for_compiled_frame(map);
276   }
277   // Must be native-compiled frame, i.e. the marshaling code for native
278   // methods that exists in the core system.
279   return frame(sender_sp(), sender_pc());
280 }
281 
282 void frame::patch_pc(Thread* thread, address pc) {
283   assert(_cb == CodeCache::find_blob(pc), "unexpected pc");
284   if (TracePcPatching) {
285     tty->print_cr("patch_pc at address  " PTR_FORMAT " [" PTR_FORMAT " -> " PTR_FORMAT "] ",
286                   p2i(&((address*) _sp)[-1]), p2i(((address*) _sp)[-1]), p2i(pc));
287   }
288   own_abi()->return_pc = (uint64_t)pc;
289   address original_pc = CompiledMethod::get_deopt_original_pc(this);
290   if (original_pc != NULL) {
291     assert(original_pc == _pc, "expected original to be stored before patching");
292     _deopt_state = is_deoptimized;
293     // Leave _pc as is.
294   } else {
295     _deopt_state = not_deoptimized;
296     _pc = pc;
297   }
298 }
299 
300 bool frame::is_interpreted_frame_valid(JavaThread* thread) const {
301   // Is there anything to do?
302   assert(is_interpreted_frame(), "Not an interpreted frame");
303   return true;
304 }
305 
306 BasicType frame::interpreter_frame_result(oop* oop_result, jvalue* value_result) {
307   assert(is_interpreted_frame(), "interpreted frame expected");
308   Method* method = interpreter_frame_method();
309   BasicType type = method->result_type();
310 
311   if (method->is_native()) {
312     address lresult = (address)&(ijava_state()->lresult);
313     address fresult = (address)&(ijava_state()->fresult);
314 
315     switch (type) {
316       case T_OBJECT:
317       case T_ARRAY: {
318         *oop_result = cast_to_oop((void*) ijava_state()->oop_tmp);
319         break;
320       }
321       // We use std/stfd to store the values.
322       case T_BOOLEAN : value_result->z = (jboolean) *(unsigned long*)lresult; break;
323       case T_INT     : value_result->i = (jint)     *(long*)lresult;          break;
324       case T_CHAR    : value_result->c = (jchar)    *(unsigned long*)lresult; break;
325       case T_SHORT   : value_result->s = (jshort)   *(long*)lresult;          break;
326       case T_BYTE    : value_result->z = (jbyte)    *(long*)lresult;          break;
327       case T_LONG    : value_result->j = (jlong)    *(long*)lresult;          break;
328       case T_FLOAT   : value_result->f = (jfloat)   *(float*)fresult;        break;
329       case T_DOUBLE  : value_result->d = (jdouble)  *(double*)fresult;        break;
330       case T_VOID    : break; // Nothing to do.
331       default        : ShouldNotReachHere();
332     }
333   } else {
334     intptr_t* tos_addr = interpreter_frame_tos_address();
335     switch (type) {
336       case T_OBJECT:
337       case T_ARRAY: {
338        oop obj = *(oop*)tos_addr;
339        assert(Universe::is_in_heap_or_null(obj), "sanity check");
340        *oop_result = obj;
341        break;
342       }
343       case T_BOOLEAN : value_result->z = (jboolean) *(jint*)tos_addr; break;
344       case T_BYTE    : value_result->b = (jbyte) *(jint*)tos_addr; break;
345       case T_CHAR    : value_result->c = (jchar) *(jint*)tos_addr; break;
346       case T_SHORT   : value_result->s = (jshort) *(jint*)tos_addr; break;
347       case T_INT     : value_result->i = *(jint*)tos_addr; break;
348       case T_LONG    : value_result->j = *(jlong*)tos_addr; break;
349       case T_FLOAT   : value_result->f = *(jfloat*)tos_addr; break;
350       case T_DOUBLE  : value_result->d = *(jdouble*)tos_addr; break;
351       case T_VOID    : break; // Nothing to do.
352       default        : ShouldNotReachHere();
353     }
354   }
355 
356   return type;
357 }
358 
359 
360 // Dump all frames starting a given C stack-pointer.
361 // Use max_frames to limit the number of traced frames.
362 void frame::back_trace(outputStream* st, intptr_t* start_sp, intptr_t* top_pc, unsigned long flags, int max_frames) {
363 
364   static char buf[ 150 ];
365 
366   bool print_outgoing_arguments = flags & 0x1;
367   bool print_istate_pointers    = flags & 0x2;
368   int num = 0;
369 
370   intptr_t* current_sp = (intptr_t*) start_sp;
371   int last_num_jargs = 0;
372   int frame_type = 0;
373   int last_frame_type = 0;
374 
375   while (current_sp) {
376     intptr_t* current_fp = (intptr_t*) *current_sp;
377     address   current_pc = (num == 0)
378                            ? (address) top_pc
379                            : (address) *((intptr_t*)(((address) current_sp) + _z_abi(return_pc)));
380 
381     if ((intptr_t*) current_fp != 0 && (intptr_t*) current_fp <= current_sp) {
382       st->print_cr("ERROR: corrupt stack");
383       return;
384     }
385 
386     st->print("#%-3d ", num);
387     const char* type_name = "    ";
388     const char* function_name = NULL;
389 
390     // Detect current frame's frame_type, default to 'C frame'.
391     frame_type = 0;
392 
393     CodeBlob* blob = NULL;
394 
395     if (Interpreter::contains(current_pc)) {
396       frame_type = 1;
397     } else if (StubRoutines::contains(current_pc)) {
398       if (StubRoutines::returns_to_call_stub(current_pc)) {
399         frame_type = 2;
400       } else {
401         frame_type = 4;
402         type_name = "stu";
403         StubCodeDesc* desc = StubCodeDesc::desc_for (current_pc);
404         if (desc) {
405           function_name = desc->name();
406         } else {
407           function_name = "unknown stub";
408         }
409       }
410     } else if (CodeCache::contains(current_pc)) {
411       blob = CodeCache::find_blob_unsafe(current_pc);
412       if (blob) {
413         if (blob->is_nmethod()) {
414           frame_type = 3;
415         } else if (blob->is_deoptimization_stub()) {
416           frame_type = 4;
417           type_name = "deo";
418           function_name = "deoptimization blob";
419         } else if (blob->is_uncommon_trap_stub()) {
420           frame_type = 4;
421           type_name = "uct";
422           function_name = "uncommon trap blob";
423         } else if (blob->is_exception_stub()) {
424           frame_type = 4;
425           type_name = "exc";
426           function_name = "exception blob";
427         } else if (blob->is_safepoint_stub()) {
428           frame_type = 4;
429           type_name = "saf";
430           function_name = "safepoint blob";
431         } else if (blob->is_runtime_stub()) {
432           frame_type = 4;
433           type_name = "run";
434           function_name = ((RuntimeStub *)blob)->name();
435         } else if (blob->is_method_handles_adapter_blob()) {
436           frame_type = 4;
437           type_name = "mha";
438           function_name = "method handles adapter blob";
439         } else {
440           frame_type = 4;
441           type_name = "blo";
442           function_name = "unknown code blob";
443         }
444       } else {
445         frame_type = 4;
446         type_name = "blo";
447         function_name = "unknown code blob";
448       }
449     }
450 
451     st->print("sp=" PTR_FORMAT " ", p2i(current_sp));
452 
453     if (frame_type == 0) {
454       current_pc = (address) *((intptr_t*)(((address) current_sp) + _z_abi(gpr14)));
455     }
456 
457     st->print("pc=" PTR_FORMAT " ", p2i(current_pc));
458     st->print(" ");
459 
460     switch (frame_type) {
461       case 0: // C frame:
462         {
463           st->print("    ");
464           if (current_pc == 0) {
465             st->print("? ");
466           } else {
467              // name
468             int func_offset;
469             char demangled_name[256];
470             int demangled_name_len = 256;
471             if (os::dll_address_to_function_name(current_pc, demangled_name, demangled_name_len, &func_offset)) {
472               demangled_name[demangled_name_len-1] = '\0';
473               st->print(func_offset == -1 ? "%s " : "%s+0x%x", demangled_name, func_offset);
474             } else {
475               st->print("? ");
476             }
477           }
478         }
479         break;
480 
481       case 1: // interpreter frame:
482         {
483           st->print(" i  ");
484 
485           if (last_frame_type != 1) last_num_jargs = 8;
486 
487           // name
488           Method* method = *(Method**)((address)current_fp + _z_ijava_state_neg(method));
489           if (method) {
490             ResourceMark rm;
491             if (method->is_synchronized()) st->print("synchronized ");
492             if (method->is_static()) st->print("static ");
493             if (method->is_native()) st->print("native ");
494             method->name_and_sig_as_C_string(buf, sizeof(buf));
495             st->print("%s ", buf);
496           }
497           else
498             st->print("? ");
499 
500           intptr_t* tos = (intptr_t*) *(intptr_t*)((address)current_fp + _z_ijava_state_neg(esp));
501           if (print_istate_pointers) {
502             st->cr();
503             st->print("     ");
504             st->print("ts=" PTR_FORMAT " ", p2i(tos));
505           }
506 
507           // Dump some Java stack slots.
508           if (print_outgoing_arguments) {
509             if (method->is_native()) {
510 #ifdef ASSERT
511               intptr_t* cargs = (intptr_t*) (((address)current_sp) + _z_abi(carg_1));
512               for (int i = 0; i < last_num_jargs; i++) {
513                 // Cargs is not prepushed.
514                 st->cr();
515                 st->print("        ");
516                 st->print(PTR_FORMAT, *(cargs));
517                 cargs++;
518               }
519 #endif /* ASSERT */
520             }
521             else {
522               if (tos) {
523                 for (int i = 0; i < last_num_jargs; i++) {
524                   // tos+0 is prepushed, ignore.
525                   tos++;
526                   if (tos >= (intptr_t *)((address)current_fp + _z_ijava_state_neg(monitors)))
527                     break;
528                   st->cr();
529                   st->print("        ");
530                   st->print(PTR_FORMAT " %+.3e %+.3le", *(tos), *(float*)(tos), *(double*)(tos));
531                 }
532               }
533             }
534             last_num_jargs = method->size_of_parameters();
535           }
536         }
537         break;
538 
539       case 2: // entry frame:
540         {
541           st->print("v2i ");
542 
543           // name
544           st->print("call stub");
545         }
546         break;
547 
548       case 3: // compiled frame:
549         {
550           st->print(" c  ");
551 
552           // name
553           Method* method = ((nmethod *)blob)->method();
554           if (method) {
555             ResourceMark rm;
556             method->name_and_sig_as_C_string(buf, sizeof(buf));
557             st->print("%s ", buf);
558           }
559           else
560             st->print("? ");
561         }
562         break;
563 
564       case 4: // named frames
565         {
566           st->print("%s ", type_name);
567 
568           // name
569           if (function_name)
570             st->print("%s", function_name);
571         }
572         break;
573 
574       default:
575         break;
576     }
577 
578     st->cr();
579     st->flush();
580 
581     current_sp = current_fp;
582     last_frame_type = frame_type;
583     num++;
584     // Check for maximum # of frames, and stop when reached.
585     if (max_frames > 0 && --max_frames == 0)
586       break;
587   }
588 
589 }
590 
591 // Convenience function for calls from the debugger.
592 
593 extern "C" void bt(intptr_t* start_sp,intptr_t* top_pc) {
594   frame::back_trace(tty,start_sp, top_pc, 0);
595 }
596 
597 extern "C" void bt_full(intptr_t* start_sp,intptr_t* top_pc) {
598   frame::back_trace(tty,start_sp, top_pc, (unsigned long)(long)-1);
599 }
600 
601 
602 // Function for tracing a limited number of frames.
603 // Use this one if you only need to see the "top of stack" frames.
604 extern "C" void bt_max(intptr_t *start_sp, intptr_t *top_pc, int max_frames) {
605   frame::back_trace(tty, start_sp, top_pc, 0, max_frames);
606 }
607 
608 #if !defined(PRODUCT)
609 
610 #define DESCRIBE_ADDRESS(name) \
611   values.describe(frame_no, (intptr_t*)&ijava_state()->name, #name);
612 
613 void frame::describe_pd(FrameValues& values, int frame_no) {
614   if (is_interpreted_frame()) {
615     // Describe z_ijava_state elements.
616     DESCRIBE_ADDRESS(method);
617     DESCRIBE_ADDRESS(locals);
618     DESCRIBE_ADDRESS(monitors);
619     DESCRIBE_ADDRESS(cpoolCache);
620     DESCRIBE_ADDRESS(bcp);
621     DESCRIBE_ADDRESS(mdx);
622     DESCRIBE_ADDRESS(esp);
623     DESCRIBE_ADDRESS(sender_sp);
624     DESCRIBE_ADDRESS(top_frame_sp);
625     DESCRIBE_ADDRESS(oop_tmp);
626     DESCRIBE_ADDRESS(lresult);
627     DESCRIBE_ADDRESS(fresult);
628   }
629 }
630 
631 #endif // !PRODUCT
632 
633 intptr_t *frame::initial_deoptimization_info() {
634   // Used to reset the saved FP.
635   return fp();
636 }