native_loader.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  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. #include "nativeloader/native_loader.h"
  17. #include <nativehelper/ScopedUtfChars.h>
  18. #include <dlfcn.h>
  19. #ifdef __ANDROID__
  20. #define LOG_TAG "libnativeloader"
  21. #include "nativeloader/dlext_namespaces.h"
  22. #include "log/log.h"
  23. #endif
  24. #include <dirent.h>
  25. #include <sys/types.h>
  26. #include "nativebridge/native_bridge.h"
  27. #include <algorithm>
  28. #include <list>
  29. #include <memory>
  30. #include <mutex>
  31. #include <regex>
  32. #include <string>
  33. #include <vector>
  34. #include <android-base/file.h>
  35. #include <android-base/macros.h>
  36. #include <android-base/strings.h>
  37. #ifdef __BIONIC__
  38. #include <android-base/properties.h>
  39. #endif
  40. #define CHECK(predicate) LOG_ALWAYS_FATAL_IF(!(predicate),\
  41. "%s:%d: %s CHECK '" #predicate "' failed.",\
  42. __FILE__, __LINE__, __FUNCTION__)
  43. using namespace std::string_literals;
  44. namespace android {
  45. #if defined(__ANDROID__)
  46. struct NativeLoaderNamespace {
  47. public:
  48. NativeLoaderNamespace()
  49. : android_ns_(nullptr), native_bridge_ns_(nullptr) { }
  50. explicit NativeLoaderNamespace(android_namespace_t* ns)
  51. : android_ns_(ns), native_bridge_ns_(nullptr) { }
  52. explicit NativeLoaderNamespace(native_bridge_namespace_t* ns)
  53. : android_ns_(nullptr), native_bridge_ns_(ns) { }
  54. NativeLoaderNamespace(NativeLoaderNamespace&& that) = default;
  55. NativeLoaderNamespace(const NativeLoaderNamespace& that) = default;
  56. NativeLoaderNamespace& operator=(const NativeLoaderNamespace& that) = default;
  57. android_namespace_t* get_android_ns() const {
  58. CHECK(native_bridge_ns_ == nullptr);
  59. return android_ns_;
  60. }
  61. native_bridge_namespace_t* get_native_bridge_ns() const {
  62. CHECK(android_ns_ == nullptr);
  63. return native_bridge_ns_;
  64. }
  65. bool is_android_namespace() const {
  66. return native_bridge_ns_ == nullptr;
  67. }
  68. private:
  69. // Only one of them can be not null
  70. android_namespace_t* android_ns_;
  71. native_bridge_namespace_t* native_bridge_ns_;
  72. };
  73. static constexpr const char kPublicNativeLibrariesSystemConfigPathFromRoot[] =
  74. "/etc/public.libraries.txt";
  75. static constexpr const char kPublicNativeLibrariesExtensionConfigPrefix[] = "public.libraries-";
  76. static constexpr const size_t kPublicNativeLibrariesExtensionConfigPrefixLen =
  77. sizeof(kPublicNativeLibrariesExtensionConfigPrefix) - 1;
  78. static constexpr const char kPublicNativeLibrariesExtensionConfigSuffix[] = ".txt";
  79. static constexpr const size_t kPublicNativeLibrariesExtensionConfigSuffixLen =
  80. sizeof(kPublicNativeLibrariesExtensionConfigSuffix) - 1;
  81. static constexpr const char kPublicNativeLibrariesVendorConfig[] =
  82. "/vendor/etc/public.libraries.txt";
  83. static constexpr const char kLlndkNativeLibrariesSystemConfigPathFromRoot[] =
  84. "/etc/llndk.libraries.txt";
  85. static constexpr const char kVndkspNativeLibrariesSystemConfigPathFromRoot[] =
  86. "/etc/vndksp.libraries.txt";
  87. static const std::vector<const std::string> kRuntimePublicLibraries = {
  88. "libicuuc.so",
  89. "libicui18n.so",
  90. };
  91. // The device may be configured to have the vendor libraries loaded to a separate namespace.
  92. // For historical reasons this namespace was named sphal but effectively it is intended
  93. // to use to load vendor libraries to separate namespace with controlled interface between
  94. // vendor and system namespaces.
  95. static constexpr const char* kVendorNamespaceName = "sphal";
  96. static constexpr const char* kVndkNamespaceName = "vndk";
  97. static constexpr const char* kDefaultNamespaceName = "default";
  98. static constexpr const char* kPlatformNamespaceName = "platform";
  99. static constexpr const char* kRuntimeNamespaceName = "runtime";
  100. // classloader-namespace is a linker namespace that is created for the loaded
  101. // app. To be specific, it is created for the app classloader. When
  102. // System.load() is called from a Java class that is loaded from the
  103. // classloader, the classloader-namespace namespace associated with that
  104. // classloader is selected for dlopen. The namespace is configured so that its
  105. // search path is set to the app-local JNI directory and it is linked to the
  106. // default namespace with the names of libs listed in the public.libraries.txt.
  107. // This way an app can only load its own JNI libraries along with the public libs.
  108. static constexpr const char* kClassloaderNamespaceName = "classloader-namespace";
  109. // Same thing for vendor APKs.
  110. static constexpr const char* kVendorClassloaderNamespaceName = "vendor-classloader-namespace";
  111. // (http://b/27588281) This is a workaround for apps using custom classloaders and calling
  112. // System.load() with an absolute path which is outside of the classloader library search path.
  113. // This list includes all directories app is allowed to access this way.
  114. static constexpr const char* kWhitelistedDirectories = "/data:/mnt/expand";
  115. static constexpr const char* kApexPath = "/apex/";
  116. #if defined(__LP64__)
  117. static constexpr const char* kRuntimeApexLibPath = "/apex/com.android.runtime/lib64";
  118. static constexpr const char* kVendorLibPath = "/vendor/lib64";
  119. static constexpr const char* kProductLibPath = "/product/lib64:/system/product/lib64";
  120. #else
  121. static constexpr const char* kRuntimeApexLibPath = "/apex/com.android.runtime/lib";
  122. static constexpr const char* kVendorLibPath = "/vendor/lib";
  123. static constexpr const char* kProductLibPath = "/product/lib:/system/product/lib";
  124. #endif
  125. static const std::regex kVendorDexPathRegex("(^|:)/vendor/");
  126. static const std::regex kProductDexPathRegex("(^|:)(/system)?/product/");
  127. // Define origin of APK if it is from vendor partition or product partition
  128. typedef enum {
  129. APK_ORIGIN_DEFAULT = 0,
  130. APK_ORIGIN_VENDOR = 1,
  131. APK_ORIGIN_PRODUCT = 2,
  132. } ApkOrigin;
  133. static bool is_debuggable() {
  134. bool debuggable = false;
  135. #ifdef __BIONIC__
  136. debuggable = android::base::GetBoolProperty("ro.debuggable", false);
  137. #endif
  138. return debuggable;
  139. }
  140. static std::string vndk_version_str() {
  141. #ifdef __BIONIC__
  142. std::string version = android::base::GetProperty("ro.vndk.version", "");
  143. if (version != "" && version != "current") {
  144. return "." + version;
  145. }
  146. #endif
  147. return "";
  148. }
  149. static void insert_vndk_version_str(std::string* file_name) {
  150. CHECK(file_name != nullptr);
  151. size_t insert_pos = file_name->find_last_of(".");
  152. if (insert_pos == std::string::npos) {
  153. insert_pos = file_name->length();
  154. }
  155. file_name->insert(insert_pos, vndk_version_str());
  156. }
  157. static const std::function<bool(const std::string&, std::string*)> always_true =
  158. [](const std::string&, std::string*) { return true; };
  159. class LibraryNamespaces {
  160. public:
  161. LibraryNamespaces() : initialized_(false) { }
  162. NativeLoaderNamespace* Create(JNIEnv* env, uint32_t target_sdk_version, jobject class_loader,
  163. bool is_shared, jstring dex_path, jstring java_library_path,
  164. jstring java_permitted_path, std::string* error_msg) {
  165. std::string library_path; // empty string by default.
  166. if (java_library_path != nullptr) {
  167. ScopedUtfChars library_path_utf_chars(env, java_library_path);
  168. library_path = library_path_utf_chars.c_str();
  169. }
  170. ApkOrigin apk_origin = GetApkOriginFromDexPath(env, dex_path);
  171. // (http://b/27588281) This is a workaround for apps using custom
  172. // classloaders and calling System.load() with an absolute path which
  173. // is outside of the classloader library search path.
  174. //
  175. // This part effectively allows such a classloader to access anything
  176. // under /data and /mnt/expand
  177. std::string permitted_path = kWhitelistedDirectories;
  178. if (java_permitted_path != nullptr) {
  179. ScopedUtfChars path(env, java_permitted_path);
  180. if (path.c_str() != nullptr && path.size() > 0) {
  181. permitted_path = permitted_path + ":" + path.c_str();
  182. }
  183. }
  184. // Initialize the anonymous namespace with the first non-empty library path.
  185. if (!library_path.empty() && !initialized_ &&
  186. !InitPublicNamespace(library_path.c_str(), error_msg)) {
  187. return nullptr;
  188. }
  189. bool found = FindNamespaceByClassLoader(env, class_loader);
  190. LOG_ALWAYS_FATAL_IF(found,
  191. "There is already a namespace associated with this classloader");
  192. uint64_t namespace_type = ANDROID_NAMESPACE_TYPE_ISOLATED;
  193. if (is_shared) {
  194. namespace_type |= ANDROID_NAMESPACE_TYPE_SHARED;
  195. }
  196. if (target_sdk_version < 24) {
  197. namespace_type |= ANDROID_NAMESPACE_TYPE_GREYLIST_ENABLED;
  198. }
  199. NativeLoaderNamespace* parent_ns = FindParentNamespaceByClassLoader(env, class_loader);
  200. bool is_native_bridge = false;
  201. if (parent_ns != nullptr) {
  202. is_native_bridge = !parent_ns->is_android_namespace();
  203. } else if (!library_path.empty()) {
  204. is_native_bridge = NativeBridgeIsPathSupported(library_path.c_str());
  205. }
  206. std::string system_exposed_libraries = system_public_libraries_;
  207. const char* namespace_name = kClassloaderNamespaceName;
  208. android_namespace_t* vndk_ns = nullptr;
  209. if ((apk_origin == APK_ORIGIN_VENDOR ||
  210. (apk_origin == APK_ORIGIN_PRODUCT && target_sdk_version > 29)) &&
  211. !is_shared) {
  212. LOG_FATAL_IF(is_native_bridge,
  213. "Unbundled vendor / product apk must not use translated architecture");
  214. // For vendor / product apks, give access to the vendor / product lib even though
  215. // they are treated as unbundled; the libs and apks are still bundled
  216. // together in the vendor / product partition.
  217. const char* origin_partition;
  218. const char* origin_lib_path;
  219. switch (apk_origin) {
  220. case APK_ORIGIN_VENDOR:
  221. origin_partition = "vendor";
  222. origin_lib_path = kVendorLibPath;
  223. break;
  224. case APK_ORIGIN_PRODUCT:
  225. origin_partition = "product";
  226. origin_lib_path = kProductLibPath;
  227. break;
  228. default:
  229. origin_partition = "unknown";
  230. origin_lib_path = "";
  231. }
  232. LOG_FATAL_IF(is_native_bridge, "Unbundled %s apk must not use translated architecture",
  233. origin_partition);
  234. library_path = library_path + ":" + origin_lib_path;
  235. permitted_path = permitted_path + ":" + origin_lib_path;
  236. // Also give access to LLNDK libraries since they are available to vendors
  237. system_exposed_libraries = system_exposed_libraries + ":" + system_llndk_libraries_.c_str();
  238. // Give access to VNDK-SP libraries from the 'vndk' namespace.
  239. vndk_ns = android_get_exported_namespace(kVndkNamespaceName);
  240. if (vndk_ns == nullptr) {
  241. ALOGW("Cannot find \"%s\" namespace for %s apks", kVndkNamespaceName, origin_partition);
  242. }
  243. // Different name is useful for debugging
  244. namespace_name = kVendorClassloaderNamespaceName;
  245. ALOGD("classloader namespace configured for unbundled %s apk. library_path=%s",
  246. origin_partition, library_path.c_str());
  247. } else {
  248. // oem and product public libraries are NOT available to vendor apks, otherwise it
  249. // would be system->vendor violation.
  250. if (!oem_public_libraries_.empty()) {
  251. system_exposed_libraries = system_exposed_libraries + ':' + oem_public_libraries_;
  252. }
  253. if (!product_public_libraries_.empty()) {
  254. system_exposed_libraries = system_exposed_libraries + ':' + product_public_libraries_;
  255. }
  256. }
  257. std::string runtime_exposed_libraries = base::Join(kRuntimePublicLibraries, ":");
  258. NativeLoaderNamespace native_loader_ns;
  259. if (!is_native_bridge) {
  260. android_namespace_t* android_parent_ns;
  261. if (parent_ns != nullptr) {
  262. android_parent_ns = parent_ns->get_android_ns();
  263. } else {
  264. // Fall back to the platform namespace if no parent is found. It is
  265. // called "default" for binaries in /system and "platform" for those in
  266. // the Runtime APEX. Try "platform" first since "default" always exists.
  267. android_parent_ns = android_get_exported_namespace(kPlatformNamespaceName);
  268. if (android_parent_ns == nullptr) {
  269. android_parent_ns = android_get_exported_namespace(kDefaultNamespaceName);
  270. }
  271. }
  272. android_namespace_t* ns = android_create_namespace(namespace_name,
  273. nullptr,
  274. library_path.c_str(),
  275. namespace_type,
  276. permitted_path.c_str(),
  277. android_parent_ns);
  278. if (ns == nullptr) {
  279. *error_msg = dlerror();
  280. return nullptr;
  281. }
  282. // Note that when vendor_ns is not configured this function will return nullptr
  283. // and it will result in linking vendor_public_libraries_ to the default namespace
  284. // which is expected behavior in this case.
  285. android_namespace_t* vendor_ns = android_get_exported_namespace(kVendorNamespaceName);
  286. android_namespace_t* runtime_ns = android_get_exported_namespace(kRuntimeNamespaceName);
  287. if (!android_link_namespaces(ns, nullptr, system_exposed_libraries.c_str())) {
  288. *error_msg = dlerror();
  289. return nullptr;
  290. }
  291. // Runtime apex does not exist in host, and under certain build conditions.
  292. if (runtime_ns != nullptr) {
  293. if (!android_link_namespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
  294. *error_msg = dlerror();
  295. return nullptr;
  296. }
  297. }
  298. if (vndk_ns != nullptr && !system_vndksp_libraries_.empty()) {
  299. // vendor apks are allowed to use VNDK-SP libraries.
  300. if (!android_link_namespaces(ns, vndk_ns, system_vndksp_libraries_.c_str())) {
  301. *error_msg = dlerror();
  302. return nullptr;
  303. }
  304. }
  305. if (!vendor_public_libraries_.empty()) {
  306. if (!android_link_namespaces(ns, vendor_ns, vendor_public_libraries_.c_str())) {
  307. *error_msg = dlerror();
  308. return nullptr;
  309. }
  310. }
  311. native_loader_ns = NativeLoaderNamespace(ns);
  312. } else {
  313. native_bridge_namespace_t* native_bridge_parent_namespace;
  314. if (parent_ns != nullptr) {
  315. native_bridge_parent_namespace = parent_ns->get_native_bridge_ns();
  316. } else {
  317. native_bridge_parent_namespace = NativeBridgeGetExportedNamespace(kPlatformNamespaceName);
  318. if (native_bridge_parent_namespace == nullptr) {
  319. native_bridge_parent_namespace = NativeBridgeGetExportedNamespace(kDefaultNamespaceName);
  320. }
  321. }
  322. native_bridge_namespace_t* ns = NativeBridgeCreateNamespace(namespace_name,
  323. nullptr,
  324. library_path.c_str(),
  325. namespace_type,
  326. permitted_path.c_str(),
  327. native_bridge_parent_namespace);
  328. if (ns == nullptr) {
  329. *error_msg = NativeBridgeGetError();
  330. return nullptr;
  331. }
  332. native_bridge_namespace_t* vendor_ns = NativeBridgeGetExportedNamespace(kVendorNamespaceName);
  333. native_bridge_namespace_t* runtime_ns =
  334. NativeBridgeGetExportedNamespace(kRuntimeNamespaceName);
  335. if (!NativeBridgeLinkNamespaces(ns, nullptr, system_exposed_libraries.c_str())) {
  336. *error_msg = NativeBridgeGetError();
  337. return nullptr;
  338. }
  339. // Runtime apex does not exist in host, and under certain build conditions.
  340. if (runtime_ns != nullptr) {
  341. if (!NativeBridgeLinkNamespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
  342. *error_msg = NativeBridgeGetError();
  343. return nullptr;
  344. }
  345. }
  346. if (!vendor_public_libraries_.empty()) {
  347. if (!NativeBridgeLinkNamespaces(ns, vendor_ns, vendor_public_libraries_.c_str())) {
  348. *error_msg = NativeBridgeGetError();
  349. return nullptr;
  350. }
  351. }
  352. native_loader_ns = NativeLoaderNamespace(ns);
  353. }
  354. namespaces_.push_back(std::make_pair(env->NewWeakGlobalRef(class_loader), native_loader_ns));
  355. return &(namespaces_.back().second);
  356. }
  357. NativeLoaderNamespace* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
  358. auto it = std::find_if(namespaces_.begin(), namespaces_.end(),
  359. [&](const std::pair<jweak, NativeLoaderNamespace>& value) {
  360. return env->IsSameObject(value.first, class_loader);
  361. });
  362. if (it != namespaces_.end()) {
  363. return &it->second;
  364. }
  365. return nullptr;
  366. }
  367. void Initialize() {
  368. // Once public namespace is initialized there is no
  369. // point in running this code - it will have no effect
  370. // on the current list of public libraries.
  371. if (initialized_) {
  372. return;
  373. }
  374. std::vector<std::string> sonames;
  375. const char* android_root_env = getenv("ANDROID_ROOT");
  376. std::string root_dir = android_root_env != nullptr ? android_root_env : "/system";
  377. std::string public_native_libraries_system_config =
  378. root_dir + kPublicNativeLibrariesSystemConfigPathFromRoot;
  379. std::string llndk_native_libraries_system_config =
  380. root_dir + kLlndkNativeLibrariesSystemConfigPathFromRoot;
  381. std::string vndksp_native_libraries_system_config =
  382. root_dir + kVndkspNativeLibrariesSystemConfigPathFromRoot;
  383. std::string product_public_native_libraries_dir = "/product/etc";
  384. std::string error_msg;
  385. LOG_ALWAYS_FATAL_IF(
  386. !ReadConfig(public_native_libraries_system_config, &sonames, always_true, &error_msg),
  387. "Error reading public native library list from \"%s\": %s",
  388. public_native_libraries_system_config.c_str(), error_msg.c_str());
  389. // For debuggable platform builds use ANDROID_ADDITIONAL_PUBLIC_LIBRARIES environment
  390. // variable to add libraries to the list. This is intended for platform tests only.
  391. if (is_debuggable()) {
  392. const char* additional_libs = getenv("ANDROID_ADDITIONAL_PUBLIC_LIBRARIES");
  393. if (additional_libs != nullptr && additional_libs[0] != '\0') {
  394. std::vector<std::string> additional_libs_vector = base::Split(additional_libs, ":");
  395. std::copy(additional_libs_vector.begin(), additional_libs_vector.end(),
  396. std::back_inserter(sonames));
  397. }
  398. }
  399. // Remove the public libs in the runtime namespace.
  400. // These libs are listed in public.android.txt, but we don't want the rest of android
  401. // in default namespace to dlopen the libs.
  402. // For example, libicuuc.so is exposed to classloader namespace from runtime namespace.
  403. // Unfortunately, it does not have stable C symbols, and default namespace should only use
  404. // stable symbols in libandroidicu.so. http://b/120786417
  405. removePublicLibsIfExistsInRuntimeApex(sonames);
  406. // android_init_namespaces() expects all the public libraries
  407. // to be loaded so that they can be found by soname alone.
  408. //
  409. // TODO(dimitry): this is a bit misleading since we do not know
  410. // if the vendor public library is going to be opened from /vendor/lib
  411. // we might as well end up loading them from /system/lib or /product/lib
  412. // For now we rely on CTS test to catch things like this but
  413. // it should probably be addressed in the future.
  414. for (const auto& soname : sonames) {
  415. LOG_ALWAYS_FATAL_IF(dlopen(soname.c_str(), RTLD_NOW | RTLD_NODELETE) == nullptr,
  416. "Error preloading public library %s: %s", soname.c_str(), dlerror());
  417. }
  418. system_public_libraries_ = base::Join(sonames, ':');
  419. // read /system/etc/public.libraries-<companyname>.txt which contain partner defined
  420. // system libs that are exposed to apps. The libs in the txt files must be
  421. // named as lib<name>.<companyname>.so.
  422. sonames.clear();
  423. ReadExtensionLibraries(base::Dirname(public_native_libraries_system_config).c_str(), &sonames);
  424. oem_public_libraries_ = base::Join(sonames, ':');
  425. // read /product/etc/public.libraries-<companyname>.txt which contain partner defined
  426. // product libs that are exposed to apps.
  427. sonames.clear();
  428. ReadExtensionLibraries(product_public_native_libraries_dir.c_str(), &sonames);
  429. product_public_libraries_ = base::Join(sonames, ':');
  430. // Insert VNDK version to llndk and vndksp config file names.
  431. insert_vndk_version_str(&llndk_native_libraries_system_config);
  432. insert_vndk_version_str(&vndksp_native_libraries_system_config);
  433. sonames.clear();
  434. ReadConfig(llndk_native_libraries_system_config, &sonames, always_true);
  435. system_llndk_libraries_ = base::Join(sonames, ':');
  436. sonames.clear();
  437. ReadConfig(vndksp_native_libraries_system_config, &sonames, always_true);
  438. system_vndksp_libraries_ = base::Join(sonames, ':');
  439. sonames.clear();
  440. // This file is optional, quietly ignore if the file does not exist.
  441. ReadConfig(kPublicNativeLibrariesVendorConfig, &sonames, always_true, nullptr);
  442. vendor_public_libraries_ = base::Join(sonames, ':');
  443. }
  444. void Reset() { namespaces_.clear(); }
  445. private:
  446. void ReadExtensionLibraries(const char* dirname, std::vector<std::string>* sonames) {
  447. std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(dirname), closedir);
  448. if (dir != nullptr) {
  449. // Failing to opening the dir is not an error, which can happen in
  450. // webview_zygote.
  451. while (struct dirent* ent = readdir(dir.get())) {
  452. if (ent->d_type != DT_REG && ent->d_type != DT_LNK) {
  453. continue;
  454. }
  455. const std::string filename(ent->d_name);
  456. if (android::base::StartsWith(filename, kPublicNativeLibrariesExtensionConfigPrefix) &&
  457. android::base::EndsWith(filename, kPublicNativeLibrariesExtensionConfigSuffix)) {
  458. const size_t start = kPublicNativeLibrariesExtensionConfigPrefixLen;
  459. const size_t end = filename.size() - kPublicNativeLibrariesExtensionConfigSuffixLen;
  460. const std::string company_name = filename.substr(start, end - start);
  461. const std::string config_file_path = dirname + "/"s + filename;
  462. LOG_ALWAYS_FATAL_IF(
  463. company_name.empty(),
  464. "Error extracting company name from public native library list file path \"%s\"",
  465. config_file_path.c_str());
  466. std::string error_msg;
  467. LOG_ALWAYS_FATAL_IF(
  468. !ReadConfig(
  469. config_file_path, sonames,
  470. [&company_name](const std::string& soname, std::string* error_msg) {
  471. if (android::base::StartsWith(soname, "lib") &&
  472. android::base::EndsWith(soname, "." + company_name + ".so")) {
  473. return true;
  474. } else {
  475. *error_msg = "Library name \"" + soname +
  476. "\" does not end with the company name: " + company_name + ".";
  477. return false;
  478. }
  479. },
  480. &error_msg),
  481. "Error reading public native library list from \"%s\": %s", config_file_path.c_str(),
  482. error_msg.c_str());
  483. }
  484. }
  485. }
  486. }
  487. /**
  488. * Remove the public libs in runtime namespace
  489. */
  490. void removePublicLibsIfExistsInRuntimeApex(std::vector<std::string>& sonames) {
  491. for (const std::string& lib_name : kRuntimePublicLibraries) {
  492. std::string path(kRuntimeApexLibPath);
  493. path.append("/").append(lib_name);
  494. struct stat s;
  495. // Do nothing if the path in /apex does not exist.
  496. // Runtime APEX must be mounted since libnativeloader is in the same APEX
  497. if (stat(path.c_str(), &s) != 0) {
  498. continue;
  499. }
  500. auto it = std::find(sonames.begin(), sonames.end(), lib_name);
  501. if (it != sonames.end()) {
  502. sonames.erase(it);
  503. }
  504. }
  505. }
  506. bool ReadConfig(const std::string& configFile, std::vector<std::string>* sonames,
  507. const std::function<bool(const std::string& /* soname */,
  508. std::string* /* error_msg */)>& check_soname,
  509. std::string* error_msg = nullptr) {
  510. // Read list of public native libraries from the config file.
  511. std::string file_content;
  512. if(!base::ReadFileToString(configFile, &file_content)) {
  513. if (error_msg) *error_msg = strerror(errno);
  514. return false;
  515. }
  516. std::vector<std::string> lines = base::Split(file_content, "\n");
  517. for (auto& line : lines) {
  518. auto trimmed_line = base::Trim(line);
  519. if (trimmed_line[0] == '#' || trimmed_line.empty()) {
  520. continue;
  521. }
  522. size_t space_pos = trimmed_line.rfind(' ');
  523. if (space_pos != std::string::npos) {
  524. std::string type = trimmed_line.substr(space_pos + 1);
  525. if (type != "32" && type != "64") {
  526. if (error_msg) *error_msg = "Malformed line: " + line;
  527. return false;
  528. }
  529. #if defined(__LP64__)
  530. // Skip 32 bit public library.
  531. if (type == "32") {
  532. continue;
  533. }
  534. #else
  535. // Skip 64 bit public library.
  536. if (type == "64") {
  537. continue;
  538. }
  539. #endif
  540. trimmed_line.resize(space_pos);
  541. }
  542. if (check_soname(trimmed_line, error_msg)) {
  543. sonames->push_back(trimmed_line);
  544. } else {
  545. return false;
  546. }
  547. }
  548. return true;
  549. }
  550. bool InitPublicNamespace(const char* library_path, std::string* error_msg) {
  551. // Ask native bride if this apps library path should be handled by it
  552. bool is_native_bridge = NativeBridgeIsPathSupported(library_path);
  553. // (http://b/25844435) - Some apps call dlopen from generated code (mono jited
  554. // code is one example) unknown to linker in which case linker uses anonymous
  555. // namespace. The second argument specifies the search path for the anonymous
  556. // namespace which is the library_path of the classloader.
  557. initialized_ = android_init_anonymous_namespace(system_public_libraries_.c_str(),
  558. is_native_bridge ? nullptr : library_path);
  559. if (!initialized_) {
  560. *error_msg = dlerror();
  561. return false;
  562. }
  563. // and now initialize native bridge namespaces if necessary.
  564. if (NativeBridgeInitialized()) {
  565. initialized_ = NativeBridgeInitAnonymousNamespace(system_public_libraries_.c_str(),
  566. is_native_bridge ? library_path : nullptr);
  567. if (!initialized_) {
  568. *error_msg = NativeBridgeGetError();
  569. }
  570. }
  571. return initialized_;
  572. }
  573. jobject GetParentClassLoader(JNIEnv* env, jobject class_loader) {
  574. jclass class_loader_class = env->FindClass("java/lang/ClassLoader");
  575. jmethodID get_parent = env->GetMethodID(class_loader_class,
  576. "getParent",
  577. "()Ljava/lang/ClassLoader;");
  578. return env->CallObjectMethod(class_loader, get_parent);
  579. }
  580. NativeLoaderNamespace* FindParentNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
  581. jobject parent_class_loader = GetParentClassLoader(env, class_loader);
  582. while (parent_class_loader != nullptr) {
  583. NativeLoaderNamespace* ns;
  584. if ((ns = FindNamespaceByClassLoader(env, parent_class_loader)) != nullptr) {
  585. return ns;
  586. }
  587. parent_class_loader = GetParentClassLoader(env, parent_class_loader);
  588. }
  589. return nullptr;
  590. }
  591. ApkOrigin GetApkOriginFromDexPath(JNIEnv* env, jstring dex_path) {
  592. ApkOrigin apk_origin = APK_ORIGIN_DEFAULT;
  593. if (dex_path != nullptr) {
  594. ScopedUtfChars dex_path_utf_chars(env, dex_path);
  595. if (std::regex_search(dex_path_utf_chars.c_str(), kVendorDexPathRegex)) {
  596. apk_origin = APK_ORIGIN_VENDOR;
  597. }
  598. if (std::regex_search(dex_path_utf_chars.c_str(), kProductDexPathRegex)) {
  599. LOG_ALWAYS_FATAL_IF(apk_origin == APK_ORIGIN_VENDOR,
  600. "Dex path contains both vendor and product partition : %s",
  601. dex_path_utf_chars.c_str());
  602. apk_origin = APK_ORIGIN_PRODUCT;
  603. }
  604. }
  605. return apk_origin;
  606. }
  607. bool initialized_;
  608. std::list<std::pair<jweak, NativeLoaderNamespace>> namespaces_;
  609. std::string system_public_libraries_;
  610. std::string vendor_public_libraries_;
  611. std::string oem_public_libraries_;
  612. std::string product_public_libraries_;
  613. std::string system_llndk_libraries_;
  614. std::string system_vndksp_libraries_;
  615. DISALLOW_COPY_AND_ASSIGN(LibraryNamespaces);
  616. };
  617. static std::mutex g_namespaces_mutex;
  618. static LibraryNamespaces* g_namespaces = new LibraryNamespaces;
  619. #endif
  620. void InitializeNativeLoader() {
  621. #if defined(__ANDROID__)
  622. std::lock_guard<std::mutex> guard(g_namespaces_mutex);
  623. g_namespaces->Initialize();
  624. #endif
  625. }
  626. void ResetNativeLoader() {
  627. #if defined(__ANDROID__)
  628. std::lock_guard<std::mutex> guard(g_namespaces_mutex);
  629. g_namespaces->Reset();
  630. #endif
  631. }
  632. jstring CreateClassLoaderNamespace(JNIEnv* env, int32_t target_sdk_version, jobject class_loader,
  633. bool is_shared, jstring dex_path, jstring library_path,
  634. jstring permitted_path) {
  635. #if defined(__ANDROID__)
  636. std::lock_guard<std::mutex> guard(g_namespaces_mutex);
  637. std::string error_msg;
  638. bool success = g_namespaces->Create(env, target_sdk_version, class_loader, is_shared, dex_path,
  639. library_path, permitted_path, &error_msg) != nullptr;
  640. if (!success) {
  641. return env->NewStringUTF(error_msg.c_str());
  642. }
  643. #else
  644. UNUSED(env, target_sdk_version, class_loader, is_shared, dex_path, library_path, permitted_path);
  645. #endif
  646. return nullptr;
  647. }
  648. #if defined(__ANDROID__)
  649. static android_namespace_t* FindExportedNamespace(const char* caller_location) {
  650. std::string location = caller_location;
  651. // Lots of implicit assumptions here: we expect `caller_location` to be of the form:
  652. // /apex/com.android...modulename/...
  653. //
  654. // And we extract from it 'modulename', which is the name of the linker namespace.
  655. if (android::base::StartsWith(location, kApexPath)) {
  656. size_t slash_index = location.find_first_of('/', strlen(kApexPath));
  657. LOG_ALWAYS_FATAL_IF((slash_index == std::string::npos),
  658. "Error finding namespace of apex: no slash in path %s", caller_location);
  659. size_t dot_index = location.find_last_of('.', slash_index);
  660. LOG_ALWAYS_FATAL_IF((dot_index == std::string::npos),
  661. "Error finding namespace of apex: no dot in apex name %s", caller_location);
  662. std::string name = location.substr(dot_index + 1, slash_index - dot_index - 1);
  663. android_namespace_t* boot_namespace = android_get_exported_namespace(name.c_str());
  664. LOG_ALWAYS_FATAL_IF((boot_namespace == nullptr),
  665. "Error finding namespace of apex: no namespace called %s", name.c_str());
  666. return boot_namespace;
  667. }
  668. return nullptr;
  669. }
  670. #endif
  671. void* OpenNativeLibrary(JNIEnv* env, int32_t target_sdk_version, const char* path,
  672. jobject class_loader, const char* caller_location, jstring library_path,
  673. bool* needs_native_bridge, char** error_msg) {
  674. #if defined(__ANDROID__)
  675. UNUSED(target_sdk_version);
  676. if (class_loader == nullptr) {
  677. *needs_native_bridge = false;
  678. if (caller_location != nullptr) {
  679. android_namespace_t* boot_namespace = FindExportedNamespace(caller_location);
  680. if (boot_namespace != nullptr) {
  681. const android_dlextinfo dlextinfo = {
  682. .flags = ANDROID_DLEXT_USE_NAMESPACE,
  683. .library_namespace = boot_namespace,
  684. };
  685. void* handle = android_dlopen_ext(path, RTLD_NOW, &dlextinfo);
  686. if (handle == nullptr) {
  687. *error_msg = strdup(dlerror());
  688. }
  689. return handle;
  690. }
  691. }
  692. void* handle = dlopen(path, RTLD_NOW);
  693. if (handle == nullptr) {
  694. *error_msg = strdup(dlerror());
  695. }
  696. return handle;
  697. }
  698. std::lock_guard<std::mutex> guard(g_namespaces_mutex);
  699. NativeLoaderNamespace* ns;
  700. if ((ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader)) == nullptr) {
  701. // This is the case where the classloader was not created by ApplicationLoaders
  702. // In this case we create an isolated not-shared namespace for it.
  703. std::string create_error_msg;
  704. if ((ns = g_namespaces->Create(env, target_sdk_version, class_loader, false /* is_shared */,
  705. nullptr, library_path, nullptr, &create_error_msg)) == nullptr) {
  706. *error_msg = strdup(create_error_msg.c_str());
  707. return nullptr;
  708. }
  709. }
  710. return OpenNativeLibraryInNamespace(ns, path, needs_native_bridge, error_msg);
  711. #else
  712. UNUSED(env, target_sdk_version, class_loader, caller_location);
  713. // Do some best effort to emulate library-path support. It will not
  714. // work for dependencies.
  715. //
  716. // Note: null has a special meaning and must be preserved.
  717. std::string c_library_path; // Empty string by default.
  718. if (library_path != nullptr && path != nullptr && path[0] != '/') {
  719. ScopedUtfChars library_path_utf_chars(env, library_path);
  720. c_library_path = library_path_utf_chars.c_str();
  721. }
  722. std::vector<std::string> library_paths = base::Split(c_library_path, ":");
  723. for (const std::string& lib_path : library_paths) {
  724. *needs_native_bridge = false;
  725. const char* path_arg;
  726. std::string complete_path;
  727. if (path == nullptr) {
  728. // Preserve null.
  729. path_arg = nullptr;
  730. } else {
  731. complete_path = lib_path;
  732. if (!complete_path.empty()) {
  733. complete_path.append("/");
  734. }
  735. complete_path.append(path);
  736. path_arg = complete_path.c_str();
  737. }
  738. void* handle = dlopen(path_arg, RTLD_NOW);
  739. if (handle != nullptr) {
  740. return handle;
  741. }
  742. if (NativeBridgeIsSupported(path_arg)) {
  743. *needs_native_bridge = true;
  744. handle = NativeBridgeLoadLibrary(path_arg, RTLD_NOW);
  745. if (handle != nullptr) {
  746. return handle;
  747. }
  748. *error_msg = strdup(NativeBridgeGetError());
  749. } else {
  750. *error_msg = strdup(dlerror());
  751. }
  752. }
  753. return nullptr;
  754. #endif
  755. }
  756. bool CloseNativeLibrary(void* handle, const bool needs_native_bridge, char** error_msg) {
  757. bool success;
  758. if (needs_native_bridge) {
  759. success = (NativeBridgeUnloadLibrary(handle) == 0);
  760. if (!success) {
  761. *error_msg = strdup(NativeBridgeGetError());
  762. }
  763. } else {
  764. success = (dlclose(handle) == 0);
  765. if (!success) {
  766. *error_msg = strdup(dlerror());
  767. }
  768. }
  769. return success;
  770. }
  771. void NativeLoaderFreeErrorMessage(char* msg) {
  772. // The error messages get allocated through strdup, so we must call free on them.
  773. free(msg);
  774. }
  775. #if defined(__ANDROID__)
  776. void* OpenNativeLibraryInNamespace(NativeLoaderNamespace* ns, const char* path,
  777. bool* needs_native_bridge, char** error_msg) {
  778. if (ns->is_android_namespace()) {
  779. android_dlextinfo extinfo;
  780. extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
  781. extinfo.library_namespace = ns->get_android_ns();
  782. void* handle = android_dlopen_ext(path, RTLD_NOW, &extinfo);
  783. if (handle == nullptr) {
  784. *error_msg = strdup(dlerror());
  785. }
  786. *needs_native_bridge = false;
  787. return handle;
  788. } else {
  789. void* handle = NativeBridgeLoadLibraryExt(path, RTLD_NOW, ns->get_native_bridge_ns());
  790. if (handle == nullptr) {
  791. *error_msg = strdup(NativeBridgeGetError());
  792. }
  793. *needs_native_bridge = true;
  794. return handle;
  795. }
  796. }
  797. // native_bridge_namespaces are not supported for callers of this function.
  798. // This function will return nullptr in the case when application is running
  799. // on native bridge.
  800. android_namespace_t* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
  801. std::lock_guard<std::mutex> guard(g_namespaces_mutex);
  802. NativeLoaderNamespace* ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader);
  803. if (ns != nullptr) {
  804. return ns->is_android_namespace() ? ns->get_android_ns() : nullptr;
  805. }
  806. return nullptr;
  807. }
  808. NativeLoaderNamespace* FindNativeLoaderNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
  809. std::lock_guard<std::mutex> guard(g_namespaces_mutex);
  810. return g_namespaces->FindNamespaceByClassLoader(env, class_loader);
  811. }
  812. #endif
  813. }; // android namespace