blob: 0efa4d2cddcbb8601e3cea2e3e157cdc25106040 [file] [log] [blame]
David Srbecky67feb172015-12-17 19:57:44 +00001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "debugger_interface.h"
18
Andreas Gampe57943812017-12-06 21:39:13 -080019#include <android-base/logging.h>
20
David Srbecky440a9b32018-02-15 17:47:29 +000021#include "base/array_ref.h"
David Srbecky8fc2f952019-07-31 18:40:09 +010022#include "base/bit_utils.h"
David Srbecky0b21e412018-12-05 13:24:06 +000023#include "base/logging.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000024#include "base/mutex.h"
David Srbecky440a9b32018-02-15 17:47:29 +000025#include "base/time_utils.h"
David Srbecky0b21e412018-12-05 13:24:06 +000026#include "base/utils.h"
David Srbeckyafc60cd2018-12-05 11:59:31 +000027#include "dex/dex_file.h"
David Srbecky8fc2f952019-07-31 18:40:09 +010028#include "jit/jit.h"
David Srbecky9ac8e432019-08-13 13:16:13 +010029#include "jit/jit_code_cache.h"
30#include "jit/jit_memory_region.h"
David Srbecky8fc2f952019-07-31 18:40:09 +010031#include "runtime.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070032#include "thread-current-inl.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000033#include "thread.h"
34
David Srbeckyd767f2d2018-02-26 16:18:40 +000035#include <atomic>
David Srbeckyd767f2d2018-02-26 16:18:40 +000036#include <cstddef>
David Srbecky5cc349f2015-12-18 15:04:48 +000037
David Srbecky440a9b32018-02-15 17:47:29 +000038//
39// Debug interface for native tools (gdb, lldb, libunwind, simpleperf).
40//
41// See http://sourceware.org/gdb/onlinedocs/gdb/Declarations.html
42//
43// There are two ways for native tools to access the debug data safely:
44//
45// 1) Synchronously, by setting a breakpoint in the __*_debug_register_code
46// method, which is called after every modification of the linked list.
47// GDB does this, but it is complex to set up and it stops the process.
48//
David Srbecky1550a662019-08-14 17:16:46 +010049// 2) Asynchronously, using the entry seqlocks.
50// * The seqlock is a monotonically increasing counter, which
51// is even if the entry is valid and odd if it is invalid.
52// It is set to even value after all other fields are set,
53// and it is set to odd value before the entry is deleted.
54// * This makes it possible to safely read the symfile data:
55// * The reader should read the value of the seqlock both
56// before and after reading the symfile. If the seqlock
57// values match and are even the copy is consistent.
58// * Entries are recycled, but never freed, which guarantees
59// that the seqlock is not overwritten by a random value.
60// * The linked-list is one level higher. The next-pointer
61// must always point to an entry with even seqlock, which
62// ensures that entries of a crashed process can be read.
63// This means the entry must be added after it is created
64// and it must be removed before it is invalidated (odd).
65// * When iterating over the linked list the reader can use
66// the timestamps to ensure that current and next entry
67// were not deleted using the following steps:
68// 1) Read next pointer and the next entry's seqlock.
69// 2) Read the symfile and re-read the next pointer.
70// 3) Re-read both the current and next seqlock.
71// 4) Go to step 1 with using new entry and seqlock.
David Srbecky440a9b32018-02-15 17:47:29 +000072//
David Srbecky94af5822019-10-03 14:48:26 +010073// 3) Asynchronously, using the global seqlock.
74// * The seqlock is a monotonically increasing counter which is incremented
75// before and after every modification of the linked list. Odd value of
76// the counter means the linked list is being modified (it is locked).
77// * The tool should read the value of the seqlock both before and after
78// copying the linked list. If the seqlock values match and are even,
79// the copy is consistent. Otherwise, the reader should try again.
80// * Note that using the data directly while is it being modified
81// might crash the tool. Therefore, the only safe way is to make
82// a copy and use the copy only after the seqlock has been checked.
83// * Note that the process might even free and munmap the data while
84// it is being copied, therefore the reader should either handle
85// SEGV or use OS calls to read the memory (e.g. process_vm_readv).
86// * The timestamps on the entry record the time when the entry was
87// created which is relevant if the unwinding is not live and is
88// postponed until much later. All timestamps must be unique.
89// * For full conformance with the C++ memory model, all seqlock
90// protected accesses should be atomic. We currently do this in the
91// more critical cases. The rest will have to be fixed before
92// attempting to run TSAN on this code.
93//
David Srbecky67feb172015-12-17 19:57:44 +000094
David Srbecky440a9b32018-02-15 17:47:29 +000095namespace art {
David Srbecky0b21e412018-12-05 13:24:06 +000096
97static Mutex g_jit_debug_lock("JIT native debug entries", kNativeDebugInterfaceLock);
98static Mutex g_dex_debug_lock("DEX native debug entries", kNativeDebugInterfaceLock);
99
David Srbecky1550a662019-08-14 17:16:46 +0100100// Most loads and stores need no synchronization since all memory is protected by the global locks.
101// Some writes are synchronized so libunwindstack can read the memory safely from another process.
102constexpr std::memory_order kNonRacingRelaxed = std::memory_order_relaxed;
103
David Srbecky30fd8512020-02-20 20:27:58 +0000104// Size of JIT code range covered by each packed JITCodeEntry.
105constexpr uint32_t kJitRepackGroupSize = 64 * KB;
106
107// Automatically call the repack method every 'n' new entries.
108constexpr uint32_t kJitRepackFrequency = 64;
109
David Srbecky1550a662019-08-14 17:16:46 +0100110// Public binary interface between ART and native tools (gdb, libunwind, etc).
David Srbecky30fd8512020-02-20 20:27:58 +0000111// The fields below need to be exported and have special names as per the gdb api.
David Srbecky67feb172015-12-17 19:57:44 +0000112extern "C" {
Andreas Gampec55bb392018-09-21 00:02:02 +0000113 enum JITAction {
David Srbecky67feb172015-12-17 19:57:44 +0000114 JIT_NOACTION = 0,
115 JIT_REGISTER_FN,
116 JIT_UNREGISTER_FN
Andreas Gampec55bb392018-09-21 00:02:02 +0000117 };
David Srbecky67feb172015-12-17 19:57:44 +0000118
David Srbecky8fc2f952019-07-31 18:40:09 +0100119 // Public/stable binary interface.
120 struct JITCodeEntryPublic {
David Srbecky1550a662019-08-14 17:16:46 +0100121 std::atomic<const JITCodeEntry*> next_; // Atomic to guarantee consistency after crash.
David Srbecky697fe5c2019-10-09 17:24:17 +0100122 const JITCodeEntry* prev_ = nullptr; // For linked list deletion. Unused in readers.
David Srbecky1550a662019-08-14 17:16:46 +0100123 const uint8_t* symfile_addr_ = nullptr; // Address of the in-memory ELF file.
David Srbecky697fe5c2019-10-09 17:24:17 +0100124 uint64_t symfile_size_ = 0; // NB: The offset is 12 on x86 but 16 on ARM32.
David Srbecky440a9b32018-02-15 17:47:29 +0000125
126 // Android-specific fields:
David Srbecky94af5822019-10-03 14:48:26 +0100127 uint64_t timestamp_; // CLOCK_MONOTONIC time of entry registration.
David Srbecky1550a662019-08-14 17:16:46 +0100128 std::atomic_uint32_t seqlock_{1}; // Synchronization. Even value if entry is valid.
David Srbecky67feb172015-12-17 19:57:44 +0000129 };
130
David Srbecky8fc2f952019-07-31 18:40:09 +0100131 // Implementation-specific fields (which can be used only in this file).
132 struct JITCodeEntry : public JITCodeEntryPublic {
133 // Unpacked entries: Code address of the symbol in the ELF file.
134 // Packed entries: The start address of the covered memory range.
135 const void* addr_ = nullptr;
136 // Allow merging of ELF files to save space.
137 // Packing drops advanced DWARF data, so it is not always desirable.
138 bool allow_packing_ = false;
139 // Whether this entry has been LZMA compressed.
140 // Compression is expensive, so we don't always do it.
141 bool is_compressed_ = false;
142 };
143
David Srbecky1550a662019-08-14 17:16:46 +0100144 // Public/stable binary interface.
145 struct JITDescriptorPublic {
David Srbeckye09b87e2019-08-19 21:31:31 +0100146 uint32_t version_ = 1; // NB: GDB supports only version 1.
147 uint32_t action_flag_ = JIT_NOACTION; // One of the JITAction enum values.
148 const JITCodeEntry* relevant_entry_ = nullptr; // The entry affected by the action.
149 std::atomic<const JITCodeEntry*> head_{nullptr}; // Head of link list of all entries.
David Srbecky94af5822019-10-03 14:48:26 +0100150
151 // Android-specific fields:
152 uint8_t magic_[8] = {'A', 'n', 'd', 'r', 'o', 'i', 'd', '2'};
153 uint32_t flags_ = 0; // Reserved for future use. Must be 0.
154 uint32_t sizeof_descriptor = sizeof(JITDescriptorPublic);
155 uint32_t sizeof_entry = sizeof(JITCodeEntryPublic);
156 std::atomic_uint32_t seqlock_{0}; // Incremented before and after any modification.
157 uint64_t timestamp_ = 1; // CLOCK_MONOTONIC time of last action.
David Srbecky67feb172015-12-17 19:57:44 +0000158 };
159
David Srbecky1550a662019-08-14 17:16:46 +0100160 // Implementation-specific fields (which can be used only in this file).
161 struct JITDescriptor : public JITDescriptorPublic {
David Srbecky697fe5c2019-10-09 17:24:17 +0100162 const JITCodeEntry* tail_ = nullptr; // Tail of link list of all live entries.
David Srbecky1550a662019-08-14 17:16:46 +0100163 const JITCodeEntry* free_entries_ = nullptr; // List of deleted entries ready for reuse.
164
165 // Used for memory sharing with zygote. See NativeDebugInfoPreFork().
166 const JITCodeEntry* zygote_head_entry_ = nullptr;
167 JITCodeEntry application_tail_entry_{};
168 };
169
170 // Public interface: Can be used by reader to check the structs have the expected size.
171 uint32_t g_art_sizeof_jit_code_entry = sizeof(JITCodeEntryPublic);
172 uint32_t g_art_sizeof_jit_descriptor = sizeof(JITDescriptorPublic);
173
David Srbeckyd767f2d2018-02-26 16:18:40 +0000174 // Check that std::atomic has the expected layout.
175 static_assert(alignof(std::atomic_uint32_t) == alignof(uint32_t), "Weird alignment");
176 static_assert(sizeof(std::atomic_uint32_t) == sizeof(uint32_t), "Weird size");
David Srbecky1550a662019-08-14 17:16:46 +0100177 static_assert(std::atomic_uint32_t::is_always_lock_free, "Expected to be lock free");
David Srbeckyd767f2d2018-02-26 16:18:40 +0000178 static_assert(alignof(std::atomic<void*>) == alignof(void*), "Weird alignment");
179 static_assert(sizeof(std::atomic<void*>) == sizeof(void*), "Weird size");
David Srbecky1550a662019-08-14 17:16:46 +0100180 static_assert(std::atomic<void*>::is_always_lock_free, "Expected to be lock free");
David Srbecky440a9b32018-02-15 17:47:29 +0000181
182 // GDB may set breakpoint here. We must ensure it is not removed or deduplicated.
David Srbecky67feb172015-12-17 19:57:44 +0000183 void __attribute__((noinline)) __jit_debug_register_code() {
184 __asm__("");
185 }
186
David Srbecky440a9b32018-02-15 17:47:29 +0000187 // Alternatively, native tools may overwrite this field to execute custom handler.
David Srbeckye8b4e852016-03-15 17:02:41 +0000188 void (*__jit_debug_register_code_ptr)() = __jit_debug_register_code;
189
David Srbecky440a9b32018-02-15 17:47:29 +0000190 // The root data structure describing of all JITed methods.
David Srbecky0b21e412018-12-05 13:24:06 +0000191 JITDescriptor __jit_debug_descriptor GUARDED_BY(g_jit_debug_lock) {};
David Srbeckyfb3de3d2018-01-29 16:11:49 +0000192
David Srbecky440a9b32018-02-15 17:47:29 +0000193 // The following globals mirror the ones above, but are used to register dex files.
194 void __attribute__((noinline)) __dex_debug_register_code() {
195 __asm__("");
David Srbeckyfb3de3d2018-01-29 16:11:49 +0000196 }
David Srbecky440a9b32018-02-15 17:47:29 +0000197 void (*__dex_debug_register_code_ptr)() = __dex_debug_register_code;
David Srbecky0b21e412018-12-05 13:24:06 +0000198 JITDescriptor __dex_debug_descriptor GUARDED_BY(g_dex_debug_lock) {};
David Srbeckyfb3de3d2018-01-29 16:11:49 +0000199}
200
David Srbecky30fd8512020-02-20 20:27:58 +0000201// The fields below are internal, but we keep them here anyway for consistency.
202// Their state is related to the static state above and it must be kept in sync.
203
204// Used only in debug builds to check that we are not adding duplicate entries.
205static std::unordered_set<const void*> g_dcheck_all_jit_functions GUARDED_BY(g_jit_debug_lock);
206
207// Methods that have been marked for deletion on the next repack pass.
208static std::vector<const void*> g_removed_jit_functions GUARDED_BY(g_jit_debug_lock);
209
210// Number of small (single symbol) ELF files. Used to trigger repacking.
211static uint32_t g_jit_num_unpacked_entries = 0;
212
David Srbecky9ac8e432019-08-13 13:16:13 +0100213struct DexNativeInfo {
214 static constexpr bool kCopySymfileData = false; // Just reference DEX files.
215 static JITDescriptor& Descriptor() { return __dex_debug_descriptor; }
216 static void NotifyNativeDebugger() { __dex_debug_register_code_ptr(); }
David Srbeckye09b87e2019-08-19 21:31:31 +0100217 static const void* Alloc(size_t size) { return malloc(size); }
218 static void Free(const void* ptr) { free(const_cast<void*>(ptr)); }
219 template<class T> static T* Writable(const T* v) { return const_cast<T*>(v); }
David Srbecky9ac8e432019-08-13 13:16:13 +0100220};
221
222struct JitNativeInfo {
223 static constexpr bool kCopySymfileData = true; // Copy debug info to JIT memory.
224 static JITDescriptor& Descriptor() { return __jit_debug_descriptor; }
225 static void NotifyNativeDebugger() { __jit_debug_register_code_ptr(); }
David Srbeckye09b87e2019-08-19 21:31:31 +0100226 static const void* Alloc(size_t size) { return Memory()->AllocateData(size); }
David Srbecky87fb0322019-08-20 10:34:02 +0100227 static void Free(const void* ptr) { Memory()->FreeData(reinterpret_cast<const uint8_t*>(ptr)); }
David Srbeckye09b87e2019-08-19 21:31:31 +0100228 static void Free(void* ptr) = delete;
David Srbecky1550a662019-08-14 17:16:46 +0100229
David Srbeckye09b87e2019-08-19 21:31:31 +0100230 template<class T> static T* Writable(const T* v) {
David Srbecky1550a662019-08-14 17:16:46 +0100231 // Special case: This entry is in static memory and not allocated in JIT memory.
232 if (v == reinterpret_cast<const void*>(&Descriptor().application_tail_entry_)) {
233 return const_cast<T*>(v);
234 }
David Srbeckye09b87e2019-08-19 21:31:31 +0100235 return const_cast<T*>(Memory()->GetWritableDataAddress(v));
236 }
David Srbecky9ac8e432019-08-13 13:16:13 +0100237
David Srbeckye09b87e2019-08-19 21:31:31 +0100238 static jit::JitMemoryRegion* Memory() ASSERT_CAPABILITY(Locks::jit_lock_) {
David Srbecky9ac8e432019-08-13 13:16:13 +0100239 Locks::jit_lock_->AssertHeld(Thread::Current());
240 jit::JitCodeCache* jit_code_cache = Runtime::Current()->GetJitCodeCache();
241 CHECK(jit_code_cache != nullptr);
242 jit::JitMemoryRegion* memory = jit_code_cache->GetCurrentRegion();
243 CHECK(memory->IsValid());
244 return memory;
245 }
246};
247
David Srbeckye09b87e2019-08-19 21:31:31 +0100248ArrayRef<const uint8_t> GetJITCodeEntrySymFile(const JITCodeEntry* entry) {
David Srbecky8fc2f952019-07-31 18:40:09 +0100249 return ArrayRef<const uint8_t>(entry->symfile_addr_, entry->symfile_size_);
250}
251
David Srbecky94af5822019-10-03 14:48:26 +0100252// Ensure the timestamp is monotonically increasing even in presence of low
253// granularity system timer. This ensures each entry has unique timestamp.
254static uint64_t GetNextTimestamp(JITDescriptor& descriptor) {
255 return std::max(descriptor.timestamp_ + 1, NanoTime());
256}
257
258// Mark the descriptor as "locked", so native tools know the data is being modified.
259static void Seqlock(JITDescriptor& descriptor) {
260 DCHECK_EQ(descriptor.seqlock_.load(kNonRacingRelaxed) & 1, 0u) << "Already locked";
261 descriptor.seqlock_.fetch_add(1, std::memory_order_relaxed);
262 // Ensure that any writes within the locked section cannot be reordered before the increment.
263 std::atomic_thread_fence(std::memory_order_release);
264}
265
266// Mark the descriptor as "unlocked", so native tools know the data is safe to read.
267static void Sequnlock(JITDescriptor& descriptor) {
268 DCHECK_EQ(descriptor.seqlock_.load(kNonRacingRelaxed) & 1, 1u) << "Already unlocked";
269 // Ensure that any writes within the locked section cannot be reordered after the increment.
270 std::atomic_thread_fence(std::memory_order_release);
271 descriptor.seqlock_.fetch_add(1, std::memory_order_relaxed);
272}
273
David Srbecky697fe5c2019-10-09 17:24:17 +0100274// Insert 'entry' in the linked list before 'next' and mark it as valid (append if 'next' is null).
275// This method must be called under global lock (g_jit_debug_lock or g_dex_debug_lock).
276template<class NativeInfo>
277static void InsertNewEntry(const JITCodeEntry* entry, const JITCodeEntry* next) {
278 CHECK_EQ(entry->seqlock_.load(kNonRacingRelaxed) & 1, 1u) << "Expected invalid entry";
279 JITDescriptor& descriptor = NativeInfo::Descriptor();
280 const JITCodeEntry* prev = (next != nullptr ? next->prev_ : descriptor.tail_);
281 JITCodeEntry* writable = NativeInfo::Writable(entry);
282 writable->next_ = next;
283 writable->prev_ = prev;
284 writable->seqlock_.fetch_add(1, std::memory_order_release); // Mark as valid.
285 // Backward pointers should not be used by readers, so they are non-atomic.
286 if (next != nullptr) {
287 NativeInfo::Writable(next)->prev_ = entry;
288 } else {
289 descriptor.tail_ = entry;
290 }
291 // Forward pointers must be atomic and they must point to a valid entry at all times.
292 if (prev != nullptr) {
293 NativeInfo::Writable(prev)->next_.store(entry, std::memory_order_release);
294 } else {
295 descriptor.head_.store(entry, std::memory_order_release);
296 }
297}
298
David Srbecky1550a662019-08-14 17:16:46 +0100299// This must be called with the appropriate lock taken (g_{jit,dex}_debug_lock).
David Srbecky9ac8e432019-08-13 13:16:13 +0100300template<class NativeInfo>
David Srbeckye09b87e2019-08-19 21:31:31 +0100301static const JITCodeEntry* CreateJITCodeEntryInternal(
David Srbecky1550a662019-08-14 17:16:46 +0100302 ArrayRef<const uint8_t> symfile = ArrayRef<const uint8_t>(),
David Srbecky8fc2f952019-07-31 18:40:09 +0100303 const void* addr = nullptr,
304 bool allow_packing = false,
305 bool is_compressed = false) {
David Srbecky9ac8e432019-08-13 13:16:13 +0100306 JITDescriptor& descriptor = NativeInfo::Descriptor();
307
David Srbecky1550a662019-08-14 17:16:46 +0100308 // Allocate JITCodeEntry if needed.
309 if (descriptor.free_entries_ == nullptr) {
310 const void* memory = NativeInfo::Alloc(sizeof(JITCodeEntry));
311 if (memory == nullptr) {
312 LOG(ERROR) << "Failed to allocate memory for native debug info";
313 return nullptr;
314 }
315 new (NativeInfo::Writable(memory)) JITCodeEntry();
316 descriptor.free_entries_ = reinterpret_cast<const JITCodeEntry*>(memory);
317 }
318
David Srbeckyafc60cd2018-12-05 11:59:31 +0000319 // Make a copy of the buffer to shrink it and to pass ownership to JITCodeEntry.
David Srbecky1550a662019-08-14 17:16:46 +0100320 if (NativeInfo::kCopySymfileData && !symfile.empty()) {
321 const uint8_t* copy = reinterpret_cast<const uint8_t*>(NativeInfo::Alloc(symfile.size()));
David Srbecky9ac8e432019-08-13 13:16:13 +0100322 if (copy == nullptr) {
323 LOG(ERROR) << "Failed to allocate memory for native debug info";
324 return nullptr;
325 }
David Srbeckye09b87e2019-08-19 21:31:31 +0100326 memcpy(NativeInfo::Writable(copy), symfile.data(), symfile.size());
David Srbeckyafc60cd2018-12-05 11:59:31 +0000327 symfile = ArrayRef<const uint8_t>(copy, symfile.size());
328 }
329
David Srbecky94af5822019-10-03 14:48:26 +0100330 uint64_t timestamp = GetNextTimestamp(descriptor);
331
David Srbecky697fe5c2019-10-09 17:24:17 +0100332 // We must insert entries at specific place. See NativeDebugInfoPreFork().
David Srbecky4d125af2019-10-31 14:51:44 +0000333 const JITCodeEntry* next = descriptor.head_.load(kNonRacingRelaxed); // Insert at the head.
334 if (descriptor.zygote_head_entry_ != nullptr && Runtime::Current()->IsZygote()) {
335 next = nullptr; // Insert zygote entries at the tail.
David Srbecky9ac8e432019-08-13 13:16:13 +0100336 }
David Srbecky1550a662019-08-14 17:16:46 +0100337
338 // Pop entry from the free list.
339 const JITCodeEntry* entry = descriptor.free_entries_;
340 descriptor.free_entries_ = descriptor.free_entries_->next_.load(kNonRacingRelaxed);
David Srbecky1550a662019-08-14 17:16:46 +0100341
342 // Create the entry and set all its fields.
David Srbeckye09b87e2019-08-19 21:31:31 +0100343 JITCodeEntry* writable_entry = NativeInfo::Writable(entry);
344 writable_entry->symfile_addr_ = symfile.data();
345 writable_entry->symfile_size_ = symfile.size();
David Srbeckye09b87e2019-08-19 21:31:31 +0100346 writable_entry->addr_ = addr;
347 writable_entry->allow_packing_ = allow_packing;
348 writable_entry->is_compressed_ = is_compressed;
David Srbecky94af5822019-10-03 14:48:26 +0100349 writable_entry->timestamp_ = timestamp;
David Srbeckyd767f2d2018-02-26 16:18:40 +0000350
David Srbecky697fe5c2019-10-09 17:24:17 +0100351 // Add the entry to the main linked list.
David Srbecky94af5822019-10-03 14:48:26 +0100352 Seqlock(descriptor);
David Srbecky697fe5c2019-10-09 17:24:17 +0100353 InsertNewEntry<NativeInfo>(entry, next);
David Srbecky440a9b32018-02-15 17:47:29 +0000354 descriptor.relevant_entry_ = entry;
355 descriptor.action_flag_ = JIT_REGISTER_FN;
David Srbecky94af5822019-10-03 14:48:26 +0100356 descriptor.timestamp_ = timestamp;
357 Sequnlock(descriptor);
358
David Srbecky9ac8e432019-08-13 13:16:13 +0100359 NativeInfo::NotifyNativeDebugger();
360
David Srbecky67feb172015-12-17 19:57:44 +0000361 return entry;
362}
363
David Srbecky9ac8e432019-08-13 13:16:13 +0100364template<class NativeInfo>
David Srbeckye09b87e2019-08-19 21:31:31 +0100365static void DeleteJITCodeEntryInternal(const JITCodeEntry* entry) {
David Srbecky440a9b32018-02-15 17:47:29 +0000366 CHECK(entry != nullptr);
David Srbecky9ac8e432019-08-13 13:16:13 +0100367 JITDescriptor& descriptor = NativeInfo::Descriptor();
David Srbecky440a9b32018-02-15 17:47:29 +0000368
David Srbecky1550a662019-08-14 17:16:46 +0100369 // Remove the entry from the main linked-list.
David Srbecky94af5822019-10-03 14:48:26 +0100370 Seqlock(descriptor);
David Srbecky1550a662019-08-14 17:16:46 +0100371 const JITCodeEntry* next = entry->next_.load(kNonRacingRelaxed);
David Srbecky697fe5c2019-10-09 17:24:17 +0100372 const JITCodeEntry* prev = entry->prev_;
373 if (next != nullptr) {
374 NativeInfo::Writable(next)->prev_ = prev;
375 } else {
376 descriptor.tail_ = prev;
377 }
378 if (prev != nullptr) {
379 NativeInfo::Writable(prev)->next_.store(next, std::memory_order_relaxed);
David Srbecky67feb172015-12-17 19:57:44 +0000380 } else {
David Srbeckyd767f2d2018-02-26 16:18:40 +0000381 descriptor.head_.store(next, std::memory_order_relaxed);
David Srbecky67feb172015-12-17 19:57:44 +0000382 }
David Srbecky440a9b32018-02-15 17:47:29 +0000383 descriptor.relevant_entry_ = entry;
384 descriptor.action_flag_ = JIT_UNREGISTER_FN;
David Srbecky94af5822019-10-03 14:48:26 +0100385 descriptor.timestamp_ = GetNextTimestamp(descriptor);
386 Sequnlock(descriptor);
387
David Srbecky9ac8e432019-08-13 13:16:13 +0100388 NativeInfo::NotifyNativeDebugger();
David Srbeckyd767f2d2018-02-26 16:18:40 +0000389
David Srbecky1550a662019-08-14 17:16:46 +0100390 // Delete the entry.
391 JITCodeEntry* writable_entry = NativeInfo::Writable(entry);
392 CHECK_EQ(writable_entry->seqlock_.load(kNonRacingRelaxed) & 1, 0u) << "Expected valid entry";
393 // Release: Ensures that "next_" points to valid entry at any time in reader.
394 writable_entry->seqlock_.fetch_add(1, std::memory_order_release); // Mark as invalid.
395 // Release: Ensures that the entry is seen as invalid before it's data is freed.
David Srbeckyd767f2d2018-02-26 16:18:40 +0000396 std::atomic_thread_fence(std::memory_order_release);
David Srbecky94af5822019-10-03 14:48:26 +0100397 const uint8_t* symfile = entry->symfile_addr_;
398 writable_entry->symfile_addr_ = nullptr;
David Srbecky1550a662019-08-14 17:16:46 +0100399 if (NativeInfo::kCopySymfileData && symfile != nullptr) {
David Srbeckye09b87e2019-08-19 21:31:31 +0100400 NativeInfo::Free(symfile);
David Srbeckyafc60cd2018-12-05 11:59:31 +0000401 }
David Srbecky1550a662019-08-14 17:16:46 +0100402
403 // Push the entry to the free list.
404 writable_entry->next_.store(descriptor.free_entries_, kNonRacingRelaxed);
David Srbecky94af5822019-10-03 14:48:26 +0100405 writable_entry->prev_ = nullptr;
David Srbecky1550a662019-08-14 17:16:46 +0100406 descriptor.free_entries_ = entry;
David Srbecky67feb172015-12-17 19:57:44 +0000407}
408
David Srbeckyafc60cd2018-12-05 11:59:31 +0000409void AddNativeDebugInfoForDex(Thread* self, const DexFile* dexfile) {
David Srbecky0b21e412018-12-05 13:24:06 +0000410 MutexLock mu(self, g_dex_debug_lock);
David Srbeckyafc60cd2018-12-05 11:59:31 +0000411 DCHECK(dexfile != nullptr);
David Srbecky8fc2f952019-07-31 18:40:09 +0100412 const ArrayRef<const uint8_t> symfile(dexfile->Begin(), dexfile->Size());
David Srbecky9ac8e432019-08-13 13:16:13 +0100413 CreateJITCodeEntryInternal<DexNativeInfo>(symfile);
David Srbeckyc684f332018-01-19 17:38:06 +0000414}
415
David Srbeckyafc60cd2018-12-05 11:59:31 +0000416void RemoveNativeDebugInfoForDex(Thread* self, const DexFile* dexfile) {
David Srbecky0b21e412018-12-05 13:24:06 +0000417 MutexLock mu(self, g_dex_debug_lock);
David Srbecky8fc2f952019-07-31 18:40:09 +0100418 DCHECK(dexfile != nullptr);
David Srbecky440a9b32018-02-15 17:47:29 +0000419 // We register dex files in the class linker and free them in DexFile_closeDexFile, but
420 // there might be cases where we load the dex file without using it in the class linker.
David Srbecky8fc2f952019-07-31 18:40:09 +0100421 // On the other hand, single dex file might also be used with different class-loaders.
David Srbeckye09b87e2019-08-19 21:31:31 +0100422 for (const JITCodeEntry* entry = __dex_debug_descriptor.head_; entry != nullptr; ) {
423 const JITCodeEntry* next = entry->next_; // Save next pointer before we free the memory.
David Srbecky8fc2f952019-07-31 18:40:09 +0100424 if (entry->symfile_addr_ == dexfile->Begin()) {
David Srbecky9ac8e432019-08-13 13:16:13 +0100425 DeleteJITCodeEntryInternal<DexNativeInfo>(entry);
David Srbecky8fc2f952019-07-31 18:40:09 +0100426 }
427 entry = next;
David Srbecky440a9b32018-02-15 17:47:29 +0000428 }
David Srbeckyc684f332018-01-19 17:38:06 +0000429}
430
David Srbecky1550a662019-08-14 17:16:46 +0100431// Splits the linked linked in to two parts:
432// The first part (including the static head pointer) is owned by the application.
433// The second part is owned by zygote and might be concurrently modified by it.
434//
435// We add two empty entries at the boundary which are never removed (app_tail, zygote_head).
436// These entries are needed to preserve the next/prev pointers in the linked list,
437// since zygote can not modify the application's data and vice versa.
438//
David Srbecky697fe5c2019-10-09 17:24:17 +0100439// <------- owned by the application memory --------> <--- owned by zygote memory --->
David Srbecky1550a662019-08-14 17:16:46 +0100440// |----------------------|------------------|-------------|-----------------|
441// head -> | application_entries* | application_tail | zygote_head | zygote_entries* |
David Srbecky4d125af2019-10-31 14:51:44 +0000442// |+---------------------|------------------|-------------|----------------+|
443// | |
444// \-(new application entries) (new zygote entries)-/
445//
446// Zygote entries are inserted at the end, which means that repacked zygote entries
447// will still be seen by single forward iteration of the linked list (avoiding race).
448//
449// Application entries are inserted at the start which introduces repacking race,
450// but that is ok, since it is easy to read new entries from head in further pass.
451// The benefit is that this makes it fast to read only the new entries.
David Srbecky1550a662019-08-14 17:16:46 +0100452//
453void NativeDebugInfoPreFork() {
454 CHECK(Runtime::Current()->IsZygote());
455 JITDescriptor& descriptor = JitNativeInfo::Descriptor();
456 if (descriptor.zygote_head_entry_ != nullptr) {
457 return; // Already done - we need to do this only on the first fork.
458 }
459
460 // Create the zygote-owned head entry (with no ELF file).
461 // The data will be allocated from the current JIT memory (owned by zygote).
462 MutexLock mu(Thread::Current(), *Locks::jit_lock_); // Needed to alloc entry.
David Srbecky697fe5c2019-10-09 17:24:17 +0100463 const JITCodeEntry* zygote_head =
464 reinterpret_cast<const JITCodeEntry*>(JitNativeInfo::Alloc(sizeof(JITCodeEntry)));
David Srbecky1550a662019-08-14 17:16:46 +0100465 CHECK(zygote_head != nullptr);
David Srbecky697fe5c2019-10-09 17:24:17 +0100466 new (JitNativeInfo::Writable(zygote_head)) JITCodeEntry(); // Initialize.
467 InsertNewEntry<JitNativeInfo>(zygote_head, descriptor.head_);
David Srbecky1550a662019-08-14 17:16:46 +0100468 descriptor.zygote_head_entry_ = zygote_head;
469
470 // Create the child-owned tail entry (with no ELF file).
471 // The data is statically allocated since it must be owned by the forked process.
David Srbecky697fe5c2019-10-09 17:24:17 +0100472 InsertNewEntry<JitNativeInfo>(&descriptor.application_tail_entry_, descriptor.head_);
David Srbecky1550a662019-08-14 17:16:46 +0100473}
474
475void NativeDebugInfoPostFork() {
Nicolas Geoffray371390f2019-09-27 09:57:38 +0100476 CHECK(!Runtime::Current()->IsZygote());
David Srbecky1550a662019-08-14 17:16:46 +0100477 JITDescriptor& descriptor = JitNativeInfo::Descriptor();
Nicolas Geoffray371390f2019-09-27 09:57:38 +0100478 descriptor.free_entries_ = nullptr; // Don't reuse zygote's entries.
David Srbecky1550a662019-08-14 17:16:46 +0100479}
480
David Srbecky8fc2f952019-07-31 18:40:09 +0100481// Split the JIT code cache into groups of fixed size and create single JITCodeEntry for each group.
David Srbecky0b21e412018-12-05 13:24:06 +0000482// The start address of method's code determines which group it belongs to. The end is irrelevant.
David Srbecky8fc2f952019-07-31 18:40:09 +0100483// New mini debug infos will be merged if possible, and entries for GCed functions will be removed.
David Srbecky9bee62a2019-10-03 15:27:21 +0100484static void RepackEntries(bool compress_entries, ArrayRef<const void*> removed)
David Srbecky0b21e412018-12-05 13:24:06 +0000485 REQUIRES(g_jit_debug_lock) {
David Srbecky8fc2f952019-07-31 18:40:09 +0100486 DCHECK(std::is_sorted(removed.begin(), removed.end()));
487 jit::Jit* jit = Runtime::Current()->GetJit();
488 if (jit == nullptr) {
489 return;
490 }
David Srbecky1550a662019-08-14 17:16:46 +0100491 JITDescriptor& descriptor = __jit_debug_descriptor;
492 bool is_zygote = Runtime::Current()->IsZygote();
David Srbecky0b21e412018-12-05 13:24:06 +0000493
David Srbecky8fc2f952019-07-31 18:40:09 +0100494 // Collect entries that we want to pack.
David Srbeckye09b87e2019-08-19 21:31:31 +0100495 std::vector<const JITCodeEntry*> entries;
David Srbecky8fc2f952019-07-31 18:40:09 +0100496 entries.reserve(2 * kJitRepackFrequency);
David Srbecky1550a662019-08-14 17:16:46 +0100497 for (const JITCodeEntry* it = descriptor.head_; it != nullptr; it = it->next_) {
498 if (it == descriptor.zygote_head_entry_ && !is_zygote) {
499 break; // Memory owned by the zygote process (read-only for an app).
500 }
David Srbecky8fc2f952019-07-31 18:40:09 +0100501 if (it->allow_packing_) {
David Srbecky9bee62a2019-10-03 15:27:21 +0100502 if (!compress_entries && it->is_compressed_ && removed.empty()) {
David Srbecky8fc2f952019-07-31 18:40:09 +0100503 continue; // If we are not compressing, also avoid decompressing.
504 }
505 entries.push_back(it);
506 }
507 }
David Srbeckye09b87e2019-08-19 21:31:31 +0100508 auto cmp = [](const JITCodeEntry* l, const JITCodeEntry* r) { return l->addr_ < r->addr_; };
David Srbecky8fc2f952019-07-31 18:40:09 +0100509 std::sort(entries.begin(), entries.end(), cmp); // Sort by address.
David Srbecky0b21e412018-12-05 13:24:06 +0000510
David Srbecky8fc2f952019-07-31 18:40:09 +0100511 // Process the entries in groups (each spanning memory range of size kJitRepackGroupSize).
512 for (auto group_it = entries.begin(); group_it != entries.end();) {
513 const void* group_ptr = AlignDown((*group_it)->addr_, kJitRepackGroupSize);
514 const void* group_end = reinterpret_cast<const uint8_t*>(group_ptr) + kJitRepackGroupSize;
515
516 // Find all entries in this group (each entry is an in-memory ELF file).
517 auto begin = group_it;
518 auto end = std::find_if(begin, entries.end(), [=](auto* e) { return e->addr_ >= group_end; });
519 CHECK(end > begin);
David Srbeckye09b87e2019-08-19 21:31:31 +0100520 ArrayRef<const JITCodeEntry*> elfs(&*begin, end - begin);
David Srbecky8fc2f952019-07-31 18:40:09 +0100521
522 // Find all symbols that have been removed in this memory range.
523 auto removed_begin = std::lower_bound(removed.begin(), removed.end(), group_ptr);
524 auto removed_end = std::lower_bound(removed.begin(), removed.end(), group_end);
525 CHECK(removed_end >= removed_begin);
526 ArrayRef<const void*> removed_subset(&*removed_begin, removed_end - removed_begin);
527
David Srbecky9bee62a2019-10-03 15:27:21 +0100528 // Optimization: Don't compress the last group since it will likely change again soon.
529 bool compress = compress_entries && end != entries.end();
530
David Srbecky8fc2f952019-07-31 18:40:09 +0100531 // Bail out early if there is nothing to do for this group.
532 if (elfs.size() == 1 && removed_subset.empty() && (*begin)->is_compressed_ == compress) {
533 group_it = end; // Go to next group.
534 continue;
David Srbecky0b21e412018-12-05 13:24:06 +0000535 }
David Srbecky76b9c692019-04-01 19:36:33 +0100536
537 // Create new single JITCodeEntry that covers this memory range.
538 uint64_t start_time = MicroTime();
David Srbecky8fc2f952019-07-31 18:40:09 +0100539 size_t live_symbols;
540 std::vector<uint8_t> packed = jit->GetJitCompiler()->PackElfFileForJIT(
541 elfs, removed_subset, compress, &live_symbols);
David Srbecky0b21e412018-12-05 13:24:06 +0000542 VLOG(jit)
David Srbecky76b9c692019-04-01 19:36:33 +0100543 << "JIT mini-debug-info repacked"
David Srbecky0b21e412018-12-05 13:24:06 +0000544 << " for " << group_ptr
David Srbecky76b9c692019-04-01 19:36:33 +0100545 << " in " << MicroTime() - start_time << "us"
David Srbecky8fc2f952019-07-31 18:40:09 +0100546 << " elfs=" << elfs.size()
547 << " dead=" << removed_subset.size()
548 << " live=" << live_symbols
549 << " size=" << packed.size() << (compress ? "(lzma)" : "");
David Srbecky0b21e412018-12-05 13:24:06 +0000550
551 // Replace the old entries with the new one (with their lifetime temporally overlapping).
David Srbecky9ac8e432019-08-13 13:16:13 +0100552 CreateJITCodeEntryInternal<JitNativeInfo>(ArrayRef<const uint8_t>(packed),
553 /*addr_=*/ group_ptr,
554 /*allow_packing_=*/ true,
555 /*is_compressed_=*/ compress);
David Srbecky8fc2f952019-07-31 18:40:09 +0100556 for (auto it : elfs) {
David Srbecky9ac8e432019-08-13 13:16:13 +0100557 DeleteJITCodeEntryInternal<JitNativeInfo>(/*entry=*/ it);
David Srbecky0b21e412018-12-05 13:24:06 +0000558 }
David Srbecky8fc2f952019-07-31 18:40:09 +0100559 group_it = end; // Go to next group.
David Srbecky0b21e412018-12-05 13:24:06 +0000560 }
David Srbecky8fc2f952019-07-31 18:40:09 +0100561 g_jit_num_unpacked_entries = 0;
David Srbecky0b21e412018-12-05 13:24:06 +0000562}
David Srbecky440a9b32018-02-15 17:47:29 +0000563
David Srbecky30fd8512020-02-20 20:27:58 +0000564void RepackNativeDebugInfoForJitLocked() REQUIRES(g_jit_debug_lock);
565
David Srbecky8fc2f952019-07-31 18:40:09 +0100566void AddNativeDebugInfoForJit(const void* code_ptr,
David Srbecky0b21e412018-12-05 13:24:06 +0000567 const std::vector<uint8_t>& symfile,
David Srbecky8fc2f952019-07-31 18:40:09 +0100568 bool allow_packing) {
569 MutexLock mu(Thread::Current(), g_jit_debug_lock);
David Srbecky440a9b32018-02-15 17:47:29 +0000570 DCHECK_NE(symfile.size(), 0u);
David Srbecky30fd8512020-02-20 20:27:58 +0000571 if (kIsDebugBuild && code_ptr != nullptr) {
572 DCHECK(g_dcheck_all_jit_functions.insert(code_ptr).second) << code_ptr << " already added";
573 }
574
575 // Remove all methods which have been marked for removal. The JIT GC should
576 // force repack, so this should happen only rarely for various corner cases.
577 // Must be done before addition in case the added code_ptr is in the removed set.
578 if (!g_removed_jit_functions.empty()) {
579 RepackNativeDebugInfoForJitLocked();
580 }
David Srbecky440a9b32018-02-15 17:47:29 +0000581
David Srbecky9ac8e432019-08-13 13:16:13 +0100582 CreateJITCodeEntryInternal<JitNativeInfo>(ArrayRef<const uint8_t>(symfile),
583 /*addr=*/ code_ptr,
584 /*allow_packing=*/ allow_packing,
585 /*is_compressed=*/ false);
David Srbecky440a9b32018-02-15 17:47:29 +0000586
David Srbecky0b21e412018-12-05 13:24:06 +0000587 VLOG(jit)
588 << "JIT mini-debug-info added"
589 << " for " << code_ptr
590 << " size=" << PrettySize(symfile.size());
591
David Srbecky8fc2f952019-07-31 18:40:09 +0100592 // Automatically repack entries on regular basis to save space.
David Srbecky76b9c692019-04-01 19:36:33 +0100593 // Pack (but don't compress) recent entries - this is cheap and reduces memory use by ~4x.
594 // We delay compression until after GC since it is more expensive (and saves further ~4x).
David Srbecky1550a662019-08-14 17:16:46 +0100595 // Always compress zygote, since it does not GC and we want to keep the high-water mark low.
David Srbecky8fc2f952019-07-31 18:40:09 +0100596 if (++g_jit_num_unpacked_entries >= kJitRepackFrequency) {
David Srbecky1550a662019-08-14 17:16:46 +0100597 bool is_zygote = Runtime::Current()->IsZygote();
David Srbecky9bee62a2019-10-03 15:27:21 +0100598 RepackEntries(/*compress_entries=*/ is_zygote, /*removed=*/ ArrayRef<const void*>());
David Srbecky440a9b32018-02-15 17:47:29 +0000599 }
600}
601
David Srbecky30fd8512020-02-20 20:27:58 +0000602void RemoveNativeDebugInfoForJit(const void* code_ptr) {
David Srbecky8fc2f952019-07-31 18:40:09 +0100603 MutexLock mu(Thread::Current(), g_jit_debug_lock);
David Srbecky30fd8512020-02-20 20:27:58 +0000604 g_dcheck_all_jit_functions.erase(code_ptr);
605
606 // Method removal is very expensive since we need to decompress and read ELF files.
607 // Collet methods to be removed and do the removal in bulk later.
608 g_removed_jit_functions.push_back(code_ptr);
609}
610
611void RepackNativeDebugInfoForJitLocked() {
612 // Remove entries which are inside packed and compressed ELF files.
613 std::vector<const void*>& removed = g_removed_jit_functions;
614 std::sort(removed.begin(), removed.end());
615 RepackEntries(/*compress_entries=*/ true, ArrayRef<const void*>(removed));
David Srbecky8fc2f952019-07-31 18:40:09 +0100616
617 // Remove entries which are not allowed to be packed (containing single method each).
David Srbecky5aa42922020-02-20 17:20:12 +0000618 for (const JITCodeEntry* it = __jit_debug_descriptor.head_; it != nullptr;) {
619 const JITCodeEntry* next = it->next_;
David Srbecky8fc2f952019-07-31 18:40:09 +0100620 if (!it->allow_packing_ && std::binary_search(removed.begin(), removed.end(), it->addr_)) {
David Srbecky9ac8e432019-08-13 13:16:13 +0100621 DeleteJITCodeEntryInternal<JitNativeInfo>(/*entry=*/ it);
David Srbecky8fc2f952019-07-31 18:40:09 +0100622 }
David Srbecky5aa42922020-02-20 17:20:12 +0000623 it = next;
David Srbeckyafc60cd2018-12-05 11:59:31 +0000624 }
David Srbecky30fd8512020-02-20 20:27:58 +0000625
626 removed.clear();
627 removed.shrink_to_fit();
628}
629
630void RepackNativeDebugInfoForJit() {
631 MutexLock mu(Thread::Current(), g_jit_debug_lock);
632 RepackNativeDebugInfoForJitLocked();
David Srbeckyafc60cd2018-12-05 11:59:31 +0000633}
634
635size_t GetJitMiniDebugInfoMemUsage() {
David Srbecky0b21e412018-12-05 13:24:06 +0000636 MutexLock mu(Thread::Current(), g_jit_debug_lock);
David Srbeckyafc60cd2018-12-05 11:59:31 +0000637 size_t size = 0;
David Srbeckye09b87e2019-08-19 21:31:31 +0100638 for (const JITCodeEntry* it = __jit_debug_descriptor.head_; it != nullptr; it = it->next_) {
David Srbecky8fc2f952019-07-31 18:40:09 +0100639 size += sizeof(JITCodeEntry) + it->symfile_size_;
David Srbeckyafc60cd2018-12-05 11:59:31 +0000640 }
641 return size;
David Srbecky5cc349f2015-12-18 15:04:48 +0000642}
643
David Srbecky1ed45152019-04-09 18:10:26 +0100644Mutex* GetNativeDebugInfoLock() {
645 return &g_jit_debug_lock;
646}
647
David Srbecky67feb172015-12-17 19:57:44 +0000648} // namespace art