xref: /aosp_15_r20/external/libchrome/base/android/library_loader/library_prefetcher.h (revision 635a864187cb8b6c713ff48b7e790a6b21769273)
1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_ANDROID_LIBRARY_LOADER_LIBRARY_PREFETCHER_H_
6 #define BASE_ANDROID_LIBRARY_LOADER_LIBRARY_PREFETCHER_H_
7 
8 #include <jni.h>
9 
10 #include <stdint.h>
11 
12 #include "base/android/library_loader/anchor_functions_buildflags.h"
13 #include "base/base_export.h"
14 #include "base/gtest_prod_util.h"
15 #include "base/macros.h"
16 
17 #if BUILDFLAG(SUPPORTS_CODE_ORDERING)
18 
19 namespace base {
20 namespace android {
21 
22 // Forks and waits for a process prefetching the native library. This is done in
23 // a forked process for the following reasons:
24 // - Isolating the main process from mistakes in getting the address range, only
25 //   crashing the forked process in case of mistake.
26 // - Not inflating the memory used by the main process uselessly, which could
27 //   increase its likelihood to be killed.
28 // The forked process has background priority and, since it is not declared to
29 // the Android runtime, can be killed at any time, which is not an issue here.
30 class BASE_EXPORT NativeLibraryPrefetcher {
31  public:
32   // Finds the executable code range, forks a low priority process pre-fetching
33   // it wait()s for the process to exit or die. If ordered_only is true, only
34   // the ordered section is prefetched. See GetOrdrderedTextRange() in
35   // library_prefetcher.cc.
36   static void ForkAndPrefetchNativeLibrary(bool ordered_only);
37 
38   // Returns the percentage of the native library code currently resident in
39   // memory, or -1 in case of error.
40   static int PercentageOfResidentNativeLibraryCode();
41 
42   // Collects residency for the native library executable multiple times, then
43   // dumps it to disk.
44   static void PeriodicallyCollectResidency();
45 
46   // Calls madvise() on the native library executable, using orderfile
47   // information to decide how to advise each part of the library.
48   static void MadviseForOrderfile();
49 
50  private:
51   // Returns the percentage of [start, end] currently resident in
52   // memory, or -1 in case of error.
53   static int PercentageOfResidentCode(size_t start, size_t end);
54 
55   FRIEND_TEST_ALL_PREFIXES(NativeLibraryPrefetcherTest,
56                            TestPercentageOfResidentCode);
57 
58   DISALLOW_IMPLICIT_CONSTRUCTORS(NativeLibraryPrefetcher);
59 };
60 
61 }  // namespace android
62 }  // namespace base
63 
64 #endif  // BUILDFLAG(SUPPORTS_CODE_ORDERING)
65 
66 #endif  // BASE_ANDROID_LIBRARY_LOADER_LIBRARY_PREFETCHER_H_
67