1 /*
2  * Copyright (C) 2020 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 "dalvik_system_DexFile.h"
18 
19 #include <memory>
20 
21 #include "class_loader_context.h"
22 #include "native_util.h"
23 #include "nativehelper/jni_macros.h"
24 #include "well_known_classes.h"
25 
26 namespace art {
27 
append_string(JNIEnv * env,jobjectArray array,uint32_t & i,const std::string & string)28 static bool append_string(JNIEnv* env, jobjectArray array, uint32_t& i, const std::string& string) {
29   ScopedLocalRef<jstring> jstring(env, env->NewStringUTF(string.c_str()));
30   if (jstring.get() == nullptr) {
31     DCHECK(env->ExceptionCheck());
32     return false;
33   }
34   env->SetObjectArrayElement(array, i++, jstring.get());
35   return true;
36 }
37 
BaseDexClassLoader_computeClassLoaderContextsNative(JNIEnv * env,jobject class_loader)38 static jobjectArray BaseDexClassLoader_computeClassLoaderContextsNative(JNIEnv* env,
39                                                                         jobject class_loader) {
40   CHECK(class_loader != nullptr);
41   std::map<std::string, std::string> contextMap =
42       ClassLoaderContext::EncodeClassPathContextsForClassLoader(class_loader);
43   jobjectArray result = env->NewObjectArray(2 * contextMap.size(),
44                                             WellKnownClasses::java_lang_String,
45                                             nullptr);
46   if (result == nullptr) {
47     DCHECK(env->ExceptionCheck());
48     return nullptr;
49   }
50   uint32_t i = 0;
51   for (const auto& classpath_to_context : contextMap) {
52     const std::string& classpath = classpath_to_context.first;
53     const std::string& context = classpath_to_context.second;
54     if (!append_string(env, result, i, classpath) || !append_string(env, result, i, context)) {
55       return nullptr;
56     }
57   }
58   return result;
59 }
60 
61 static JNINativeMethod gMethods[] = {
62   NATIVE_METHOD(BaseDexClassLoader, computeClassLoaderContextsNative,
63                 "()[Ljava/lang/String;"),
64 };
65 
register_dalvik_system_BaseDexClassLoader(JNIEnv * env)66 void register_dalvik_system_BaseDexClassLoader(JNIEnv* env) {
67   REGISTER_NATIVE_METHODS("dalvik/system/BaseDexClassLoader");
68 }
69 
70 }  // namespace art
71