native_loader.cpp revision 24db75c1ce7ff8376a475214b059b9a37ac07936
1/*
2 * Copyright (C) 2015 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 "nativeloader/native_loader.h"
18#include "ScopedUtfChars.h"
19
20#include <dlfcn.h>
21#ifdef __ANDROID__
22#include "dlext_namespaces.h"
23#include "cutils/properties.h"
24#include "log/log.h"
25#endif
26
27#include <algorithm>
28#include <vector>
29#include <string>
30#include <mutex>
31
32#include "android-base/file.h"
33#include "android-base/macros.h"
34#include "android-base/strings.h"
35
36namespace android {
37
38#if defined(__ANDROID__)
39static constexpr const char* kPublicNativeLibrariesSystemConfigPathFromRoot = "/etc/public.libraries.txt";
40static constexpr const char* kPublicNativeLibrariesVendorConfig = "/vendor/etc/public.libraries.txt";
41
42// (http://b/27588281) This is a workaround for apps using custom classloaders and calling
43// System.load() with an absolute path which is outside of the classloader library search path.
44// This list includes all directories app is allowed to access this way.
45static constexpr const char* kWhitelistedDirectories = "/data:/mnt/expand";
46
47static bool is_debuggable() {
48  char debuggable[PROP_VALUE_MAX];
49  property_get("ro.debuggable", debuggable, "0");
50  return std::string(debuggable) == "1";
51}
52
53class LibraryNamespaces {
54 public:
55  LibraryNamespaces() : initialized_(false) { }
56
57  android_namespace_t* Create(JNIEnv* env,
58                              jobject class_loader,
59                              bool is_shared,
60                              jstring java_library_path,
61                              jstring java_permitted_path) {
62    std::string library_path; // empty string by default.
63
64    if (java_library_path != nullptr) {
65      ScopedUtfChars library_path_utf_chars(env, java_library_path);
66      library_path = library_path_utf_chars.c_str();
67    }
68
69    // (http://b/27588281) This is a workaround for apps using custom
70    // classloaders and calling System.load() with an absolute path which
71    // is outside of the classloader library search path.
72    //
73    // This part effectively allows such a classloader to access anything
74    // under /data and /mnt/expand
75    std::string permitted_path = kWhitelistedDirectories;
76
77    if (java_permitted_path != nullptr) {
78      ScopedUtfChars path(env, java_permitted_path);
79      if (path.c_str() != nullptr && path.size() > 0) {
80        permitted_path = permitted_path + ":" + path.c_str();
81      }
82    }
83
84    if (!initialized_ && !InitPublicNamespace(library_path.c_str())) {
85      return nullptr;
86    }
87
88    android_namespace_t* ns = FindNamespaceByClassLoader(env, class_loader);
89
90    LOG_ALWAYS_FATAL_IF(ns != nullptr,
91                        "There is already a namespace associated with this classloader");
92
93    uint64_t namespace_type = ANDROID_NAMESPACE_TYPE_ISOLATED;
94    if (is_shared) {
95      namespace_type |= ANDROID_NAMESPACE_TYPE_SHARED;
96    }
97
98    android_namespace_t* parent_ns = FindParentNamespaceByClassLoader(env, class_loader);
99
100    ns = android_create_namespace("classloader-namespace",
101                                  nullptr,
102                                  library_path.c_str(),
103                                  namespace_type,
104                                  permitted_path.c_str(),
105                                  parent_ns);
106
107    if (ns != nullptr) {
108      namespaces_.push_back(std::make_pair(env->NewWeakGlobalRef(class_loader), ns));
109    }
110
111    return ns;
112  }
113
114  android_namespace_t* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
115    auto it = std::find_if(namespaces_.begin(), namespaces_.end(),
116                [&](const std::pair<jweak, android_namespace_t*>& value) {
117                  return env->IsSameObject(value.first, class_loader);
118                });
119    return it != namespaces_.end() ? it->second : nullptr;
120  }
121
122  void Initialize() {
123    // Once public namespace is initialized there is no
124    // point in running this code - it will have no effect
125    // on the current list of public libraries.
126    if (initialized_) {
127      return;
128    }
129
130    std::vector<std::string> sonames;
131    const char* android_root_env = getenv("ANDROID_ROOT");
132    std::string root_dir = android_root_env != nullptr ? android_root_env : "/system";
133    std::string public_native_libraries_system_config =
134            root_dir + kPublicNativeLibrariesSystemConfigPathFromRoot;
135
136    LOG_ALWAYS_FATAL_IF(!ReadConfig(public_native_libraries_system_config, &sonames),
137                        "Error reading public native library list from \"%s\": %s",
138                        public_native_libraries_system_config.c_str(), strerror(errno));
139
140    // For debuggable platform builds use ANDROID_ADDITIONAL_PUBLIC_LIBRARIES environment
141    // variable to add libraries to the list. This is intended for platform tests only.
142    if (is_debuggable()) {
143      const char* additional_libs = getenv("ANDROID_ADDITIONAL_PUBLIC_LIBRARIES");
144      if (additional_libs != nullptr && additional_libs[0] != '\0') {
145        std::vector<std::string> additional_libs_vector = base::Split(additional_libs, ":");
146        std::copy(additional_libs_vector.begin(),
147                  additional_libs_vector.end(),
148                  std::back_inserter(sonames));
149      }
150    }
151
152    // This file is optional, quietly ignore if the file does not exist.
153    ReadConfig(kPublicNativeLibrariesVendorConfig, &sonames);
154
155    // android_init_namespaces() expects all the public libraries
156    // to be loaded so that they can be found by soname alone.
157    //
158    // TODO(dimitry): this is a bit misleading since we do not know
159    // if the vendor public library is going to be opened from /vendor/lib
160    // we might as well end up loading them from /system/lib
161    // For now we rely on CTS test to catch things like this but
162    // it should probably be addressed in the future.
163    for (const auto& soname : sonames) {
164      dlopen(soname.c_str(), RTLD_NOW | RTLD_NODELETE);
165    }
166
167    public_libraries_ = base::Join(sonames, ':');
168  }
169
170  void Reset() {
171    namespaces_.clear();
172  }
173
174 private:
175  bool ReadConfig(const std::string& configFile, std::vector<std::string>* sonames) {
176    // Read list of public native libraries from the config file.
177    std::string file_content;
178    if(!base::ReadFileToString(configFile, &file_content)) {
179      return false;
180    }
181
182    std::vector<std::string> lines = base::Split(file_content, "\n");
183
184    for (const auto& line : lines) {
185      auto trimmed_line = base::Trim(line);
186      if (trimmed_line[0] == '#' || trimmed_line.empty()) {
187        continue;
188      }
189
190      sonames->push_back(trimmed_line);
191    }
192
193    return true;
194  }
195
196  bool InitPublicNamespace(const char* library_path) {
197    // (http://b/25844435) - Some apps call dlopen from generated code (mono jited
198    // code is one example) unknown to linker in which  case linker uses anonymous
199    // namespace. The second argument specifies the search path for the anonymous
200    // namespace which is the library_path of the classloader.
201    initialized_ = android_init_namespaces(public_libraries_.c_str(), library_path);
202
203    return initialized_;
204  }
205
206  jobject GetParentClassLoader(JNIEnv* env, jobject class_loader) {
207    jclass class_loader_class = env->FindClass("java/lang/ClassLoader");
208    jmethodID get_parent = env->GetMethodID(class_loader_class,
209                                            "getParent",
210                                            "()Ljava/lang/ClassLoader;");
211
212    return env->CallObjectMethod(class_loader, get_parent);
213  }
214
215  android_namespace_t* FindParentNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
216    jobject parent_class_loader = GetParentClassLoader(env, class_loader);
217
218    while (parent_class_loader != nullptr) {
219      android_namespace_t* ns = FindNamespaceByClassLoader(env, parent_class_loader);
220      if (ns != nullptr) {
221        return ns;
222      }
223
224      parent_class_loader = GetParentClassLoader(env, parent_class_loader);
225    }
226    return nullptr;
227  }
228
229  bool initialized_;
230  std::vector<std::pair<jweak, android_namespace_t*>> namespaces_;
231  std::string public_libraries_;
232
233
234  DISALLOW_COPY_AND_ASSIGN(LibraryNamespaces);
235};
236
237static std::mutex g_namespaces_mutex;
238static LibraryNamespaces* g_namespaces = new LibraryNamespaces;
239#endif
240
241void InitializeNativeLoader() {
242#if defined(__ANDROID__)
243  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
244  g_namespaces->Initialize();
245#endif
246}
247
248void ResetNativeLoader() {
249#if defined(__ANDROID__)
250  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
251  g_namespaces->Reset();
252#endif
253}
254
255jstring CreateClassLoaderNamespace(JNIEnv* env,
256                                   int32_t target_sdk_version,
257                                   jobject class_loader,
258                                   bool is_shared,
259                                   jstring library_path,
260                                   jstring permitted_path) {
261#if defined(__ANDROID__)
262  UNUSED(target_sdk_version);
263  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
264  android_namespace_t* ns = g_namespaces->Create(env,
265                                                 class_loader,
266                                                 is_shared,
267                                                 library_path,
268                                                 permitted_path);
269  if (ns == nullptr) {
270    return env->NewStringUTF(dlerror());
271  }
272#else
273  UNUSED(env, target_sdk_version, class_loader, is_shared,
274         library_path, permitted_path);
275#endif
276  return nullptr;
277}
278
279void* OpenNativeLibrary(JNIEnv* env,
280                        int32_t target_sdk_version,
281                        const char* path,
282                        jobject class_loader,
283                        jstring library_path) {
284#if defined(__ANDROID__)
285  UNUSED(target_sdk_version);
286  if (class_loader == nullptr) {
287    return dlopen(path, RTLD_NOW);
288  }
289
290  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
291  android_namespace_t* ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader);
292
293  if (ns == nullptr) {
294    // This is the case where the classloader was not created by ApplicationLoaders
295    // In this case we create an isolated not-shared namespace for it.
296    ns = g_namespaces->Create(env, class_loader, false, library_path, nullptr);
297    if (ns == nullptr) {
298      return nullptr;
299    }
300  }
301
302  android_dlextinfo extinfo;
303  extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
304  extinfo.library_namespace = ns;
305
306  return android_dlopen_ext(path, RTLD_NOW, &extinfo);
307#else
308  UNUSED(env, target_sdk_version, class_loader, library_path);
309  return dlopen(path, RTLD_NOW);
310#endif
311}
312
313bool CloseNativeLibrary(void* handle) {
314  return dlclose(handle) == 0;
315}
316
317#if defined(__ANDROID__)
318android_namespace_t* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
319  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
320  return g_namespaces->FindNamespaceByClassLoader(env, class_loader);
321}
322#endif
323
324}; //  android namespace
325