1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #ifndef ART_OPENJDKJVMTI_EVENTS_H_
18 #define ART_OPENJDKJVMTI_EVENTS_H_
19
20 #include <bitset>
21 #include <unordered_map>
22 #include <vector>
23
24 #include "android-base/logging.h"
25 #include "android-base/thread_annotations.h"
26 #include "base/macros.h"
27 #include "base/mutex.h"
28 #include "jvmti.h"
29 #include "managed_stack.h"
30 #include "thread.h"
31
32 namespace openjdkjvmti {
33
34 struct ArtJvmTiEnv;
35 class JvmtiEventAllocationListener;
36 class JvmtiDdmChunkListener;
37 class JvmtiGcPauseListener;
38 class JvmtiMethodTraceListener;
39 class JvmtiMonitorListener;
40 class JvmtiParkListener;
41
42 // an enum for ArtEvents. This differs from the JVMTI events only in that we distinguish between
43 // retransformation capable and incapable loading
44 enum class ArtJvmtiEvent : jint {
45 kMinEventTypeVal = JVMTI_MIN_EVENT_TYPE_VAL,
46 kVmInit = JVMTI_EVENT_VM_INIT,
47 kVmDeath = JVMTI_EVENT_VM_DEATH,
48 kThreadStart = JVMTI_EVENT_THREAD_START,
49 kThreadEnd = JVMTI_EVENT_THREAD_END,
50 kClassFileLoadHookNonRetransformable = JVMTI_EVENT_CLASS_FILE_LOAD_HOOK,
51 kClassLoad = JVMTI_EVENT_CLASS_LOAD,
52 kClassPrepare = JVMTI_EVENT_CLASS_PREPARE,
53 kVmStart = JVMTI_EVENT_VM_START,
54 kException = JVMTI_EVENT_EXCEPTION,
55 kExceptionCatch = JVMTI_EVENT_EXCEPTION_CATCH,
56 kSingleStep = JVMTI_EVENT_SINGLE_STEP,
57 kFramePop = JVMTI_EVENT_FRAME_POP,
58 kBreakpoint = JVMTI_EVENT_BREAKPOINT,
59 kFieldAccess = JVMTI_EVENT_FIELD_ACCESS,
60 kFieldModification = JVMTI_EVENT_FIELD_MODIFICATION,
61 kMethodEntry = JVMTI_EVENT_METHOD_ENTRY,
62 kMethodExit = JVMTI_EVENT_METHOD_EXIT,
63 kNativeMethodBind = JVMTI_EVENT_NATIVE_METHOD_BIND,
64 kCompiledMethodLoad = JVMTI_EVENT_COMPILED_METHOD_LOAD,
65 kCompiledMethodUnload = JVMTI_EVENT_COMPILED_METHOD_UNLOAD,
66 kDynamicCodeGenerated = JVMTI_EVENT_DYNAMIC_CODE_GENERATED,
67 kDataDumpRequest = JVMTI_EVENT_DATA_DUMP_REQUEST,
68 kMonitorWait = JVMTI_EVENT_MONITOR_WAIT,
69 kMonitorWaited = JVMTI_EVENT_MONITOR_WAITED,
70 kMonitorContendedEnter = JVMTI_EVENT_MONITOR_CONTENDED_ENTER,
71 kMonitorContendedEntered = JVMTI_EVENT_MONITOR_CONTENDED_ENTERED,
72 kResourceExhausted = JVMTI_EVENT_RESOURCE_EXHAUSTED,
73 kGarbageCollectionStart = JVMTI_EVENT_GARBAGE_COLLECTION_START,
74 kGarbageCollectionFinish = JVMTI_EVENT_GARBAGE_COLLECTION_FINISH,
75 kObjectFree = JVMTI_EVENT_OBJECT_FREE,
76 kVmObjectAlloc = JVMTI_EVENT_VM_OBJECT_ALLOC,
77 // Internal event to mark a ClassFileLoadHook as one created with the can_retransform_classes
78 // capability.
79 kClassFileLoadHookRetransformable = JVMTI_MAX_EVENT_TYPE_VAL + 1,
80 kDdmPublishChunk = JVMTI_MAX_EVENT_TYPE_VAL + 2,
81 kObsoleteObjectCreated = JVMTI_MAX_EVENT_TYPE_VAL + 3,
82 kStructuralDexFileLoadHook = JVMTI_MAX_EVENT_TYPE_VAL + 4,
83 kMaxNormalEventTypeVal = kStructuralDexFileLoadHook,
84
85 // All that follow are events used to implement internal JVMTI functions. They are not settable
86 // directly by agents.
87 kMinInternalEventTypeVal = kMaxNormalEventTypeVal + 1,
88
89 // Internal event we use to implement the ForceEarlyReturn functions.
90 kForceEarlyReturnUpdateReturnValue = kMinInternalEventTypeVal,
91 kMaxInternalEventTypeVal = kForceEarlyReturnUpdateReturnValue,
92
93 kMaxEventTypeVal = kMaxInternalEventTypeVal,
94 };
95
96 constexpr jint kInternalEventCount = static_cast<jint>(ArtJvmtiEvent::kMaxInternalEventTypeVal) -
97 static_cast<jint>(ArtJvmtiEvent::kMinInternalEventTypeVal) + 1;
98
99 using ArtJvmtiEventDdmPublishChunk = void (*)(jvmtiEnv *jvmti_env,
100 jint data_type,
101 jint data_len,
102 const jbyte* data);
103
104 using ArtJvmtiEventObsoleteObjectCreated = void (*)(jvmtiEnv *jvmti_env,
105 jlong* obsolete_tag,
106 jlong* new_tag);
107
108 using ArtJvmtiEventStructuralDexFileLoadHook = void (*)(jvmtiEnv *jvmti_env,
109 JNIEnv* jni_env,
110 jclass class_being_redefined,
111 jobject loader,
112 const char* name,
113 jobject protection_domain,
114 jint dex_data_len,
115 const unsigned char* dex_data,
116 jint* new_dex_data_len,
117 unsigned char** new_dex_data);
118
119 // It is not enough to store a Thread pointer, as these may be reused. Use the pointer and the
120 // thread id.
121 // Note: We could just use the tid like tracing does.
122 using UniqueThread = std::pair<art::Thread*, uint32_t>;
123
124 struct UniqueThreadHasher {
operatorUniqueThreadHasher125 std::size_t operator()(const UniqueThread& k) const {
126 return std::hash<uint32_t>{}(k.second) ^ (std::hash<void*>{}(k.first) << 1);
127 }
128 };
129
130 struct ArtJvmtiEventCallbacks : jvmtiEventCallbacks {
ArtJvmtiEventCallbacksArtJvmtiEventCallbacks131 ArtJvmtiEventCallbacks()
132 : DdmPublishChunk(nullptr),
133 ObsoleteObjectCreated(nullptr),
134 StructuralDexFileLoadHook(nullptr) {
135 memset(this, 0, sizeof(jvmtiEventCallbacks));
136 }
137
138 // Copies extension functions from other callback struct if it exists. There must not have been
139 // any modifications to this struct when it is called.
140 void CopyExtensionsFrom(const ArtJvmtiEventCallbacks* cb);
141
142 jvmtiError Set(jint index, jvmtiExtensionEvent cb);
143
144 ArtJvmtiEventDdmPublishChunk DdmPublishChunk;
145 ArtJvmtiEventObsoleteObjectCreated ObsoleteObjectCreated;
146 ArtJvmtiEventStructuralDexFileLoadHook StructuralDexFileLoadHook;
147 };
148
149 bool IsExtensionEvent(jint e);
150 bool IsExtensionEvent(ArtJvmtiEvent e);
151
152 // Convert a jvmtiEvent into a ArtJvmtiEvent
153 ALWAYS_INLINE static inline ArtJvmtiEvent GetArtJvmtiEvent(ArtJvmTiEnv* env, jvmtiEvent e);
154
GetJvmtiEvent(ArtJvmtiEvent e)155 static inline jvmtiEvent GetJvmtiEvent(ArtJvmtiEvent e) {
156 if (UNLIKELY(e == ArtJvmtiEvent::kClassFileLoadHookRetransformable)) {
157 return JVMTI_EVENT_CLASS_FILE_LOAD_HOOK;
158 } else {
159 return static_cast<jvmtiEvent>(e);
160 }
161 }
162
163 struct EventMask {
164 static constexpr size_t kEventsSize =
165 static_cast<size_t>(ArtJvmtiEvent::kMaxEventTypeVal) -
166 static_cast<size_t>(ArtJvmtiEvent::kMinEventTypeVal) + 1;
167 std::bitset<kEventsSize> bit_set;
168
EventIsInRangeEventMask169 static bool EventIsInRange(ArtJvmtiEvent event) {
170 return event >= ArtJvmtiEvent::kMinEventTypeVal && event <= ArtJvmtiEvent::kMaxEventTypeVal;
171 }
172
173 void Set(ArtJvmtiEvent event, bool value = true) {
174 DCHECK(EventIsInRange(event));
175 bit_set.set(static_cast<size_t>(event) - static_cast<size_t>(ArtJvmtiEvent::kMinEventTypeVal),
176 value);
177 }
178
TestEventMask179 bool Test(ArtJvmtiEvent event) const {
180 DCHECK(EventIsInRange(event));
181 return bit_set.test(
182 static_cast<size_t>(event) - static_cast<size_t>(ArtJvmtiEvent::kMinEventTypeVal));
183 }
184 };
185
186 struct EventMasks {
187 // The globally enabled events.
188 EventMask global_event_mask;
189
190 // The per-thread enabled events.
191
192 // TODO: Native thread objects are immovable, so we can use them as keys in an (unordered) map,
193 // if necessary.
194 std::vector<std::pair<UniqueThread, EventMask>> thread_event_masks;
195
196 // A union of the per-thread events, for fast-pathing.
197 EventMask unioned_thread_event_mask;
198
199 EventMask& GetEventMask(art::Thread* thread);
200 EventMask* GetEventMaskOrNull(art::Thread* thread);
201 // Circular dependencies mean we cannot see the definition of ArtJvmTiEnv so the mutex is simply
202 // asserted in the function.
203 // Note that the 'env' passed in must be the same env this EventMasks is associated with.
204 void EnableEvent(ArtJvmTiEnv* env, art::Thread* thread, ArtJvmtiEvent event);
205 // REQUIRES(env->event_info_mutex_);
206 // Circular dependencies mean we cannot see the definition of ArtJvmTiEnv so the mutex is simply
207 // asserted in the function.
208 // Note that the 'env' passed in must be the same env this EventMasks is associated with.
209 void DisableEvent(ArtJvmTiEnv* env, art::Thread* thread, ArtJvmtiEvent event);
210 // REQUIRES(env->event_info_mutex_);
211 bool IsEnabledAnywhere(ArtJvmtiEvent event);
212 // Make any changes to event masks needed for the given capability changes. If caps_added is true
213 // then caps is all the newly set capabilities of the jvmtiEnv. If it is false then caps is the
214 // set of all capabilities that were removed from the jvmtiEnv.
215 void HandleChangedCapabilities(const jvmtiCapabilities& caps, bool caps_added);
216 };
217
218 namespace impl {
219 template <ArtJvmtiEvent kEvent> struct EventHandlerFunc { };
220 } // namespace impl
221
222 // Helper class for event handling.
223 class EventHandler {
224 public:
225 EventHandler();
226 ~EventHandler();
227
228 // do cleanup for the event handler.
229 void Shutdown();
230
231 // Register an env. It is assumed that this happens on env creation, that is, no events are
232 // enabled, yet.
233 void RegisterArtJvmTiEnv(ArtJvmTiEnv* env) REQUIRES(!envs_lock_);
234
235 // Remove an env.
236 void RemoveArtJvmTiEnv(ArtJvmTiEnv* env) REQUIRES(!envs_lock_);
237
IsEventEnabledAnywhere(ArtJvmtiEvent event)238 bool IsEventEnabledAnywhere(ArtJvmtiEvent event) const {
239 if (!EventMask::EventIsInRange(event)) {
240 return false;
241 }
242 return global_mask.Test(event);
243 }
244
245 // Sets an internal event. Unlike normal JVMTI events internal events are not associated with any
246 // particular jvmtiEnv and are refcounted. This refcounting is done to allow us to easily enable
247 // events during functions and disable them during the requested event callback. Since these are
248 // used to implement various JVMTI functions these events always have a single target thread. If
249 // target is null the current thread is used.
250 jvmtiError SetInternalEvent(jthread target,
251 ArtJvmtiEvent event,
252 jvmtiEventMode mode)
253 REQUIRES(!envs_lock_, !art::Locks::mutator_lock_);
254
255 jvmtiError SetEvent(ArtJvmTiEnv* env,
256 jthread thread,
257 ArtJvmtiEvent event,
258 jvmtiEventMode mode)
259 REQUIRES(!envs_lock_);
260
261 // Dispatch event to all registered environments. Since this one doesn't have a JNIEnv* it doesn't
262 // matter if it has the mutator_lock.
263 template <ArtJvmtiEvent kEvent, typename ...Args>
264 ALWAYS_INLINE
265 inline void DispatchEvent(art::Thread* thread, Args... args) const
266 REQUIRES(!envs_lock_);
267
268 // Dispatch event to all registered environments stashing exceptions as needed. This works since
269 // JNIEnv* is always the second argument if it is passed to an event. Needed since C++ does not
270 // allow partial template function specialization.
271 //
272 // We need both of these since we want to make sure to push a stack frame when it is possible for
273 // the event to allocate local references.
274 template <ArtJvmtiEvent kEvent, typename ...Args>
275 ALWAYS_INLINE
276 inline void DispatchEvent(art::Thread* thread, JNIEnv* jnienv, Args... args) const
277 REQUIRES(!envs_lock_);
278
279 // Tell the event handler capabilities were added/lost so it can adjust the sent events.If
280 // caps_added is true then caps is all the newly set capabilities of the jvmtiEnv. If it is false
281 // then caps is the set of all capabilities that were removed from the jvmtiEnv.
282 ALWAYS_INLINE
283 inline void HandleChangedCapabilities(ArtJvmTiEnv* env,
284 const jvmtiCapabilities& caps,
285 bool added)
286 REQUIRES(!envs_lock_);
287
288 // Dispatch event to the given environment, only.
289 template <ArtJvmtiEvent kEvent, typename ...Args>
290 ALWAYS_INLINE
291 inline void DispatchEventOnEnv(ArtJvmTiEnv* env,
292 art::Thread* thread,
293 JNIEnv* jnienv,
294 Args... args) const
295 REQUIRES(!envs_lock_);
296
297 // Dispatch event to the given environment, only.
298 template <ArtJvmtiEvent kEvent, typename ...Args>
299 ALWAYS_INLINE
300 inline void DispatchEventOnEnv(ArtJvmTiEnv* env, art::Thread* thread, Args... args) const
301 REQUIRES(!envs_lock_);
302
303 void AddDelayedNonStandardExitEvent(const art::ShadowFrame* frame, bool is_object, jvalue val)
304 REQUIRES_SHARED(art::Locks::mutator_lock_)
305 REQUIRES(art::Locks::user_code_suspension_lock_, art::Locks::thread_list_lock_);
306
307 template<typename Visitor>
ForEachEnv(art::Thread * self,Visitor v)308 void ForEachEnv(art::Thread* self, Visitor v) REQUIRES(!envs_lock_) {
309 art::ReaderMutexLock mu(self, envs_lock_);
310 for (ArtJvmTiEnv* e : envs) {
311 if (e != nullptr) {
312 v(e);
313 }
314 }
315 }
316
317 private:
318 void SetupTraceListener(JvmtiMethodTraceListener* listener, ArtJvmtiEvent event, bool enable);
319
320 uint32_t GetInstrumentationEventsFor(ArtJvmtiEvent event);
321
322 // Specifically handle the FramePop event which it might not always be possible to turn off.
323 void SetupFramePopTraceListener(bool enable);
324
325 template <ArtJvmtiEvent kEvent, typename ...Args>
326 ALWAYS_INLINE
327 inline std::vector<impl::EventHandlerFunc<kEvent>> CollectEvents(art::Thread* thread,
328 Args... args) const
329 REQUIRES(!envs_lock_);
330
331 template <ArtJvmtiEvent kEvent>
332 ALWAYS_INLINE
333 inline bool ShouldDispatchOnThread(ArtJvmTiEnv* env, art::Thread* thread) const;
334
335 template <ArtJvmtiEvent kEvent, typename ...Args>
336 ALWAYS_INLINE
337 static inline void ExecuteCallback(impl::EventHandlerFunc<kEvent> handler,
338 JNIEnv* env,
339 Args... args)
340 REQUIRES(!envs_lock_);
341
342 template <ArtJvmtiEvent kEvent, typename ...Args>
343 ALWAYS_INLINE
344 static inline void ExecuteCallback(impl::EventHandlerFunc<kEvent> handler, Args... args)
345 REQUIRES(!envs_lock_);
346
347 // Public for use to collect dispatches
348 template <ArtJvmtiEvent kEvent, typename ...Args>
349 ALWAYS_INLINE
350 inline bool ShouldDispatch(ArtJvmTiEnv* env, art::Thread* thread, Args... args) const;
351
352 ALWAYS_INLINE
353 inline bool NeedsEventUpdate(ArtJvmTiEnv* env,
354 const jvmtiCapabilities& caps,
355 bool added);
356
357 // Recalculates the event mask for the given event.
358 ALWAYS_INLINE
359 inline void RecalculateGlobalEventMask(ArtJvmtiEvent event) REQUIRES(!envs_lock_);
360 ALWAYS_INLINE
361 inline void RecalculateGlobalEventMaskLocked(ArtJvmtiEvent event) REQUIRES_SHARED(envs_lock_);
362
363 // Returns whether there are any active requests for the given event on the given thread. This
364 // should only be used while modifying the events for a thread.
365 bool GetThreadEventState(ArtJvmtiEvent event, art::Thread* thread)
366 REQUIRES(envs_lock_, art::Locks::thread_list_lock_);
367
368 template <ArtJvmtiEvent kEvent>
369 ALWAYS_INLINE inline void DispatchClassFileLoadHookEvent(art::Thread* thread,
370 JNIEnv* jnienv,
371 jclass class_being_redefined,
372 jobject loader,
373 const char* name,
374 jobject protection_domain,
375 jint class_data_len,
376 const unsigned char* class_data,
377 jint* new_class_data_len,
378 unsigned char** new_class_data) const
379 REQUIRES(!envs_lock_);
380
381 template <ArtJvmtiEvent kEvent>
382 ALWAYS_INLINE inline void DispatchClassLoadOrPrepareEvent(art::Thread* thread,
383 JNIEnv* jnienv,
384 jthread jni_thread,
385 jclass klass) const
386 REQUIRES(!envs_lock_);
387
388 // Sets up the global state needed for the first/last enable of an event across all threads
389 void HandleEventType(ArtJvmtiEvent event, bool enable);
390 // Perform deopts required for enabling the event on the given thread. Null thread indicates
391 // global event enabled.
392 jvmtiError HandleEventDeopt(ArtJvmtiEvent event, jthread thread, bool enable);
393 void HandleLocalAccessCapabilityAdded();
394 void HandleBreakpointEventsChanged(bool enable);
395
396 bool OtherMonitorEventsEnabledAnywhere(ArtJvmtiEvent event);
397
398 int32_t GetInternalEventRefcount(ArtJvmtiEvent event) const REQUIRES(envs_lock_);
399 // Increment internal event refcount for the given event and return the new count.
400 int32_t IncrInternalEventRefcount(ArtJvmtiEvent event) REQUIRES(envs_lock_);
401 // Decrement internal event refcount for the given event and return the new count.
402 int32_t DecrInternalEventRefcount(ArtJvmtiEvent event) REQUIRES(envs_lock_);
403
404 int32_t& GetInternalEventThreadRefcount(ArtJvmtiEvent event, art::Thread* target)
405 REQUIRES(envs_lock_, art::Locks::thread_list_lock_);
406 // Increment internal event refcount for the given event and return the new count.
407 int32_t IncrInternalEventThreadRefcount(ArtJvmtiEvent event, art::Thread* target)
408 REQUIRES(envs_lock_, art::Locks::thread_list_lock_);
409 // Decrement internal event refcount for the given event and return the new count.
410 int32_t DecrInternalEventThreadRefcount(ArtJvmtiEvent event, art::Thread* target)
411 REQUIRES(envs_lock_, art::Locks::thread_list_lock_);
412
413 // List of all JvmTiEnv objects that have been created, in their creation order. It is a std::list
414 // since we mostly access it by iterating over the entire thing, only ever append to the end, and
415 // need to be able to remove arbitrary elements from it.
416 std::list<ArtJvmTiEnv*> envs GUARDED_BY(envs_lock_);
417
418 // Close to top level lock. Nothing should be held when we lock this (except for mutator_lock_
419 // which is needed when setting new events).
420 mutable art::ReaderWriterMutex envs_lock_ ACQUIRED_AFTER(art::Locks::mutator_lock_);
421
422 // A union of all enabled events, anywhere.
423 EventMask global_mask;
424
425 std::unique_ptr<JvmtiEventAllocationListener> alloc_listener_;
426 std::unique_ptr<JvmtiDdmChunkListener> ddm_listener_;
427 std::unique_ptr<JvmtiGcPauseListener> gc_pause_listener_;
428 std::unique_ptr<JvmtiMethodTraceListener> method_trace_listener_;
429 std::unique_ptr<JvmtiMonitorListener> monitor_listener_;
430 std::unique_ptr<JvmtiParkListener> park_listener_;
431
432 // True if frame pop has ever been enabled. Since we store pointers to stack frames we need to
433 // continue to listen to this event even if it has been disabled.
434 // TODO We could remove the listeners once all jvmtiEnvs have drained their shadow-frame vectors.
435 bool frame_pop_enabled;
436
437 // The overall refcount for each internal event across all threads.
438 std::array<int32_t, kInternalEventCount> internal_event_refcount_ GUARDED_BY(envs_lock_);
439 // The refcount for each thread for each internal event.
440 // TODO We should clean both this and the normal EventMask lists up when threads end.
441 std::array<std::unordered_map<UniqueThread, int32_t, UniqueThreadHasher>, kInternalEventCount>
442 internal_event_thread_refcount_
443 GUARDED_BY(envs_lock_) GUARDED_BY(art::Locks::thread_list_lock_);
444
445 friend class JvmtiMethodTraceListener;
446 };
447
448 } // namespace openjdkjvmti
449
450 #endif // ART_OPENJDKJVMTI_EVENTS_H_
451