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