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 template <bool stub>
234 frame frame::sender_for_compiled_frame(RegisterMap *map) const {
235   assert(map != NULL, "map must be set");
236   // Frame owned by compiler.
237 
238   address pc = *compiled_sender_pc_addr(_cb);
239   frame caller(compiled_sender_sp(_cb), pc);
240 
241   // Now adjust the map.
242 
243   // Get the rest.
244   if (map->update_map()) {
245     // Tell GC to use argument oopmaps for some runtime stubs that need it.
246     map->set_include_argument_oops(_cb->caller_must_gc_arguments(map->thread()));
247     if (_cb->oop_maps() != NULL) {
248       OopMapSet::update_register_map(this, map);
249     }
250   }
251 
252   return caller;
253 }
254 
255 intptr_t* frame::compiled_sender_sp(CodeBlob* cb) const {
256   return sender_sp();
257 }
258 
259 address* frame::compiled_sender_pc_addr(CodeBlob* cb) const {
260   return sender_pc_addr();
261 }
262 
263 frame frame::sender(RegisterMap* map) const {
264   // Default is we don't have to follow them. The sender_for_xxx will
265   // update it accordingly.
266   map->set_include_argument_oops(false);
267 
268   if (is_entry_frame()) {
269     return sender_for_entry_frame(map);
270   }
271   if (is_interpreted_frame()) {
272     return sender_for_interpreter_frame(map);
273   }
274   assert(_cb == CodeCache::find_blob(pc()),"Must be the same");
275   if (_cb != NULL) {
276     return sender_for_compiled_frame<false>(map);
277   }
278   // Must be native-compiled frame, i.e. the marshaling code for native
279   // methods that exists in the core system.
280   return frame(sender_sp(), sender_pc());
281 }
282 
283 void frame::patch_pc(Thread* thread, address pc) {
284   assert(_cb == CodeCache::find_blob(pc), "unexpected pc");
285   if (TracePcPatching) {
286     tty->print_cr("patch_pc at address  " PTR_FORMAT " [" PTR_FORMAT " -> " PTR_FORMAT "] ",
287                   p2i(&((address*) _sp)[-1]), p2i(((address*) _sp)[-1]), p2i(pc));
288   }
289   own_abi()->return_pc = (uint64_t)pc;
290   address original_pc = CompiledMethod::get_deopt_original_pc(this);
291   if (original_pc != NULL) {
292     assert(original_pc == _pc, "expected original to be stored before patching");
293     _deopt_state = is_deoptimized;
294     // Leave _pc as is.
295   } else {
296     _deopt_state = not_deoptimized;
297     _pc = pc;
298   }
299 }
300 
301 bool frame::is_interpreted_frame_valid(JavaThread* thread) const {
302   // Is there anything to do?
303   assert(is_interpreted_frame(), "Not an interpreted frame");
304   return true;
305 }
306 
307 BasicType frame::interpreter_frame_result(oop* oop_result, jvalue* value_result) {
308   assert(is_interpreted_frame(), "interpreted frame expected");
309   Method* method = interpreter_frame_method();
310   BasicType type = method->result_type();
311 
312   if (method->is_native()) {
313     address lresult = (address)&(ijava_state()->lresult);
314     address fresult = (address)&(ijava_state()->fresult);
315 
316     switch (type) {
317       case T_OBJECT:
318       case T_ARRAY: {
319         *oop_result = cast_to_oop((void*) ijava_state()->oop_tmp);
320         break;
321       }
322       // We use std/stfd to store the values.
323       case T_BOOLEAN : value_result->z = (jboolean) *(unsigned long*)lresult; break;
324       case T_INT     : value_result->i = (jint)     *(long*)lresult;          break;
325       case T_CHAR    : value_result->c = (jchar)    *(unsigned long*)lresult; break;
326       case T_SHORT   : value_result->s = (jshort)   *(long*)lresult;          break;
327       case T_BYTE    : value_result->z = (jbyte)    *(long*)lresult;          break;
328       case T_LONG    : value_result->j = (jlong)    *(long*)lresult;          break;
329       case T_FLOAT   : value_result->f = (jfloat)   *(float*)fresult;        break;
330       case T_DOUBLE  : value_result->d = (jdouble)  *(double*)fresult;        break;
331       case T_VOID    : break; // Nothing to do.
332       default        : ShouldNotReachHere();
333     }
334   } else {
335     intptr_t* tos_addr = interpreter_frame_tos_address();
336     switch (type) {
337       case T_OBJECT:
338       case T_ARRAY: {
339        oop obj = *(oop*)tos_addr;
340        assert(Universe::is_in_heap_or_null(obj), "sanity check");
341        *oop_result = obj;
342        break;
343       }
344       case T_BOOLEAN : value_result->z = (jboolean) *(jint*)tos_addr; break;
345       case T_BYTE    : value_result->b = (jbyte) *(jint*)tos_addr; break;
346       case T_CHAR    : value_result->c = (jchar) *(jint*)tos_addr; break;
347       case T_SHORT   : value_result->s = (jshort) *(jint*)tos_addr; break;
348       case T_INT     : value_result->i = *(jint*)tos_addr; break;
349       case T_LONG    : value_result->j = *(jlong*)tos_addr; break;
350       case T_FLOAT   : value_result->f = *(jfloat*)tos_addr; break;
351       case T_DOUBLE  : value_result->d = *(jdouble*)tos_addr; break;
352       case T_VOID    : break; // Nothing to do.
353       default        : ShouldNotReachHere();
354     }
355   }
356 
357   return type;
358 }
359 
360 
361 // Dump all frames starting a given C stack-pointer.
362 // Use max_frames to limit the number of traced frames.
363 void frame::back_trace(outputStream* st, intptr_t* start_sp, intptr_t* top_pc, unsigned long flags, int max_frames) {
364 
365   static char buf[ 150 ];
366 
367   bool print_outgoing_arguments = flags & 0x1;
368   bool print_istate_pointers    = flags & 0x2;
369   int num = 0;
370 
371   intptr_t* current_sp = (intptr_t*) start_sp;
372   int last_num_jargs = 0;
373   int frame_type = 0;
374   int last_frame_type = 0;
375 
376   while (current_sp) {
377     intptr_t* current_fp = (intptr_t*) *current_sp;
378     address   current_pc = (num == 0)
379                            ? (address) top_pc
380                            : (address) *((intptr_t*)(((address) current_sp) + _z_abi(return_pc)));
381 
382     if ((intptr_t*) current_fp != 0 && (intptr_t*) current_fp <= current_sp) {
383       st->print_cr("ERROR: corrupt stack");
384       return;
385     }
386 
387     st->print("#%-3d ", num);
388     const char* type_name = "    ";
389     const char* function_name = NULL;
390 
391     // Detect current frame's frame_type, default to 'C frame'.
392     frame_type = 0;
393 
394     CodeBlob* blob = NULL;
395 
396     if (Interpreter::contains(current_pc)) {
397       frame_type = 1;
398     } else if (StubRoutines::contains(current_pc)) {
399       if (StubRoutines::returns_to_call_stub(current_pc)) {
400         frame_type = 2;
401       } else {
402         frame_type = 4;
403         type_name = "stu";
404         StubCodeDesc* desc = StubCodeDesc::desc_for (current_pc);
405         if (desc) {
406           function_name = desc->name();
407         } else {
408           function_name = "unknown stub";
409         }
410       }
411     } else if (CodeCache::contains(current_pc)) {
412       blob = CodeCache::find_blob_unsafe(current_pc);
413       if (blob) {
414         if (blob->is_nmethod()) {
415           frame_type = 3;
416         } else if (blob->is_deoptimization_stub()) {
417           frame_type = 4;
418           type_name = "deo";
419           function_name = "deoptimization blob";
420         } else if (blob->is_uncommon_trap_stub()) {
421           frame_type = 4;
422           type_name = "uct";
423           function_name = "uncommon trap blob";
424         } else if (blob->is_exception_stub()) {
425           frame_type = 4;
426           type_name = "exc";
427           function_name = "exception blob";
428         } else if (blob->is_safepoint_stub()) {
429           frame_type = 4;
430           type_name = "saf";
431           function_name = "safepoint blob";
432         } else if (blob->is_runtime_stub()) {
433           frame_type = 4;
434           type_name = "run";
435           function_name = ((RuntimeStub *)blob)->name();
436         } else if (blob->is_method_handles_adapter_blob()) {
437           frame_type = 4;
438           type_name = "mha";
439           function_name = "method handles adapter blob";
440         } else {
441           frame_type = 4;
442           type_name = "blo";
443           function_name = "unknown code blob";
444         }
445       } else {
446         frame_type = 4;
447         type_name = "blo";
448         function_name = "unknown code blob";
449       }
450     }
451 
452     st->print("sp=" PTR_FORMAT " ", p2i(current_sp));
453 
454     if (frame_type == 0) {
455       current_pc = (address) *((intptr_t*)(((address) current_sp) + _z_abi(gpr14)));
456     }
457 
458     st->print("pc=" PTR_FORMAT " ", p2i(current_pc));
459     st->print(" ");
460 
461     switch (frame_type) {
462       case 0: // C frame:
463         {
464           st->print("    ");
465           if (current_pc == 0) {
466             st->print("? ");
467           } else {
468              // name
469             int func_offset;
470             char demangled_name[256];
471             int demangled_name_len = 256;
472             if (os::dll_address_to_function_name(current_pc, demangled_name, demangled_name_len, &func_offset)) {
473               demangled_name[demangled_name_len-1] = '\0';
474               st->print(func_offset == -1 ? "%s " : "%s+0x%x", demangled_name, func_offset);
475             } else {
476               st->print("? ");
477             }
478           }
479         }
480         break;
481 
482       case 1: // interpreter frame:
483         {
484           st->print(" i  ");
485 
486           if (last_frame_type != 1) last_num_jargs = 8;
487 
488           // name
489           Method* method = *(Method**)((address)current_fp + _z_ijava_state_neg(method));
490           if (method) {
491             ResourceMark rm;
492             if (method->is_synchronized()) st->print("synchronized ");
493             if (method->is_static()) st->print("static ");
494             if (method->is_native()) st->print("native ");
495             method->name_and_sig_as_C_string(buf, sizeof(buf));
496             st->print("%s ", buf);
497           }
498           else
499             st->print("? ");
500 
501           intptr_t* tos = (intptr_t*) *(intptr_t*)((address)current_fp + _z_ijava_state_neg(esp));
502           if (print_istate_pointers) {
503             st->cr();
504             st->print("     ");
505             st->print("ts=" PTR_FORMAT " ", p2i(tos));
506           }
507 
508           // Dump some Java stack slots.
509           if (print_outgoing_arguments) {
510             if (method->is_native()) {
511 #ifdef ASSERT
512               intptr_t* cargs = (intptr_t*) (((address)current_sp) + _z_abi(carg_1));
513               for (int i = 0; i < last_num_jargs; i++) {
514                 // Cargs is not prepushed.
515                 st->cr();
516                 st->print("        ");
517                 st->print(PTR_FORMAT, *(cargs));
518                 cargs++;
519               }
520 #endif /* ASSERT */
521             }
522             else {
523               if (tos) {
524                 for (int i = 0; i < last_num_jargs; i++) {
525                   // tos+0 is prepushed, ignore.
526                   tos++;
527                   if (tos >= (intptr_t *)((address)current_fp + _z_ijava_state_neg(monitors)))
528                     break;
529                   st->cr();
530                   st->print("        ");
531                   st->print(PTR_FORMAT " %+.3e %+.3le", *(tos), *(float*)(tos), *(double*)(tos));
532                 }
533               }
534             }
535             last_num_jargs = method->size_of_parameters();
536           }
537         }
538         break;
539 
540       case 2: // entry frame:
541         {
542           st->print("v2i ");
543 
544           // name
545           st->print("call stub");
546         }
547         break;
548 
549       case 3: // compiled frame:
550         {
551           st->print(" c  ");
552 
553           // name
554           Method* method = ((nmethod *)blob)->method();
555           if (method) {
556             ResourceMark rm;
557             method->name_and_sig_as_C_string(buf, sizeof(buf));
558             st->print("%s ", buf);
559           }
560           else
561             st->print("? ");
562         }
563         break;
564 
565       case 4: // named frames
566         {
567           st->print("%s ", type_name);
568 
569           // name
570           if (function_name)
571             st->print("%s", function_name);
572         }
573         break;
574 
575       default:
576         break;
577     }
578 
579     st->cr();
580     st->flush();
581 
582     current_sp = current_fp;
583     last_frame_type = frame_type;
584     num++;
585     // Check for maximum # of frames, and stop when reached.
586     if (max_frames > 0 && --max_frames == 0)
587       break;
588   }
589 
590 }
591 
592 // Convenience function for calls from the debugger.
593 
594 extern "C" void bt(intptr_t* start_sp,intptr_t* top_pc) {
595   frame::back_trace(tty,start_sp, top_pc, 0);
596 }
597 
598 extern "C" void bt_full(intptr_t* start_sp,intptr_t* top_pc) {
599   frame::back_trace(tty,start_sp, top_pc, (unsigned long)(long)-1);
600 }
601 
602 
603 // Function for tracing a limited number of frames.
604 // Use this one if you only need to see the "top of stack" frames.
605 extern "C" void bt_max(intptr_t *start_sp, intptr_t *top_pc, int max_frames) {
606   frame::back_trace(tty, start_sp, top_pc, 0, max_frames);
607 }
608 
609 #if !defined(PRODUCT)
610 
611 #define DESCRIBE_ADDRESS(name) \
612   values.describe(frame_no, (intptr_t*)&ijava_state()->name, #name);
613 
614 void frame::describe_pd(FrameValues& values, int frame_no) {
615   if (is_interpreted_frame()) {
616     // Describe z_ijava_state elements.
617     DESCRIBE_ADDRESS(method);
618     DESCRIBE_ADDRESS(locals);
619     DESCRIBE_ADDRESS(monitors);
620     DESCRIBE_ADDRESS(cpoolCache);
621     DESCRIBE_ADDRESS(bcp);
622     DESCRIBE_ADDRESS(mdx);
623     DESCRIBE_ADDRESS(esp);
624     DESCRIBE_ADDRESS(sender_sp);
625     DESCRIBE_ADDRESS(top_frame_sp);
626     DESCRIBE_ADDRESS(oop_tmp);
627     DESCRIBE_ADDRESS(lresult);
628     DESCRIBE_ADDRESS(fresult);
629   }
630 }
631 
632 void frame::describe_top_pd(FrameValues& values) {
633   Unimplemented();
634 }
635 #endif // !PRODUCT
636 
637 intptr_t *frame::initial_deoptimization_info() {
638   // Used to reset the saved FP.
639   return fp();
640 }
641 
642 // Pointer beyond the "oldest/deepest" BasicObjectLock on stack.
643 template BasicObjectLock* frame::interpreter_frame_monitor_end<true>() const;
644 template BasicObjectLock* frame::interpreter_frame_monitor_end<false>() const;
645 
646 template <bool relative>
647 inline BasicObjectLock* frame::interpreter_frame_monitor_end() const {
648   return interpreter_frame_monitors();
649 }
650 
651 template intptr_t* frame::interpreter_frame_tos_at<false>(jint offset) const;
652 template intptr_t* frame::interpreter_frame_tos_at<true >(jint offset) const;
653 
654 template <bool relative>
655 inline intptr_t* frame::interpreter_frame_tos_at(jint offset) const {
656   return &interpreter_frame_tos_address()[offset];
657 }
658