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 #include "909-attach-agent/attach.h" 18 19 #include <jni.h> 20 #include <stdio.h> 21 #include <string.h> 22 23 #include "android-base/macros.h" 24 25 #include "jvmti.h" 26 27 namespace art { 28 namespace Test909AttachAgent { 29 30 static void Println(const char* c) { 31 fprintf(stdout, "%s\n", c); 32 fflush(stdout); 33 } 34 35 jint OnAttach(JavaVM* vm, 36 char* options ATTRIBUTE_UNUSED, 37 void* reserved ATTRIBUTE_UNUSED) { 38 Println("Attached Agent for test 909-attach-agent"); 39 jvmtiEnv* env = nullptr; 40 jvmtiEnv* env2 = nullptr; 41 42 #define CHECK_CALL_SUCCESS(c) \ 43 do { \ 44 if ((c) != JNI_OK) { \ 45 Println("call " #c " did not succeed"); \ 46 return -1; \ 47 } \ 48 } while (false) 49 50 CHECK_CALL_SUCCESS(vm->GetEnv(reinterpret_cast<void**>(&env), JVMTI_VERSION_1_0)); 51 CHECK_CALL_SUCCESS(vm->GetEnv(reinterpret_cast<void**>(&env2), JVMTI_VERSION_1_0)); 52 if (env == env2) { 53 Println("GetEnv returned same environment twice!"); 54 return -1; 55 } 56 unsigned char* local_data = nullptr; 57 CHECK_CALL_SUCCESS(env->Allocate(8, &local_data)); 58 strcpy(reinterpret_cast<char*>(local_data), "hello!!"); 59 CHECK_CALL_SUCCESS(env->SetEnvironmentLocalStorage(local_data)); 60 unsigned char* get_data = nullptr; 61 CHECK_CALL_SUCCESS(env->GetEnvironmentLocalStorage(reinterpret_cast<void**>(&get_data))); 62 if (get_data != local_data) { 63 Println("Got different data from local storage then what was set!"); 64 return -1; 65 } 66 CHECK_CALL_SUCCESS(env2->GetEnvironmentLocalStorage(reinterpret_cast<void**>(&get_data))); 67 if (get_data != nullptr) { 68 Println("env2 did not have nullptr local storage."); 69 return -1; 70 } 71 CHECK_CALL_SUCCESS(env->Deallocate(local_data)); 72 jint version = 0; 73 CHECK_CALL_SUCCESS(env->GetVersionNumber(&version)); 74 if ((version & JVMTI_VERSION_1) != JVMTI_VERSION_1) { 75 Println("Unexpected version number!"); 76 return -1; 77 } 78 CHECK_CALL_SUCCESS(env->DisposeEnvironment()); 79 CHECK_CALL_SUCCESS(env2->DisposeEnvironment()); 80 #undef CHECK_CALL_SUCCESS 81 return JNI_OK; 82 } 83 84 } // namespace Test909AttachAgent 85 } // namespace art 86