xref: /aosp_15_r20/art/runtime/jit/debugger_interface.cc (revision 795d594fd825385562da6b089ea9b2033f3abf5a)
1*795d594fSAndroid Build Coastguard Worker /*
2*795d594fSAndroid Build Coastguard Worker  * Copyright (C) 2015 The Android Open Source Project
3*795d594fSAndroid Build Coastguard Worker  *
4*795d594fSAndroid Build Coastguard Worker  * Licensed under the Apache License, Version 2.0 (the "License");
5*795d594fSAndroid Build Coastguard Worker  * you may not use this file except in compliance with the License.
6*795d594fSAndroid Build Coastguard Worker  * You may obtain a copy of the License at
7*795d594fSAndroid Build Coastguard Worker  *
8*795d594fSAndroid Build Coastguard Worker  *      http://www.apache.org/licenses/LICENSE-2.0
9*795d594fSAndroid Build Coastguard Worker  *
10*795d594fSAndroid Build Coastguard Worker  * Unless required by applicable law or agreed to in writing, software
11*795d594fSAndroid Build Coastguard Worker  * distributed under the License is distributed on an "AS IS" BASIS,
12*795d594fSAndroid Build Coastguard Worker  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13*795d594fSAndroid Build Coastguard Worker  * See the License for the specific language governing permissions and
14*795d594fSAndroid Build Coastguard Worker  * limitations under the License.
15*795d594fSAndroid Build Coastguard Worker  */
16*795d594fSAndroid Build Coastguard Worker 
17*795d594fSAndroid Build Coastguard Worker #include "debugger_interface.h"
18*795d594fSAndroid Build Coastguard Worker 
19*795d594fSAndroid Build Coastguard Worker #include <android-base/logging.h>
20*795d594fSAndroid Build Coastguard Worker 
21*795d594fSAndroid Build Coastguard Worker #include "base/array_ref.h"
22*795d594fSAndroid Build Coastguard Worker #include "base/bit_utils.h"
23*795d594fSAndroid Build Coastguard Worker #include "base/logging.h"
24*795d594fSAndroid Build Coastguard Worker #include "base/mutex.h"
25*795d594fSAndroid Build Coastguard Worker #include "base/time_utils.h"
26*795d594fSAndroid Build Coastguard Worker #include "base/utils.h"
27*795d594fSAndroid Build Coastguard Worker #include "dex/dex_file.h"
28*795d594fSAndroid Build Coastguard Worker #include "elf/elf_debug_reader.h"
29*795d594fSAndroid Build Coastguard Worker #include "jit/jit.h"
30*795d594fSAndroid Build Coastguard Worker #include "jit/jit_code_cache.h"
31*795d594fSAndroid Build Coastguard Worker #include "jit/jit_memory_region.h"
32*795d594fSAndroid Build Coastguard Worker #include "runtime.h"
33*795d594fSAndroid Build Coastguard Worker #include "thread-current-inl.h"
34*795d594fSAndroid Build Coastguard Worker #include "thread.h"
35*795d594fSAndroid Build Coastguard Worker 
36*795d594fSAndroid Build Coastguard Worker #include <atomic>
37*795d594fSAndroid Build Coastguard Worker #include <cstddef>
38*795d594fSAndroid Build Coastguard Worker 
39*795d594fSAndroid Build Coastguard Worker //
40*795d594fSAndroid Build Coastguard Worker // Debug interface for native tools (gdb, lldb, libunwind, simpleperf).
41*795d594fSAndroid Build Coastguard Worker //
42*795d594fSAndroid Build Coastguard Worker // See http://sourceware.org/gdb/onlinedocs/gdb/Declarations.html
43*795d594fSAndroid Build Coastguard Worker //
44*795d594fSAndroid Build Coastguard Worker // There are two ways for native tools to access the debug data safely:
45*795d594fSAndroid Build Coastguard Worker //
46*795d594fSAndroid Build Coastguard Worker // 1) Synchronously, by setting a breakpoint in the __*_debug_register_code
47*795d594fSAndroid Build Coastguard Worker //    method, which is called after every modification of the linked list.
48*795d594fSAndroid Build Coastguard Worker //    GDB does this, but it is complex to set up and it stops the process.
49*795d594fSAndroid Build Coastguard Worker //
50*795d594fSAndroid Build Coastguard Worker // 2) Asynchronously, using the entry seqlocks.
51*795d594fSAndroid Build Coastguard Worker //   * The seqlock is a monotonically increasing counter, which
52*795d594fSAndroid Build Coastguard Worker //     is even if the entry is valid and odd if it is invalid.
53*795d594fSAndroid Build Coastguard Worker //     It is set to even value after all other fields are set,
54*795d594fSAndroid Build Coastguard Worker //     and it is set to odd value before the entry is deleted.
55*795d594fSAndroid Build Coastguard Worker //   * This makes it possible to safely read the symfile data:
56*795d594fSAndroid Build Coastguard Worker //     * The reader should read the value of the seqlock both
57*795d594fSAndroid Build Coastguard Worker //       before and after reading the symfile. If the seqlock
58*795d594fSAndroid Build Coastguard Worker //       values match and are even the copy is consistent.
59*795d594fSAndroid Build Coastguard Worker //   * Entries are recycled, but never freed, which guarantees
60*795d594fSAndroid Build Coastguard Worker //     that the seqlock is not overwritten by a random value.
61*795d594fSAndroid Build Coastguard Worker //   * The linked-list is one level higher.  The next-pointer
62*795d594fSAndroid Build Coastguard Worker //     must always point to an entry with even seqlock, which
63*795d594fSAndroid Build Coastguard Worker //     ensures that entries of a crashed process can be read.
64*795d594fSAndroid Build Coastguard Worker //     This means the entry must be added after it is created
65*795d594fSAndroid Build Coastguard Worker //     and it must be removed before it is invalidated (odd).
66*795d594fSAndroid Build Coastguard Worker //   * When iterating over the linked list the reader can use
67*795d594fSAndroid Build Coastguard Worker //     the timestamps to ensure that current and next entry
68*795d594fSAndroid Build Coastguard Worker //     were not deleted using the following steps:
69*795d594fSAndroid Build Coastguard Worker //       1) Read next pointer and the next entry's seqlock.
70*795d594fSAndroid Build Coastguard Worker //       2) Read the symfile and re-read the next pointer.
71*795d594fSAndroid Build Coastguard Worker //       3) Re-read both the current and next seqlock.
72*795d594fSAndroid Build Coastguard Worker //       4) Go to step 1 with using new entry and seqlock.
73*795d594fSAndroid Build Coastguard Worker //
74*795d594fSAndroid Build Coastguard Worker // 3) Asynchronously, using the global seqlock.
75*795d594fSAndroid Build Coastguard Worker //   * The seqlock is a monotonically increasing counter which is incremented
76*795d594fSAndroid Build Coastguard Worker //     before and after every modification of the linked list. Odd value of
77*795d594fSAndroid Build Coastguard Worker //     the counter means the linked list is being modified (it is locked).
78*795d594fSAndroid Build Coastguard Worker //   * The tool should read the value of the seqlock both before and after
79*795d594fSAndroid Build Coastguard Worker //     copying the linked list.  If the seqlock values match and are even,
80*795d594fSAndroid Build Coastguard Worker //     the copy is consistent.  Otherwise, the reader should try again.
81*795d594fSAndroid Build Coastguard Worker //     * Note that using the data directly while is it being modified
82*795d594fSAndroid Build Coastguard Worker //       might crash the tool.  Therefore, the only safe way is to make
83*795d594fSAndroid Build Coastguard Worker //       a copy and use the copy only after the seqlock has been checked.
84*795d594fSAndroid Build Coastguard Worker //     * Note that the process might even free and munmap the data while
85*795d594fSAndroid Build Coastguard Worker //       it is being copied, therefore the reader should either handle
86*795d594fSAndroid Build Coastguard Worker //       SEGV or use OS calls to read the memory (e.g. process_vm_readv).
87*795d594fSAndroid Build Coastguard Worker //   * The timestamps on the entry record the time when the entry was
88*795d594fSAndroid Build Coastguard Worker //     created which is relevant if the unwinding is not live and is
89*795d594fSAndroid Build Coastguard Worker //     postponed until much later.  All timestamps must be unique.
90*795d594fSAndroid Build Coastguard Worker //   * For full conformance with the C++ memory model, all seqlock
91*795d594fSAndroid Build Coastguard Worker //     protected accesses should be atomic. We currently do this in the
92*795d594fSAndroid Build Coastguard Worker //     more critical cases. The rest will have to be fixed before
93*795d594fSAndroid Build Coastguard Worker //     attempting to run TSAN on this code.
94*795d594fSAndroid Build Coastguard Worker //
95*795d594fSAndroid Build Coastguard Worker 
96*795d594fSAndroid Build Coastguard Worker namespace art HIDDEN {
97*795d594fSAndroid Build Coastguard Worker 
98*795d594fSAndroid Build Coastguard Worker static Mutex g_jit_debug_lock("JIT native debug entries", kNativeDebugInterfaceLock);
99*795d594fSAndroid Build Coastguard Worker static Mutex g_dex_debug_lock("DEX native debug entries", kNativeDebugInterfaceLock);
100*795d594fSAndroid Build Coastguard Worker 
101*795d594fSAndroid Build Coastguard Worker // Most loads and stores need no synchronization since all memory is protected by the global locks.
102*795d594fSAndroid Build Coastguard Worker // Some writes are synchronized so libunwindstack can read the memory safely from another process.
103*795d594fSAndroid Build Coastguard Worker constexpr std::memory_order kNonRacingRelaxed = std::memory_order_relaxed;
104*795d594fSAndroid Build Coastguard Worker 
105*795d594fSAndroid Build Coastguard Worker // Size of JIT code range covered by each packed JITCodeEntry.
106*795d594fSAndroid Build Coastguard Worker constexpr uint32_t kJitRepackGroupSize = 64 * KB;
107*795d594fSAndroid Build Coastguard Worker 
108*795d594fSAndroid Build Coastguard Worker // Automatically call the repack method every 'n' new entries.
109*795d594fSAndroid Build Coastguard Worker constexpr uint32_t kJitRepackFrequency = 64;
110*795d594fSAndroid Build Coastguard Worker 
111*795d594fSAndroid Build Coastguard Worker }  // namespace art
112*795d594fSAndroid Build Coastguard Worker 
113*795d594fSAndroid Build Coastguard Worker // Public binary interface between ART and native tools (gdb, libunwind, etc).
114*795d594fSAndroid Build Coastguard Worker // The fields below need to be exported and have special names as per the gdb api.
115*795d594fSAndroid Build Coastguard Worker namespace art EXPORT {
116*795d594fSAndroid Build Coastguard Worker extern "C" {
117*795d594fSAndroid Build Coastguard Worker   enum JITAction {
118*795d594fSAndroid Build Coastguard Worker     JIT_NOACTION = 0,
119*795d594fSAndroid Build Coastguard Worker     JIT_REGISTER_FN,
120*795d594fSAndroid Build Coastguard Worker     JIT_UNREGISTER_FN
121*795d594fSAndroid Build Coastguard Worker   };
122*795d594fSAndroid Build Coastguard Worker 
123*795d594fSAndroid Build Coastguard Worker   // Public/stable binary interface.
124*795d594fSAndroid Build Coastguard Worker   struct JITCodeEntryPublic {
125*795d594fSAndroid Build Coastguard Worker     std::atomic<const JITCodeEntry*> next_;  // Atomic to guarantee consistency after crash.
126*795d594fSAndroid Build Coastguard Worker     const JITCodeEntry* prev_ = nullptr;     // For linked list deletion. Unused in readers.
127*795d594fSAndroid Build Coastguard Worker     const uint8_t* symfile_addr_ = nullptr;  // Address of the in-memory ELF file.
128*795d594fSAndroid Build Coastguard Worker     uint64_t symfile_size_ = 0;              // NB: The offset is 12 on x86 but 16 on ARM32.
129*795d594fSAndroid Build Coastguard Worker 
130*795d594fSAndroid Build Coastguard Worker     // Android-specific fields:
131*795d594fSAndroid Build Coastguard Worker     uint64_t timestamp_;                     // CLOCK_MONOTONIC time of entry registration.
132*795d594fSAndroid Build Coastguard Worker     std::atomic_uint32_t seqlock_{1};        // Synchronization. Even value if entry is valid.
133*795d594fSAndroid Build Coastguard Worker   };
134*795d594fSAndroid Build Coastguard Worker 
135*795d594fSAndroid Build Coastguard Worker   // Implementation-specific fields (which can be used only in this file).
136*795d594fSAndroid Build Coastguard Worker   struct JITCodeEntry : public JITCodeEntryPublic {
137*795d594fSAndroid Build Coastguard Worker     // Unpacked entries: Code address of the symbol in the ELF file.
138*795d594fSAndroid Build Coastguard Worker     // Packed entries: The start address of the covered memory range.
139*795d594fSAndroid Build Coastguard Worker     const void* addr_ = nullptr;
140*795d594fSAndroid Build Coastguard Worker     // Allow merging of ELF files to save space.
141*795d594fSAndroid Build Coastguard Worker     // Packing drops advanced DWARF data, so it is not always desirable.
142*795d594fSAndroid Build Coastguard Worker     bool allow_packing_ = false;
143*795d594fSAndroid Build Coastguard Worker     // Whether this entry has been LZMA compressed.
144*795d594fSAndroid Build Coastguard Worker     // Compression is expensive, so we don't always do it.
145*795d594fSAndroid Build Coastguard Worker     bool is_compressed_ = false;
146*795d594fSAndroid Build Coastguard Worker   };
147*795d594fSAndroid Build Coastguard Worker 
148*795d594fSAndroid Build Coastguard Worker   // Public/stable binary interface.
149*795d594fSAndroid Build Coastguard Worker   struct JITDescriptorPublic {
150*795d594fSAndroid Build Coastguard Worker     uint32_t version_ = 1;                            // NB: GDB supports only version 1.
151*795d594fSAndroid Build Coastguard Worker     uint32_t action_flag_ = JIT_NOACTION;             // One of the JITAction enum values.
152*795d594fSAndroid Build Coastguard Worker     const JITCodeEntry* relevant_entry_ = nullptr;    // The entry affected by the action.
153*795d594fSAndroid Build Coastguard Worker     std::atomic<const JITCodeEntry*> head_{nullptr};  // Head of link list of all entries.
154*795d594fSAndroid Build Coastguard Worker 
155*795d594fSAndroid Build Coastguard Worker     // Android-specific fields:
156*795d594fSAndroid Build Coastguard Worker     uint8_t magic_[8] = {'A', 'n', 'd', 'r', 'o', 'i', 'd', '2'};
157*795d594fSAndroid Build Coastguard Worker     uint32_t flags_ = 0;  // Reserved for future use. Must be 0.
158*795d594fSAndroid Build Coastguard Worker     uint32_t sizeof_descriptor = sizeof(JITDescriptorPublic);
159*795d594fSAndroid Build Coastguard Worker     uint32_t sizeof_entry = sizeof(JITCodeEntryPublic);
160*795d594fSAndroid Build Coastguard Worker     std::atomic_uint32_t seqlock_{0};  // Incremented before and after any modification.
161*795d594fSAndroid Build Coastguard Worker     uint64_t timestamp_ = 1;           // CLOCK_MONOTONIC time of last action.
162*795d594fSAndroid Build Coastguard Worker   };
163*795d594fSAndroid Build Coastguard Worker 
164*795d594fSAndroid Build Coastguard Worker   // Implementation-specific fields (which can be used only in this file).
165*795d594fSAndroid Build Coastguard Worker   struct JITDescriptor : public JITDescriptorPublic {
166*795d594fSAndroid Build Coastguard Worker     const JITCodeEntry* tail_ = nullptr;          // Tail of link list of all live entries.
167*795d594fSAndroid Build Coastguard Worker     const JITCodeEntry* free_entries_ = nullptr;  // List of deleted entries ready for reuse.
168*795d594fSAndroid Build Coastguard Worker 
169*795d594fSAndroid Build Coastguard Worker     // Used for memory sharing with zygote. See NativeDebugInfoPreFork().
170*795d594fSAndroid Build Coastguard Worker     const JITCodeEntry* zygote_head_entry_ = nullptr;
171*795d594fSAndroid Build Coastguard Worker     JITCodeEntry application_tail_entry_{};
172*795d594fSAndroid Build Coastguard Worker   };
173*795d594fSAndroid Build Coastguard Worker 
174*795d594fSAndroid Build Coastguard Worker   // Public interface: Can be used by reader to check the structs have the expected size.
175*795d594fSAndroid Build Coastguard Worker   uint32_t g_art_sizeof_jit_code_entry = sizeof(JITCodeEntryPublic);
176*795d594fSAndroid Build Coastguard Worker   uint32_t g_art_sizeof_jit_descriptor = sizeof(JITDescriptorPublic);
177*795d594fSAndroid Build Coastguard Worker 
178*795d594fSAndroid Build Coastguard Worker   // Check that std::atomic has the expected layout.
179*795d594fSAndroid Build Coastguard Worker   static_assert(alignof(std::atomic_uint32_t) == alignof(uint32_t), "Weird alignment");
180*795d594fSAndroid Build Coastguard Worker   static_assert(sizeof(std::atomic_uint32_t) == sizeof(uint32_t), "Weird size");
181*795d594fSAndroid Build Coastguard Worker   static_assert(std::atomic_uint32_t::is_always_lock_free, "Expected to be lock free");
182*795d594fSAndroid Build Coastguard Worker   static_assert(alignof(std::atomic<void*>) == alignof(void*), "Weird alignment");
183*795d594fSAndroid Build Coastguard Worker   static_assert(sizeof(std::atomic<void*>) == sizeof(void*), "Weird size");
184*795d594fSAndroid Build Coastguard Worker   static_assert(std::atomic<void*>::is_always_lock_free, "Expected to be lock free");
185*795d594fSAndroid Build Coastguard Worker 
186*795d594fSAndroid Build Coastguard Worker   // GDB may set breakpoint here. We must ensure it is not removed or deduplicated.
__jit_debug_register_code()187*795d594fSAndroid Build Coastguard Worker   void __attribute__((noinline)) __jit_debug_register_code() {
188*795d594fSAndroid Build Coastguard Worker     __asm__("");
189*795d594fSAndroid Build Coastguard Worker   }
190*795d594fSAndroid Build Coastguard Worker 
191*795d594fSAndroid Build Coastguard Worker   // Alternatively, native tools may overwrite this field to execute custom handler.
192*795d594fSAndroid Build Coastguard Worker   void (*__jit_debug_register_code_ptr)() = __jit_debug_register_code;
193*795d594fSAndroid Build Coastguard Worker 
194*795d594fSAndroid Build Coastguard Worker   // The root data structure describing of all JITed methods.
GUARDED_BY(g_jit_debug_lock)195*795d594fSAndroid Build Coastguard Worker   JITDescriptor __jit_debug_descriptor GUARDED_BY(g_jit_debug_lock) {};
196*795d594fSAndroid Build Coastguard Worker 
197*795d594fSAndroid Build Coastguard Worker   // The following globals mirror the ones above, but are used to register dex files.
__dex_debug_register_code()198*795d594fSAndroid Build Coastguard Worker   void __attribute__((noinline)) __dex_debug_register_code() {
199*795d594fSAndroid Build Coastguard Worker     __asm__("");
200*795d594fSAndroid Build Coastguard Worker   }
201*795d594fSAndroid Build Coastguard Worker   void (*__dex_debug_register_code_ptr)() = __dex_debug_register_code;
GUARDED_BY(g_dex_debug_lock)202*795d594fSAndroid Build Coastguard Worker   JITDescriptor __dex_debug_descriptor GUARDED_BY(g_dex_debug_lock) {};
203*795d594fSAndroid Build Coastguard Worker }
204*795d594fSAndroid Build Coastguard Worker }  // namespace art
205*795d594fSAndroid Build Coastguard Worker 
206*795d594fSAndroid Build Coastguard Worker namespace art HIDDEN {
207*795d594fSAndroid Build Coastguard Worker 
208*795d594fSAndroid Build Coastguard Worker // The fields below are internal, but we keep them here anyway for consistency.
209*795d594fSAndroid Build Coastguard Worker // Their state is related to the static state above and it must be kept in sync.
210*795d594fSAndroid Build Coastguard Worker 
211*795d594fSAndroid Build Coastguard Worker // Used only in debug builds to check that we are not adding duplicate entries.
212*795d594fSAndroid Build Coastguard Worker static std::unordered_set<const void*> g_dcheck_all_jit_functions GUARDED_BY(g_jit_debug_lock);
213*795d594fSAndroid Build Coastguard Worker 
214*795d594fSAndroid Build Coastguard Worker // Methods that have been marked for deletion on the next repack pass.
215*795d594fSAndroid Build Coastguard Worker static std::vector<const void*> g_removed_jit_functions GUARDED_BY(g_jit_debug_lock);
216*795d594fSAndroid Build Coastguard Worker 
217*795d594fSAndroid Build Coastguard Worker // Number of small (single symbol) ELF files. Used to trigger repacking.
218*795d594fSAndroid Build Coastguard Worker static uint32_t g_jit_num_unpacked_entries = 0;
219*795d594fSAndroid Build Coastguard Worker 
220*795d594fSAndroid Build Coastguard Worker struct DexNativeInfo {
Lockart::DexNativeInfo221*795d594fSAndroid Build Coastguard Worker   static Mutex* Lock() RETURN_CAPABILITY(g_dex_debug_lock) { return &g_dex_debug_lock; }
222*795d594fSAndroid Build Coastguard Worker   static constexpr bool kCopySymfileData = false;  // Just reference DEX files.
Descriptorart::DexNativeInfo223*795d594fSAndroid Build Coastguard Worker   static JITDescriptor& Descriptor() REQUIRES(g_dex_debug_lock) {
224*795d594fSAndroid Build Coastguard Worker     g_dex_debug_lock.AssertHeld(Thread::Current());
225*795d594fSAndroid Build Coastguard Worker     return __dex_debug_descriptor;
226*795d594fSAndroid Build Coastguard Worker   }
NotifyNativeDebuggerart::DexNativeInfo227*795d594fSAndroid Build Coastguard Worker   static void NotifyNativeDebugger() { __dex_debug_register_code_ptr(); }
Allocart::DexNativeInfo228*795d594fSAndroid Build Coastguard Worker   static const void* Alloc(size_t size) { return malloc(size); }
Freeart::DexNativeInfo229*795d594fSAndroid Build Coastguard Worker   static void Free(const void* ptr) { free(const_cast<void*>(ptr)); }
Writableart::DexNativeInfo230*795d594fSAndroid Build Coastguard Worker   template<class T> static T* Writable(const T* v) { return const_cast<T*>(v); }
231*795d594fSAndroid Build Coastguard Worker };
232*795d594fSAndroid Build Coastguard Worker 
233*795d594fSAndroid Build Coastguard Worker struct JitNativeInfo {
Lockart::JitNativeInfo234*795d594fSAndroid Build Coastguard Worker   static Mutex* Lock() RETURN_CAPABILITY(g_jit_debug_lock) { return &g_jit_debug_lock; }
235*795d594fSAndroid Build Coastguard Worker   static constexpr bool kCopySymfileData = true;  // Copy debug info to JIT memory.
Descriptorart::JitNativeInfo236*795d594fSAndroid Build Coastguard Worker   static JITDescriptor& Descriptor() REQUIRES(g_jit_debug_lock) {
237*795d594fSAndroid Build Coastguard Worker     g_jit_debug_lock.AssertHeld(Thread::Current());
238*795d594fSAndroid Build Coastguard Worker     return __jit_debug_descriptor;
239*795d594fSAndroid Build Coastguard Worker   }
NotifyNativeDebuggerart::JitNativeInfo240*795d594fSAndroid Build Coastguard Worker   static void NotifyNativeDebugger() { __jit_debug_register_code_ptr(); }
Allocart::JitNativeInfo241*795d594fSAndroid Build Coastguard Worker   static const void* Alloc(size_t size) { return Memory()->AllocateData(size); }
Freeart::JitNativeInfo242*795d594fSAndroid Build Coastguard Worker   static void Free(const void* ptr) { Memory()->FreeData(reinterpret_cast<const uint8_t*>(ptr)); }
243*795d594fSAndroid Build Coastguard Worker   static void Free(void* ptr) = delete;
244*795d594fSAndroid Build Coastguard Worker 
245*795d594fSAndroid Build Coastguard Worker   template <class T>
Writableart::JitNativeInfo246*795d594fSAndroid Build Coastguard Worker   static T* Writable(const T* v) REQUIRES(g_jit_debug_lock) {
247*795d594fSAndroid Build Coastguard Worker     // Special case: This entry is in static memory and not allocated in JIT memory.
248*795d594fSAndroid Build Coastguard Worker     if (v == reinterpret_cast<const void*>(&Descriptor().application_tail_entry_)) {
249*795d594fSAndroid Build Coastguard Worker       return const_cast<T*>(v);
250*795d594fSAndroid Build Coastguard Worker     }
251*795d594fSAndroid Build Coastguard Worker     return const_cast<T*>(Memory()->GetWritableDataAddress(v));
252*795d594fSAndroid Build Coastguard Worker   }
253*795d594fSAndroid Build Coastguard Worker 
Memoryart::JitNativeInfo254*795d594fSAndroid Build Coastguard Worker   static jit::JitMemoryRegion* Memory() ASSERT_CAPABILITY(Locks::jit_lock_) {
255*795d594fSAndroid Build Coastguard Worker     Locks::jit_lock_->AssertHeld(Thread::Current());
256*795d594fSAndroid Build Coastguard Worker     jit::JitCodeCache* jit_code_cache = Runtime::Current()->GetJitCodeCache();
257*795d594fSAndroid Build Coastguard Worker     CHECK(jit_code_cache != nullptr);
258*795d594fSAndroid Build Coastguard Worker     jit::JitMemoryRegion* memory = jit_code_cache->GetCurrentRegion();
259*795d594fSAndroid Build Coastguard Worker     CHECK(memory->IsValid());
260*795d594fSAndroid Build Coastguard Worker     return memory;
261*795d594fSAndroid Build Coastguard Worker   }
262*795d594fSAndroid Build Coastguard Worker };
263*795d594fSAndroid Build Coastguard Worker 
GetJITCodeEntrySymFile(const JITCodeEntry * entry)264*795d594fSAndroid Build Coastguard Worker ArrayRef<const uint8_t> GetJITCodeEntrySymFile(const JITCodeEntry* entry) {
265*795d594fSAndroid Build Coastguard Worker   return ArrayRef<const uint8_t>(entry->symfile_addr_, entry->symfile_size_);
266*795d594fSAndroid Build Coastguard Worker }
267*795d594fSAndroid Build Coastguard Worker 
268*795d594fSAndroid Build Coastguard Worker // Ensure the timestamp is monotonically increasing even in presence of low
269*795d594fSAndroid Build Coastguard Worker // granularity system timer.  This ensures each entry has unique timestamp.
GetNextTimestamp(JITDescriptor & descriptor)270*795d594fSAndroid Build Coastguard Worker static uint64_t GetNextTimestamp(JITDescriptor& descriptor) {
271*795d594fSAndroid Build Coastguard Worker   return std::max(descriptor.timestamp_ + 1, NanoTime());
272*795d594fSAndroid Build Coastguard Worker }
273*795d594fSAndroid Build Coastguard Worker 
274*795d594fSAndroid Build Coastguard Worker // Mark the descriptor as "locked", so native tools know the data is being modified.
Seqlock(JITDescriptor & descriptor)275*795d594fSAndroid Build Coastguard Worker static void Seqlock(JITDescriptor& descriptor) {
276*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(descriptor.seqlock_.load(kNonRacingRelaxed) & 1, 0u) << "Already locked";
277*795d594fSAndroid Build Coastguard Worker   descriptor.seqlock_.fetch_add(1, std::memory_order_relaxed);
278*795d594fSAndroid Build Coastguard Worker   // Ensure that any writes within the locked section cannot be reordered before the increment.
279*795d594fSAndroid Build Coastguard Worker   std::atomic_thread_fence(std::memory_order_release);
280*795d594fSAndroid Build Coastguard Worker }
281*795d594fSAndroid Build Coastguard Worker 
282*795d594fSAndroid Build Coastguard Worker // Mark the descriptor as "unlocked", so native tools know the data is safe to read.
Sequnlock(JITDescriptor & descriptor)283*795d594fSAndroid Build Coastguard Worker static void Sequnlock(JITDescriptor& descriptor) {
284*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(descriptor.seqlock_.load(kNonRacingRelaxed) & 1, 1u) << "Already unlocked";
285*795d594fSAndroid Build Coastguard Worker   // Ensure that any writes within the locked section cannot be reordered after the increment.
286*795d594fSAndroid Build Coastguard Worker   std::atomic_thread_fence(std::memory_order_release);
287*795d594fSAndroid Build Coastguard Worker   descriptor.seqlock_.fetch_add(1, std::memory_order_relaxed);
288*795d594fSAndroid Build Coastguard Worker }
289*795d594fSAndroid Build Coastguard Worker 
290*795d594fSAndroid Build Coastguard Worker // Insert 'entry' in the linked list before 'next' and mark it as valid (append if 'next' is null).
291*795d594fSAndroid Build Coastguard Worker // This method must be called under global lock (g_jit_debug_lock or g_dex_debug_lock).
292*795d594fSAndroid Build Coastguard Worker template <class NativeInfo>
InsertNewEntry(const JITCodeEntry * entry,const JITCodeEntry * next)293*795d594fSAndroid Build Coastguard Worker static void InsertNewEntry(const JITCodeEntry* entry, const JITCodeEntry* next)
294*795d594fSAndroid Build Coastguard Worker     REQUIRES(NativeInfo::Lock()) {
295*795d594fSAndroid Build Coastguard Worker   CHECK_EQ(entry->seqlock_.load(kNonRacingRelaxed) & 1, 1u) << "Expected invalid entry";
296*795d594fSAndroid Build Coastguard Worker   JITDescriptor& descriptor = NativeInfo::Descriptor();
297*795d594fSAndroid Build Coastguard Worker   const JITCodeEntry* prev = (next != nullptr ? next->prev_ : descriptor.tail_);
298*795d594fSAndroid Build Coastguard Worker   JITCodeEntry* writable = NativeInfo::Writable(entry);
299*795d594fSAndroid Build Coastguard Worker   writable->next_ = next;
300*795d594fSAndroid Build Coastguard Worker   writable->prev_ = prev;
301*795d594fSAndroid Build Coastguard Worker   writable->seqlock_.fetch_add(1, std::memory_order_release);  // Mark as valid.
302*795d594fSAndroid Build Coastguard Worker   // Backward pointers should not be used by readers, so they are non-atomic.
303*795d594fSAndroid Build Coastguard Worker   if (next != nullptr) {
304*795d594fSAndroid Build Coastguard Worker     NativeInfo::Writable(next)->prev_ = entry;
305*795d594fSAndroid Build Coastguard Worker   } else {
306*795d594fSAndroid Build Coastguard Worker     descriptor.tail_ = entry;
307*795d594fSAndroid Build Coastguard Worker   }
308*795d594fSAndroid Build Coastguard Worker   // Forward pointers must be atomic and they must point to a valid entry at all times.
309*795d594fSAndroid Build Coastguard Worker   if (prev != nullptr) {
310*795d594fSAndroid Build Coastguard Worker     NativeInfo::Writable(prev)->next_.store(entry, std::memory_order_release);
311*795d594fSAndroid Build Coastguard Worker   } else {
312*795d594fSAndroid Build Coastguard Worker     descriptor.head_.store(entry, std::memory_order_release);
313*795d594fSAndroid Build Coastguard Worker   }
314*795d594fSAndroid Build Coastguard Worker }
315*795d594fSAndroid Build Coastguard Worker 
316*795d594fSAndroid Build Coastguard Worker // This must be called with the appropriate lock taken (g_{jit,dex}_debug_lock).
317*795d594fSAndroid Build Coastguard Worker template <class NativeInfo>
CreateJITCodeEntryInternal(ArrayRef<const uint8_t> symfile=ArrayRef<const uint8_t> (),const void * addr=nullptr,bool allow_packing=false,bool is_compressed=false)318*795d594fSAndroid Build Coastguard Worker static const JITCodeEntry* CreateJITCodeEntryInternal(
319*795d594fSAndroid Build Coastguard Worker     ArrayRef<const uint8_t> symfile = ArrayRef<const uint8_t>(),
320*795d594fSAndroid Build Coastguard Worker     const void* addr = nullptr,
321*795d594fSAndroid Build Coastguard Worker     bool allow_packing = false,
322*795d594fSAndroid Build Coastguard Worker     bool is_compressed = false) REQUIRES(NativeInfo::Lock()) {
323*795d594fSAndroid Build Coastguard Worker   JITDescriptor& descriptor = NativeInfo::Descriptor();
324*795d594fSAndroid Build Coastguard Worker 
325*795d594fSAndroid Build Coastguard Worker   // Allocate JITCodeEntry if needed.
326*795d594fSAndroid Build Coastguard Worker   if (descriptor.free_entries_ == nullptr) {
327*795d594fSAndroid Build Coastguard Worker     const void* memory = NativeInfo::Alloc(sizeof(JITCodeEntry));
328*795d594fSAndroid Build Coastguard Worker     if (memory == nullptr) {
329*795d594fSAndroid Build Coastguard Worker       LOG(ERROR) << "Failed to allocate memory for native debug info";
330*795d594fSAndroid Build Coastguard Worker       return nullptr;
331*795d594fSAndroid Build Coastguard Worker     }
332*795d594fSAndroid Build Coastguard Worker     new (NativeInfo::Writable(memory)) JITCodeEntry();
333*795d594fSAndroid Build Coastguard Worker     descriptor.free_entries_ = reinterpret_cast<const JITCodeEntry*>(memory);
334*795d594fSAndroid Build Coastguard Worker   }
335*795d594fSAndroid Build Coastguard Worker 
336*795d594fSAndroid Build Coastguard Worker   // Make a copy of the buffer to shrink it and to pass ownership to JITCodeEntry.
337*795d594fSAndroid Build Coastguard Worker   if (NativeInfo::kCopySymfileData && !symfile.empty()) {
338*795d594fSAndroid Build Coastguard Worker     const uint8_t* copy = reinterpret_cast<const uint8_t*>(NativeInfo::Alloc(symfile.size()));
339*795d594fSAndroid Build Coastguard Worker     if (copy == nullptr) {
340*795d594fSAndroid Build Coastguard Worker       LOG(ERROR) << "Failed to allocate memory for native debug info";
341*795d594fSAndroid Build Coastguard Worker       return nullptr;
342*795d594fSAndroid Build Coastguard Worker     }
343*795d594fSAndroid Build Coastguard Worker     memcpy(NativeInfo::Writable(copy), symfile.data(), symfile.size());
344*795d594fSAndroid Build Coastguard Worker     symfile = ArrayRef<const uint8_t>(copy, symfile.size());
345*795d594fSAndroid Build Coastguard Worker   }
346*795d594fSAndroid Build Coastguard Worker 
347*795d594fSAndroid Build Coastguard Worker   uint64_t timestamp = GetNextTimestamp(descriptor);
348*795d594fSAndroid Build Coastguard Worker 
349*795d594fSAndroid Build Coastguard Worker   // We must insert entries at specific place.  See NativeDebugInfoPreFork().
350*795d594fSAndroid Build Coastguard Worker   const JITCodeEntry* next = descriptor.head_.load(kNonRacingRelaxed);  // Insert at the head.
351*795d594fSAndroid Build Coastguard Worker   if (descriptor.zygote_head_entry_ != nullptr && Runtime::Current()->IsZygote()) {
352*795d594fSAndroid Build Coastguard Worker     next = nullptr;  // Insert zygote entries at the tail.
353*795d594fSAndroid Build Coastguard Worker   }
354*795d594fSAndroid Build Coastguard Worker 
355*795d594fSAndroid Build Coastguard Worker   // Pop entry from the free list.
356*795d594fSAndroid Build Coastguard Worker   const JITCodeEntry* entry = descriptor.free_entries_;
357*795d594fSAndroid Build Coastguard Worker   descriptor.free_entries_ = descriptor.free_entries_->next_.load(kNonRacingRelaxed);
358*795d594fSAndroid Build Coastguard Worker 
359*795d594fSAndroid Build Coastguard Worker   // Create the entry and set all its fields.
360*795d594fSAndroid Build Coastguard Worker   JITCodeEntry* writable_entry = NativeInfo::Writable(entry);
361*795d594fSAndroid Build Coastguard Worker   writable_entry->symfile_addr_ = symfile.data();
362*795d594fSAndroid Build Coastguard Worker   writable_entry->symfile_size_ = symfile.size();
363*795d594fSAndroid Build Coastguard Worker   writable_entry->addr_ = addr;
364*795d594fSAndroid Build Coastguard Worker   writable_entry->allow_packing_ = allow_packing;
365*795d594fSAndroid Build Coastguard Worker   writable_entry->is_compressed_ = is_compressed;
366*795d594fSAndroid Build Coastguard Worker   writable_entry->timestamp_ = timestamp;
367*795d594fSAndroid Build Coastguard Worker 
368*795d594fSAndroid Build Coastguard Worker   // Add the entry to the main linked list.
369*795d594fSAndroid Build Coastguard Worker   Seqlock(descriptor);
370*795d594fSAndroid Build Coastguard Worker   InsertNewEntry<NativeInfo>(entry, next);
371*795d594fSAndroid Build Coastguard Worker   descriptor.relevant_entry_ = entry;
372*795d594fSAndroid Build Coastguard Worker   descriptor.action_flag_ = JIT_REGISTER_FN;
373*795d594fSAndroid Build Coastguard Worker   descriptor.timestamp_ = timestamp;
374*795d594fSAndroid Build Coastguard Worker   Sequnlock(descriptor);
375*795d594fSAndroid Build Coastguard Worker 
376*795d594fSAndroid Build Coastguard Worker   NativeInfo::NotifyNativeDebugger();
377*795d594fSAndroid Build Coastguard Worker 
378*795d594fSAndroid Build Coastguard Worker   return entry;
379*795d594fSAndroid Build Coastguard Worker }
380*795d594fSAndroid Build Coastguard Worker 
381*795d594fSAndroid Build Coastguard Worker template <class NativeInfo>
DeleteJITCodeEntryInternal(const JITCodeEntry * entry)382*795d594fSAndroid Build Coastguard Worker static void DeleteJITCodeEntryInternal(const JITCodeEntry* entry) REQUIRES(NativeInfo::Lock()) {
383*795d594fSAndroid Build Coastguard Worker   CHECK(entry != nullptr);
384*795d594fSAndroid Build Coastguard Worker   JITDescriptor& descriptor = NativeInfo::Descriptor();
385*795d594fSAndroid Build Coastguard Worker 
386*795d594fSAndroid Build Coastguard Worker   // Remove the entry from the main linked-list.
387*795d594fSAndroid Build Coastguard Worker   Seqlock(descriptor);
388*795d594fSAndroid Build Coastguard Worker   const JITCodeEntry* next = entry->next_.load(kNonRacingRelaxed);
389*795d594fSAndroid Build Coastguard Worker   const JITCodeEntry* prev = entry->prev_;
390*795d594fSAndroid Build Coastguard Worker   if (next != nullptr) {
391*795d594fSAndroid Build Coastguard Worker     NativeInfo::Writable(next)->prev_ = prev;
392*795d594fSAndroid Build Coastguard Worker   } else {
393*795d594fSAndroid Build Coastguard Worker     descriptor.tail_ = prev;
394*795d594fSAndroid Build Coastguard Worker   }
395*795d594fSAndroid Build Coastguard Worker   if (prev != nullptr) {
396*795d594fSAndroid Build Coastguard Worker     NativeInfo::Writable(prev)->next_.store(next, std::memory_order_relaxed);
397*795d594fSAndroid Build Coastguard Worker   } else {
398*795d594fSAndroid Build Coastguard Worker     descriptor.head_.store(next, std::memory_order_relaxed);
399*795d594fSAndroid Build Coastguard Worker   }
400*795d594fSAndroid Build Coastguard Worker   descriptor.relevant_entry_ = entry;
401*795d594fSAndroid Build Coastguard Worker   descriptor.action_flag_ = JIT_UNREGISTER_FN;
402*795d594fSAndroid Build Coastguard Worker   descriptor.timestamp_ = GetNextTimestamp(descriptor);
403*795d594fSAndroid Build Coastguard Worker   Sequnlock(descriptor);
404*795d594fSAndroid Build Coastguard Worker 
405*795d594fSAndroid Build Coastguard Worker   NativeInfo::NotifyNativeDebugger();
406*795d594fSAndroid Build Coastguard Worker 
407*795d594fSAndroid Build Coastguard Worker   // Delete the entry.
408*795d594fSAndroid Build Coastguard Worker   JITCodeEntry* writable_entry = NativeInfo::Writable(entry);
409*795d594fSAndroid Build Coastguard Worker   CHECK_EQ(writable_entry->seqlock_.load(kNonRacingRelaxed) & 1, 0u) << "Expected valid entry";
410*795d594fSAndroid Build Coastguard Worker   // Release: Ensures that "next_" points to valid entry at any time in reader.
411*795d594fSAndroid Build Coastguard Worker   writable_entry->seqlock_.fetch_add(1, std::memory_order_release);  // Mark as invalid.
412*795d594fSAndroid Build Coastguard Worker   // Release: Ensures that the entry is seen as invalid before it's data is freed.
413*795d594fSAndroid Build Coastguard Worker   std::atomic_thread_fence(std::memory_order_release);
414*795d594fSAndroid Build Coastguard Worker   const uint8_t* symfile = entry->symfile_addr_;
415*795d594fSAndroid Build Coastguard Worker   writable_entry->symfile_addr_ = nullptr;
416*795d594fSAndroid Build Coastguard Worker   if (NativeInfo::kCopySymfileData && symfile != nullptr) {
417*795d594fSAndroid Build Coastguard Worker     NativeInfo::Free(symfile);
418*795d594fSAndroid Build Coastguard Worker   }
419*795d594fSAndroid Build Coastguard Worker 
420*795d594fSAndroid Build Coastguard Worker   // Push the entry to the free list.
421*795d594fSAndroid Build Coastguard Worker   writable_entry->next_.store(descriptor.free_entries_, kNonRacingRelaxed);
422*795d594fSAndroid Build Coastguard Worker   writable_entry->prev_ = nullptr;
423*795d594fSAndroid Build Coastguard Worker   descriptor.free_entries_ = entry;
424*795d594fSAndroid Build Coastguard Worker }
425*795d594fSAndroid Build Coastguard Worker 
AddNativeDebugInfoForDex(Thread * self,const DexFile * dexfile)426*795d594fSAndroid Build Coastguard Worker void AddNativeDebugInfoForDex(Thread* self, const DexFile* dexfile) {
427*795d594fSAndroid Build Coastguard Worker   MutexLock mu(self, g_dex_debug_lock);
428*795d594fSAndroid Build Coastguard Worker   DCHECK(dexfile != nullptr);
429*795d594fSAndroid Build Coastguard Worker   // Container dex files (v41) may store data past the size defined in the header.
430*795d594fSAndroid Build Coastguard Worker   uint32_t size = dexfile->SizeIncludingSharedData();
431*795d594fSAndroid Build Coastguard Worker   if (dexfile->IsCompactDexFile()) {
432*795d594fSAndroid Build Coastguard Worker     // Compact dex files may store data past the size defined in the header.
433*795d594fSAndroid Build Coastguard Worker     const DexFile::Header& header = dexfile->GetHeader();
434*795d594fSAndroid Build Coastguard Worker     size = std::max(size, header.data_off_ + header.data_size_);
435*795d594fSAndroid Build Coastguard Worker   }
436*795d594fSAndroid Build Coastguard Worker   const ArrayRef<const uint8_t> symfile(dexfile->Begin(), size);
437*795d594fSAndroid Build Coastguard Worker   CreateJITCodeEntryInternal<DexNativeInfo>(symfile);
438*795d594fSAndroid Build Coastguard Worker }
439*795d594fSAndroid Build Coastguard Worker 
RemoveNativeDebugInfoForDex(Thread * self,const DexFile * dexfile)440*795d594fSAndroid Build Coastguard Worker void RemoveNativeDebugInfoForDex(Thread* self, const DexFile* dexfile) {
441*795d594fSAndroid Build Coastguard Worker   MutexLock mu(self, g_dex_debug_lock);
442*795d594fSAndroid Build Coastguard Worker   DCHECK(dexfile != nullptr);
443*795d594fSAndroid Build Coastguard Worker   // We register dex files in the class linker and free them in DexFile_closeDexFile, but
444*795d594fSAndroid Build Coastguard Worker   // there might be cases where we load the dex file without using it in the class linker.
445*795d594fSAndroid Build Coastguard Worker   // On the other hand, single dex file might also be used with different class-loaders.
446*795d594fSAndroid Build Coastguard Worker   for (const JITCodeEntry* entry = __dex_debug_descriptor.head_; entry != nullptr; ) {
447*795d594fSAndroid Build Coastguard Worker     const JITCodeEntry* next = entry->next_;  // Save next pointer before we free the memory.
448*795d594fSAndroid Build Coastguard Worker     if (entry->symfile_addr_ == dexfile->Begin()) {
449*795d594fSAndroid Build Coastguard Worker       DeleteJITCodeEntryInternal<DexNativeInfo>(entry);
450*795d594fSAndroid Build Coastguard Worker     }
451*795d594fSAndroid Build Coastguard Worker     entry = next;
452*795d594fSAndroid Build Coastguard Worker   }
453*795d594fSAndroid Build Coastguard Worker }
454*795d594fSAndroid Build Coastguard Worker 
455*795d594fSAndroid Build Coastguard Worker // Splits the linked linked in to two parts:
456*795d594fSAndroid Build Coastguard Worker // The first part (including the static head pointer) is owned by the application.
457*795d594fSAndroid Build Coastguard Worker // The second part is owned by zygote and might be concurrently modified by it.
458*795d594fSAndroid Build Coastguard Worker //
459*795d594fSAndroid Build Coastguard Worker // We add two empty entries at the boundary which are never removed (app_tail, zygote_head).
460*795d594fSAndroid Build Coastguard Worker // These entries are needed to preserve the next/prev pointers in the linked list,
461*795d594fSAndroid Build Coastguard Worker // since zygote can not modify the application's data and vice versa.
462*795d594fSAndroid Build Coastguard Worker //
463*795d594fSAndroid Build Coastguard Worker // <------- owned by the application memory --------> <--- owned by zygote memory --->
464*795d594fSAndroid Build Coastguard Worker //         |----------------------|------------------|-------------|-----------------|
465*795d594fSAndroid Build Coastguard Worker // head -> | application_entries* | application_tail | zygote_head | zygote_entries* |
466*795d594fSAndroid Build Coastguard Worker //         |+---------------------|------------------|-------------|----------------+|
467*795d594fSAndroid Build Coastguard Worker //          |                                                                       |
468*795d594fSAndroid Build Coastguard Worker //          \-(new application entries)                        (new zygote entries)-/
469*795d594fSAndroid Build Coastguard Worker //
470*795d594fSAndroid Build Coastguard Worker // Zygote entries are inserted at the end, which means that repacked zygote entries
471*795d594fSAndroid Build Coastguard Worker // will still be seen by single forward iteration of the linked list (avoiding race).
472*795d594fSAndroid Build Coastguard Worker //
473*795d594fSAndroid Build Coastguard Worker // Application entries are inserted at the start which introduces repacking race,
474*795d594fSAndroid Build Coastguard Worker // but that is ok, since it is easy to read new entries from head in further pass.
475*795d594fSAndroid Build Coastguard Worker // The benefit is that this makes it fast to read only the new entries.
476*795d594fSAndroid Build Coastguard Worker //
NativeDebugInfoPreFork()477*795d594fSAndroid Build Coastguard Worker void NativeDebugInfoPreFork() {
478*795d594fSAndroid Build Coastguard Worker   CHECK(Runtime::Current()->IsZygote());
479*795d594fSAndroid Build Coastguard Worker   MutexLock mu(Thread::Current(), *Locks::jit_lock_);  // Needed to alloc entry.
480*795d594fSAndroid Build Coastguard Worker   MutexLock mu2(Thread::Current(), g_jit_debug_lock);
481*795d594fSAndroid Build Coastguard Worker   JITDescriptor& descriptor = JitNativeInfo::Descriptor();
482*795d594fSAndroid Build Coastguard Worker   if (descriptor.zygote_head_entry_ != nullptr) {
483*795d594fSAndroid Build Coastguard Worker     return;  // Already done - we need to do this only on the first fork.
484*795d594fSAndroid Build Coastguard Worker   }
485*795d594fSAndroid Build Coastguard Worker 
486*795d594fSAndroid Build Coastguard Worker   // Create the zygote-owned head entry (with no ELF file).
487*795d594fSAndroid Build Coastguard Worker   // The data will be allocated from the current JIT memory (owned by zygote).
488*795d594fSAndroid Build Coastguard Worker   const JITCodeEntry* zygote_head =
489*795d594fSAndroid Build Coastguard Worker     reinterpret_cast<const JITCodeEntry*>(JitNativeInfo::Alloc(sizeof(JITCodeEntry)));
490*795d594fSAndroid Build Coastguard Worker   CHECK(zygote_head != nullptr);
491*795d594fSAndroid Build Coastguard Worker   new (JitNativeInfo::Writable(zygote_head)) JITCodeEntry();  // Initialize.
492*795d594fSAndroid Build Coastguard Worker   InsertNewEntry<JitNativeInfo>(zygote_head, descriptor.head_);
493*795d594fSAndroid Build Coastguard Worker   descriptor.zygote_head_entry_ = zygote_head;
494*795d594fSAndroid Build Coastguard Worker 
495*795d594fSAndroid Build Coastguard Worker   // Create the child-owned tail entry (with no ELF file).
496*795d594fSAndroid Build Coastguard Worker   // The data is statically allocated since it must be owned by the forked process.
497*795d594fSAndroid Build Coastguard Worker   InsertNewEntry<JitNativeInfo>(&descriptor.application_tail_entry_, descriptor.head_);
498*795d594fSAndroid Build Coastguard Worker }
499*795d594fSAndroid Build Coastguard Worker 
NativeDebugInfoPostFork()500*795d594fSAndroid Build Coastguard Worker void NativeDebugInfoPostFork() {
501*795d594fSAndroid Build Coastguard Worker   CHECK(!Runtime::Current()->IsZygote());
502*795d594fSAndroid Build Coastguard Worker   MutexLock mu(Thread::Current(), g_jit_debug_lock);
503*795d594fSAndroid Build Coastguard Worker   JITDescriptor& descriptor = JitNativeInfo::Descriptor();
504*795d594fSAndroid Build Coastguard Worker   descriptor.free_entries_ = nullptr;  // Don't reuse zygote's entries.
505*795d594fSAndroid Build Coastguard Worker }
506*795d594fSAndroid Build Coastguard Worker 
507*795d594fSAndroid Build Coastguard Worker // Split the JIT code cache into groups of fixed size and create single JITCodeEntry for each group.
508*795d594fSAndroid Build Coastguard Worker // The start address of method's code determines which group it belongs to.  The end is irrelevant.
509*795d594fSAndroid Build Coastguard Worker // New mini debug infos will be merged if possible, and entries for GCed functions will be removed.
RepackEntries(bool compress_entries,ArrayRef<const void * > removed)510*795d594fSAndroid Build Coastguard Worker static void RepackEntries(bool compress_entries, ArrayRef<const void*> removed)
511*795d594fSAndroid Build Coastguard Worker     REQUIRES(g_jit_debug_lock) {
512*795d594fSAndroid Build Coastguard Worker   DCHECK(std::is_sorted(removed.begin(), removed.end()));
513*795d594fSAndroid Build Coastguard Worker   jit::Jit* jit = Runtime::Current()->GetJit();
514*795d594fSAndroid Build Coastguard Worker   if (jit == nullptr) {
515*795d594fSAndroid Build Coastguard Worker     return;
516*795d594fSAndroid Build Coastguard Worker   }
517*795d594fSAndroid Build Coastguard Worker   JITDescriptor& descriptor = __jit_debug_descriptor;
518*795d594fSAndroid Build Coastguard Worker   bool is_zygote = Runtime::Current()->IsZygote();
519*795d594fSAndroid Build Coastguard Worker 
520*795d594fSAndroid Build Coastguard Worker   // Collect entries that we want to pack.
521*795d594fSAndroid Build Coastguard Worker   std::vector<const JITCodeEntry*> entries;
522*795d594fSAndroid Build Coastguard Worker   entries.reserve(2 * kJitRepackFrequency);
523*795d594fSAndroid Build Coastguard Worker   for (const JITCodeEntry* it = descriptor.head_; it != nullptr; it = it->next_) {
524*795d594fSAndroid Build Coastguard Worker     if (it == descriptor.zygote_head_entry_ && !is_zygote) {
525*795d594fSAndroid Build Coastguard Worker       break;  // Memory owned by the zygote process (read-only for an app).
526*795d594fSAndroid Build Coastguard Worker     }
527*795d594fSAndroid Build Coastguard Worker     if (it->allow_packing_) {
528*795d594fSAndroid Build Coastguard Worker       if (!compress_entries && it->is_compressed_ && removed.empty()) {
529*795d594fSAndroid Build Coastguard Worker         continue;  // If we are not compressing, also avoid decompressing.
530*795d594fSAndroid Build Coastguard Worker       }
531*795d594fSAndroid Build Coastguard Worker       entries.push_back(it);
532*795d594fSAndroid Build Coastguard Worker     }
533*795d594fSAndroid Build Coastguard Worker   }
534*795d594fSAndroid Build Coastguard Worker   auto cmp = [](const JITCodeEntry* l, const JITCodeEntry* r) { return l->addr_ < r->addr_; };
535*795d594fSAndroid Build Coastguard Worker   std::sort(entries.begin(), entries.end(), cmp);  // Sort by address.
536*795d594fSAndroid Build Coastguard Worker 
537*795d594fSAndroid Build Coastguard Worker   // Process the entries in groups (each spanning memory range of size kJitRepackGroupSize).
538*795d594fSAndroid Build Coastguard Worker   for (auto group_it = entries.begin(); group_it != entries.end();) {
539*795d594fSAndroid Build Coastguard Worker     const void* group_ptr = AlignDown((*group_it)->addr_, kJitRepackGroupSize);
540*795d594fSAndroid Build Coastguard Worker     const void* group_end = reinterpret_cast<const uint8_t*>(group_ptr) + kJitRepackGroupSize;
541*795d594fSAndroid Build Coastguard Worker 
542*795d594fSAndroid Build Coastguard Worker     // Find all entries in this group (each entry is an in-memory ELF file).
543*795d594fSAndroid Build Coastguard Worker     auto begin = group_it;
544*795d594fSAndroid Build Coastguard Worker     auto end = std::find_if(begin, entries.end(), [=](auto* e) { return e->addr_ >= group_end; });
545*795d594fSAndroid Build Coastguard Worker     CHECK(end > begin);
546*795d594fSAndroid Build Coastguard Worker     ArrayRef<const JITCodeEntry*> elfs(&*begin, end - begin);
547*795d594fSAndroid Build Coastguard Worker 
548*795d594fSAndroid Build Coastguard Worker     // Find all symbols that have been removed in this memory range.
549*795d594fSAndroid Build Coastguard Worker     auto removed_begin = std::lower_bound(removed.begin(), removed.end(), group_ptr);
550*795d594fSAndroid Build Coastguard Worker     auto removed_end = std::lower_bound(removed.begin(), removed.end(), group_end);
551*795d594fSAndroid Build Coastguard Worker     CHECK(removed_end >= removed_begin);
552*795d594fSAndroid Build Coastguard Worker     ArrayRef<const void*> removed_subset(&*removed_begin, removed_end - removed_begin);
553*795d594fSAndroid Build Coastguard Worker 
554*795d594fSAndroid Build Coastguard Worker     // Optimization: Don't compress the last group since it will likely change again soon.
555*795d594fSAndroid Build Coastguard Worker     bool compress = compress_entries && end != entries.end();
556*795d594fSAndroid Build Coastguard Worker 
557*795d594fSAndroid Build Coastguard Worker     // Bail out early if there is nothing to do for this group.
558*795d594fSAndroid Build Coastguard Worker     if (elfs.size() == 1 && removed_subset.empty() && (*begin)->is_compressed_ == compress) {
559*795d594fSAndroid Build Coastguard Worker       group_it = end;  // Go to next group.
560*795d594fSAndroid Build Coastguard Worker       continue;
561*795d594fSAndroid Build Coastguard Worker     }
562*795d594fSAndroid Build Coastguard Worker 
563*795d594fSAndroid Build Coastguard Worker     // Create new single JITCodeEntry that covers this memory range.
564*795d594fSAndroid Build Coastguard Worker     uint64_t start_time = MicroTime();
565*795d594fSAndroid Build Coastguard Worker     size_t live_symbols;
566*795d594fSAndroid Build Coastguard Worker     std::vector<uint8_t> packed = jit->GetJitCompiler()->PackElfFileForJIT(
567*795d594fSAndroid Build Coastguard Worker         elfs, removed_subset, compress, &live_symbols);
568*795d594fSAndroid Build Coastguard Worker     VLOG(jit)
569*795d594fSAndroid Build Coastguard Worker         << "JIT mini-debug-info repacked"
570*795d594fSAndroid Build Coastguard Worker         << " for " << group_ptr
571*795d594fSAndroid Build Coastguard Worker         << " in " << MicroTime() - start_time << "us"
572*795d594fSAndroid Build Coastguard Worker         << " elfs=" << elfs.size()
573*795d594fSAndroid Build Coastguard Worker         << " dead=" << removed_subset.size()
574*795d594fSAndroid Build Coastguard Worker         << " live=" << live_symbols
575*795d594fSAndroid Build Coastguard Worker         << " size=" << packed.size() << (compress ? "(lzma)" : "");
576*795d594fSAndroid Build Coastguard Worker 
577*795d594fSAndroid Build Coastguard Worker     // Replace the old entries with the new one (with their lifetime temporally overlapping).
578*795d594fSAndroid Build Coastguard Worker     CreateJITCodeEntryInternal<JitNativeInfo>(ArrayRef<const uint8_t>(packed),
579*795d594fSAndroid Build Coastguard Worker                                               /*addr_=*/ group_ptr,
580*795d594fSAndroid Build Coastguard Worker                                               /*allow_packing_=*/ true,
581*795d594fSAndroid Build Coastguard Worker                                               /*is_compressed_=*/ compress);
582*795d594fSAndroid Build Coastguard Worker     for (auto it : elfs) {
583*795d594fSAndroid Build Coastguard Worker       DeleteJITCodeEntryInternal<JitNativeInfo>(/*entry=*/ it);
584*795d594fSAndroid Build Coastguard Worker     }
585*795d594fSAndroid Build Coastguard Worker     group_it = end;  // Go to next group.
586*795d594fSAndroid Build Coastguard Worker   }
587*795d594fSAndroid Build Coastguard Worker   g_jit_num_unpacked_entries = 0;
588*795d594fSAndroid Build Coastguard Worker }
589*795d594fSAndroid Build Coastguard Worker 
590*795d594fSAndroid Build Coastguard Worker static void RepackNativeDebugInfoForJitLocked() REQUIRES(g_jit_debug_lock);
591*795d594fSAndroid Build Coastguard Worker 
AddNativeDebugInfoForJit(const void * code_ptr,const std::vector<uint8_t> & symfile,bool allow_packing)592*795d594fSAndroid Build Coastguard Worker void AddNativeDebugInfoForJit(const void* code_ptr,
593*795d594fSAndroid Build Coastguard Worker                               const std::vector<uint8_t>& symfile,
594*795d594fSAndroid Build Coastguard Worker                               bool allow_packing) {
595*795d594fSAndroid Build Coastguard Worker   MutexLock mu(Thread::Current(), g_jit_debug_lock);
596*795d594fSAndroid Build Coastguard Worker   DCHECK_NE(symfile.size(), 0u);
597*795d594fSAndroid Build Coastguard Worker   if (kIsDebugBuild && code_ptr != nullptr) {
598*795d594fSAndroid Build Coastguard Worker     DCHECK(g_dcheck_all_jit_functions.insert(code_ptr).second) << code_ptr << " already added";
599*795d594fSAndroid Build Coastguard Worker   }
600*795d594fSAndroid Build Coastguard Worker 
601*795d594fSAndroid Build Coastguard Worker   // Remove all methods which have been marked for removal.  The JIT GC should
602*795d594fSAndroid Build Coastguard Worker   // force repack, so this should happen only rarely for various corner cases.
603*795d594fSAndroid Build Coastguard Worker   // Must be done before addition in case the added code_ptr is in the removed set.
604*795d594fSAndroid Build Coastguard Worker   if (!g_removed_jit_functions.empty()) {
605*795d594fSAndroid Build Coastguard Worker     RepackNativeDebugInfoForJitLocked();
606*795d594fSAndroid Build Coastguard Worker   }
607*795d594fSAndroid Build Coastguard Worker 
608*795d594fSAndroid Build Coastguard Worker   CreateJITCodeEntryInternal<JitNativeInfo>(ArrayRef<const uint8_t>(symfile),
609*795d594fSAndroid Build Coastguard Worker                                             /*addr=*/ code_ptr,
610*795d594fSAndroid Build Coastguard Worker                                             /*allow_packing=*/ allow_packing,
611*795d594fSAndroid Build Coastguard Worker                                             /*is_compressed=*/ false);
612*795d594fSAndroid Build Coastguard Worker 
613*795d594fSAndroid Build Coastguard Worker   if (code_ptr == nullptr) {
614*795d594fSAndroid Build Coastguard Worker     VLOG(jit) << "JIT mini-debug-info added for new type, size=" << PrettySize(symfile.size());
615*795d594fSAndroid Build Coastguard Worker   } else {
616*795d594fSAndroid Build Coastguard Worker     VLOG(jit)
617*795d594fSAndroid Build Coastguard Worker         << "JIT mini-debug-info added for native code at " << code_ptr
618*795d594fSAndroid Build Coastguard Worker         << ", size=" << PrettySize(symfile.size());
619*795d594fSAndroid Build Coastguard Worker   }
620*795d594fSAndroid Build Coastguard Worker 
621*795d594fSAndroid Build Coastguard Worker   // Automatically repack entries on regular basis to save space.
622*795d594fSAndroid Build Coastguard Worker   // Pack (but don't compress) recent entries - this is cheap and reduces memory use by ~4x.
623*795d594fSAndroid Build Coastguard Worker   // We delay compression until after GC since it is more expensive (and saves further ~4x).
624*795d594fSAndroid Build Coastguard Worker   // Always compress zygote, since it does not GC and we want to keep the high-water mark low.
625*795d594fSAndroid Build Coastguard Worker   if (++g_jit_num_unpacked_entries >= kJitRepackFrequency) {
626*795d594fSAndroid Build Coastguard Worker     bool is_zygote = Runtime::Current()->IsZygote();
627*795d594fSAndroid Build Coastguard Worker     RepackEntries(/*compress_entries=*/ is_zygote, /*removed=*/ ArrayRef<const void*>());
628*795d594fSAndroid Build Coastguard Worker   }
629*795d594fSAndroid Build Coastguard Worker }
630*795d594fSAndroid Build Coastguard Worker 
RemoveNativeDebugInfoForJit(const void * code_ptr)631*795d594fSAndroid Build Coastguard Worker void RemoveNativeDebugInfoForJit(const void* code_ptr) {
632*795d594fSAndroid Build Coastguard Worker   MutexLock mu(Thread::Current(), g_jit_debug_lock);
633*795d594fSAndroid Build Coastguard Worker   g_dcheck_all_jit_functions.erase(code_ptr);
634*795d594fSAndroid Build Coastguard Worker 
635*795d594fSAndroid Build Coastguard Worker   // Method removal is very expensive since we need to decompress and read ELF files.
636*795d594fSAndroid Build Coastguard Worker   // Collet methods to be removed and do the removal in bulk later.
637*795d594fSAndroid Build Coastguard Worker   g_removed_jit_functions.push_back(code_ptr);
638*795d594fSAndroid Build Coastguard Worker 
639*795d594fSAndroid Build Coastguard Worker   VLOG(jit) << "JIT mini-debug-info removed for " << code_ptr;
640*795d594fSAndroid Build Coastguard Worker }
641*795d594fSAndroid Build Coastguard Worker 
RepackNativeDebugInfoForJitLocked()642*795d594fSAndroid Build Coastguard Worker static void RepackNativeDebugInfoForJitLocked() {
643*795d594fSAndroid Build Coastguard Worker   // Remove entries which are inside packed and compressed ELF files.
644*795d594fSAndroid Build Coastguard Worker   std::vector<const void*>& removed = g_removed_jit_functions;
645*795d594fSAndroid Build Coastguard Worker   std::sort(removed.begin(), removed.end());
646*795d594fSAndroid Build Coastguard Worker   RepackEntries(/*compress_entries=*/ true, ArrayRef<const void*>(removed));
647*795d594fSAndroid Build Coastguard Worker 
648*795d594fSAndroid Build Coastguard Worker   // Remove entries which are not allowed to be packed (containing single method each).
649*795d594fSAndroid Build Coastguard Worker   for (const JITCodeEntry* it = __jit_debug_descriptor.head_; it != nullptr;) {
650*795d594fSAndroid Build Coastguard Worker     const JITCodeEntry* next = it->next_;
651*795d594fSAndroid Build Coastguard Worker     if (!it->allow_packing_ && std::binary_search(removed.begin(), removed.end(), it->addr_)) {
652*795d594fSAndroid Build Coastguard Worker       DeleteJITCodeEntryInternal<JitNativeInfo>(/*entry=*/ it);
653*795d594fSAndroid Build Coastguard Worker     }
654*795d594fSAndroid Build Coastguard Worker     it = next;
655*795d594fSAndroid Build Coastguard Worker   }
656*795d594fSAndroid Build Coastguard Worker 
657*795d594fSAndroid Build Coastguard Worker   removed.clear();
658*795d594fSAndroid Build Coastguard Worker   removed.shrink_to_fit();
659*795d594fSAndroid Build Coastguard Worker }
660*795d594fSAndroid Build Coastguard Worker 
RepackNativeDebugInfoForJit()661*795d594fSAndroid Build Coastguard Worker void RepackNativeDebugInfoForJit() {
662*795d594fSAndroid Build Coastguard Worker   MutexLock mu(Thread::Current(), g_jit_debug_lock);
663*795d594fSAndroid Build Coastguard Worker   RepackNativeDebugInfoForJitLocked();
664*795d594fSAndroid Build Coastguard Worker }
665*795d594fSAndroid Build Coastguard Worker 
GetJitMiniDebugInfoMemUsage()666*795d594fSAndroid Build Coastguard Worker size_t GetJitMiniDebugInfoMemUsage() {
667*795d594fSAndroid Build Coastguard Worker   MutexLock mu(Thread::Current(), g_jit_debug_lock);
668*795d594fSAndroid Build Coastguard Worker   size_t size = 0;
669*795d594fSAndroid Build Coastguard Worker   for (const JITCodeEntry* it = __jit_debug_descriptor.head_; it != nullptr; it = it->next_) {
670*795d594fSAndroid Build Coastguard Worker     size += sizeof(JITCodeEntry) + it->symfile_size_;
671*795d594fSAndroid Build Coastguard Worker   }
672*795d594fSAndroid Build Coastguard Worker   return size;
673*795d594fSAndroid Build Coastguard Worker }
674*795d594fSAndroid Build Coastguard Worker 
GetNativeDebugInfoLock()675*795d594fSAndroid Build Coastguard Worker Mutex* GetNativeDebugInfoLock() {
676*795d594fSAndroid Build Coastguard Worker   return &g_jit_debug_lock;
677*795d594fSAndroid Build Coastguard Worker }
678*795d594fSAndroid Build Coastguard Worker 
ForEachNativeDebugSymbol(std::function<void (const void *,size_t,const char *)> cb)679*795d594fSAndroid Build Coastguard Worker void ForEachNativeDebugSymbol(std::function<void(const void*, size_t, const char*)> cb) {
680*795d594fSAndroid Build Coastguard Worker   MutexLock mu(Thread::Current(), g_jit_debug_lock);
681*795d594fSAndroid Build Coastguard Worker   using ElfRuntimeTypes = std::conditional<sizeof(void*) == 4, ElfTypes32, ElfTypes64>::type;
682*795d594fSAndroid Build Coastguard Worker   const JITCodeEntry* end = __jit_debug_descriptor.zygote_head_entry_;
683*795d594fSAndroid Build Coastguard Worker   for (const JITCodeEntry* it = __jit_debug_descriptor.head_; it != end; it = it->next_) {
684*795d594fSAndroid Build Coastguard Worker     ArrayRef<const uint8_t> buffer(it->symfile_addr_, it->symfile_size_);
685*795d594fSAndroid Build Coastguard Worker     if (!buffer.empty()) {
686*795d594fSAndroid Build Coastguard Worker       ElfDebugReader<ElfRuntimeTypes> reader(buffer);
687*795d594fSAndroid Build Coastguard Worker       reader.VisitFunctionSymbols([&](ElfRuntimeTypes::Sym sym, const char* name) {
688*795d594fSAndroid Build Coastguard Worker         cb(reinterpret_cast<const void*>(sym.st_value), sym.st_size, name);
689*795d594fSAndroid Build Coastguard Worker       });
690*795d594fSAndroid Build Coastguard Worker     }
691*795d594fSAndroid Build Coastguard Worker   }
692*795d594fSAndroid Build Coastguard Worker }
693*795d594fSAndroid Build Coastguard Worker 
694*795d594fSAndroid Build Coastguard Worker }  // namespace art
695