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