get_loaded_classes.cc revision e657424ab0105227358422452f566c3e72a77c8b
1/*
2 * Copyright (C) 2013 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#include "get_loaded_classes.h"
18
19#include <iostream>
20#include <pthread.h>
21#include <stdio.h>
22#include <vector>
23
24#include "base/macros.h"
25#include "jni.h"
26#include "openjdkjvmti/jvmti.h"
27#include "ScopedLocalRef.h"
28#include "ScopedUtfChars.h"
29
30#include "ti-agent/common_helper.h"
31#include "ti-agent/common_load.h"
32
33namespace art {
34namespace Test907GetLoadedClasses {
35
36static jstring GetClassName(JNIEnv* jni_env, jclass cls) {
37  ScopedLocalRef<jclass> class_class(jni_env, jni_env->GetObjectClass(cls));
38  jmethodID mid = jni_env->GetMethodID(class_class.get(), "getName", "()Ljava/lang/String;");
39  return reinterpret_cast<jstring>(jni_env->CallObjectMethod(cls, mid));
40}
41
42extern "C" JNIEXPORT jobjectArray JNICALL Java_Main_getLoadedClasses(
43    JNIEnv* env, jclass klass ATTRIBUTE_UNUSED) {
44  jint count = -1;
45  jclass* classes = nullptr;
46  jvmtiError result = jvmti_env->GetLoadedClasses(&count, &classes);
47  if (result != JVMTI_ERROR_NONE) {
48    char* err;
49    jvmti_env->GetErrorName(result, &err);
50    printf("Failure running GetLoadedClasses: %s\n", err);
51    return nullptr;
52  }
53
54  auto callback = [&](jint i) {
55    jstring class_name = GetClassName(env, classes[i]);
56    env->DeleteLocalRef(classes[i]);
57    return class_name;
58  };
59  jobjectArray ret = CreateObjectArray(env, count, "java/lang/String", callback);
60
61  // Need to Deallocate.
62  jvmti_env->Deallocate(reinterpret_cast<unsigned char*>(classes));
63
64  return ret;
65}
66
67// Don't do anything
68jint OnLoad(JavaVM* vm,
69            char* options ATTRIBUTE_UNUSED,
70            void* reserved ATTRIBUTE_UNUSED) {
71  if (vm->GetEnv(reinterpret_cast<void**>(&jvmti_env), JVMTI_VERSION_1_0)) {
72    printf("Unable to get jvmti env!\n");
73    return 1;
74  }
75  SetAllCapabilities(jvmti_env);
76  return 0;
77}
78
79}  // namespace Test907GetLoadedClasses
80}  // namespace art
81