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