1 /*
 2  * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.
 3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 4  *
 5  * This code is free software; you can redistribute it and/or modify it
 6  * under the terms of the GNU General Public License version 2 only, as
 7  * published by the Free Software Foundation.
 8  *
 9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  */
23 
24 #include <stdio.h>
25 #include "jvmti.h"
26 #include "jvmti_common.h"
27 
28 extern "C" {
29 
30 static jvmtiEnv *jvmti_env = NULL;
31 
32 jint Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) {
33   jvmtiCapabilities caps;
34   jint res;
35 
36   res = jvm->GetEnv((void **) &jvmti_env, JVMTI_VERSION_1_1);
37   if (res != JNI_OK || jvmti_env == NULL) {
38     LOG("Wrong result of a valid call to GetEnv!\n");
39     return JNI_ERR;
40   }
41 
42   memset(&caps, 0, sizeof(caps));
43   caps.can_support_virtual_threads = true;
44   caps.can_suspend = true;
45 
46   jvmtiError err = jvmti_env->AddCapabilities(&caps);
47   if (err != JVMTI_ERROR_NONE) {
48    LOG("(AddCapabilities) unexpected error: %s (%d)\n",
49            TranslateError(err), err);
50     return JNI_ERR;
51   }
52 
53   return JNI_OK;
54 }
55 
56 JNIEXPORT jboolean JNICALL Java_framecnt01_checkFrames0(JNIEnv *jni, jclass cls, jthread thread,
57                                                         jboolean suspend, jint expected_count) {
58   jboolean result = JNI_TRUE;
59 
60   if (suspend) {
61     suspend_thread(jvmti_env, jni, thread);
62   }
63 
64   LOG("Testing:\n");
65   print_stack_trace(jvmti_env, jni, thread);
66   jint frame_count = get_frame_count(jvmti_env, jni, thread);
67   if (frame_count != expected_count) {
68     LOG("Thread #%s: number of frames expected: %d, got: %d\n",
69         get_thread_name(jvmti_env, jni, thread), expected_count, frame_count);
70     result = JNI_FALSE;
71     print_stack_trace(jvmti_env, jni, thread); // DBG: print stack trace once more
72   }
73 
74   if (suspend) {
75     resume_thread(jvmti_env, jni, thread);
76   }
77 
78   return result;
79 }
80 
81 }