1 /*
2  * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  *
23  */
24 
25 #include "precompiled.hpp"
26 #include "classfile/symbolTable.hpp"
27 #include "classfile/systemDictionary.hpp"
28 #include "code/nmethod.hpp"
29 #include "interpreter/interpreter.hpp"
30 #include "interpreter/oopMapCache.hpp"
31 #include "jvmtifiles/jvmtiEnv.hpp"
32 #include "logging/log.hpp"
33 #include "logging/logStream.hpp"
34 #include "memory/allocation.inline.hpp"
35 #include "memory/resourceArea.hpp"
36 #include "oops/instanceKlass.hpp"
37 #include "oops/oop.inline.hpp"
38 #include "prims/jvmtiAgentThread.hpp"
39 #include "prims/jvmtiEventController.inline.hpp"
40 #include "prims/jvmtiImpl.hpp"
41 #include "prims/jvmtiRedefineClasses.hpp"
42 #include "runtime/deoptimization.hpp"
43 #include "runtime/frame.inline.hpp"
44 #include "runtime/handles.inline.hpp"
45 #include "runtime/interfaceSupport.inline.hpp"
46 #include "runtime/javaCalls.hpp"
47 #include "runtime/os.hpp"
48 #include "runtime/serviceThread.hpp"
49 #include "runtime/signature.hpp"
50 #include "runtime/thread.inline.hpp"
51 #include "runtime/threadSMR.hpp"
52 #include "runtime/vframe.hpp"
53 #include "runtime/vframe_hp.hpp"
54 #include "runtime/vmOperations.hpp"
55 #include "utilities/exceptions.hpp"
56 
57 //
58 // class JvmtiAgentThread
59 //
60 // JavaThread used to wrap a thread started by an agent
61 // using the JVMTI method RunAgentThread.
62 //
63 
JvmtiAgentThread(JvmtiEnv * env,jvmtiStartFunction start_fn,const void * start_arg)64 JvmtiAgentThread::JvmtiAgentThread(JvmtiEnv* env, jvmtiStartFunction start_fn, const void *start_arg)
65     : JavaThread(start_function_wrapper) {
66     _env = env;
67     _start_fn = start_fn;
68     _start_arg = start_arg;
69 }
70 
71 void
start_function_wrapper(JavaThread * thread,TRAPS)72 JvmtiAgentThread::start_function_wrapper(JavaThread *thread, TRAPS) {
73     // It is expected that any Agent threads will be created as
74     // Java Threads.  If this is the case, notification of the creation
75     // of the thread is given in JavaThread::thread_main().
76     assert(thread->is_Java_thread(), "debugger thread should be a Java Thread");
77     assert(thread == JavaThread::current(), "sanity check");
78 
79     JvmtiAgentThread *dthread = (JvmtiAgentThread *)thread;
80     dthread->call_start_function();
81 }
82 
83 void
call_start_function()84 JvmtiAgentThread::call_start_function() {
85     ThreadToNativeFromVM transition(this);
86     _start_fn(_env->jvmti_external(), jni_environment(), (void*)_start_arg);
87 }
88 
89 
90 //
91 // class GrowableCache - private methods
92 //
93 
recache()94 void GrowableCache::recache() {
95   int len = _elements->length();
96 
97   FREE_C_HEAP_ARRAY(address, _cache);
98   _cache = NEW_C_HEAP_ARRAY(address,len+1, mtInternal);
99 
100   for (int i=0; i<len; i++) {
101     _cache[i] = _elements->at(i)->getCacheValue();
102     //
103     // The cache entry has gone bad. Without a valid frame pointer
104     // value, the entry is useless so we simply delete it in product
105     // mode. The call to remove() will rebuild the cache again
106     // without the bad entry.
107     //
108     if (_cache[i] == NULL) {
109       assert(false, "cannot recache NULL elements");
110       remove(i);
111       return;
112     }
113   }
114   _cache[len] = NULL;
115 
116   _listener_fun(_this_obj,_cache);
117 }
118 
equals(void * v,GrowableElement * e2)119 bool GrowableCache::equals(void* v, GrowableElement *e2) {
120   GrowableElement *e1 = (GrowableElement *) v;
121   assert(e1 != NULL, "e1 != NULL");
122   assert(e2 != NULL, "e2 != NULL");
123 
124   return e1->equals(e2);
125 }
126 
127 //
128 // class GrowableCache - public methods
129 //
130 
GrowableCache()131 GrowableCache::GrowableCache() {
132   _this_obj       = NULL;
133   _listener_fun   = NULL;
134   _elements       = NULL;
135   _cache          = NULL;
136 }
137 
~GrowableCache()138 GrowableCache::~GrowableCache() {
139   clear();
140   delete _elements;
141   FREE_C_HEAP_ARRAY(address, _cache);
142 }
143 
initialize(void * this_obj,void listener_fun (void *,address *))144 void GrowableCache::initialize(void *this_obj, void listener_fun(void *, address*) ) {
145   _this_obj       = this_obj;
146   _listener_fun   = listener_fun;
147   _elements       = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<GrowableElement*>(5,true);
148   recache();
149 }
150 
151 // number of elements in the collection
length()152 int GrowableCache::length() {
153   return _elements->length();
154 }
155 
156 // get the value of the index element in the collection
at(int index)157 GrowableElement* GrowableCache::at(int index) {
158   GrowableElement *e = (GrowableElement *) _elements->at(index);
159   assert(e != NULL, "e != NULL");
160   return e;
161 }
162 
find(GrowableElement * e)163 int GrowableCache::find(GrowableElement* e) {
164   return _elements->find(e, GrowableCache::equals);
165 }
166 
167 // append a copy of the element to the end of the collection
append(GrowableElement * e)168 void GrowableCache::append(GrowableElement* e) {
169   GrowableElement *new_e = e->clone();
170   _elements->append(new_e);
171   recache();
172 }
173 
174 // insert a copy of the element using lessthan()
insert(GrowableElement * e)175 void GrowableCache::insert(GrowableElement* e) {
176   GrowableElement *new_e = e->clone();
177   _elements->append(new_e);
178 
179   int n = length()-2;
180   for (int i=n; i>=0; i--) {
181     GrowableElement *e1 = _elements->at(i);
182     GrowableElement *e2 = _elements->at(i+1);
183     if (e2->lessThan(e1)) {
184       _elements->at_put(i+1, e1);
185       _elements->at_put(i,   e2);
186     }
187   }
188 
189   recache();
190 }
191 
192 // remove the element at index
remove(int index)193 void GrowableCache::remove (int index) {
194   GrowableElement *e = _elements->at(index);
195   assert(e != NULL, "e != NULL");
196   _elements->remove(e);
197   delete e;
198   recache();
199 }
200 
201 // clear out all elements, release all heap space and
202 // let our listener know that things have changed.
clear()203 void GrowableCache::clear() {
204   int len = _elements->length();
205   for (int i=0; i<len; i++) {
206     delete _elements->at(i);
207   }
208   _elements->clear();
209   recache();
210 }
211 
oops_do(OopClosure * f)212 void GrowableCache::oops_do(OopClosure* f) {
213   int len = _elements->length();
214   for (int i=0; i<len; i++) {
215     GrowableElement *e = _elements->at(i);
216     e->oops_do(f);
217   }
218 }
219 
metadata_do(void f (Metadata *))220 void GrowableCache::metadata_do(void f(Metadata*)) {
221   int len = _elements->length();
222   for (int i=0; i<len; i++) {
223     GrowableElement *e = _elements->at(i);
224     e->metadata_do(f);
225   }
226 }
227 
228 //
229 // class JvmtiBreakpoint
230 //
231 
JvmtiBreakpoint()232 JvmtiBreakpoint::JvmtiBreakpoint() {
233   _method = NULL;
234   _bci    = 0;
235   _class_holder = NULL;
236 }
237 
JvmtiBreakpoint(Method * m_method,jlocation location)238 JvmtiBreakpoint::JvmtiBreakpoint(Method* m_method, jlocation location) {
239   _method        = m_method;
240   _class_holder  = _method->method_holder()->klass_holder();
241 #ifdef CHECK_UNHANDLED_OOPS
242   // _class_holder can't be wrapped in a Handle, because JvmtiBreakpoints are
243   // sometimes allocated on the heap.
244   //
245   // The code handling JvmtiBreakpoints allocated on the stack can't be
246   // interrupted by a GC until _class_holder is reachable by the GC via the
247   // oops_do method.
248   Thread::current()->allow_unhandled_oop(&_class_holder);
249 #endif // CHECK_UNHANDLED_OOPS
250   assert(_method != NULL, "_method != NULL");
251   _bci           = (int) location;
252   assert(_bci >= 0, "_bci >= 0");
253 }
254 
copy(JvmtiBreakpoint & bp)255 void JvmtiBreakpoint::copy(JvmtiBreakpoint& bp) {
256   _method   = bp._method;
257   _bci      = bp._bci;
258   _class_holder = bp._class_holder;
259 }
260 
lessThan(JvmtiBreakpoint & bp)261 bool JvmtiBreakpoint::lessThan(JvmtiBreakpoint& bp) {
262   Unimplemented();
263   return false;
264 }
265 
equals(JvmtiBreakpoint & bp)266 bool JvmtiBreakpoint::equals(JvmtiBreakpoint& bp) {
267   return _method   == bp._method
268     &&   _bci      == bp._bci;
269 }
270 
is_valid()271 bool JvmtiBreakpoint::is_valid() {
272   // class loader can be NULL
273   return _method != NULL &&
274          _bci >= 0;
275 }
276 
getBcp() const277 address JvmtiBreakpoint::getBcp() const {
278   return _method->bcp_from(_bci);
279 }
280 
each_method_version_do(method_action meth_act)281 void JvmtiBreakpoint::each_method_version_do(method_action meth_act) {
282   ((Method*)_method->*meth_act)(_bci);
283 
284   // add/remove breakpoint to/from versions of the method that are EMCP.
285   Thread *thread = Thread::current();
286   InstanceKlass* ik = _method->method_holder();
287   Symbol* m_name = _method->name();
288   Symbol* m_signature = _method->signature();
289 
290   // search previous versions if they exist
291   for (InstanceKlass* pv_node = ik->previous_versions();
292        pv_node != NULL;
293        pv_node = pv_node->previous_versions()) {
294     Array<Method*>* methods = pv_node->methods();
295 
296     for (int i = methods->length() - 1; i >= 0; i--) {
297       Method* method = methods->at(i);
298       // Only set breakpoints in running EMCP methods.
299       if (method->is_running_emcp() &&
300           method->name() == m_name &&
301           method->signature() == m_signature) {
302         ResourceMark rm;
303         log_debug(redefine, class, breakpoint)
304           ("%sing breakpoint in %s(%s)", meth_act == &Method::set_breakpoint ? "sett" : "clear",
305            method->name()->as_C_string(), method->signature()->as_C_string());
306         (method->*meth_act)(_bci);
307         break;
308       }
309     }
310   }
311 }
312 
set()313 void JvmtiBreakpoint::set() {
314   each_method_version_do(&Method::set_breakpoint);
315 }
316 
clear()317 void JvmtiBreakpoint::clear() {
318   each_method_version_do(&Method::clear_breakpoint);
319 }
320 
print_on(outputStream * out) const321 void JvmtiBreakpoint::print_on(outputStream* out) const {
322 #ifndef PRODUCT
323   ResourceMark rm;
324   const char *class_name  = (_method == NULL) ? "NULL" : _method->klass_name()->as_C_string();
325   const char *method_name = (_method == NULL) ? "NULL" : _method->name()->as_C_string();
326   out->print("Breakpoint(%s,%s,%d,%p)", class_name, method_name, _bci, getBcp());
327 #endif
328 }
329 
330 
331 //
332 // class VM_ChangeBreakpoints
333 //
334 // Modify the Breakpoints data structure at a safepoint
335 //
336 
doit()337 void VM_ChangeBreakpoints::doit() {
338   switch (_operation) {
339   case SET_BREAKPOINT:
340     _breakpoints->set_at_safepoint(*_bp);
341     break;
342   case CLEAR_BREAKPOINT:
343     _breakpoints->clear_at_safepoint(*_bp);
344     break;
345   default:
346     assert(false, "Unknown operation");
347   }
348 }
349 
oops_do(OopClosure * f)350 void VM_ChangeBreakpoints::oops_do(OopClosure* f) {
351   // The JvmtiBreakpoints in _breakpoints will be visited via
352   // JvmtiExport::oops_do.
353   if (_bp != NULL) {
354     _bp->oops_do(f);
355   }
356 }
357 
metadata_do(void f (Metadata *))358 void VM_ChangeBreakpoints::metadata_do(void f(Metadata*)) {
359   // Walk metadata in breakpoints to keep from being deallocated with RedefineClasses
360   if (_bp != NULL) {
361     _bp->metadata_do(f);
362   }
363 }
364 
365 //
366 // class JvmtiBreakpoints
367 //
368 // a JVMTI internal collection of JvmtiBreakpoint
369 //
370 
JvmtiBreakpoints(void listener_fun (void *,address *))371 JvmtiBreakpoints::JvmtiBreakpoints(void listener_fun(void *,address *)) {
372   _bps.initialize(this,listener_fun);
373 }
374 
~JvmtiBreakpoints()375 JvmtiBreakpoints:: ~JvmtiBreakpoints() {}
376 
oops_do(OopClosure * f)377 void  JvmtiBreakpoints::oops_do(OopClosure* f) {
378   _bps.oops_do(f);
379 }
380 
metadata_do(void f (Metadata *))381 void  JvmtiBreakpoints::metadata_do(void f(Metadata*)) {
382   _bps.metadata_do(f);
383 }
384 
print()385 void JvmtiBreakpoints::print() {
386 #ifndef PRODUCT
387   LogTarget(Trace, jvmti) log;
388   LogStream log_stream(log);
389 
390   int n = _bps.length();
391   for (int i=0; i<n; i++) {
392     JvmtiBreakpoint& bp = _bps.at(i);
393     log_stream.print("%d: ", i);
394     bp.print_on(&log_stream);
395     log_stream.cr();
396   }
397 #endif
398 }
399 
400 
set_at_safepoint(JvmtiBreakpoint & bp)401 void JvmtiBreakpoints::set_at_safepoint(JvmtiBreakpoint& bp) {
402   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
403 
404   int i = _bps.find(bp);
405   if (i == -1) {
406     _bps.append(bp);
407     bp.set();
408   }
409 }
410 
clear_at_safepoint(JvmtiBreakpoint & bp)411 void JvmtiBreakpoints::clear_at_safepoint(JvmtiBreakpoint& bp) {
412   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
413 
414   int i = _bps.find(bp);
415   if (i != -1) {
416     _bps.remove(i);
417     bp.clear();
418   }
419 }
420 
length()421 int JvmtiBreakpoints::length() { return _bps.length(); }
422 
set(JvmtiBreakpoint & bp)423 int JvmtiBreakpoints::set(JvmtiBreakpoint& bp) {
424   if ( _bps.find(bp) != -1) {
425      return JVMTI_ERROR_DUPLICATE;
426   }
427   VM_ChangeBreakpoints set_breakpoint(VM_ChangeBreakpoints::SET_BREAKPOINT, &bp);
428   VMThread::execute(&set_breakpoint);
429   return JVMTI_ERROR_NONE;
430 }
431 
clear(JvmtiBreakpoint & bp)432 int JvmtiBreakpoints::clear(JvmtiBreakpoint& bp) {
433   if ( _bps.find(bp) == -1) {
434      return JVMTI_ERROR_NOT_FOUND;
435   }
436 
437   VM_ChangeBreakpoints clear_breakpoint(VM_ChangeBreakpoints::CLEAR_BREAKPOINT, &bp);
438   VMThread::execute(&clear_breakpoint);
439   return JVMTI_ERROR_NONE;
440 }
441 
clearall_in_class_at_safepoint(Klass * klass)442 void JvmtiBreakpoints::clearall_in_class_at_safepoint(Klass* klass) {
443   bool changed = true;
444   // We are going to run thru the list of bkpts
445   // and delete some.  This deletion probably alters
446   // the list in some implementation defined way such
447   // that when we delete entry i, the next entry might
448   // no longer be at i+1.  To be safe, each time we delete
449   // an entry, we'll just start again from the beginning.
450   // We'll stop when we make a pass thru the whole list without
451   // deleting anything.
452   while (changed) {
453     int len = _bps.length();
454     changed = false;
455     for (int i = 0; i < len; i++) {
456       JvmtiBreakpoint& bp = _bps.at(i);
457       if (bp.method()->method_holder() == klass) {
458         bp.clear();
459         _bps.remove(i);
460         // This changed 'i' so we have to start over.
461         changed = true;
462         break;
463       }
464     }
465   }
466 }
467 
468 //
469 // class JvmtiCurrentBreakpoints
470 //
471 
472 JvmtiBreakpoints *JvmtiCurrentBreakpoints::_jvmti_breakpoints  = NULL;
473 address *         JvmtiCurrentBreakpoints::_breakpoint_list    = NULL;
474 
475 
get_jvmti_breakpoints()476 JvmtiBreakpoints& JvmtiCurrentBreakpoints::get_jvmti_breakpoints() {
477   if (_jvmti_breakpoints != NULL) return (*_jvmti_breakpoints);
478   _jvmti_breakpoints = new JvmtiBreakpoints(listener_fun);
479   assert(_jvmti_breakpoints != NULL, "_jvmti_breakpoints != NULL");
480   return (*_jvmti_breakpoints);
481 }
482 
listener_fun(void * this_obj,address * cache)483 void  JvmtiCurrentBreakpoints::listener_fun(void *this_obj, address *cache) {
484   JvmtiBreakpoints *this_jvmti = (JvmtiBreakpoints *) this_obj;
485   assert(this_jvmti != NULL, "this_jvmti != NULL");
486 
487   debug_only(int n = this_jvmti->length(););
488   assert(cache[n] == NULL, "cache must be NULL terminated");
489 
490   set_breakpoint_list(cache);
491 }
492 
493 
oops_do(OopClosure * f)494 void JvmtiCurrentBreakpoints::oops_do(OopClosure* f) {
495   if (_jvmti_breakpoints != NULL) {
496     _jvmti_breakpoints->oops_do(f);
497   }
498 }
499 
metadata_do(void f (Metadata *))500 void JvmtiCurrentBreakpoints::metadata_do(void f(Metadata*)) {
501   if (_jvmti_breakpoints != NULL) {
502     _jvmti_breakpoints->metadata_do(f);
503   }
504 }
505 
506 ///////////////////////////////////////////////////////////////
507 //
508 // class VM_GetOrSetLocal
509 //
510 
511 // Constructor for non-object getter
VM_GetOrSetLocal(JavaThread * thread,jint depth,jint index,BasicType type)512 VM_GetOrSetLocal::VM_GetOrSetLocal(JavaThread* thread, jint depth, jint index, BasicType type)
513   : _thread(thread)
514   , _calling_thread(NULL)
515   , _depth(depth)
516   , _index(index)
517   , _type(type)
518   , _jvf(NULL)
519   , _set(false)
520   , _result(JVMTI_ERROR_NONE)
521 {
522 }
523 
524 // Constructor for object or non-object setter
VM_GetOrSetLocal(JavaThread * thread,jint depth,jint index,BasicType type,jvalue value)525 VM_GetOrSetLocal::VM_GetOrSetLocal(JavaThread* thread, jint depth, jint index, BasicType type, jvalue value)
526   : _thread(thread)
527   , _calling_thread(NULL)
528   , _depth(depth)
529   , _index(index)
530   , _type(type)
531   , _value(value)
532   , _jvf(NULL)
533   , _set(true)
534   , _result(JVMTI_ERROR_NONE)
535 {
536 }
537 
538 // Constructor for object getter
VM_GetOrSetLocal(JavaThread * thread,JavaThread * calling_thread,jint depth,int index)539 VM_GetOrSetLocal::VM_GetOrSetLocal(JavaThread* thread, JavaThread* calling_thread, jint depth, int index)
540   : _thread(thread)
541   , _calling_thread(calling_thread)
542   , _depth(depth)
543   , _index(index)
544   , _type(T_OBJECT)
545   , _jvf(NULL)
546   , _set(false)
547   , _result(JVMTI_ERROR_NONE)
548 {
549 }
550 
get_vframe()551 vframe *VM_GetOrSetLocal::get_vframe() {
552   if (!_thread->has_last_Java_frame()) {
553     return NULL;
554   }
555   RegisterMap reg_map(_thread);
556   vframe *vf = _thread->last_java_vframe(&reg_map);
557   int d = 0;
558   while ((vf != NULL) && (d < _depth)) {
559     vf = vf->java_sender();
560     d++;
561   }
562   return vf;
563 }
564 
get_java_vframe()565 javaVFrame *VM_GetOrSetLocal::get_java_vframe() {
566   vframe* vf = get_vframe();
567   if (vf == NULL) {
568     _result = JVMTI_ERROR_NO_MORE_FRAMES;
569     return NULL;
570   }
571   javaVFrame *jvf = (javaVFrame*)vf;
572 
573   if (!vf->is_java_frame()) {
574     _result = JVMTI_ERROR_OPAQUE_FRAME;
575     return NULL;
576   }
577   return jvf;
578 }
579 
580 // Check that the klass is assignable to a type with the given signature.
581 // Another solution could be to use the function Klass::is_subtype_of(type).
582 // But the type class can be forced to load/initialize eagerly in such a case.
583 // This may cause unexpected consequences like CFLH or class-init JVMTI events.
584 // It is better to avoid such a behavior.
is_assignable(const char * ty_sign,Klass * klass,Thread * thread)585 bool VM_GetOrSetLocal::is_assignable(const char* ty_sign, Klass* klass, Thread* thread) {
586   assert(ty_sign != NULL, "type signature must not be NULL");
587   assert(thread != NULL, "thread must not be NULL");
588   assert(klass != NULL, "klass must not be NULL");
589 
590   int len = (int) strlen(ty_sign);
591   if (ty_sign[0] == JVM_SIGNATURE_CLASS &&
592       ty_sign[len-1] == JVM_SIGNATURE_ENDCLASS) { // Need pure class/interface name
593     ty_sign++;
594     len -= 2;
595   }
596   TempNewSymbol ty_sym = SymbolTable::new_symbol(ty_sign, len);
597   if (klass->name() == ty_sym) {
598     return true;
599   }
600   // Compare primary supers
601   int super_depth = klass->super_depth();
602   int idx;
603   for (idx = 0; idx < super_depth; idx++) {
604     if (klass->primary_super_of_depth(idx)->name() == ty_sym) {
605       return true;
606     }
607   }
608   // Compare secondary supers
609   const Array<Klass*>* sec_supers = klass->secondary_supers();
610   for (idx = 0; idx < sec_supers->length(); idx++) {
611     if (((Klass*) sec_supers->at(idx))->name() == ty_sym) {
612       return true;
613     }
614   }
615   return false;
616 }
617 
618 // Checks error conditions:
619 //   JVMTI_ERROR_INVALID_SLOT
620 //   JVMTI_ERROR_TYPE_MISMATCH
621 // Returns: 'true' - everything is Ok, 'false' - error code
622 
check_slot_type_lvt(javaVFrame * jvf)623 bool VM_GetOrSetLocal::check_slot_type_lvt(javaVFrame* jvf) {
624   Method* method_oop = jvf->method();
625   jint num_entries = method_oop->localvariable_table_length();
626   if (num_entries == 0) {
627     _result = JVMTI_ERROR_INVALID_SLOT;
628     return false;       // There are no slots
629   }
630   int signature_idx = -1;
631   int vf_bci = jvf->bci();
632   LocalVariableTableElement* table = method_oop->localvariable_table_start();
633   for (int i = 0; i < num_entries; i++) {
634     int start_bci = table[i].start_bci;
635     int end_bci = start_bci + table[i].length;
636 
637     // Here we assume that locations of LVT entries
638     // with the same slot number cannot be overlapped
639     if (_index == (jint) table[i].slot && start_bci <= vf_bci && vf_bci <= end_bci) {
640       signature_idx = (int) table[i].descriptor_cp_index;
641       break;
642     }
643   }
644   if (signature_idx == -1) {
645     _result = JVMTI_ERROR_INVALID_SLOT;
646     return false;       // Incorrect slot index
647   }
648   Symbol*   sign_sym  = method_oop->constants()->symbol_at(signature_idx);
649   const char* signature = (const char *) sign_sym->as_utf8();
650   BasicType slot_type = char2type(signature[0]);
651 
652   switch (slot_type) {
653   case T_BYTE:
654   case T_SHORT:
655   case T_CHAR:
656   case T_BOOLEAN:
657     slot_type = T_INT;
658     break;
659   case T_ARRAY:
660     slot_type = T_OBJECT;
661     break;
662   default:
663     break;
664   };
665   if (_type != slot_type) {
666     _result = JVMTI_ERROR_TYPE_MISMATCH;
667     return false;
668   }
669 
670   jobject jobj = _value.l;
671   if (_set && slot_type == T_OBJECT && jobj != NULL) { // NULL reference is allowed
672     // Check that the jobject class matches the return type signature.
673     JavaThread* cur_thread = JavaThread::current();
674     HandleMark hm(cur_thread);
675 
676     Handle obj(cur_thread, JNIHandles::resolve_external_guard(jobj));
677     NULL_CHECK(obj, (_result = JVMTI_ERROR_INVALID_OBJECT, false));
678     Klass* ob_k = obj->klass();
679     NULL_CHECK(ob_k, (_result = JVMTI_ERROR_INVALID_OBJECT, false));
680 
681     if (!is_assignable(signature, ob_k, cur_thread)) {
682       _result = JVMTI_ERROR_TYPE_MISMATCH;
683       return false;
684     }
685   }
686   return true;
687 }
688 
check_slot_type_no_lvt(javaVFrame * jvf)689 bool VM_GetOrSetLocal::check_slot_type_no_lvt(javaVFrame* jvf) {
690   Method* method_oop = jvf->method();
691   jint extra_slot = (_type == T_LONG || _type == T_DOUBLE) ? 1 : 0;
692 
693   if (_index < 0 || _index + extra_slot >= method_oop->max_locals()) {
694     _result = JVMTI_ERROR_INVALID_SLOT;
695     return false;
696   }
697   StackValueCollection *locals = _jvf->locals();
698   BasicType slot_type = locals->at(_index)->type();
699 
700   if (slot_type == T_CONFLICT) {
701     _result = JVMTI_ERROR_INVALID_SLOT;
702     return false;
703   }
704   if (extra_slot) {
705     BasicType extra_slot_type = locals->at(_index + 1)->type();
706     if (extra_slot_type != T_INT) {
707       _result = JVMTI_ERROR_INVALID_SLOT;
708       return false;
709     }
710   }
711   if (_type != slot_type && (_type == T_OBJECT || slot_type != T_INT)) {
712     _result = JVMTI_ERROR_TYPE_MISMATCH;
713     return false;
714   }
715   return true;
716 }
717 
can_be_deoptimized(vframe * vf)718 static bool can_be_deoptimized(vframe* vf) {
719   return (vf->is_compiled_frame() && vf->fr().can_be_deoptimized());
720 }
721 
doit_prologue()722 bool VM_GetOrSetLocal::doit_prologue() {
723   _jvf = get_java_vframe();
724   NULL_CHECK(_jvf, false);
725 
726   Method* method_oop = _jvf->method();
727   if (getting_receiver()) {
728     if (method_oop->is_static()) {
729       _result = JVMTI_ERROR_INVALID_SLOT;
730       return false;
731     }
732     return true;
733   }
734 
735   if (method_oop->is_native()) {
736     _result = JVMTI_ERROR_OPAQUE_FRAME;
737     return false;
738   }
739 
740   if (!check_slot_type_no_lvt(_jvf)) {
741     return false;
742   }
743   if (method_oop->has_localvariable_table()) {
744     return check_slot_type_lvt(_jvf);
745   }
746   return true;
747 }
748 
doit()749 void VM_GetOrSetLocal::doit() {
750   InterpreterOopMap oop_mask;
751   _jvf->method()->mask_for(_jvf->bci(), &oop_mask);
752   if (oop_mask.is_dead(_index)) {
753     // The local can be invalid and uninitialized in the scope of current bci
754     _result = JVMTI_ERROR_INVALID_SLOT;
755     return;
756   }
757   if (_set) {
758     // Force deoptimization of frame if compiled because it's
759     // possible the compiler emitted some locals as constant values,
760     // meaning they are not mutable.
761     if (can_be_deoptimized(_jvf)) {
762 
763       // Schedule deoptimization so that eventually the local
764       // update will be written to an interpreter frame.
765       Deoptimization::deoptimize_frame(_jvf->thread(), _jvf->fr().id());
766 
767       // Now store a new value for the local which will be applied
768       // once deoptimization occurs. Note however that while this
769       // write is deferred until deoptimization actually happens
770       // can vframe created after this point will have its locals
771       // reflecting this update so as far as anyone can see the
772       // write has already taken place.
773 
774       // If we are updating an oop then get the oop from the handle
775       // since the handle will be long gone by the time the deopt
776       // happens. The oop stored in the deferred local will be
777       // gc'd on its own.
778       if (_type == T_OBJECT) {
779         _value.l = (jobject) (JNIHandles::resolve_external_guard(_value.l));
780       }
781       // Re-read the vframe so we can see that it is deoptimized
782       // [ Only need because of assert in update_local() ]
783       _jvf = get_java_vframe();
784       ((compiledVFrame*)_jvf)->update_local(_type, _index, _value);
785       return;
786     }
787     StackValueCollection *locals = _jvf->locals();
788     HandleMark hm;
789 
790     switch (_type) {
791       case T_INT:    locals->set_int_at   (_index, _value.i); break;
792       case T_LONG:   locals->set_long_at  (_index, _value.j); break;
793       case T_FLOAT:  locals->set_float_at (_index, _value.f); break;
794       case T_DOUBLE: locals->set_double_at(_index, _value.d); break;
795       case T_OBJECT: {
796         Handle ob_h(Thread::current(), JNIHandles::resolve_external_guard(_value.l));
797         locals->set_obj_at (_index, ob_h);
798         break;
799       }
800       default: ShouldNotReachHere();
801     }
802     _jvf->set_locals(locals);
803   } else {
804     if (_jvf->method()->is_native() && _jvf->is_compiled_frame()) {
805       assert(getting_receiver(), "Can only get here when getting receiver");
806       oop receiver = _jvf->fr().get_native_receiver();
807       _value.l = JNIHandles::make_local(_calling_thread, receiver);
808     } else {
809       StackValueCollection *locals = _jvf->locals();
810 
811       switch (_type) {
812         case T_INT:    _value.i = locals->int_at   (_index);   break;
813         case T_LONG:   _value.j = locals->long_at  (_index);   break;
814         case T_FLOAT:  _value.f = locals->float_at (_index);   break;
815         case T_DOUBLE: _value.d = locals->double_at(_index);   break;
816         case T_OBJECT: {
817           // Wrap the oop to be returned in a local JNI handle since
818           // oops_do() no longer applies after doit() is finished.
819           oop obj = locals->obj_at(_index)();
820           _value.l = JNIHandles::make_local(_calling_thread, obj);
821           break;
822         }
823         default: ShouldNotReachHere();
824       }
825     }
826   }
827 }
828 
829 
allow_nested_vm_operations() const830 bool VM_GetOrSetLocal::allow_nested_vm_operations() const {
831   return true; // May need to deoptimize
832 }
833 
834 
VM_GetReceiver(JavaThread * thread,JavaThread * caller_thread,jint depth)835 VM_GetReceiver::VM_GetReceiver(
836     JavaThread* thread, JavaThread* caller_thread, jint depth)
837     : VM_GetOrSetLocal(thread, caller_thread, depth, 0) {}
838 
839 /////////////////////////////////////////////////////////////////////////////////////////
840 
841 //
842 // class JvmtiSuspendControl - see comments in jvmtiImpl.hpp
843 //
844 
suspend(JavaThread * java_thread)845 bool JvmtiSuspendControl::suspend(JavaThread *java_thread) {
846   // external suspend should have caught suspending a thread twice
847 
848   // Immediate suspension required for JPDA back-end so JVMTI agent threads do
849   // not deadlock due to later suspension on transitions while holding
850   // raw monitors.  Passing true causes the immediate suspension.
851   // java_suspend() will catch threads in the process of exiting
852   // and will ignore them.
853   java_thread->java_suspend();
854 
855   // It would be nice to have the following assertion in all the time,
856   // but it is possible for a racing resume request to have resumed
857   // this thread right after we suspended it. Temporarily enable this
858   // assertion if you are chasing a different kind of bug.
859   //
860   // assert(java_lang_Thread::thread(java_thread->threadObj()) == NULL ||
861   //   java_thread->is_being_ext_suspended(), "thread is not suspended");
862 
863   if (java_lang_Thread::thread(java_thread->threadObj()) == NULL) {
864     // check again because we can get delayed in java_suspend():
865     // the thread is in process of exiting.
866     return false;
867   }
868 
869   return true;
870 }
871 
resume(JavaThread * java_thread)872 bool JvmtiSuspendControl::resume(JavaThread *java_thread) {
873   // external suspend should have caught resuming a thread twice
874   assert(java_thread->is_being_ext_suspended(), "thread should be suspended");
875 
876   // resume thread
877   {
878     // must always grab Threads_lock, see JVM_SuspendThread
879     MutexLocker ml(Threads_lock);
880     java_thread->java_resume();
881   }
882 
883   return true;
884 }
885 
886 
print()887 void JvmtiSuspendControl::print() {
888 #ifndef PRODUCT
889   ResourceMark rm;
890   LogStreamHandle(Trace, jvmti) log_stream;
891   log_stream.print("Suspended Threads: [");
892   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thread = jtiwh.next(); ) {
893 #ifdef JVMTI_TRACE
894     const char *name   = JvmtiTrace::safe_get_thread_name(thread);
895 #else
896     const char *name   = "";
897 #endif /*JVMTI_TRACE */
898     log_stream.print("%s(%c ", name, thread->is_being_ext_suspended() ? 'S' : '_');
899     if (!thread->has_last_Java_frame()) {
900       log_stream.print("no stack");
901     }
902     log_stream.print(") ");
903   }
904   log_stream.print_cr("]");
905 #endif
906 }
907 
compiled_method_load_event(nmethod * nm)908 JvmtiDeferredEvent JvmtiDeferredEvent::compiled_method_load_event(
909     nmethod* nm) {
910   JvmtiDeferredEvent event = JvmtiDeferredEvent(TYPE_COMPILED_METHOD_LOAD);
911   event._event_data.compiled_method_load = nm;
912   return event;
913 }
914 
compiled_method_unload_event(jmethodID id,const void * code)915 JvmtiDeferredEvent JvmtiDeferredEvent::compiled_method_unload_event(
916     jmethodID id, const void* code) {
917   JvmtiDeferredEvent event = JvmtiDeferredEvent(TYPE_COMPILED_METHOD_UNLOAD);
918   event._event_data.compiled_method_unload.method_id = id;
919   event._event_data.compiled_method_unload.code_begin = code;
920   return event;
921 }
922 
dynamic_code_generated_event(const char * name,const void * code_begin,const void * code_end)923 JvmtiDeferredEvent JvmtiDeferredEvent::dynamic_code_generated_event(
924       const char* name, const void* code_begin, const void* code_end) {
925   JvmtiDeferredEvent event = JvmtiDeferredEvent(TYPE_DYNAMIC_CODE_GENERATED);
926   // Need to make a copy of the name since we don't know how long
927   // the event poster will keep it around after we enqueue the
928   // deferred event and return. strdup() failure is handled in
929   // the post() routine below.
930   event._event_data.dynamic_code_generated.name = os::strdup(name);
931   event._event_data.dynamic_code_generated.code_begin = code_begin;
932   event._event_data.dynamic_code_generated.code_end = code_end;
933   return event;
934 }
935 
class_unload_event(const char * name)936 JvmtiDeferredEvent JvmtiDeferredEvent::class_unload_event(const char* name) {
937   JvmtiDeferredEvent event = JvmtiDeferredEvent(TYPE_CLASS_UNLOAD);
938   // Need to make a copy of the name since we don't know how long
939   // the event poster will keep it around after we enqueue the
940   // deferred event and return. strdup() failure is handled in
941   // the post() routine below.
942   event._event_data.class_unload.name = os::strdup(name);
943   return event;
944 }
945 
post()946 void JvmtiDeferredEvent::post() {
947   assert(Thread::current()->is_service_thread(),
948          "Service thread must post enqueued events");
949   switch(_type) {
950     case TYPE_COMPILED_METHOD_LOAD: {
951       nmethod* nm = _event_data.compiled_method_load;
952       JvmtiExport::post_compiled_method_load(nm);
953       break;
954     }
955     case TYPE_COMPILED_METHOD_UNLOAD: {
956       JvmtiExport::post_compiled_method_unload(
957         _event_data.compiled_method_unload.method_id,
958         _event_data.compiled_method_unload.code_begin);
959       break;
960     }
961     case TYPE_DYNAMIC_CODE_GENERATED: {
962       JvmtiExport::post_dynamic_code_generated_internal(
963         // if strdup failed give the event a default name
964         (_event_data.dynamic_code_generated.name == NULL)
965           ? "unknown_code" : _event_data.dynamic_code_generated.name,
966         _event_data.dynamic_code_generated.code_begin,
967         _event_data.dynamic_code_generated.code_end);
968       if (_event_data.dynamic_code_generated.name != NULL) {
969         // release our copy
970         os::free((void *)_event_data.dynamic_code_generated.name);
971       }
972       break;
973     }
974     case TYPE_CLASS_UNLOAD: {
975       JvmtiExport::post_class_unload_internal(
976         // if strdup failed give the event a default name
977         (_event_data.class_unload.name == NULL)
978           ? "unknown_class" : _event_data.class_unload.name);
979       if (_event_data.class_unload.name != NULL) {
980         // release our copy
981         os::free((void *)_event_data.class_unload.name);
982       }
983       break;
984     }
985     default:
986       ShouldNotReachHere();
987   }
988 }
989 
post_compiled_method_load_event(JvmtiEnv * env)990 void JvmtiDeferredEvent::post_compiled_method_load_event(JvmtiEnv* env) {
991   assert(_type == TYPE_COMPILED_METHOD_LOAD, "only user of this method");
992   nmethod* nm = _event_data.compiled_method_load;
993   JvmtiExport::post_compiled_method_load(env, nm);
994 }
995 
run_nmethod_entry_barriers()996 void JvmtiDeferredEvent::run_nmethod_entry_barriers() {
997   if (_type == TYPE_COMPILED_METHOD_LOAD) {
998     _event_data.compiled_method_load->run_nmethod_entry_barrier();
999   }
1000 }
1001 
1002 
1003 // Keep the nmethod for compiled_method_load from being unloaded.
oops_do(OopClosure * f,CodeBlobClosure * cf)1004 void JvmtiDeferredEvent::oops_do(OopClosure* f, CodeBlobClosure* cf) {
1005   if (cf != NULL && _type == TYPE_COMPILED_METHOD_LOAD) {
1006     cf->do_code_blob(_event_data.compiled_method_load);
1007   }
1008 }
1009 
1010 // The sweeper calls this and marks the nmethods here on the stack so that
1011 // they cannot be turned into zombies while in the queue.
nmethods_do(CodeBlobClosure * cf)1012 void JvmtiDeferredEvent::nmethods_do(CodeBlobClosure* cf) {
1013   if (cf != NULL && _type == TYPE_COMPILED_METHOD_LOAD) {
1014     cf->do_code_blob(_event_data.compiled_method_load);
1015   }
1016 }
1017 
1018 
has_events()1019 bool JvmtiDeferredEventQueue::has_events() {
1020   // We save the queued events before the live phase and post them when it starts.
1021   // This code could skip saving the events on the queue before the live
1022   // phase and ignore them, but this would change how we do things now.
1023   // Starting the service thread earlier causes this to be called before the live phase begins.
1024   // The events on the queue should all be posted after the live phase so this is an
1025   // ok check.  Before the live phase, DynamicCodeGenerated events are posted directly.
1026   // If we add other types of events to the deferred queue, this could get ugly.
1027   return JvmtiEnvBase::get_phase() == JVMTI_PHASE_LIVE  && _queue_head != NULL;
1028 }
1029 
enqueue(JvmtiDeferredEvent event)1030 void JvmtiDeferredEventQueue::enqueue(JvmtiDeferredEvent event) {
1031   // Events get added to the end of the queue (and are pulled off the front).
1032   QueueNode* node = new QueueNode(event);
1033   if (_queue_tail == NULL) {
1034     _queue_tail = _queue_head = node;
1035   } else {
1036     assert(_queue_tail->next() == NULL, "Must be the last element in the list");
1037     _queue_tail->set_next(node);
1038     _queue_tail = node;
1039   }
1040 
1041   assert((_queue_head == NULL) == (_queue_tail == NULL),
1042          "Inconsistent queue markers");
1043 }
1044 
dequeue()1045 JvmtiDeferredEvent JvmtiDeferredEventQueue::dequeue() {
1046   assert(_queue_head != NULL, "Nothing to dequeue");
1047 
1048   if (_queue_head == NULL) {
1049     // Just in case this happens in product; it shouldn't but let's not crash
1050     return JvmtiDeferredEvent();
1051   }
1052 
1053   QueueNode* node = _queue_head;
1054   _queue_head = _queue_head->next();
1055   if (_queue_head == NULL) {
1056     _queue_tail = NULL;
1057   }
1058 
1059   assert((_queue_head == NULL) == (_queue_tail == NULL),
1060          "Inconsistent queue markers");
1061 
1062   JvmtiDeferredEvent event = node->event();
1063   delete node;
1064   return event;
1065 }
1066 
post(JvmtiEnv * env)1067 void JvmtiDeferredEventQueue::post(JvmtiEnv* env) {
1068   // Post and destroy queue nodes
1069   while (_queue_head != NULL) {
1070      JvmtiDeferredEvent event = dequeue();
1071      event.post_compiled_method_load_event(env);
1072   }
1073 }
1074 
run_nmethod_entry_barriers()1075 void JvmtiDeferredEventQueue::run_nmethod_entry_barriers() {
1076   for(QueueNode* node = _queue_head; node != NULL; node = node->next()) {
1077      node->event().run_nmethod_entry_barriers();
1078   }
1079 }
1080 
1081 
oops_do(OopClosure * f,CodeBlobClosure * cf)1082 void JvmtiDeferredEventQueue::oops_do(OopClosure* f, CodeBlobClosure* cf) {
1083   for(QueueNode* node = _queue_head; node != NULL; node = node->next()) {
1084      node->event().oops_do(f, cf);
1085   }
1086 }
1087 
nmethods_do(CodeBlobClosure * cf)1088 void JvmtiDeferredEventQueue::nmethods_do(CodeBlobClosure* cf) {
1089   for(QueueNode* node = _queue_head; node != NULL; node = node->next()) {
1090      node->event().nmethods_do(cf);
1091   }
1092 }
1093