Coverage Report

Created: 2024-11-21 16:04

/root/doris/be/src/util/jni-util.cpp
Line
Count
Source (jump to first uncovered line)
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "util/jni-util.h"
19
20
#include <fmt/format.h>
21
#include <glog/logging.h>
22
#include <jni.h>
23
#include <jni_md.h>
24
25
#include <algorithm>
26
#include <cstdlib>
27
#include <filesystem>
28
#include <iterator>
29
#include <memory>
30
#include <mutex>
31
#include <sstream>
32
#include <string>
33
#include <vector>
34
35
#include "gutil/strings/substitute.h"
36
#include "util/doris_metrics.h"
37
#include "util/jni_native_method.h"
38
#include "util/libjvm_loader.h"
39
40
using std::string;
41
42
namespace doris {
43
44
namespace {
45
JavaVM* g_vm;
46
[[maybe_unused]] std::once_flag g_vm_once;
47
48
0
const std::string GetDorisJNIDefaultClasspath() {
49
0
    const auto* doris_home = getenv("DORIS_HOME");
50
0
    DCHECK(doris_home) << "Environment variable DORIS_HOME is not set.";
51
52
0
    std::ostringstream out;
53
54
0
    auto add_jars_from_path = [&](const std::string& base_path) {
55
0
        if (!std::filesystem::exists(base_path)) {
56
0
            return;
57
0
        }
58
0
        for (const auto& entry : std::filesystem::recursive_directory_iterator(base_path)) {
59
0
            if (entry.path().extension() == ".jar") {
60
0
                if (!out.str().empty()) {
61
0
                    out << ":";
62
0
                }
63
0
                out << entry.path().string();
64
0
            }
65
0
        }
66
0
    };
67
68
0
    add_jars_from_path(std::string(doris_home) + "/lib");
69
0
    add_jars_from_path(std::string(doris_home) + "/custom_lib");
70
71
    // Check and add HADOOP_CONF_DIR if it's set
72
0
    const auto* hadoop_conf_dir = getenv("HADOOP_CONF_DIR");
73
0
    if (hadoop_conf_dir != nullptr && strlen(hadoop_conf_dir) > 0) {
74
0
        if (!out.str().empty()) {
75
0
            out << ":";
76
0
        }
77
0
        out << hadoop_conf_dir;
78
0
    }
79
80
0
    DCHECK(!out.str().empty()) << "Empty classpath is invalid.";
81
0
    return out.str();
82
0
}
83
84
0
const std::string GetDorisJNIClasspathOption() {
85
0
    const auto* classpath = getenv("DORIS_CLASSPATH");
86
0
    if (classpath) {
87
0
        return classpath;
88
0
    } else {
89
0
        return "-Djava.class.path=" + GetDorisJNIDefaultClasspath();
90
0
    }
91
0
}
92
93
0
[[maybe_unused]] void SetEnvIfNecessary() {
94
0
    const auto* doris_home = getenv("DORIS_HOME");
95
0
    DCHECK(doris_home) << "Environment variable DORIS_HOME is not set.";
96
97
    // CLASSPATH
98
0
    const std::string original_classpath = getenv("CLASSPATH") ? getenv("CLASSPATH") : "";
99
0
    static const std::string classpath = fmt::format(
100
0
            "{}/conf:{}:{}", doris_home, GetDorisJNIDefaultClasspath(), original_classpath);
101
0
    setenv("CLASSPATH", classpath.c_str(), 0);
102
103
    // LIBHDFS_OPTS
104
0
    const std::string java_opts = getenv("JAVA_OPTS") ? getenv("JAVA_OPTS") : "";
105
0
    std::string libhdfs_opts =
106
0
            fmt::format("{} -Djava.library.path={}/lib/hadoop_hdfs/native:{}", java_opts,
107
0
                        getenv("DORIS_HOME"), getenv("DORIS_HOME") + std::string("/lib"));
108
109
0
    setenv("LIBHDFS_OPTS", libhdfs_opts.c_str(), 0);
110
0
}
111
112
// Only used on non-x86 platform
113
0
[[maybe_unused]] void FindOrCreateJavaVM() {
114
0
    int num_vms;
115
0
    int rv = JNI_GetCreatedJavaVMs(&g_vm, 1, &num_vms);
116
0
    if (rv == 0) {
117
0
        std::vector<std::string> options;
118
0
119
0
        char* java_opts = getenv("JAVA_OPTS");
120
0
        if (java_opts == nullptr) {
121
0
            options = {
122
0
                    GetDorisJNIClasspathOption(), fmt::format("-Xmx{}", "1g"),
123
0
                    fmt::format("-DlogPath={}/log/jni.log", getenv("DORIS_HOME")),
124
0
                    fmt::format("-Dsun.java.command={}", "DorisBE"), "-XX:-CriticalJNINatives",
125
0
#ifdef __APPLE__
126
0
                    // On macOS, we should disable MaxFDLimit, otherwise the RLIMIT_NOFILE
127
0
                    // will be assigned the minimum of OPEN_MAX (10240) and rlim_cur (See src/hotspot/os/bsd/os_bsd.cpp)
128
0
                    // and it can not pass the check performed by storage engine.
129
0
                    // The newer JDK has fixed this issue.
130
0
                    "-XX:-MaxFDLimit"
131
0
#endif
132
0
            };
133
0
        } else {
134
0
            std::istringstream stream(java_opts);
135
0
            options = std::vector<std::string>(std::istream_iterator<std::string> {stream},
136
0
                                               std::istream_iterator<std::string>());
137
0
            options.push_back(GetDorisJNIClasspathOption());
138
0
        }
139
0
        std::unique_ptr<JavaVMOption[]> jvm_options(new JavaVMOption[options.size()]);
140
0
        for (int i = 0; i < options.size(); ++i) {
141
0
            jvm_options[i] = {const_cast<char*>(options[i].c_str()), nullptr};
142
0
        }
143
0
144
0
        JNIEnv* env = nullptr;
145
0
        JavaVMInitArgs vm_args;
146
0
        vm_args.version = JNI_VERSION_1_8;
147
0
        vm_args.options = jvm_options.get();
148
0
        vm_args.nOptions = options.size();
149
0
        // Set it to JNI_FALSE because JNI_TRUE will let JVM ignore the max size config.
150
0
        vm_args.ignoreUnrecognized = JNI_FALSE;
151
0
152
0
        jint res = JNI_CreateJavaVM(&g_vm, (void**)&env, &vm_args);
153
0
        if (JNI_OK != res) {
154
0
            DCHECK(false) << "Failed to create JVM, code= " << res;
155
0
        }
156
0
    } else {
157
0
        CHECK_EQ(rv, 0) << "Could not find any created Java VM";
158
0
        CHECK_EQ(num_vms, 1) << "No VMs returned";
159
0
    }
160
0
}
161
162
} // anonymous namespace
163
164
bool JniUtil::jvm_inited_ = false;
165
__thread JNIEnv* JniUtil::tls_env_ = nullptr;
166
jclass JniUtil::internal_exc_cl_ = nullptr;
167
jclass JniUtil::jni_util_cl_ = nullptr;
168
jclass JniUtil::jni_native_method_exc_cl_ = nullptr;
169
jmethodID JniUtil::throwable_to_string_id_ = nullptr;
170
jmethodID JniUtil::throwable_to_stack_trace_id_ = nullptr;
171
jmethodID JniUtil::get_jvm_metrics_id_ = nullptr;
172
jmethodID JniUtil::get_jvm_threads_id_ = nullptr;
173
jmethodID JniUtil::get_jmx_json_ = nullptr;
174
jobject JniUtil::jni_scanner_loader_obj_ = nullptr;
175
jmethodID JniUtil::jni_scanner_loader_method_ = nullptr;
176
177
0
Status JniUtfCharGuard::create(JNIEnv* env, jstring jstr, JniUtfCharGuard* out) {
178
0
    DCHECK(jstr != nullptr);
179
0
    DCHECK(!env->ExceptionCheck());
180
0
    jboolean is_copy;
181
0
    const char* utf_chars = env->GetStringUTFChars(jstr, &is_copy);
182
0
    bool exception_check = static_cast<bool>(env->ExceptionCheck());
183
0
    if (utf_chars == nullptr || exception_check) {
184
0
        if (exception_check) env->ExceptionClear();
185
0
        if (utf_chars != nullptr) env->ReleaseStringUTFChars(jstr, utf_chars);
186
0
        auto fail_message = "GetStringUTFChars failed. Probable OOM on JVM side";
187
0
        LOG(WARNING) << fail_message;
188
0
        return Status::InternalError(fail_message);
189
0
    }
190
0
    out->env = env;
191
0
    out->jstr = jstr;
192
0
    out->utf_chars = utf_chars;
193
0
    return Status::OK();
194
0
}
195
196
0
Status JniLocalFrame::push(JNIEnv* env, int max_local_ref) {
197
0
    DCHECK(env_ == nullptr);
198
0
    DCHECK_GT(max_local_ref, 0);
199
0
    if (env->PushLocalFrame(max_local_ref) < 0) {
200
0
        env->ExceptionClear();
201
0
        return Status::InternalError("failed to push frame");
202
0
    }
203
0
    env_ = env;
204
0
    return Status::OK();
205
0
}
206
207
0
Status JniUtil::GetJNIEnvSlowPath(JNIEnv** env) {
208
0
    DCHECK(!tls_env_) << "Call GetJNIEnv() fast path";
209
210
#ifdef USE_LIBHDFS3
211
    std::call_once(g_vm_once, FindOrCreateJavaVM);
212
    int rc = g_vm->GetEnv(reinterpret_cast<void**>(&tls_env_), JNI_VERSION_1_8);
213
    if (rc == JNI_EDETACHED) {
214
        rc = g_vm->AttachCurrentThread((void**)&tls_env_, nullptr);
215
    }
216
    if (rc != 0 || tls_env_ == nullptr) {
217
        return Status::InternalError("Unable to get JVM: {}", rc);
218
    }
219
#else
220
    // the hadoop libhdfs will do all the stuff
221
0
    SetEnvIfNecessary();
222
0
    tls_env_ = getJNIEnv();
223
0
#endif
224
0
    *env = tls_env_;
225
0
    return Status::OK();
226
0
}
227
228
0
Status JniUtil::GetJniExceptionMsg(JNIEnv* env, bool log_stack, const string& prefix) {
229
0
    jthrowable exc = env->ExceptionOccurred();
230
0
    if (exc == nullptr) {
231
0
        return Status::OK();
232
0
    }
233
0
    env->ExceptionClear();
234
0
    DCHECK(throwable_to_string_id() != nullptr);
235
0
    const char* oom_msg_template =
236
0
            "$0 threw an unchecked exception. The JVM is likely out "
237
0
            "of memory (OOM).";
238
0
    jstring msg = static_cast<jstring>(
239
0
            env->CallStaticObjectMethod(jni_util_class(), throwable_to_string_id(), exc));
240
0
    if (env->ExceptionOccurred()) {
241
0
        env->ExceptionClear();
242
0
        string oom_msg = strings::Substitute(oom_msg_template, "throwableToString");
243
0
        LOG(WARNING) << oom_msg;
244
0
        return Status::InternalError(oom_msg);
245
0
    }
246
0
    JniUtfCharGuard msg_str_guard;
247
0
    RETURN_IF_ERROR(JniUtfCharGuard::create(env, msg, &msg_str_guard));
248
0
    if (log_stack) {
249
0
        jstring stack = static_cast<jstring>(
250
0
                env->CallStaticObjectMethod(jni_util_class(), throwable_to_stack_trace_id(), exc));
251
0
        if (env->ExceptionOccurred()) {
252
0
            env->ExceptionClear();
253
0
            string oom_msg = strings::Substitute(oom_msg_template, "throwableToStackTrace");
254
0
            LOG(WARNING) << oom_msg;
255
0
            return Status::InternalError(oom_msg);
256
0
        }
257
0
        JniUtfCharGuard c_stack_guard;
258
0
        RETURN_IF_ERROR(JniUtfCharGuard::create(env, stack, &c_stack_guard));
259
0
        LOG(WARNING) << c_stack_guard.get();
260
0
    }
261
262
0
    env->DeleteLocalRef(exc);
263
0
    return Status::InternalError("{}{}", prefix, msg_str_guard.get());
264
0
}
265
266
0
jobject JniUtil::convert_to_java_map(JNIEnv* env, const std::map<std::string, std::string>& map) {
267
    //TODO: ADD EXCEPTION CHECK.
268
0
    jclass hashmap_class = env->FindClass("java/util/HashMap");
269
0
    jmethodID hashmap_constructor = env->GetMethodID(hashmap_class, "<init>", "(I)V");
270
0
    jobject hashmap_object = env->NewObject(hashmap_class, hashmap_constructor, map.size());
271
0
    jmethodID hashmap_put = env->GetMethodID(
272
0
            hashmap_class, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
273
0
    for (const auto& it : map) {
274
0
        jstring key = env->NewStringUTF(it.first.c_str());
275
0
        jstring value = env->NewStringUTF(it.second.c_str());
276
0
        env->CallObjectMethod(hashmap_object, hashmap_put, key, value);
277
0
        env->DeleteLocalRef(key);
278
0
        env->DeleteLocalRef(value);
279
0
    }
280
0
    env->DeleteLocalRef(hashmap_class);
281
0
    return hashmap_object;
282
0
}
283
284
0
std::map<std::string, std::string> JniUtil::convert_to_cpp_map(JNIEnv* env, jobject map) {
285
0
    std::map<std::string, std::string> resultMap;
286
287
    // Get the class and method ID of the java.util.Map interface
288
0
    jclass mapClass = env->FindClass("java/util/Map");
289
0
    jmethodID entrySetMethod = env->GetMethodID(mapClass, "entrySet", "()Ljava/util/Set;");
290
291
    // Get the class and method ID of the java.util.Set interface
292
0
    jclass setClass = env->FindClass("java/util/Set");
293
0
    jmethodID iteratorSetMethod = env->GetMethodID(setClass, "iterator", "()Ljava/util/Iterator;");
294
295
    // Get the class and method ID of the java.util.Iterator interface
296
0
    jclass iteratorClass = env->FindClass("java/util/Iterator");
297
0
    jmethodID hasNextMethod = env->GetMethodID(iteratorClass, "hasNext", "()Z");
298
0
    jmethodID nextMethod = env->GetMethodID(iteratorClass, "next", "()Ljava/lang/Object;");
299
300
    // Get the class and method ID of the java.util.Map.Entry interface
301
0
    jclass entryClass = env->FindClass("java/util/Map$Entry");
302
0
    jmethodID getKeyMethod = env->GetMethodID(entryClass, "getKey", "()Ljava/lang/Object;");
303
0
    jmethodID getValueMethod = env->GetMethodID(entryClass, "getValue", "()Ljava/lang/Object;");
304
305
    // Call the entrySet method to get the set of key-value pairs
306
0
    jobject entrySet = env->CallObjectMethod(map, entrySetMethod);
307
308
    // Call the iterator method on the set to iterate over the key-value pairs
309
0
    jobject iteratorSet = env->CallObjectMethod(entrySet, iteratorSetMethod);
310
311
    // Iterate over the key-value pairs
312
0
    while (env->CallBooleanMethod(iteratorSet, hasNextMethod)) {
313
        // Get the current entry
314
0
        jobject entry = env->CallObjectMethod(iteratorSet, nextMethod);
315
316
        // Get the key and value from the entry
317
0
        jobject javaKey = env->CallObjectMethod(entry, getKeyMethod);
318
0
        jobject javaValue = env->CallObjectMethod(entry, getValueMethod);
319
320
        // Convert the key and value to C++ strings
321
0
        const char* key = env->GetStringUTFChars(static_cast<jstring>(javaKey), nullptr);
322
0
        const char* value = env->GetStringUTFChars(static_cast<jstring>(javaValue), nullptr);
323
324
        // Store the key-value pair in the map
325
0
        resultMap[key] = value;
326
327
        // Release the string references
328
0
        env->ReleaseStringUTFChars(static_cast<jstring>(javaKey), key);
329
0
        env->ReleaseStringUTFChars(static_cast<jstring>(javaValue), value);
330
331
        // Delete local references
332
0
        env->DeleteLocalRef(entry);
333
0
        env->DeleteLocalRef(javaKey);
334
0
        env->DeleteLocalRef(javaValue);
335
0
    }
336
337
    // Delete local references
338
0
    env->DeleteLocalRef(iteratorSet);
339
0
    env->DeleteLocalRef(entrySet);
340
0
    env->DeleteLocalRef(mapClass);
341
0
    env->DeleteLocalRef(setClass);
342
0
    env->DeleteLocalRef(iteratorClass);
343
0
    env->DeleteLocalRef(entryClass);
344
345
0
    return resultMap;
346
0
}
347
348
0
Status JniUtil::GetGlobalClassRef(JNIEnv* env, const char* class_str, jclass* class_ref) {
349
0
    *class_ref = NULL;
350
0
    JNI_CALL_METHOD_CHECK_EXCEPTION_DELETE_REF(jclass, local_cl, env, FindClass(class_str));
351
0
    RETURN_IF_ERROR(LocalToGlobalRef(env, local_cl, reinterpret_cast<jobject*>(class_ref)));
352
0
    return Status::OK();
353
0
}
354
355
0
Status JniUtil::LocalToGlobalRef(JNIEnv* env, jobject local_ref, jobject* global_ref) {
356
0
    *global_ref = env->NewGlobalRef(local_ref);
357
    // NewGlobalRef:
358
    // Returns a global reference to the given obj.
359
    //
360
    //May return NULL if:
361
    //  obj refers to null
362
    //  the system has run out of memory
363
    //  obj was a weak global reference and has already been garbage collected
364
0
    if (*global_ref == NULL) {
365
0
        return Status::InternalError(
366
0
                "LocalToGlobalRef fail,global ref is NULL,maybe the system has run out of memory.");
367
0
    }
368
369
    //NewGlobalRef not throw exception,maybe we just need check NULL.
370
0
    RETURN_ERROR_IF_EXC(env);
371
0
    return Status::OK();
372
0
}
373
374
0
Status JniUtil::init_jni_scanner_loader(JNIEnv* env) {
375
    // Get scanner loader;
376
0
    jclass jni_scanner_loader_cls;
377
0
    std::string jni_scanner_loader_str = "org/apache/doris/common/classloader/ScannerLoader";
378
0
    RETURN_IF_ERROR(JniUtil::GetGlobalClassRef(env, jni_scanner_loader_str.c_str(),
379
0
                                               &jni_scanner_loader_cls));
380
0
    jmethodID jni_scanner_loader_constructor =
381
0
            env->GetMethodID(jni_scanner_loader_cls, "<init>", "()V");
382
0
    RETURN_ERROR_IF_EXC(env);
383
0
    jni_scanner_loader_method_ = env->GetMethodID(jni_scanner_loader_cls, "getLoadedClass",
384
0
                                                  "(Ljava/lang/String;)Ljava/lang/Class;");
385
0
    if (jni_scanner_loader_method_ == NULL) {
386
0
        if (env->ExceptionOccurred()) env->ExceptionDescribe();
387
0
        return Status::InternalError("Failed to find ScannerLoader.getLoadedClass method.");
388
0
    }
389
0
    RETURN_ERROR_IF_EXC(env);
390
0
    jmethodID load_jni_scanner =
391
0
            env->GetMethodID(jni_scanner_loader_cls, "loadAllScannerJars", "()V");
392
0
    RETURN_ERROR_IF_EXC(env);
393
394
0
    jni_scanner_loader_obj_ =
395
0
            env->NewObject(jni_scanner_loader_cls, jni_scanner_loader_constructor);
396
0
    RETURN_ERROR_IF_EXC(env);
397
0
    if (jni_scanner_loader_obj_ == NULL) {
398
0
        if (env->ExceptionOccurred()) env->ExceptionDescribe();
399
0
        return Status::InternalError("Failed to create ScannerLoader object.");
400
0
    }
401
0
    env->CallVoidMethod(jni_scanner_loader_obj_, load_jni_scanner);
402
0
    RETURN_ERROR_IF_EXC(env);
403
0
    return Status::OK();
404
0
}
405
406
Status JniUtil::get_jni_scanner_class(JNIEnv* env, const char* classname,
407
0
                                      jclass* jni_scanner_class) {
408
    // Get JNI scanner class by class name;
409
0
    jobject loaded_class_obj = env->CallObjectMethod(
410
0
            jni_scanner_loader_obj_, jni_scanner_loader_method_, env->NewStringUTF(classname));
411
0
    RETURN_ERROR_IF_EXC(env);
412
0
    *jni_scanner_class = reinterpret_cast<jclass>(env->NewGlobalRef(loaded_class_obj));
413
0
    RETURN_ERROR_IF_EXC(env);
414
0
    return Status::OK();
415
0
}
416
417
0
Status JniUtil::Init() {
418
0
    RETURN_IF_ERROR(LibJVMLoader::instance().load());
419
420
    // Get the JNIEnv* corresponding to current thread.
421
0
    JNIEnv* env = nullptr;
422
0
    RETURN_IF_ERROR(JniUtil::GetJNIEnv(&env));
423
424
0
    if (env == NULL) return Status::InternalError("Failed to get/create JVM");
425
    // Find JniUtil class and create a global ref.
426
0
    jclass local_jni_util_cl = env->FindClass("org/apache/doris/common/jni/utils/JniUtil");
427
0
    if (local_jni_util_cl == NULL) {
428
0
        if (env->ExceptionOccurred()) env->ExceptionDescribe();
429
0
        return Status::InternalError("Failed to find JniUtil class.");
430
0
    }
431
0
    jni_util_cl_ = reinterpret_cast<jclass>(env->NewGlobalRef(local_jni_util_cl));
432
0
    if (jni_util_cl_ == NULL) {
433
0
        if (env->ExceptionOccurred()) env->ExceptionDescribe();
434
0
        return Status::InternalError("Failed to create global reference to JniUtil class.");
435
0
    }
436
0
    env->DeleteLocalRef(local_jni_util_cl);
437
0
    if (env->ExceptionOccurred()) {
438
0
        return Status::InternalError("Failed to delete local reference to JniUtil class.");
439
0
    }
440
441
    // Find InternalException class and create a global ref.
442
0
    jclass local_internal_exc_cl =
443
0
            env->FindClass("org/apache/doris/common/exception/InternalException");
444
0
    if (local_internal_exc_cl == NULL) {
445
0
        if (env->ExceptionOccurred()) env->ExceptionDescribe();
446
0
        return Status::InternalError("Failed to find JniUtil class.");
447
0
    }
448
0
    internal_exc_cl_ = reinterpret_cast<jclass>(env->NewGlobalRef(local_internal_exc_cl));
449
0
    if (internal_exc_cl_ == NULL) {
450
0
        if (env->ExceptionOccurred()) env->ExceptionDescribe();
451
0
        return Status::InternalError("Failed to create global reference to JniUtil class.");
452
0
    }
453
0
    env->DeleteLocalRef(local_internal_exc_cl);
454
0
    if (env->ExceptionOccurred()) {
455
0
        return Status::InternalError("Failed to delete local reference to JniUtil class.");
456
0
    }
457
458
    // Find JNINativeMethod class and create a global ref.
459
0
    jclass local_jni_native_exc_cl =
460
0
            env->FindClass("org/apache/doris/common/jni/utils/JNINativeMethod");
461
0
    if (local_jni_native_exc_cl == nullptr) {
462
0
        if (env->ExceptionOccurred()) {
463
0
            env->ExceptionDescribe();
464
0
        }
465
0
        return Status::InternalError("Failed to find JNINativeMethod class.");
466
0
    }
467
0
    jni_native_method_exc_cl_ =
468
0
            reinterpret_cast<jclass>(env->NewGlobalRef(local_jni_native_exc_cl));
469
0
    if (jni_native_method_exc_cl_ == nullptr) {
470
0
        if (env->ExceptionOccurred()) {
471
0
            env->ExceptionDescribe();
472
0
        }
473
0
        return Status::InternalError("Failed to create global reference to JNINativeMethod class.");
474
0
    }
475
0
    env->DeleteLocalRef(local_jni_native_exc_cl);
476
0
    if (env->ExceptionOccurred()) {
477
0
        return Status::InternalError("Failed to delete local reference to JNINativeMethod class.");
478
0
    }
479
0
    std::string resize_column_name = "resizeStringColumn";
480
0
    std::string resize_column_sign = "(JI)J";
481
0
    std::string memory_alloc_name = "memoryTrackerMalloc";
482
0
    std::string memory_alloc_sign = "(J)J";
483
0
    std::string memory_free_name = "memoryTrackerFree";
484
0
    std::string memory_free_sign = "(J)V";
485
0
    static JNINativeMethod java_native_methods[] = {
486
0
            {const_cast<char*>(resize_column_name.c_str()),
487
0
             const_cast<char*>(resize_column_sign.c_str()),
488
0
             (void*)&JavaNativeMethods::resizeStringColumn},
489
0
            {const_cast<char*>(memory_alloc_name.c_str()),
490
0
             const_cast<char*>(memory_alloc_sign.c_str()), (void*)&JavaNativeMethods::memoryMalloc},
491
0
            {const_cast<char*>(memory_free_name.c_str()),
492
0
             const_cast<char*>(memory_free_sign.c_str()), (void*)&JavaNativeMethods::memoryFree},
493
0
    };
494
495
0
    int res = env->RegisterNatives(jni_native_method_exc_cl_, java_native_methods,
496
0
                                   sizeof(java_native_methods) / sizeof(java_native_methods[0]));
497
0
    DCHECK_EQ(res, 0);
498
499
    // Throwable toString()
500
0
    throwable_to_string_id_ = env->GetStaticMethodID(jni_util_cl_, "throwableToString",
501
0
                                                     "(Ljava/lang/Throwable;)Ljava/lang/String;");
502
0
    if (throwable_to_string_id_ == NULL) {
503
0
        if (env->ExceptionOccurred()) env->ExceptionDescribe();
504
0
        return Status::InternalError("Failed to find JniUtil.throwableToString method.");
505
0
    }
506
507
    // throwableToStackTrace()
508
0
    throwable_to_stack_trace_id_ = env->GetStaticMethodID(
509
0
            jni_util_cl_, "throwableToStackTrace", "(Ljava/lang/Throwable;)Ljava/lang/String;");
510
0
    if (throwable_to_stack_trace_id_ == NULL) {
511
0
        if (env->ExceptionOccurred()) env->ExceptionDescribe();
512
0
        return Status::InternalError("Failed to find JniUtil.throwableToFullStackTrace method.");
513
0
    }
514
515
0
    get_jvm_metrics_id_ = env->GetStaticMethodID(jni_util_cl_, "getJvmMemoryMetrics", "()[B");
516
0
    if (get_jvm_metrics_id_ == NULL) {
517
0
        if (env->ExceptionOccurred()) env->ExceptionDescribe();
518
0
        return Status::InternalError("Failed to find JniUtil.getJvmMemoryMetrics method.");
519
0
    }
520
521
0
    get_jvm_threads_id_ = env->GetStaticMethodID(jni_util_cl_, "getJvmThreadsInfo", "([B)[B");
522
0
    if (get_jvm_threads_id_ == NULL) {
523
0
        if (env->ExceptionOccurred()) env->ExceptionDescribe();
524
0
        return Status::InternalError("Failed to find JniUtil.getJvmThreadsInfo method.");
525
0
    }
526
527
0
    get_jmx_json_ = env->GetStaticMethodID(jni_util_cl_, "getJMXJson", "()[B");
528
0
    if (get_jmx_json_ == NULL) {
529
0
        if (env->ExceptionOccurred()) env->ExceptionDescribe();
530
0
        return Status::InternalError("Failed to find JniUtil.getJMXJson method.");
531
0
    }
532
0
    RETURN_IF_ERROR(init_jni_scanner_loader(env));
533
0
    jvm_inited_ = true;
534
0
    DorisMetrics::instance()->init_jvm_metrics(env);
535
0
    return Status::OK();
536
0
}
537
538
} // namespace doris