1/* Copyright (C) 2016 The Android Open Source Project
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This file implements interfaces from the file jvmti.h. This implementation
5 * is licensed under the same terms as the file jvmti.h.  The
6 * copyright and license information for the file jvmti.h follows.
7 *
8 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation.  Oracle designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Oracle in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
28 * or visit www.oracle.com if you need additional information or have any
29 * questions.
30 */
31
32#include "ti_method.h"
33
34#include "art_jvmti.h"
35#include "art_method-inl.h"
36#include "base/enums.h"
37#include "dex_file_annotations.h"
38#include "events-inl.h"
39#include "jni_internal.h"
40#include "mirror/object_array-inl.h"
41#include "modifiers.h"
42#include "runtime_callbacks.h"
43#include "scoped_thread_state_change-inl.h"
44#include "ScopedLocalRef.h"
45#include "thread-inl.h"
46#include "thread_list.h"
47#include "ti_phase.h"
48
49namespace openjdkjvmti {
50
51struct TiMethodCallback : public art::MethodCallback {
52  void RegisterNativeMethod(art::ArtMethod* method,
53                            const void* cur_method,
54                            /*out*/void** new_method)
55      OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
56    if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kNativeMethodBind)) {
57      art::Thread* thread = art::Thread::Current();
58      art::JNIEnvExt* jnienv = thread->GetJniEnv();
59      ScopedLocalRef<jthread> thread_jni(
60          jnienv, PhaseUtil::IsLivePhase() ? jnienv->AddLocalReference<jthread>(thread->GetPeer())
61                                           : nullptr);
62      art::ScopedThreadSuspension sts(thread, art::ThreadState::kNative);
63      event_handler->DispatchEvent<ArtJvmtiEvent::kNativeMethodBind>(
64          thread,
65          static_cast<JNIEnv*>(jnienv),
66          thread_jni.get(),
67          art::jni::EncodeArtMethod(method),
68          const_cast<void*>(cur_method),
69          new_method);
70    }
71  }
72
73  EventHandler* event_handler = nullptr;
74};
75
76TiMethodCallback gMethodCallback;
77
78void MethodUtil::Register(EventHandler* handler) {
79  gMethodCallback.event_handler = handler;
80  art::ScopedThreadStateChange stsc(art::Thread::Current(),
81                                    art::ThreadState::kWaitingForDebuggerToAttach);
82  art::ScopedSuspendAll ssa("Add method callback");
83  art::Runtime::Current()->GetRuntimeCallbacks()->AddMethodCallback(&gMethodCallback);
84}
85
86void MethodUtil::Unregister() {
87  art::ScopedThreadStateChange stsc(art::Thread::Current(),
88                                    art::ThreadState::kWaitingForDebuggerToAttach);
89  art::ScopedSuspendAll ssa("Remove method callback");
90  art::Runtime* runtime = art::Runtime::Current();
91  runtime->GetRuntimeCallbacks()->RemoveMethodCallback(&gMethodCallback);
92}
93
94jvmtiError MethodUtil::GetArgumentsSize(jvmtiEnv* env ATTRIBUTE_UNUSED,
95                                        jmethodID method,
96                                        jint* size_ptr) {
97  if (method == nullptr) {
98    return ERR(INVALID_METHODID);
99  }
100  art::ArtMethod* art_method = art::jni::DecodeArtMethod(method);
101
102  if (art_method->IsNative()) {
103    return ERR(NATIVE_METHOD);
104  }
105
106  if (size_ptr == nullptr) {
107    return ERR(NULL_POINTER);
108  }
109
110  art::ScopedObjectAccess soa(art::Thread::Current());
111  if (art_method->IsProxyMethod() || art_method->IsAbstract()) {
112    // Use the shorty.
113    art::ArtMethod* base_method = art_method->GetInterfaceMethodIfProxy(art::kRuntimePointerSize);
114    size_t arg_count = art::ArtMethod::NumArgRegisters(base_method->GetShorty());
115    if (!base_method->IsStatic()) {
116      arg_count++;
117    }
118    *size_ptr = static_cast<jint>(arg_count);
119    return ERR(NONE);
120  }
121
122  DCHECK_NE(art_method->GetCodeItemOffset(), 0u);
123  *size_ptr = art_method->GetCodeItem()->ins_size_;
124
125  return ERR(NONE);
126}
127
128jvmtiError MethodUtil::GetMaxLocals(jvmtiEnv* env ATTRIBUTE_UNUSED,
129                                    jmethodID method,
130                                    jint* max_ptr) {
131  if (method == nullptr) {
132    return ERR(INVALID_METHODID);
133  }
134  art::ArtMethod* art_method = art::jni::DecodeArtMethod(method);
135
136  if (art_method->IsNative()) {
137    return ERR(NATIVE_METHOD);
138  }
139
140  if (max_ptr == nullptr) {
141    return ERR(NULL_POINTER);
142  }
143
144  art::ScopedObjectAccess soa(art::Thread::Current());
145  if (art_method->IsProxyMethod() || art_method->IsAbstract()) {
146    // This isn't specified as an error case, so return 0.
147    *max_ptr = 0;
148    return ERR(NONE);
149  }
150
151  DCHECK_NE(art_method->GetCodeItemOffset(), 0u);
152  *max_ptr = art_method->GetCodeItem()->registers_size_;
153
154  return ERR(NONE);
155}
156
157jvmtiError MethodUtil::GetMethodName(jvmtiEnv* env,
158                                     jmethodID method,
159                                     char** name_ptr,
160                                     char** signature_ptr,
161                                     char** generic_ptr) {
162  art::ScopedObjectAccess soa(art::Thread::Current());
163  art::ArtMethod* art_method = art::jni::DecodeArtMethod(method);
164  art_method = art_method->GetInterfaceMethodIfProxy(art::kRuntimePointerSize);
165
166  JvmtiUniquePtr<char[]> name_copy;
167  if (name_ptr != nullptr) {
168    const char* method_name = art_method->GetName();
169    if (method_name == nullptr) {
170      method_name = "<error>";
171    }
172    jvmtiError ret;
173    name_copy = CopyString(env, method_name, &ret);
174    if (name_copy == nullptr) {
175      return ret;
176    }
177    *name_ptr = name_copy.get();
178  }
179
180  JvmtiUniquePtr<char[]> signature_copy;
181  if (signature_ptr != nullptr) {
182    const art::Signature sig = art_method->GetSignature();
183    std::string str = sig.ToString();
184    jvmtiError ret;
185    signature_copy = CopyString(env, str.c_str(), &ret);
186    if (signature_copy == nullptr) {
187      return ret;
188    }
189    *signature_ptr = signature_copy.get();
190  }
191
192  if (generic_ptr != nullptr) {
193    *generic_ptr = nullptr;
194    if (!art_method->GetDeclaringClass()->IsProxyClass()) {
195      art::mirror::ObjectArray<art::mirror::String>* str_array =
196          art::annotations::GetSignatureAnnotationForMethod(art_method);
197      if (str_array != nullptr) {
198        std::ostringstream oss;
199        for (int32_t i = 0; i != str_array->GetLength(); ++i) {
200          oss << str_array->Get(i)->ToModifiedUtf8();
201        }
202        std::string output_string = oss.str();
203        jvmtiError ret;
204        JvmtiUniquePtr<char[]> generic_copy = CopyString(env, output_string.c_str(), &ret);
205        if (generic_copy == nullptr) {
206          return ret;
207        }
208        *generic_ptr = generic_copy.release();
209      } else if (soa.Self()->IsExceptionPending()) {
210        // TODO: Should we report an error here?
211        soa.Self()->ClearException();
212      }
213    }
214  }
215
216  // Everything is fine, release the buffers.
217  name_copy.release();
218  signature_copy.release();
219
220  return ERR(NONE);
221}
222
223jvmtiError MethodUtil::GetMethodDeclaringClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
224                                               jmethodID method,
225                                               jclass* declaring_class_ptr) {
226  if (declaring_class_ptr == nullptr) {
227    return ERR(NULL_POINTER);
228  }
229
230  art::ArtMethod* art_method = art::jni::DecodeArtMethod(method);
231  // Note: No GetInterfaceMethodIfProxy, we want to actual class.
232
233  art::ScopedObjectAccess soa(art::Thread::Current());
234  art::mirror::Class* klass = art_method->GetDeclaringClass();
235  *declaring_class_ptr = soa.AddLocalReference<jclass>(klass);
236
237  return ERR(NONE);
238}
239
240jvmtiError MethodUtil::GetMethodLocation(jvmtiEnv* env ATTRIBUTE_UNUSED,
241                                         jmethodID method,
242                                         jlocation* start_location_ptr,
243                                         jlocation* end_location_ptr) {
244  if (method == nullptr) {
245    return ERR(INVALID_METHODID);
246  }
247  art::ArtMethod* art_method = art::jni::DecodeArtMethod(method);
248
249  if (art_method->IsNative()) {
250    return ERR(NATIVE_METHOD);
251  }
252
253  if (start_location_ptr == nullptr || end_location_ptr == nullptr) {
254    return ERR(NULL_POINTER);
255  }
256
257  art::ScopedObjectAccess soa(art::Thread::Current());
258  if (art_method->IsProxyMethod() || art_method->IsAbstract()) {
259    // This isn't specified as an error case, so return -1/-1 as the RI does.
260    *start_location_ptr = -1;
261    *end_location_ptr = -1;
262    return ERR(NONE);
263  }
264
265  DCHECK_NE(art_method->GetCodeItemOffset(), 0u);
266  *start_location_ptr = 0;
267  *end_location_ptr = art_method->GetCodeItem()->insns_size_in_code_units_ - 1;
268
269  return ERR(NONE);
270}
271
272jvmtiError MethodUtil::GetMethodModifiers(jvmtiEnv* env ATTRIBUTE_UNUSED,
273                                          jmethodID method,
274                                          jint* modifiers_ptr) {
275  if (modifiers_ptr == nullptr) {
276    return ERR(NULL_POINTER);
277  }
278
279  art::ArtMethod* art_method = art::jni::DecodeArtMethod(method);
280  uint32_t modifiers = art_method->GetAccessFlags();
281
282  // Note: Keep this code in sync with Executable.fixMethodFlags.
283  if ((modifiers & art::kAccAbstract) != 0) {
284    modifiers &= ~art::kAccNative;
285  }
286  modifiers &= ~art::kAccSynchronized;
287  if ((modifiers & art::kAccDeclaredSynchronized) != 0) {
288    modifiers |= art::kAccSynchronized;
289  }
290  modifiers &= art::kAccJavaFlagsMask;
291
292  *modifiers_ptr = modifiers;
293  return ERR(NONE);
294}
295
296using LineNumberContext = std::vector<jvmtiLineNumberEntry>;
297
298static bool CollectLineNumbers(void* void_context, const art::DexFile::PositionInfo& entry) {
299  LineNumberContext* context = reinterpret_cast<LineNumberContext*>(void_context);
300  jvmtiLineNumberEntry jvmti_entry = { static_cast<jlocation>(entry.address_),
301                                       static_cast<jint>(entry.line_) };
302  context->push_back(jvmti_entry);
303  return false;  // Collect all, no early exit.
304}
305
306jvmtiError MethodUtil::GetLineNumberTable(jvmtiEnv* env,
307                                          jmethodID method,
308                                          jint* entry_count_ptr,
309                                          jvmtiLineNumberEntry** table_ptr) {
310  if (method == nullptr) {
311    return ERR(NULL_POINTER);
312  }
313  art::ArtMethod* art_method = art::jni::DecodeArtMethod(method);
314  DCHECK(!art_method->IsRuntimeMethod());
315
316  const art::DexFile::CodeItem* code_item;
317  const art::DexFile* dex_file;
318  {
319    art::ScopedObjectAccess soa(art::Thread::Current());
320
321    if (art_method->IsProxyMethod()) {
322      return ERR(ABSENT_INFORMATION);
323    }
324    if (art_method->IsNative()) {
325      return ERR(NATIVE_METHOD);
326    }
327    if (entry_count_ptr == nullptr || table_ptr == nullptr) {
328      return ERR(NULL_POINTER);
329    }
330
331    code_item = art_method->GetCodeItem();
332    dex_file = art_method->GetDexFile();
333    DCHECK(code_item != nullptr) << art_method->PrettyMethod() << " " << dex_file->GetLocation();
334  }
335
336  LineNumberContext context;
337  bool success = dex_file->DecodeDebugPositionInfo(code_item, CollectLineNumbers, &context);
338  if (!success) {
339    return ERR(ABSENT_INFORMATION);
340  }
341
342  unsigned char* data;
343  jlong mem_size = context.size() * sizeof(jvmtiLineNumberEntry);
344  jvmtiError alloc_error = env->Allocate(mem_size, &data);
345  if (alloc_error != ERR(NONE)) {
346    return alloc_error;
347  }
348  *table_ptr = reinterpret_cast<jvmtiLineNumberEntry*>(data);
349  memcpy(*table_ptr, context.data(), mem_size);
350  *entry_count_ptr = static_cast<jint>(context.size());
351
352  return ERR(NONE);
353}
354
355template <typename T>
356static jvmtiError IsMethodT(jvmtiEnv* env ATTRIBUTE_UNUSED,
357                            jmethodID method,
358                            T test,
359                            jboolean* is_t_ptr) {
360  if (method == nullptr) {
361    return ERR(INVALID_METHODID);
362  }
363  if (is_t_ptr == nullptr) {
364    return ERR(NULL_POINTER);
365  }
366
367  art::ArtMethod* art_method = art::jni::DecodeArtMethod(method);
368  *is_t_ptr = test(art_method) ? JNI_TRUE : JNI_FALSE;
369
370  return ERR(NONE);
371}
372
373jvmtiError MethodUtil::IsMethodNative(jvmtiEnv* env, jmethodID m, jboolean* is_native_ptr) {
374  auto test = [](art::ArtMethod* method) {
375    return method->IsNative();
376  };
377  return IsMethodT(env, m, test, is_native_ptr);
378}
379
380jvmtiError MethodUtil::IsMethodObsolete(jvmtiEnv* env, jmethodID m, jboolean* is_obsolete_ptr) {
381  auto test = [](art::ArtMethod* method) {
382    return method->IsObsolete();
383  };
384  return IsMethodT(env, m, test, is_obsolete_ptr);
385}
386
387jvmtiError MethodUtil::IsMethodSynthetic(jvmtiEnv* env, jmethodID m, jboolean* is_synthetic_ptr) {
388  auto test = [](art::ArtMethod* method) {
389    return method->IsSynthetic();
390  };
391  return IsMethodT(env, m, test, is_synthetic_ptr);
392}
393
394}  // namespace openjdkjvmti
395