File: native_loader.cpp

package info (click to toggle)
android-platform-system-core 1%3A10.0.0%2Br36-7
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 123,760 kB
  • sloc: cpp: 197,034; ansic: 18,211; asm: 3,606; sh: 3,180; python: 2,671; java: 693; xml: 266; makefile: 237
file content (952 lines) | stat: -rw-r--r-- 36,934 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "nativeloader/native_loader.h"
#include <nativehelper/ScopedUtfChars.h>

#include <dlfcn.h>
#ifdef __ANDROID__
#define LOG_TAG "libnativeloader"
#include "nativeloader/dlext_namespaces.h"
#include "log/log.h"
#endif
#include <dirent.h>
#include <sys/types.h>
#include "nativebridge/native_bridge.h"

#include <algorithm>
#include <list>
#include <memory>
#include <mutex>
#include <regex>
#include <string>
#include <vector>

#include <android-base/file.h>
#include <android-base/macros.h>
#include <android-base/strings.h>

#ifdef __BIONIC__
#include <android-base/properties.h>
#endif

#define CHECK(predicate) LOG_ALWAYS_FATAL_IF(!(predicate),\
                                             "%s:%d: %s CHECK '" #predicate "' failed.",\
                                             __FILE__, __LINE__, __FUNCTION__)

using namespace std::string_literals;

namespace android {

#if defined(__ANDROID__)
struct NativeLoaderNamespace {
 public:
  NativeLoaderNamespace()
      : android_ns_(nullptr), native_bridge_ns_(nullptr) { }

  explicit NativeLoaderNamespace(android_namespace_t* ns)
      : android_ns_(ns), native_bridge_ns_(nullptr) { }

  explicit NativeLoaderNamespace(native_bridge_namespace_t* ns)
      : android_ns_(nullptr), native_bridge_ns_(ns) { }

  NativeLoaderNamespace(NativeLoaderNamespace&& that) = default;
  NativeLoaderNamespace(const NativeLoaderNamespace& that) = default;

  NativeLoaderNamespace& operator=(const NativeLoaderNamespace& that) = default;

  android_namespace_t* get_android_ns() const {
    CHECK(native_bridge_ns_ == nullptr);
    return android_ns_;
  }

  native_bridge_namespace_t* get_native_bridge_ns() const {
    CHECK(android_ns_ == nullptr);
    return native_bridge_ns_;
  }

  bool is_android_namespace() const {
    return native_bridge_ns_ == nullptr;
  }

 private:
  // Only one of them can be not null
  android_namespace_t* android_ns_;
  native_bridge_namespace_t* native_bridge_ns_;
};

static constexpr const char kPublicNativeLibrariesSystemConfigPathFromRoot[] =
    "/etc/public.libraries.txt";
static constexpr const char kPublicNativeLibrariesExtensionConfigPrefix[] = "public.libraries-";
static constexpr const size_t kPublicNativeLibrariesExtensionConfigPrefixLen =
    sizeof(kPublicNativeLibrariesExtensionConfigPrefix) - 1;
static constexpr const char kPublicNativeLibrariesExtensionConfigSuffix[] = ".txt";
static constexpr const size_t kPublicNativeLibrariesExtensionConfigSuffixLen =
    sizeof(kPublicNativeLibrariesExtensionConfigSuffix) - 1;
static constexpr const char kPublicNativeLibrariesVendorConfig[] =
    "/vendor/etc/public.libraries.txt";
static constexpr const char kLlndkNativeLibrariesSystemConfigPathFromRoot[] =
    "/etc/llndk.libraries.txt";
static constexpr const char kVndkspNativeLibrariesSystemConfigPathFromRoot[] =
    "/etc/vndksp.libraries.txt";

static const std::vector<const std::string> kRuntimePublicLibraries = {
    "libicuuc.so",
    "libicui18n.so",
};

// The device may be configured to have the vendor libraries loaded to a separate namespace.
// For historical reasons this namespace was named sphal but effectively it is intended
// to use to load vendor libraries to separate namespace with controlled interface between
// vendor and system namespaces.
static constexpr const char* kVendorNamespaceName = "sphal";

static constexpr const char* kVndkNamespaceName = "vndk";

static constexpr const char* kDefaultNamespaceName = "default";
static constexpr const char* kPlatformNamespaceName = "platform";
static constexpr const char* kRuntimeNamespaceName = "runtime";

// classloader-namespace is a linker namespace that is created for the loaded
// app. To be specific, it is created for the app classloader. When
// System.load() is called from a Java class that is loaded from the
// classloader, the classloader-namespace namespace associated with that
// classloader is selected for dlopen. The namespace is configured so that its
// search path is set to the app-local JNI directory and it is linked to the
// default namespace with the names of libs listed in the public.libraries.txt.
// This way an app can only load its own JNI libraries along with the public libs.
static constexpr const char* kClassloaderNamespaceName = "classloader-namespace";
// Same thing for vendor APKs.
static constexpr const char* kVendorClassloaderNamespaceName = "vendor-classloader-namespace";

// (http://b/27588281) This is a workaround for apps using custom classloaders and calling
// System.load() with an absolute path which is outside of the classloader library search path.
// This list includes all directories app is allowed to access this way.
static constexpr const char* kWhitelistedDirectories = "/data:/mnt/expand";

static constexpr const char* kApexPath = "/apex/";

#if defined(__LP64__)
static constexpr const char* kRuntimeApexLibPath = "/apex/com.android.runtime/lib64";
static constexpr const char* kVendorLibPath = "/vendor/lib64";
static constexpr const char* kProductLibPath = "/product/lib64:/system/product/lib64";
#else
static constexpr const char* kRuntimeApexLibPath = "/apex/com.android.runtime/lib";
static constexpr const char* kVendorLibPath = "/vendor/lib";
static constexpr const char* kProductLibPath = "/product/lib:/system/product/lib";
#endif

static const std::regex kVendorDexPathRegex("(^|:)/vendor/");
static const std::regex kProductDexPathRegex("(^|:)(/system)?/product/");

// Define origin of APK if it is from vendor partition or product partition
typedef enum {
  APK_ORIGIN_DEFAULT = 0,
  APK_ORIGIN_VENDOR = 1,
  APK_ORIGIN_PRODUCT = 2,
} ApkOrigin;

static bool is_debuggable() {
  bool debuggable = false;
#ifdef __BIONIC__
  debuggable = android::base::GetBoolProperty("ro.debuggable", false);
#endif
  return debuggable;
}

static std::string vndk_version_str() {
#ifdef __BIONIC__
  std::string version = android::base::GetProperty("ro.vndk.version", "");
  if (version != "" && version != "current") {
    return "." + version;
  }
#endif
  return "";
}

static void insert_vndk_version_str(std::string* file_name) {
  CHECK(file_name != nullptr);
  size_t insert_pos = file_name->find_last_of(".");
  if (insert_pos == std::string::npos) {
    insert_pos = file_name->length();
  }
  file_name->insert(insert_pos, vndk_version_str());
}

static const std::function<bool(const std::string&, std::string*)> always_true =
    [](const std::string&, std::string*) { return true; };

class LibraryNamespaces {
 public:
  LibraryNamespaces() : initialized_(false) { }

  NativeLoaderNamespace* Create(JNIEnv* env, uint32_t target_sdk_version, jobject class_loader,
                                bool is_shared, jstring dex_path, jstring java_library_path,
                                jstring java_permitted_path, std::string* error_msg) {
    std::string library_path; // empty string by default.

    if (java_library_path != nullptr) {
      ScopedUtfChars library_path_utf_chars(env, java_library_path);
      library_path = library_path_utf_chars.c_str();
    }

    ApkOrigin apk_origin = GetApkOriginFromDexPath(env, dex_path);

    // (http://b/27588281) This is a workaround for apps using custom
    // classloaders and calling System.load() with an absolute path which
    // is outside of the classloader library search path.
    //
    // This part effectively allows such a classloader to access anything
    // under /data and /mnt/expand
    std::string permitted_path = kWhitelistedDirectories;

    if (java_permitted_path != nullptr) {
      ScopedUtfChars path(env, java_permitted_path);
      if (path.c_str() != nullptr && path.size() > 0) {
        permitted_path = permitted_path + ":" + path.c_str();
      }
    }

    // Initialize the anonymous namespace with the first non-empty library path.
    if (!library_path.empty() && !initialized_ &&
        !InitPublicNamespace(library_path.c_str(), error_msg)) {
      return nullptr;
    }

    bool found = FindNamespaceByClassLoader(env, class_loader);

    LOG_ALWAYS_FATAL_IF(found,
                        "There is already a namespace associated with this classloader");

    uint64_t namespace_type = ANDROID_NAMESPACE_TYPE_ISOLATED;
    if (is_shared) {
      namespace_type |= ANDROID_NAMESPACE_TYPE_SHARED;
    }

    if (target_sdk_version < 24) {
      namespace_type |= ANDROID_NAMESPACE_TYPE_GREYLIST_ENABLED;
    }

    NativeLoaderNamespace* parent_ns = FindParentNamespaceByClassLoader(env, class_loader);

    bool is_native_bridge = false;

    if (parent_ns != nullptr) {
      is_native_bridge = !parent_ns->is_android_namespace();
    } else if (!library_path.empty()) {
      is_native_bridge = NativeBridgeIsPathSupported(library_path.c_str());
    }

    std::string system_exposed_libraries = system_public_libraries_;
    const char* namespace_name = kClassloaderNamespaceName;
    android_namespace_t* vndk_ns = nullptr;
    if ((apk_origin == APK_ORIGIN_VENDOR ||
         (apk_origin == APK_ORIGIN_PRODUCT && target_sdk_version > 29)) &&
        !is_shared) {
      LOG_FATAL_IF(is_native_bridge,
                   "Unbundled vendor / product apk must not use translated architecture");

      // For vendor / product apks, give access to the vendor / product lib even though
      // they are treated as unbundled; the libs and apks are still bundled
      // together in the vendor / product partition.
      const char* origin_partition;
      const char* origin_lib_path;

      switch (apk_origin) {
        case APK_ORIGIN_VENDOR:
          origin_partition = "vendor";
          origin_lib_path = kVendorLibPath;
          break;
        case APK_ORIGIN_PRODUCT:
          origin_partition = "product";
          origin_lib_path = kProductLibPath;
          break;
        default:
          origin_partition = "unknown";
          origin_lib_path = "";
      }

      LOG_FATAL_IF(is_native_bridge, "Unbundled %s apk must not use translated architecture",
                   origin_partition);

      library_path = library_path + ":" + origin_lib_path;
      permitted_path = permitted_path + ":" + origin_lib_path;

      // Also give access to LLNDK libraries since they are available to vendors
      system_exposed_libraries = system_exposed_libraries + ":" + system_llndk_libraries_.c_str();

      // Give access to VNDK-SP libraries from the 'vndk' namespace.
      vndk_ns = android_get_exported_namespace(kVndkNamespaceName);
      if (vndk_ns == nullptr) {
        ALOGW("Cannot find \"%s\" namespace for %s apks", kVndkNamespaceName, origin_partition);
      }

      // Different name is useful for debugging
      namespace_name = kVendorClassloaderNamespaceName;
      ALOGD("classloader namespace configured for unbundled %s apk. library_path=%s",
            origin_partition, library_path.c_str());
    } else {
      // oem and product public libraries are NOT available to vendor apks, otherwise it
      // would be system->vendor violation.
      if (!oem_public_libraries_.empty()) {
        system_exposed_libraries = system_exposed_libraries + ':' + oem_public_libraries_;
      }
      if (!product_public_libraries_.empty()) {
        system_exposed_libraries = system_exposed_libraries + ':' + product_public_libraries_;
      }
    }

    std::string runtime_exposed_libraries = base::Join(kRuntimePublicLibraries, ":");

    NativeLoaderNamespace native_loader_ns;
    if (!is_native_bridge) {
      android_namespace_t* android_parent_ns;
      if (parent_ns != nullptr) {
        android_parent_ns = parent_ns->get_android_ns();
      } else {
        // Fall back to the platform namespace if no parent is found. It is
        // called "default" for binaries in /system and "platform" for those in
        // the Runtime APEX. Try "platform" first since "default" always exists.
        android_parent_ns = android_get_exported_namespace(kPlatformNamespaceName);
        if (android_parent_ns == nullptr) {
          android_parent_ns = android_get_exported_namespace(kDefaultNamespaceName);
        }
      }

      android_namespace_t* ns = android_create_namespace(namespace_name,
                                                         nullptr,
                                                         library_path.c_str(),
                                                         namespace_type,
                                                         permitted_path.c_str(),
                                                         android_parent_ns);
      if (ns == nullptr) {
        *error_msg = dlerror();
        return nullptr;
      }

      // Note that when vendor_ns is not configured this function will return nullptr
      // and it will result in linking vendor_public_libraries_ to the default namespace
      // which is expected behavior in this case.
      android_namespace_t* vendor_ns = android_get_exported_namespace(kVendorNamespaceName);

      android_namespace_t* runtime_ns = android_get_exported_namespace(kRuntimeNamespaceName);

      if (!android_link_namespaces(ns, nullptr, system_exposed_libraries.c_str())) {
        *error_msg = dlerror();
        return nullptr;
      }

      // Runtime apex does not exist in host, and under certain build conditions.
      if (runtime_ns != nullptr) {
        if (!android_link_namespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
          *error_msg = dlerror();
          return nullptr;
        }
      }

      if (vndk_ns != nullptr && !system_vndksp_libraries_.empty()) {
        // vendor apks are allowed to use VNDK-SP libraries.
        if (!android_link_namespaces(ns, vndk_ns, system_vndksp_libraries_.c_str())) {
          *error_msg = dlerror();
          return nullptr;
        }
      }

      if (!vendor_public_libraries_.empty()) {
        if (!android_link_namespaces(ns, vendor_ns, vendor_public_libraries_.c_str())) {
          *error_msg = dlerror();
          return nullptr;
        }
      }

      native_loader_ns = NativeLoaderNamespace(ns);
    } else {
      native_bridge_namespace_t* native_bridge_parent_namespace;
      if (parent_ns != nullptr) {
        native_bridge_parent_namespace = parent_ns->get_native_bridge_ns();
      } else {
        native_bridge_parent_namespace = NativeBridgeGetExportedNamespace(kPlatformNamespaceName);
        if (native_bridge_parent_namespace == nullptr) {
          native_bridge_parent_namespace = NativeBridgeGetExportedNamespace(kDefaultNamespaceName);
        }
      }

      native_bridge_namespace_t* ns = NativeBridgeCreateNamespace(namespace_name,
                                                                  nullptr,
                                                                  library_path.c_str(),
                                                                  namespace_type,
                                                                  permitted_path.c_str(),
                                                                  native_bridge_parent_namespace);
      if (ns == nullptr) {
        *error_msg = NativeBridgeGetError();
        return nullptr;
      }

      native_bridge_namespace_t* vendor_ns = NativeBridgeGetExportedNamespace(kVendorNamespaceName);
      native_bridge_namespace_t* runtime_ns =
          NativeBridgeGetExportedNamespace(kRuntimeNamespaceName);

      if (!NativeBridgeLinkNamespaces(ns, nullptr, system_exposed_libraries.c_str())) {
        *error_msg = NativeBridgeGetError();
        return nullptr;
      }

      // Runtime apex does not exist in host, and under certain build conditions.
      if (runtime_ns != nullptr) {
        if (!NativeBridgeLinkNamespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
          *error_msg = NativeBridgeGetError();
          return nullptr;
        }
      }
      if (!vendor_public_libraries_.empty()) {
        if (!NativeBridgeLinkNamespaces(ns, vendor_ns, vendor_public_libraries_.c_str())) {
          *error_msg = NativeBridgeGetError();
          return nullptr;
        }
      }

      native_loader_ns = NativeLoaderNamespace(ns);
    }

    namespaces_.push_back(std::make_pair(env->NewWeakGlobalRef(class_loader), native_loader_ns));

    return &(namespaces_.back().second);
  }

  NativeLoaderNamespace* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
    auto it = std::find_if(namespaces_.begin(), namespaces_.end(),
                [&](const std::pair<jweak, NativeLoaderNamespace>& value) {
                  return env->IsSameObject(value.first, class_loader);
                });
    if (it != namespaces_.end()) {
      return &it->second;
    }

    return nullptr;
  }

  void Initialize() {
    // Once public namespace is initialized there is no
    // point in running this code - it will have no effect
    // on the current list of public libraries.
    if (initialized_) {
      return;
    }

    std::vector<std::string> sonames;
    const char* android_root_env = getenv("ANDROID_ROOT");
    std::string root_dir = android_root_env != nullptr ? android_root_env : "/system";
    std::string public_native_libraries_system_config =
            root_dir + kPublicNativeLibrariesSystemConfigPathFromRoot;
    std::string llndk_native_libraries_system_config =
            root_dir + kLlndkNativeLibrariesSystemConfigPathFromRoot;
    std::string vndksp_native_libraries_system_config =
            root_dir + kVndkspNativeLibrariesSystemConfigPathFromRoot;

    std::string product_public_native_libraries_dir = "/product/etc";

    std::string error_msg;
    LOG_ALWAYS_FATAL_IF(
        !ReadConfig(public_native_libraries_system_config, &sonames, always_true, &error_msg),
        "Error reading public native library list from \"%s\": %s",
        public_native_libraries_system_config.c_str(), error_msg.c_str());

    // For debuggable platform builds use ANDROID_ADDITIONAL_PUBLIC_LIBRARIES environment
    // variable to add libraries to the list. This is intended for platform tests only.
    if (is_debuggable()) {
      const char* additional_libs = getenv("ANDROID_ADDITIONAL_PUBLIC_LIBRARIES");
      if (additional_libs != nullptr && additional_libs[0] != '\0') {
        std::vector<std::string> additional_libs_vector = base::Split(additional_libs, ":");
        std::copy(additional_libs_vector.begin(), additional_libs_vector.end(),
                  std::back_inserter(sonames));
      }
    }

    // Remove the public libs in the runtime namespace.
    // These libs are listed in public.android.txt, but we don't want the rest of android
    // in default namespace to dlopen the libs.
    // For example, libicuuc.so is exposed to classloader namespace from runtime namespace.
    // Unfortunately, it does not have stable C symbols, and default namespace should only use
    // stable symbols in libandroidicu.so. http://b/120786417
    removePublicLibsIfExistsInRuntimeApex(sonames);

    // android_init_namespaces() expects all the public libraries
    // to be loaded so that they can be found by soname alone.
    //
    // TODO(dimitry): this is a bit misleading since we do not know
    // if the vendor public library is going to be opened from /vendor/lib
    // we might as well end up loading them from /system/lib or /product/lib
    // For now we rely on CTS test to catch things like this but
    // it should probably be addressed in the future.
    for (const auto& soname : sonames) {
      LOG_ALWAYS_FATAL_IF(dlopen(soname.c_str(), RTLD_NOW | RTLD_NODELETE) == nullptr,
                          "Error preloading public library %s: %s", soname.c_str(), dlerror());
    }

    system_public_libraries_ = base::Join(sonames, ':');

    // read /system/etc/public.libraries-<companyname>.txt which contain partner defined
    // system libs that are exposed to apps. The libs in the txt files must be
    // named as lib<name>.<companyname>.so.
    sonames.clear();
    ReadExtensionLibraries(base::Dirname(public_native_libraries_system_config).c_str(), &sonames);
    oem_public_libraries_ = base::Join(sonames, ':');

    // read /product/etc/public.libraries-<companyname>.txt which contain partner defined
    // product libs that are exposed to apps.
    sonames.clear();
    ReadExtensionLibraries(product_public_native_libraries_dir.c_str(), &sonames);
    product_public_libraries_ = base::Join(sonames, ':');

    // Insert VNDK version to llndk and vndksp config file names.
    insert_vndk_version_str(&llndk_native_libraries_system_config);
    insert_vndk_version_str(&vndksp_native_libraries_system_config);

    sonames.clear();
    ReadConfig(llndk_native_libraries_system_config, &sonames, always_true);
    system_llndk_libraries_ = base::Join(sonames, ':');

    sonames.clear();
    ReadConfig(vndksp_native_libraries_system_config, &sonames, always_true);
    system_vndksp_libraries_ = base::Join(sonames, ':');

    sonames.clear();
    // This file is optional, quietly ignore if the file does not exist.
    ReadConfig(kPublicNativeLibrariesVendorConfig, &sonames, always_true, nullptr);

    vendor_public_libraries_ = base::Join(sonames, ':');
  }

  void Reset() { namespaces_.clear(); }

 private:
  void ReadExtensionLibraries(const char* dirname, std::vector<std::string>* sonames) {
    std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(dirname), closedir);
    if (dir != nullptr) {
      // Failing to opening the dir is not an error, which can happen in
      // webview_zygote.
      while (struct dirent* ent = readdir(dir.get())) {
        if (ent->d_type != DT_REG && ent->d_type != DT_LNK) {
          continue;
        }
        const std::string filename(ent->d_name);
        if (android::base::StartsWith(filename, kPublicNativeLibrariesExtensionConfigPrefix) &&
            android::base::EndsWith(filename, kPublicNativeLibrariesExtensionConfigSuffix)) {
          const size_t start = kPublicNativeLibrariesExtensionConfigPrefixLen;
          const size_t end = filename.size() - kPublicNativeLibrariesExtensionConfigSuffixLen;
          const std::string company_name = filename.substr(start, end - start);
          const std::string config_file_path = dirname + "/"s + filename;
          LOG_ALWAYS_FATAL_IF(
              company_name.empty(),
              "Error extracting company name from public native library list file path \"%s\"",
              config_file_path.c_str());

          std::string error_msg;

          LOG_ALWAYS_FATAL_IF(
              !ReadConfig(
                  config_file_path, sonames,
                  [&company_name](const std::string& soname, std::string* error_msg) {
                    if (android::base::StartsWith(soname, "lib") &&
                        android::base::EndsWith(soname, "." + company_name + ".so")) {
                      return true;
                    } else {
                      *error_msg = "Library name \"" + soname +
                                   "\" does not end with the company name: " + company_name + ".";
                      return false;
                    }
                  },
                  &error_msg),
              "Error reading public native library list from \"%s\": %s", config_file_path.c_str(),
              error_msg.c_str());
        }
      }
    }
  }

  /**
   * Remove the public libs in runtime namespace
   */
  void removePublicLibsIfExistsInRuntimeApex(std::vector<std::string>& sonames) {
    for (const std::string& lib_name : kRuntimePublicLibraries) {
      std::string path(kRuntimeApexLibPath);
      path.append("/").append(lib_name);

      struct stat s;
      // Do nothing if the path in /apex does not exist.
      // Runtime APEX must be mounted since libnativeloader is in the same APEX
      if (stat(path.c_str(), &s) != 0) {
        continue;
      }

      auto it = std::find(sonames.begin(), sonames.end(), lib_name);
      if (it != sonames.end()) {
        sonames.erase(it);
      }
    }
  }

  bool ReadConfig(const std::string& configFile, std::vector<std::string>* sonames,
                  const std::function<bool(const std::string& /* soname */,
                                           std::string* /* error_msg */)>& check_soname,
                  std::string* error_msg = nullptr) {
    // Read list of public native libraries from the config file.
    std::string file_content;
    if(!base::ReadFileToString(configFile, &file_content)) {
      if (error_msg) *error_msg = strerror(errno);
      return false;
    }

    std::vector<std::string> lines = base::Split(file_content, "\n");

    for (auto& line : lines) {
      auto trimmed_line = base::Trim(line);
      if (trimmed_line[0] == '#' || trimmed_line.empty()) {
        continue;
      }
      size_t space_pos = trimmed_line.rfind(' ');
      if (space_pos != std::string::npos) {
        std::string type = trimmed_line.substr(space_pos + 1);
        if (type != "32" && type != "64") {
          if (error_msg) *error_msg = "Malformed line: " + line;
          return false;
        }
#if defined(__LP64__)
        // Skip 32 bit public library.
        if (type == "32") {
          continue;
        }
#else
        // Skip 64 bit public library.
        if (type == "64") {
          continue;
        }
#endif
        trimmed_line.resize(space_pos);
      }

      if (check_soname(trimmed_line, error_msg)) {
        sonames->push_back(trimmed_line);
      } else {
        return false;
      }
    }

    return true;
  }

  bool InitPublicNamespace(const char* library_path, std::string* error_msg) {
    // Ask native bride if this apps library path should be handled by it
    bool is_native_bridge = NativeBridgeIsPathSupported(library_path);

    // (http://b/25844435) - Some apps call dlopen from generated code (mono jited
    // code is one example) unknown to linker in which  case linker uses anonymous
    // namespace. The second argument specifies the search path for the anonymous
    // namespace which is the library_path of the classloader.
    initialized_ = android_init_anonymous_namespace(system_public_libraries_.c_str(),
                                                    is_native_bridge ? nullptr : library_path);
    if (!initialized_) {
      *error_msg = dlerror();
      return false;
    }

    // and now initialize native bridge namespaces if necessary.
    if (NativeBridgeInitialized()) {
      initialized_ = NativeBridgeInitAnonymousNamespace(system_public_libraries_.c_str(),
                                                        is_native_bridge ? library_path : nullptr);
      if (!initialized_) {
        *error_msg = NativeBridgeGetError();
      }
    }

    return initialized_;
  }

  jobject GetParentClassLoader(JNIEnv* env, jobject class_loader) {
    jclass class_loader_class = env->FindClass("java/lang/ClassLoader");
    jmethodID get_parent = env->GetMethodID(class_loader_class,
                                            "getParent",
                                            "()Ljava/lang/ClassLoader;");

    return env->CallObjectMethod(class_loader, get_parent);
  }

  NativeLoaderNamespace* FindParentNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
    jobject parent_class_loader = GetParentClassLoader(env, class_loader);

    while (parent_class_loader != nullptr) {
      NativeLoaderNamespace* ns;
      if ((ns = FindNamespaceByClassLoader(env, parent_class_loader)) != nullptr) {
        return ns;
      }

      parent_class_loader = GetParentClassLoader(env, parent_class_loader);
    }

    return nullptr;
  }

  ApkOrigin GetApkOriginFromDexPath(JNIEnv* env, jstring dex_path) {
    ApkOrigin apk_origin = APK_ORIGIN_DEFAULT;

    if (dex_path != nullptr) {
      ScopedUtfChars dex_path_utf_chars(env, dex_path);

      if (std::regex_search(dex_path_utf_chars.c_str(), kVendorDexPathRegex)) {
        apk_origin = APK_ORIGIN_VENDOR;
      }

      if (std::regex_search(dex_path_utf_chars.c_str(), kProductDexPathRegex)) {
        LOG_ALWAYS_FATAL_IF(apk_origin == APK_ORIGIN_VENDOR,
                            "Dex path contains both vendor and product partition : %s",
                            dex_path_utf_chars.c_str());

        apk_origin = APK_ORIGIN_PRODUCT;
      }
    }

    return apk_origin;
  }

  bool initialized_;
  std::list<std::pair<jweak, NativeLoaderNamespace>> namespaces_;
  std::string system_public_libraries_;
  std::string vendor_public_libraries_;
  std::string oem_public_libraries_;
  std::string product_public_libraries_;
  std::string system_llndk_libraries_;
  std::string system_vndksp_libraries_;

  DISALLOW_COPY_AND_ASSIGN(LibraryNamespaces);
};

static std::mutex g_namespaces_mutex;
static LibraryNamespaces* g_namespaces = new LibraryNamespaces;
#endif

void InitializeNativeLoader() {
#if defined(__ANDROID__)
  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
  g_namespaces->Initialize();
#endif
}

void ResetNativeLoader() {
#if defined(__ANDROID__)
  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
  g_namespaces->Reset();
#endif
}

jstring CreateClassLoaderNamespace(JNIEnv* env, int32_t target_sdk_version, jobject class_loader,
                                   bool is_shared, jstring dex_path, jstring library_path,
                                   jstring permitted_path) {
#if defined(__ANDROID__)
  std::lock_guard<std::mutex> guard(g_namespaces_mutex);

  std::string error_msg;
  bool success = g_namespaces->Create(env, target_sdk_version, class_loader, is_shared, dex_path,
                                      library_path, permitted_path, &error_msg) != nullptr;
  if (!success) {
    return env->NewStringUTF(error_msg.c_str());
  }
#else
  UNUSED(env, target_sdk_version, class_loader, is_shared, dex_path, library_path, permitted_path);
#endif
  return nullptr;
}

#if defined(__ANDROID__)
static android_namespace_t* FindExportedNamespace(const char* caller_location) {
  std::string location = caller_location;
  // Lots of implicit assumptions here: we expect `caller_location` to be of the form:
  // /apex/com.android...modulename/...
  //
  // And we extract from it 'modulename', which is the name of the linker namespace.
  if (android::base::StartsWith(location, kApexPath)) {
    size_t slash_index = location.find_first_of('/', strlen(kApexPath));
    LOG_ALWAYS_FATAL_IF((slash_index == std::string::npos),
                        "Error finding namespace of apex: no slash in path %s", caller_location);
    size_t dot_index = location.find_last_of('.', slash_index);
    LOG_ALWAYS_FATAL_IF((dot_index == std::string::npos),
                        "Error finding namespace of apex: no dot in apex name %s", caller_location);
    std::string name = location.substr(dot_index + 1, slash_index - dot_index - 1);
    android_namespace_t* boot_namespace = android_get_exported_namespace(name.c_str());
    LOG_ALWAYS_FATAL_IF((boot_namespace == nullptr),
                        "Error finding namespace of apex: no namespace called %s", name.c_str());
    return boot_namespace;
  }
  return nullptr;
}
#endif

void* OpenNativeLibrary(JNIEnv* env, int32_t target_sdk_version, const char* path,
                        jobject class_loader, const char* caller_location, jstring library_path,
                        bool* needs_native_bridge, char** error_msg) {
#if defined(__ANDROID__)
  UNUSED(target_sdk_version);
  if (class_loader == nullptr) {
    *needs_native_bridge = false;
    if (caller_location != nullptr) {
      android_namespace_t* boot_namespace = FindExportedNamespace(caller_location);
      if (boot_namespace != nullptr) {
        const android_dlextinfo dlextinfo = {
            .flags = ANDROID_DLEXT_USE_NAMESPACE,
            .library_namespace = boot_namespace,
        };
        void* handle = android_dlopen_ext(path, RTLD_NOW, &dlextinfo);
        if (handle == nullptr) {
          *error_msg = strdup(dlerror());
        }
        return handle;
      }
    }
    void* handle = dlopen(path, RTLD_NOW);
    if (handle == nullptr) {
      *error_msg = strdup(dlerror());
    }
    return handle;
  }

  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
  NativeLoaderNamespace* ns;

  if ((ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader)) == nullptr) {
    // This is the case where the classloader was not created by ApplicationLoaders
    // In this case we create an isolated not-shared namespace for it.
    std::string create_error_msg;
    if ((ns = g_namespaces->Create(env, target_sdk_version, class_loader, false /* is_shared */,
                                   nullptr, library_path, nullptr, &create_error_msg)) == nullptr) {
      *error_msg = strdup(create_error_msg.c_str());
      return nullptr;
    }
  }

  return OpenNativeLibraryInNamespace(ns, path, needs_native_bridge, error_msg);
#else
  UNUSED(env, target_sdk_version, class_loader, caller_location);

  // Do some best effort to emulate library-path support. It will not
  // work for dependencies.
  //
  // Note: null has a special meaning and must be preserved.
  std::string c_library_path;  // Empty string by default.
  if (library_path != nullptr && path != nullptr && path[0] != '/') {
    ScopedUtfChars library_path_utf_chars(env, library_path);
    c_library_path = library_path_utf_chars.c_str();
  }

  std::vector<std::string> library_paths = base::Split(c_library_path, ":");

  for (const std::string& lib_path : library_paths) {
    *needs_native_bridge = false;
    const char* path_arg;
    std::string complete_path;
    if (path == nullptr) {
      // Preserve null.
      path_arg = nullptr;
    } else {
      complete_path = lib_path;
      if (!complete_path.empty()) {
        complete_path.append("/");
      }
      complete_path.append(path);
      path_arg = complete_path.c_str();
    }
    void* handle = dlopen(path_arg, RTLD_NOW);
    if (handle != nullptr) {
      return handle;
    }
    if (NativeBridgeIsSupported(path_arg)) {
      *needs_native_bridge = true;
      handle = NativeBridgeLoadLibrary(path_arg, RTLD_NOW);
      if (handle != nullptr) {
        return handle;
      }
      *error_msg = strdup(NativeBridgeGetError());
    } else {
      *error_msg = strdup(dlerror());
    }
  }
  return nullptr;
#endif
}

bool CloseNativeLibrary(void* handle, const bool needs_native_bridge, char** error_msg) {
  bool success;
  if (needs_native_bridge) {
    success = (NativeBridgeUnloadLibrary(handle) == 0);
    if (!success) {
      *error_msg = strdup(NativeBridgeGetError());
    }
  } else {
    success = (dlclose(handle) == 0);
    if (!success) {
      *error_msg = strdup(dlerror());
    }
  }

  return success;
}

void NativeLoaderFreeErrorMessage(char* msg) {
  // The error messages get allocated through strdup, so we must call free on them.
  free(msg);
}

#if defined(__ANDROID__)
void* OpenNativeLibraryInNamespace(NativeLoaderNamespace* ns, const char* path,
                                   bool* needs_native_bridge, char** error_msg) {
  if (ns->is_android_namespace()) {
    android_dlextinfo extinfo;
    extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
    extinfo.library_namespace = ns->get_android_ns();

    void* handle = android_dlopen_ext(path, RTLD_NOW, &extinfo);
    if (handle == nullptr) {
      *error_msg = strdup(dlerror());
    }
    *needs_native_bridge = false;
    return handle;
  } else {
    void* handle = NativeBridgeLoadLibraryExt(path, RTLD_NOW, ns->get_native_bridge_ns());
    if (handle == nullptr) {
      *error_msg = strdup(NativeBridgeGetError());
    }
    *needs_native_bridge = true;
    return handle;
  }
}

// native_bridge_namespaces are not supported for callers of this function.
// This function will return nullptr in the case when application is running
// on native bridge.
android_namespace_t* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
  NativeLoaderNamespace* ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader);
  if (ns != nullptr) {
    return ns->is_android_namespace() ? ns->get_android_ns() : nullptr;
  }

  return nullptr;
}
NativeLoaderNamespace* FindNativeLoaderNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
  return g_namespaces->FindNamespaceByClassLoader(env, class_loader);
}
#endif

}; //  android namespace