native_loader.cpp revision e8fb11dfa1b376124d0a1a349c8800799f25606a
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#define LOG_TAG "libnativeloader"
23#include "nativeloader/dlext_namespaces.h"
24#include "cutils/properties.h"
25#include "log/log.h"
26#endif
27#include "nativebridge/native_bridge.h"
28
29#include <algorithm>
30#include <vector>
31#include <string>
32#include <mutex>
33
34#include <android-base/file.h>
35#include <android-base/macros.h>
36#include <android-base/strings.h>
37
38#define CHECK(predicate) LOG_ALWAYS_FATAL_IF(!(predicate),\
39                                             "%s:%d: %s CHECK '" #predicate "' failed.",\
40                                             __FILE__, __LINE__, __FUNCTION__)
41
42namespace android {
43
44#if defined(__ANDROID__)
45class NativeLoaderNamespace {
46 public:
47  NativeLoaderNamespace()
48      : android_ns_(nullptr), native_bridge_ns_(nullptr) { }
49
50  explicit NativeLoaderNamespace(android_namespace_t* ns)
51      : android_ns_(ns), native_bridge_ns_(nullptr) { }
52
53  explicit NativeLoaderNamespace(native_bridge_namespace_t* ns)
54      : android_ns_(nullptr), native_bridge_ns_(ns) { }
55
56  NativeLoaderNamespace(NativeLoaderNamespace&& that) = default;
57  NativeLoaderNamespace(const NativeLoaderNamespace& that) = default;
58
59  NativeLoaderNamespace& operator=(const NativeLoaderNamespace& that) = default;
60
61  android_namespace_t* get_android_ns() const {
62    CHECK(native_bridge_ns_ == nullptr);
63    return android_ns_;
64  }
65
66  native_bridge_namespace_t* get_native_bridge_ns() const {
67    CHECK(android_ns_ == nullptr);
68    return native_bridge_ns_;
69  }
70
71  bool is_android_namespace() const {
72    return native_bridge_ns_ == nullptr;
73  }
74
75 private:
76  // Only one of them can be not null
77  android_namespace_t* android_ns_;
78  native_bridge_namespace_t* native_bridge_ns_;
79};
80
81static constexpr const char* kPublicNativeLibrariesSystemConfigPathFromRoot =
82                                  "/etc/public.libraries.txt";
83static constexpr const char* kPublicNativeLibrariesVendorConfig =
84                                  "/vendor/etc/public.libraries.txt";
85
86// (http://b/27588281) This is a workaround for apps using custom classloaders and calling
87// System.load() with an absolute path which is outside of the classloader library search path.
88// This list includes all directories app is allowed to access this way.
89static constexpr const char* kWhitelistedDirectories = "/data:/mnt/expand";
90
91static bool is_debuggable() {
92  char debuggable[PROP_VALUE_MAX];
93  property_get("ro.debuggable", debuggable, "0");
94  return std::string(debuggable) == "1";
95}
96
97class LibraryNamespaces {
98 public:
99  LibraryNamespaces() : initialized_(false) { }
100
101  bool Create(JNIEnv* env,
102              jobject class_loader,
103              bool is_shared,
104              jstring java_library_path,
105              jstring java_permitted_path,
106              NativeLoaderNamespace* ns,
107              std::string* error_msg) {
108    std::string library_path; // empty string by default.
109
110    if (java_library_path != nullptr) {
111      ScopedUtfChars library_path_utf_chars(env, java_library_path);
112      library_path = library_path_utf_chars.c_str();
113    }
114
115    // (http://b/27588281) This is a workaround for apps using custom
116    // classloaders and calling System.load() with an absolute path which
117    // is outside of the classloader library search path.
118    //
119    // This part effectively allows such a classloader to access anything
120    // under /data and /mnt/expand
121    std::string permitted_path = kWhitelistedDirectories;
122
123    if (java_permitted_path != nullptr) {
124      ScopedUtfChars path(env, java_permitted_path);
125      if (path.c_str() != nullptr && path.size() > 0) {
126        permitted_path = permitted_path + ":" + path.c_str();
127      }
128    }
129
130    if (!initialized_ && !InitPublicNamespace(library_path.c_str(), error_msg)) {
131      return false;
132    }
133
134    bool found = FindNamespaceByClassLoader(env, class_loader, nullptr);
135
136    LOG_ALWAYS_FATAL_IF(found,
137                        "There is already a namespace associated with this classloader");
138
139    uint64_t namespace_type = ANDROID_NAMESPACE_TYPE_ISOLATED;
140    if (is_shared) {
141      namespace_type |= ANDROID_NAMESPACE_TYPE_SHARED;
142    }
143
144    NativeLoaderNamespace parent_ns;
145    bool found_parent_namespace = FindParentNamespaceByClassLoader(env, class_loader, &parent_ns);
146
147    bool is_native_bridge = false;
148
149    if (found_parent_namespace) {
150      is_native_bridge = !parent_ns.is_android_namespace();
151    } else if (!library_path.empty()) {
152      is_native_bridge = NativeBridgeIsPathSupported(library_path.c_str());
153    }
154
155    NativeLoaderNamespace native_loader_ns;
156    if (!is_native_bridge) {
157      android_namespace_t* ns = android_create_namespace("classloader-namespace",
158                                                         nullptr,
159                                                         library_path.c_str(),
160                                                         namespace_type,
161                                                         permitted_path.c_str(),
162                                                         parent_ns.get_android_ns());
163      if (ns == nullptr) {
164        *error_msg = dlerror();
165        return false;
166      }
167
168      if (!android_link_namespaces(ns, nullptr, public_libraries_.c_str())) {
169        *error_msg = dlerror();
170        return false;
171      }
172
173      native_loader_ns = NativeLoaderNamespace(ns);
174    } else {
175      native_bridge_namespace_t* ns = NativeBridgeCreateNamespace("classloader-namespace",
176                                                                  nullptr,
177                                                                  library_path.c_str(),
178                                                                  namespace_type,
179                                                                  permitted_path.c_str(),
180                                                                  parent_ns.get_native_bridge_ns());
181      if (ns == nullptr) {
182        *error_msg = NativeBridgeGetError();
183        return false;
184      }
185
186      if (!NativeBridgeLinkNamespaces(ns, nullptr, public_libraries_.c_str())) {
187        *error_msg = NativeBridgeGetError();
188        return false;
189      }
190
191      native_loader_ns = NativeLoaderNamespace(ns);
192    }
193
194    namespaces_.push_back(std::make_pair(env->NewWeakGlobalRef(class_loader), native_loader_ns));
195
196    *ns = native_loader_ns;
197    return true;
198  }
199
200  bool FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader, NativeLoaderNamespace* ns) {
201    auto it = std::find_if(namespaces_.begin(), namespaces_.end(),
202                [&](const std::pair<jweak, NativeLoaderNamespace>& value) {
203                  return env->IsSameObject(value.first, class_loader);
204                });
205    if (it != namespaces_.end()) {
206      if (ns != nullptr) {
207        *ns = it->second;
208      }
209
210      return true;
211    }
212
213    return false;
214  }
215
216  void Initialize() {
217    // Once public namespace is initialized there is no
218    // point in running this code - it will have no effect
219    // on the current list of public libraries.
220    if (initialized_) {
221      return;
222    }
223
224    std::vector<std::string> sonames;
225    const char* android_root_env = getenv("ANDROID_ROOT");
226    std::string root_dir = android_root_env != nullptr ? android_root_env : "/system";
227    std::string public_native_libraries_system_config =
228            root_dir + kPublicNativeLibrariesSystemConfigPathFromRoot;
229
230    std::string error_msg;
231    LOG_ALWAYS_FATAL_IF(!ReadConfig(public_native_libraries_system_config, &sonames, &error_msg),
232                        "Error reading public native library list from \"%s\": %s",
233                        public_native_libraries_system_config.c_str(), error_msg.c_str());
234
235    // For debuggable platform builds use ANDROID_ADDITIONAL_PUBLIC_LIBRARIES environment
236    // variable to add libraries to the list. This is intended for platform tests only.
237    if (is_debuggable()) {
238      const char* additional_libs = getenv("ANDROID_ADDITIONAL_PUBLIC_LIBRARIES");
239      if (additional_libs != nullptr && additional_libs[0] != '\0') {
240        std::vector<std::string> additional_libs_vector = base::Split(additional_libs, ":");
241        std::copy(additional_libs_vector.begin(),
242                  additional_libs_vector.end(),
243                  std::back_inserter(sonames));
244      }
245    }
246
247    // This file is optional, quietly ignore if the file does not exist.
248    ReadConfig(kPublicNativeLibrariesVendorConfig, &sonames);
249
250    // android_init_namespaces() expects all the public libraries
251    // to be loaded so that they can be found by soname alone.
252    //
253    // TODO(dimitry): this is a bit misleading since we do not know
254    // if the vendor public library is going to be opened from /vendor/lib
255    // we might as well end up loading them from /system/lib
256    // For now we rely on CTS test to catch things like this but
257    // it should probably be addressed in the future.
258    for (const auto& soname : sonames) {
259      LOG_ALWAYS_FATAL_IF(dlopen(soname.c_str(), RTLD_NOW | RTLD_NODELETE) == nullptr,
260                          "Error preloading public library %s: %s",
261                          soname.c_str(), dlerror());
262    }
263
264    public_libraries_ = base::Join(sonames, ':');
265  }
266
267  void Reset() {
268    namespaces_.clear();
269  }
270
271 private:
272  bool ReadConfig(const std::string& configFile, std::vector<std::string>* sonames,
273                  std::string* error_msg = nullptr) {
274    // Read list of public native libraries from the config file.
275    std::string file_content;
276    if(!base::ReadFileToString(configFile, &file_content)) {
277      if (error_msg) *error_msg = strerror(errno);
278      return false;
279    }
280
281    std::vector<std::string> lines = base::Split(file_content, "\n");
282
283    for (auto& line : lines) {
284      auto trimmed_line = base::Trim(line);
285      if (trimmed_line[0] == '#' || trimmed_line.empty()) {
286        continue;
287      }
288      size_t space_pos = trimmed_line.rfind(' ');
289      if (space_pos != std::string::npos) {
290        std::string type = trimmed_line.substr(space_pos + 1);
291        if (type != "32" && type != "64") {
292          if (error_msg) *error_msg = "Malformed line: " + line;
293          return false;
294        }
295#if defined(__LP64__)
296        // Skip 32 bit public library.
297        if (type == "32") {
298          continue;
299        }
300#else
301        // Skip 64 bit public library.
302        if (type == "64") {
303          continue;
304        }
305#endif
306        trimmed_line.resize(space_pos);
307      }
308
309      sonames->push_back(trimmed_line);
310    }
311
312    return true;
313  }
314
315  bool InitPublicNamespace(const char* library_path, std::string* error_msg) {
316    // Ask native bride if this apps library path should be handled by it
317    bool is_native_bridge = NativeBridgeIsPathSupported(library_path);
318
319    // (http://b/25844435) - Some apps call dlopen from generated code (mono jited
320    // code is one example) unknown to linker in which  case linker uses anonymous
321    // namespace. The second argument specifies the search path for the anonymous
322    // namespace which is the library_path of the classloader.
323    initialized_ = android_init_anonymous_namespace(public_libraries_.c_str(),
324                                                    is_native_bridge ? nullptr : library_path);
325    if (!initialized_) {
326      *error_msg = dlerror();
327      return false;
328    }
329
330    // and now initialize native bridge namespaces if necessary.
331    if (NativeBridgeInitialized()) {
332      initialized_ = NativeBridgeInitAnonymousNamespace(public_libraries_.c_str(),
333                                                        is_native_bridge ? library_path : nullptr);
334      if (!initialized_) {
335        *error_msg = NativeBridgeGetError();
336      }
337    }
338
339    return initialized_;
340  }
341
342  jobject GetParentClassLoader(JNIEnv* env, jobject class_loader) {
343    jclass class_loader_class = env->FindClass("java/lang/ClassLoader");
344    jmethodID get_parent = env->GetMethodID(class_loader_class,
345                                            "getParent",
346                                            "()Ljava/lang/ClassLoader;");
347
348    return env->CallObjectMethod(class_loader, get_parent);
349  }
350
351  bool FindParentNamespaceByClassLoader(JNIEnv* env,
352                                        jobject class_loader,
353                                        NativeLoaderNamespace* ns) {
354    jobject parent_class_loader = GetParentClassLoader(env, class_loader);
355
356    while (parent_class_loader != nullptr) {
357      if (FindNamespaceByClassLoader(env, parent_class_loader, ns)) {
358        return true;
359      }
360
361      parent_class_loader = GetParentClassLoader(env, parent_class_loader);
362    }
363
364    return false;
365  }
366
367  bool initialized_;
368  std::vector<std::pair<jweak, NativeLoaderNamespace>> namespaces_;
369  std::string public_libraries_;
370
371
372  DISALLOW_COPY_AND_ASSIGN(LibraryNamespaces);
373};
374
375static std::mutex g_namespaces_mutex;
376static LibraryNamespaces* g_namespaces = new LibraryNamespaces;
377#endif
378
379void InitializeNativeLoader() {
380#if defined(__ANDROID__)
381  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
382  g_namespaces->Initialize();
383#endif
384}
385
386void ResetNativeLoader() {
387#if defined(__ANDROID__)
388  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
389  g_namespaces->Reset();
390#endif
391}
392
393jstring CreateClassLoaderNamespace(JNIEnv* env,
394                                   int32_t target_sdk_version,
395                                   jobject class_loader,
396                                   bool is_shared,
397                                   jstring library_path,
398                                   jstring permitted_path) {
399#if defined(__ANDROID__)
400  UNUSED(target_sdk_version);
401  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
402
403  std::string error_msg;
404  NativeLoaderNamespace ns;
405  bool success = g_namespaces->Create(env,
406                                      class_loader,
407                                      is_shared,
408                                      library_path,
409                                      permitted_path,
410                                      &ns,
411                                      &error_msg);
412  if (!success) {
413    return env->NewStringUTF(error_msg.c_str());
414  }
415#else
416  UNUSED(env, target_sdk_version, class_loader, is_shared,
417         library_path, permitted_path);
418#endif
419  return nullptr;
420}
421
422void* OpenNativeLibrary(JNIEnv* env,
423                        int32_t target_sdk_version,
424                        const char* path,
425                        jobject class_loader,
426                        jstring library_path,
427                        bool* needs_native_bridge,
428                        std::string* error_msg) {
429#if defined(__ANDROID__)
430  UNUSED(target_sdk_version);
431  if (class_loader == nullptr) {
432    *needs_native_bridge = false;
433    return dlopen(path, RTLD_NOW);
434  }
435
436  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
437  NativeLoaderNamespace ns;
438
439  if (!g_namespaces->FindNamespaceByClassLoader(env, class_loader, &ns)) {
440    // This is the case where the classloader was not created by ApplicationLoaders
441    // In this case we create an isolated not-shared namespace for it.
442    if (!g_namespaces->Create(env, class_loader, false, library_path, nullptr, &ns, error_msg)) {
443      return nullptr;
444    }
445  }
446
447  if (ns.is_android_namespace()) {
448    android_dlextinfo extinfo;
449    extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
450    extinfo.library_namespace = ns.get_android_ns();
451
452    void* handle = android_dlopen_ext(path, RTLD_NOW, &extinfo);
453    if (handle == nullptr) {
454      *error_msg = dlerror();
455    }
456    *needs_native_bridge = false;
457    return handle;
458  } else {
459    void* handle = NativeBridgeLoadLibraryExt(path, RTLD_NOW, ns.get_native_bridge_ns());
460    if (handle == nullptr) {
461      *error_msg = NativeBridgeGetError();
462    }
463    *needs_native_bridge = true;
464    return handle;
465  }
466#else
467  UNUSED(env, target_sdk_version, class_loader, library_path);
468  *needs_native_bridge = false;
469  void* handle = dlopen(path, RTLD_NOW);
470  if (handle == nullptr) {
471    if (NativeBridgeIsSupported(path)) {
472      *needs_native_bridge = true;
473      handle = NativeBridgeLoadLibrary(path, RTLD_NOW);
474      if (handle == nullptr) {
475        *error_msg = NativeBridgeGetError();
476      }
477    } else {
478      *needs_native_bridge = false;
479      *error_msg = dlerror();
480    }
481  }
482  return handle;
483#endif
484}
485
486bool CloseNativeLibrary(void* handle, const bool needs_native_bridge) {
487    return needs_native_bridge ? NativeBridgeUnloadLibrary(handle) :
488                                 dlclose(handle);
489}
490
491#if defined(__ANDROID__)
492// native_bridge_namespaces are not supported for callers of this function.
493// This function will return nullptr in the case when application is running
494// on native bridge.
495android_namespace_t* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
496  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
497  NativeLoaderNamespace ns;
498  if (g_namespaces->FindNamespaceByClassLoader(env, class_loader, &ns)) {
499    return ns.is_android_namespace() ? ns.get_android_ns() : nullptr;
500  }
501
502  return nullptr;
503}
504#endif
505
506}; //  android namespace
507