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