blob: f3982ec342fa3a5ece0f35106034748ba8a7a998 [file] [log] [blame]
Igor Murashkin37743352014-11-13 14:38:00 -08001/*
2 * Copyright (C) 2014 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 <stdio.h>
18#include <stdlib.h>
19
20#include <fstream>
Andreas Gampe7ad71d02016-04-04 13:49:18 -070021#include <functional>
Igor Murashkin37743352014-11-13 14:38:00 -080022#include <iostream>
Igor Murashkin37743352014-11-13 14:38:00 -080023#include <map>
Vladimir Marko1f146b72019-03-08 16:28:08 +000024#include <optional>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070025#include <set>
26#include <string>
Mathieu Chartiercb044bc2016-04-01 13:56:41 -070027#include <unordered_set>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070028#include <vector>
Igor Murashkin37743352014-11-13 14:38:00 -080029
Andreas Gampef9411702018-09-06 17:16:57 -070030#include <android-base/parseint.h>
Andreas Gampe46ee31b2016-12-14 10:11:49 -080031#include "android-base/stringprintf.h"
32
Andreas Gampea1d2f952017-04-20 22:53:58 -070033#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070034#include "art_method-inl.h"
Vladimir Marko1f146b72019-03-08 16:28:08 +000035#include "base/array_ref.h"
David Sehrc431b9d2018-03-02 12:01:51 -080036#include "base/os.h"
Vladimir Marko1f146b72019-03-08 16:28:08 +000037#include "base/string_view_cpp20.h"
Igor Murashkin37743352014-11-13 14:38:00 -080038#include "base/unix_file/fd_file.h"
David Sehra49e0532017-08-25 08:05:29 -070039#include "class_linker.h"
Igor Murashkin37743352014-11-13 14:38:00 -080040#include "gc/heap.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070041#include "gc/space/image_space.h"
Vladimir Marko4df2d802018-09-27 16:42:44 +000042#include "image-inl.h"
Igor Murashkin37743352014-11-13 14:38:00 -080043#include "mirror/class-inl.h"
44#include "mirror/object-inl.h"
David Sehra49e0532017-08-25 08:05:29 -070045#include "oat.h"
46#include "oat_file.h"
47#include "oat_file_manager.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070048#include "scoped_thread_state_change-inl.h"
Igor Murashkin37743352014-11-13 14:38:00 -080049
Igor Murashkin37743352014-11-13 14:38:00 -080050#include "backtrace/BacktraceMap.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070051#include "cmdline.h"
Igor Murashkin37743352014-11-13 14:38:00 -080052
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070053#include <signal.h>
Igor Murashkin37743352014-11-13 14:38:00 -080054#include <sys/stat.h>
55#include <sys/types.h>
Igor Murashkin37743352014-11-13 14:38:00 -080056
57namespace art {
58
Andreas Gampe46ee31b2016-12-14 10:11:49 -080059using android::base::StringPrintf;
60
David Sehrb4005f02017-06-20 19:11:40 -070061namespace {
62
63constexpr size_t kMaxAddressPrint = 5;
64
65enum class ProcessType {
66 kZygote,
67 kRemote
68};
69
70enum class RemoteProcesses {
71 kImageOnly,
72 kZygoteOnly,
73 kImageAndZygote
74};
75
76struct MappingData {
77 // The count of pages that are considered dirty by the OS.
78 size_t dirty_pages = 0;
79 // The count of pages that differ by at least one byte.
80 size_t different_pages = 0;
81 // The count of differing bytes.
82 size_t different_bytes = 0;
83 // The count of differing four-byte units.
84 size_t different_int32s = 0;
85 // The count of pages that have mapping count == 1.
86 size_t private_pages = 0;
87 // The count of private pages that are also dirty.
88 size_t private_dirty_pages = 0;
89 // The count of pages that are marked dirty but do not differ.
90 size_t false_dirty_pages = 0;
91 // Set of the local virtual page indices that are dirty.
92 std::set<size_t> dirty_page_set;
93};
94
95static std::string GetClassDescriptor(mirror::Class* klass)
96 REQUIRES_SHARED(Locks::mutator_lock_) {
97 CHECK(klass != nullptr);
98
99 std::string descriptor;
100 const char* descriptor_str = klass->GetDescriptor(&descriptor /*out*/);
101
102 return std::string(descriptor_str);
103}
104
105static std::string PrettyFieldValue(ArtField* field, mirror::Object* object)
106 REQUIRES_SHARED(Locks::mutator_lock_) {
107 std::ostringstream oss;
108 switch (field->GetTypeAsPrimitiveType()) {
109 case Primitive::kPrimNot: {
110 oss << object->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
111 field->GetOffset());
112 break;
113 }
114 case Primitive::kPrimBoolean: {
115 oss << static_cast<bool>(object->GetFieldBoolean<kVerifyNone>(field->GetOffset()));
116 break;
117 }
118 case Primitive::kPrimByte: {
119 oss << static_cast<int32_t>(object->GetFieldByte<kVerifyNone>(field->GetOffset()));
120 break;
121 }
122 case Primitive::kPrimChar: {
123 oss << object->GetFieldChar<kVerifyNone>(field->GetOffset());
124 break;
125 }
126 case Primitive::kPrimShort: {
127 oss << object->GetFieldShort<kVerifyNone>(field->GetOffset());
128 break;
129 }
130 case Primitive::kPrimInt: {
131 oss << object->GetField32<kVerifyNone>(field->GetOffset());
132 break;
133 }
134 case Primitive::kPrimLong: {
135 oss << object->GetField64<kVerifyNone>(field->GetOffset());
136 break;
137 }
138 case Primitive::kPrimFloat: {
139 oss << object->GetField32<kVerifyNone>(field->GetOffset());
140 break;
141 }
142 case Primitive::kPrimDouble: {
143 oss << object->GetField64<kVerifyNone>(field->GetOffset());
144 break;
145 }
146 case Primitive::kPrimVoid: {
147 oss << "void";
148 break;
149 }
150 }
151 return oss.str();
152}
153
154template <typename K, typename V, typename D>
155static std::vector<std::pair<V, K>> SortByValueDesc(
156 const std::map<K, D> map,
157 std::function<V(const D&)> value_mapper = [](const D& d) { return static_cast<V>(d); }) {
158 // Store value->key so that we can use the default sort from pair which
159 // sorts by value first and then key
160 std::vector<std::pair<V, K>> value_key_vector;
161
162 for (const auto& kv_pair : map) {
163 value_key_vector.push_back(std::make_pair(value_mapper(kv_pair.second), kv_pair.first));
164 }
165
166 // Sort in reverse (descending order)
167 std::sort(value_key_vector.rbegin(), value_key_vector.rend());
168 return value_key_vector;
169}
170
171// Fixup a remote pointer that we read from a foreign boot.art to point to our own memory.
172// Returned pointer will point to inside of remote_contents.
173template <typename T>
Vladimir Markod93e3742018-07-18 10:58:13 +0100174static ObjPtr<T> FixUpRemotePointer(ObjPtr<T> remote_ptr,
175 std::vector<uint8_t>& remote_contents,
176 const backtrace_map_t& boot_map)
177 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehrb4005f02017-06-20 19:11:40 -0700178 if (remote_ptr == nullptr) {
179 return nullptr;
180 }
181
Vladimir Markod93e3742018-07-18 10:58:13 +0100182 uintptr_t remote = reinterpret_cast<uintptr_t>(remote_ptr.Ptr());
David Sehrb4005f02017-06-20 19:11:40 -0700183
Mathieu Chartier21f7ac12018-07-09 16:18:27 -0700184 // In the case the remote pointer is out of range, it probably belongs to another image.
185 // Just return null for this case.
186 if (remote < boot_map.start || remote >= boot_map.end) {
187 return nullptr;
188 }
David Sehrb4005f02017-06-20 19:11:40 -0700189
190 off_t boot_offset = remote - boot_map.start;
191
192 return reinterpret_cast<T*>(&remote_contents[boot_offset]);
193}
194
195template <typename T>
Vladimir Markod93e3742018-07-18 10:58:13 +0100196static ObjPtr<T> RemoteContentsPointerToLocal(ObjPtr<T> remote_ptr,
197 std::vector<uint8_t>& remote_contents,
198 const ImageHeader& image_header)
199 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehrb4005f02017-06-20 19:11:40 -0700200 if (remote_ptr == nullptr) {
201 return nullptr;
202 }
203
Vladimir Markod93e3742018-07-18 10:58:13 +0100204 uint8_t* remote = reinterpret_cast<uint8_t*>(remote_ptr.Ptr());
David Sehrb4005f02017-06-20 19:11:40 -0700205 ptrdiff_t boot_offset = remote - &remote_contents[0];
206
207 const uint8_t* local_ptr = reinterpret_cast<const uint8_t*>(&image_header) + boot_offset;
208
209 return reinterpret_cast<T*>(const_cast<uint8_t*>(local_ptr));
210}
211
212template <typename T> size_t EntrySize(T* entry);
213template<> size_t EntrySize(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
214 return object->SizeOf();
215}
216template<> size_t EntrySize(ArtMethod* art_method) REQUIRES_SHARED(Locks::mutator_lock_) {
217 return sizeof(*art_method);
218}
219
220template <typename T>
221static bool EntriesDiffer(T* entry1, T* entry2) REQUIRES_SHARED(Locks::mutator_lock_) {
222 return memcmp(entry1, entry2, EntrySize(entry1)) != 0;
223}
224
225template <typename T>
226struct RegionCommon {
227 public:
228 RegionCommon(std::ostream* os,
229 std::vector<uint8_t>* remote_contents,
230 std::vector<uint8_t>* zygote_contents,
231 const backtrace_map_t& boot_map,
232 const ImageHeader& image_header) :
233 os_(*os),
234 remote_contents_(remote_contents),
235 zygote_contents_(zygote_contents),
236 boot_map_(boot_map),
237 image_header_(image_header),
238 different_entries_(0),
239 dirty_entry_bytes_(0),
240 false_dirty_entry_bytes_(0) {
241 CHECK(remote_contents != nullptr);
242 CHECK(zygote_contents != nullptr);
243 }
244
245 void DumpSamplesAndOffsetCount() {
246 os_ << " sample object addresses: ";
247 for (size_t i = 0; i < dirty_entries_.size() && i < kMaxAddressPrint; ++i) {
248 T* entry = dirty_entries_[i];
249 os_ << reinterpret_cast<void*>(entry) << ", ";
250 }
251 os_ << "\n";
252 os_ << " dirty byte +offset:count list = ";
253 std::vector<std::pair<size_t, off_t>> field_dirty_count_sorted =
254 SortByValueDesc<off_t, size_t, size_t>(field_dirty_count_);
255 for (const std::pair<size_t, off_t>& pair : field_dirty_count_sorted) {
256 off_t offset = pair.second;
257 size_t count = pair.first;
258 os_ << "+" << offset << ":" << count << ", ";
259 }
260 os_ << "\n";
261 }
262
263 size_t GetDifferentEntryCount() const { return different_entries_; }
264 size_t GetDirtyEntryBytes() const { return dirty_entry_bytes_; }
265 size_t GetFalseDirtyEntryCount() const { return false_dirty_entries_.size(); }
266 size_t GetFalseDirtyEntryBytes() const { return false_dirty_entry_bytes_; }
267 size_t GetZygoteDirtyEntryCount() const { return zygote_dirty_entries_.size(); }
268
269 protected:
270 bool IsEntryOnDirtyPage(T* entry, const std::set<size_t>& dirty_pages) const
271 REQUIRES_SHARED(Locks::mutator_lock_) {
272 size_t size = EntrySize(entry);
273 size_t page_off = 0;
274 size_t current_page_idx;
275 uintptr_t entry_address = reinterpret_cast<uintptr_t>(entry);
276 // Iterate every page this entry belongs to
277 do {
278 current_page_idx = entry_address / kPageSize + page_off;
279 if (dirty_pages.find(current_page_idx) != dirty_pages.end()) {
280 // This entry is on a dirty page
281 return true;
282 }
283 page_off++;
284 } while ((current_page_idx * kPageSize) < RoundUp(entry_address + size, kObjectAlignment));
285 return false;
286 }
287
288 void AddZygoteDirtyEntry(T* entry) REQUIRES_SHARED(Locks::mutator_lock_) {
289 zygote_dirty_entries_.insert(entry);
290 }
291
292 void AddImageDirtyEntry(T* entry) REQUIRES_SHARED(Locks::mutator_lock_) {
293 image_dirty_entries_.insert(entry);
294 }
295
296 void AddFalseDirtyEntry(T* entry) REQUIRES_SHARED(Locks::mutator_lock_) {
297 false_dirty_entries_.push_back(entry);
298 false_dirty_entry_bytes_ += EntrySize(entry);
299 }
300
301 // The output stream to write to.
302 std::ostream& os_;
303 // The byte contents of the remote (image) process' image.
304 std::vector<uint8_t>* remote_contents_;
305 // The byte contents of the zygote process' image.
306 std::vector<uint8_t>* zygote_contents_;
307 const backtrace_map_t& boot_map_;
308 const ImageHeader& image_header_;
309
310 // Count of entries that are different.
311 size_t different_entries_;
312
313 // Local entries that are dirty (differ in at least one byte).
314 size_t dirty_entry_bytes_;
315 std::vector<T*> dirty_entries_;
316
317 // Local entries that are clean, but located on dirty pages.
318 size_t false_dirty_entry_bytes_;
319 std::vector<T*> false_dirty_entries_;
320
321 // Image dirty entries
322 // If zygote_pid_only_ == true, these are shared dirty entries in the zygote.
323 // If zygote_pid_only_ == false, these are private dirty entries in the application.
324 std::set<T*> image_dirty_entries_;
325
326 // Zygote dirty entries (probably private dirty).
327 // We only add entries here if they differed in both the image and the zygote, so
328 // they are probably private dirty.
329 std::set<T*> zygote_dirty_entries_;
330
331 std::map<off_t /* field offset */, size_t /* count */> field_dirty_count_;
332
333 private:
334 DISALLOW_COPY_AND_ASSIGN(RegionCommon);
335};
336
337template <typename T>
338class RegionSpecializedBase : public RegionCommon<T> {
339};
340
341// Region analysis for mirror::Objects
David Sehra49e0532017-08-25 08:05:29 -0700342class ImgObjectVisitor : public ObjectVisitor {
343 public:
344 using ComputeDirtyFunc = std::function<void(mirror::Object* object,
345 const uint8_t* begin_image_ptr,
346 const std::set<size_t>& dirty_pages)>;
Andreas Gampe68562142018-06-20 21:49:11 +0000347 ImgObjectVisitor(ComputeDirtyFunc dirty_func,
David Sehra49e0532017-08-25 08:05:29 -0700348 const uint8_t* begin_image_ptr,
349 const std::set<size_t>& dirty_pages) :
Andreas Gampebc802de2018-06-20 17:24:11 -0700350 dirty_func_(std::move(dirty_func)),
David Sehra49e0532017-08-25 08:05:29 -0700351 begin_image_ptr_(begin_image_ptr),
352 dirty_pages_(dirty_pages) { }
353
Roland Levillainf73caca2018-08-24 17:19:07 +0100354 ~ImgObjectVisitor() override { }
David Sehra49e0532017-08-25 08:05:29 -0700355
Roland Levillainf73caca2018-08-24 17:19:07 +0100356 void Visit(mirror::Object* object) override REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehra49e0532017-08-25 08:05:29 -0700357 // Sanity check that we are reading a real mirror::Object
358 CHECK(object->GetClass() != nullptr) << "Image object at address "
359 << object
360 << " has null class";
361 if (kUseBakerReadBarrier) {
362 object->AssertReadBarrierState();
363 }
364 dirty_func_(object, begin_image_ptr_, dirty_pages_);
365 }
366
367 private:
Andreas Gampebc802de2018-06-20 17:24:11 -0700368 const ComputeDirtyFunc dirty_func_;
David Sehra49e0532017-08-25 08:05:29 -0700369 const uint8_t* begin_image_ptr_;
370 const std::set<size_t>& dirty_pages_;
371};
372
David Sehrb4005f02017-06-20 19:11:40 -0700373template<>
374class RegionSpecializedBase<mirror::Object> : public RegionCommon<mirror::Object> {
375 public:
376 RegionSpecializedBase(std::ostream* os,
377 std::vector<uint8_t>* remote_contents,
378 std::vector<uint8_t>* zygote_contents,
379 const backtrace_map_t& boot_map,
Jeff Haoc23b0c02017-07-27 18:19:38 -0700380 const ImageHeader& image_header,
381 bool dump_dirty_objects)
382 : RegionCommon<mirror::Object>(os, remote_contents, zygote_contents, boot_map, image_header),
383 os_(*os),
384 dump_dirty_objects_(dump_dirty_objects) { }
David Sehrb4005f02017-06-20 19:11:40 -0700385
David Sehra49e0532017-08-25 08:05:29 -0700386 // Define a common public type name for use by RegionData.
387 using VisitorClass = ImgObjectVisitor;
David Sehrb4005f02017-06-20 19:11:40 -0700388
David Sehra49e0532017-08-25 08:05:29 -0700389 void VisitEntries(VisitorClass* visitor,
390 uint8_t* base,
391 PointerSize pointer_size)
David Sehrb4005f02017-06-20 19:11:40 -0700392 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehra49e0532017-08-25 08:05:29 -0700393 RegionCommon<mirror::Object>::image_header_.VisitObjects(visitor, base, pointer_size);
David Sehrb4005f02017-06-20 19:11:40 -0700394 }
395
396 void VisitEntry(mirror::Object* entry)
397 REQUIRES_SHARED(Locks::mutator_lock_) {
398 // Unconditionally store the class descriptor in case we need it later
399 mirror::Class* klass = entry->GetClass();
400 class_data_[klass].descriptor = GetClassDescriptor(klass);
401 }
402
403 void AddCleanEntry(mirror::Object* entry)
404 REQUIRES_SHARED(Locks::mutator_lock_) {
405 class_data_[entry->GetClass()].AddCleanObject();
406 }
407
408 void AddFalseDirtyEntry(mirror::Object* entry)
409 REQUIRES_SHARED(Locks::mutator_lock_) {
410 RegionCommon<mirror::Object>::AddFalseDirtyEntry(entry);
411 class_data_[entry->GetClass()].AddFalseDirtyObject(entry);
412 }
413
414 void AddDirtyEntry(mirror::Object* entry, mirror::Object* entry_remote)
415 REQUIRES_SHARED(Locks::mutator_lock_) {
416 size_t entry_size = EntrySize(entry);
417 ++different_entries_;
418 dirty_entry_bytes_ += entry_size;
419 // Log dirty count and objects for class objects only.
420 mirror::Class* klass = entry->GetClass();
421 if (klass->IsClassClass()) {
422 // Increment counts for the fields that are dirty
423 const uint8_t* current = reinterpret_cast<const uint8_t*>(entry);
424 const uint8_t* current_remote = reinterpret_cast<const uint8_t*>(entry_remote);
425 for (size_t i = 0; i < entry_size; ++i) {
426 if (current[i] != current_remote[i]) {
427 field_dirty_count_[i]++;
428 }
429 }
430 dirty_entries_.push_back(entry);
431 }
432 class_data_[klass].AddDirtyObject(entry, entry_remote);
433 }
434
Jeff Haoc23b0c02017-07-27 18:19:38 -0700435 void DiffEntryContents(mirror::Object* entry,
436 uint8_t* remote_bytes,
437 const uint8_t* base_ptr,
438 bool log_dirty_objects)
David Sehrb4005f02017-06-20 19:11:40 -0700439 REQUIRES_SHARED(Locks::mutator_lock_) {
440 const char* tabs = " ";
441 // Attempt to find fields for all dirty bytes.
442 mirror::Class* klass = entry->GetClass();
443 if (entry->IsClass()) {
444 os_ << tabs
445 << "Class " << mirror::Class::PrettyClass(entry->AsClass()) << " " << entry << "\n";
446 } else {
447 os_ << tabs
448 << "Instance of " << mirror::Class::PrettyClass(klass) << " " << entry << "\n";
449 }
450
451 std::unordered_set<ArtField*> dirty_instance_fields;
452 std::unordered_set<ArtField*> dirty_static_fields;
453 // Examine the bytes comprising the Object, computing which fields are dirty
454 // and recording them for later display. If the Object is an array object,
455 // compute the dirty entries.
David Sehrb4005f02017-06-20 19:11:40 -0700456 mirror::Object* remote_entry = reinterpret_cast<mirror::Object*>(remote_bytes);
457 for (size_t i = 0, count = entry->SizeOf(); i < count; ++i) {
Mathieu Chartier51e79652017-07-24 15:43:38 -0700458 if (base_ptr[i] != remote_bytes[i]) {
David Sehrb4005f02017-06-20 19:11:40 -0700459 ArtField* field = ArtField::FindInstanceFieldWithOffset</*exact*/false>(klass, i);
460 if (field != nullptr) {
461 dirty_instance_fields.insert(field);
462 } else if (entry->IsClass()) {
463 field = ArtField::FindStaticFieldWithOffset</*exact*/false>(entry->AsClass(), i);
464 if (field != nullptr) {
465 dirty_static_fields.insert(field);
466 }
467 }
468 if (field == nullptr) {
469 if (klass->IsArrayClass()) {
470 mirror::Class* component_type = klass->GetComponentType();
471 Primitive::Type primitive_type = component_type->GetPrimitiveType();
472 size_t component_size = Primitive::ComponentSize(primitive_type);
473 size_t data_offset = mirror::Array::DataOffset(component_size).Uint32Value();
Vladimir Marko1f146b72019-03-08 16:28:08 +0000474 DCHECK_ALIGNED_PARAM(data_offset, component_size);
David Sehrb4005f02017-06-20 19:11:40 -0700475 if (i >= data_offset) {
476 os_ << tabs << "Dirty array element " << (i - data_offset) / component_size << "\n";
Vladimir Marko1f146b72019-03-08 16:28:08 +0000477 // Skip the remaining bytes of this element to prevent spam.
478 DCHECK(IsPowerOfTwo(component_size));
479 i |= component_size - 1;
David Sehrb4005f02017-06-20 19:11:40 -0700480 continue;
481 }
482 }
483 os_ << tabs << "No field for byte offset " << i << "\n";
484 }
485 }
486 }
487 // Dump different fields.
488 if (!dirty_instance_fields.empty()) {
489 os_ << tabs << "Dirty instance fields " << dirty_instance_fields.size() << "\n";
490 for (ArtField* field : dirty_instance_fields) {
491 os_ << tabs << ArtField::PrettyField(field)
492 << " original=" << PrettyFieldValue(field, entry)
493 << " remote=" << PrettyFieldValue(field, remote_entry) << "\n";
494 }
495 }
496 if (!dirty_static_fields.empty()) {
Jeff Haoc23b0c02017-07-27 18:19:38 -0700497 if (dump_dirty_objects_ && log_dirty_objects) {
498 dirty_objects_.insert(entry);
499 }
David Sehrb4005f02017-06-20 19:11:40 -0700500 os_ << tabs << "Dirty static fields " << dirty_static_fields.size() << "\n";
501 for (ArtField* field : dirty_static_fields) {
502 os_ << tabs << ArtField::PrettyField(field)
503 << " original=" << PrettyFieldValue(field, entry)
504 << " remote=" << PrettyFieldValue(field, remote_entry) << "\n";
505 }
506 }
507 os_ << "\n";
508 }
509
Jeff Haoc23b0c02017-07-27 18:19:38 -0700510 void DumpDirtyObjects() REQUIRES_SHARED(Locks::mutator_lock_) {
511 for (mirror::Object* obj : dirty_objects_) {
512 if (obj->IsClass()) {
513 os_ << "Private dirty object: " << obj->AsClass()->PrettyDescriptor() << "\n";
514 }
515 }
516 }
517
David Sehrb4005f02017-06-20 19:11:40 -0700518 void DumpDirtyEntries() REQUIRES_SHARED(Locks::mutator_lock_) {
519 // vector of pairs (size_t count, Class*)
520 auto dirty_object_class_values =
521 SortByValueDesc<mirror::Class*, size_t, ClassData>(
522 class_data_,
523 [](const ClassData& d) { return d.dirty_object_count; });
524 os_ << "\n" << " Dirty object count by class:\n";
525 for (const auto& vk_pair : dirty_object_class_values) {
526 size_t dirty_object_count = vk_pair.first;
527 mirror::Class* klass = vk_pair.second;
528 ClassData& class_data = class_data_[klass];
529 size_t object_sizes = class_data.dirty_object_size_in_bytes;
530 float avg_dirty_bytes_per_class =
531 class_data.dirty_object_byte_count * 1.0f / object_sizes;
532 float avg_object_size = object_sizes * 1.0f / dirty_object_count;
533 const std::string& descriptor = class_data.descriptor;
534 os_ << " " << mirror::Class::PrettyClass(klass) << " ("
535 << "objects: " << dirty_object_count << ", "
536 << "avg dirty bytes: " << avg_dirty_bytes_per_class << ", "
537 << "avg object size: " << avg_object_size << ", "
538 << "class descriptor: '" << descriptor << "'"
539 << ")\n";
540 if (strcmp(descriptor.c_str(), "Ljava/lang/Class;") == 0) {
541 DumpSamplesAndOffsetCount();
542 os_ << " field contents:\n";
543 for (mirror::Object* object : class_data.dirty_objects) {
544 // remote class object
Vladimir Markod93e3742018-07-18 10:58:13 +0100545 ObjPtr<mirror::Class> remote_klass =
546 ObjPtr<mirror::Class>::DownCast<mirror::Object>(object);
David Sehrb4005f02017-06-20 19:11:40 -0700547 // local class object
Vladimir Markod93e3742018-07-18 10:58:13 +0100548 ObjPtr<mirror::Class> local_klass =
David Sehrb4005f02017-06-20 19:11:40 -0700549 RemoteContentsPointerToLocal(remote_klass,
550 *RegionCommon<mirror::Object>::remote_contents_,
551 RegionCommon<mirror::Object>::image_header_);
552 os_ << " " << reinterpret_cast<const void*>(object) << " ";
553 os_ << " class_status (remote): " << remote_klass->GetStatus() << ", ";
554 os_ << " class_status (local): " << local_klass->GetStatus();
555 os_ << "\n";
556 }
557 }
558 }
559 }
560
561 void DumpFalseDirtyEntries() REQUIRES_SHARED(Locks::mutator_lock_) {
562 // vector of pairs (size_t count, Class*)
563 auto false_dirty_object_class_values =
564 SortByValueDesc<mirror::Class*, size_t, ClassData>(
565 class_data_,
566 [](const ClassData& d) { return d.false_dirty_object_count; });
567 os_ << "\n" << " False-dirty object count by class:\n";
568 for (const auto& vk_pair : false_dirty_object_class_values) {
569 size_t object_count = vk_pair.first;
570 mirror::Class* klass = vk_pair.second;
571 ClassData& class_data = class_data_[klass];
572 size_t object_sizes = class_data.false_dirty_byte_count;
573 float avg_object_size = object_sizes * 1.0f / object_count;
574 const std::string& descriptor = class_data.descriptor;
575 os_ << " " << mirror::Class::PrettyClass(klass) << " ("
576 << "objects: " << object_count << ", "
577 << "avg object size: " << avg_object_size << ", "
578 << "total bytes: " << object_sizes << ", "
579 << "class descriptor: '" << descriptor << "'"
580 << ")\n";
581 }
582 }
583
584 void DumpCleanEntries() REQUIRES_SHARED(Locks::mutator_lock_) {
585 // vector of pairs (size_t count, Class*)
586 auto clean_object_class_values =
587 SortByValueDesc<mirror::Class*, size_t, ClassData>(
588 class_data_,
589 [](const ClassData& d) { return d.clean_object_count; });
590 os_ << "\n" << " Clean object count by class:\n";
591 for (const auto& vk_pair : clean_object_class_values) {
592 os_ << " " << mirror::Class::PrettyClass(vk_pair.second) << " (" << vk_pair.first << ")\n";
593 }
594 }
595
596 private:
597 // Aggregate and detail class data from an image diff.
598 struct ClassData {
599 size_t dirty_object_count = 0;
600 // Track only the byte-per-byte dirtiness (in bytes)
601 size_t dirty_object_byte_count = 0;
602 // Track the object-by-object dirtiness (in bytes)
603 size_t dirty_object_size_in_bytes = 0;
604 size_t clean_object_count = 0;
605 std::string descriptor;
606 size_t false_dirty_byte_count = 0;
607 size_t false_dirty_object_count = 0;
608 std::vector<mirror::Object*> false_dirty_objects;
609 // Remote pointers to dirty objects
610 std::vector<mirror::Object*> dirty_objects;
611
612 void AddCleanObject() REQUIRES_SHARED(Locks::mutator_lock_) {
613 ++clean_object_count;
614 }
615
616 void AddDirtyObject(mirror::Object* object, mirror::Object* object_remote)
617 REQUIRES_SHARED(Locks::mutator_lock_) {
618 ++dirty_object_count;
619 dirty_object_byte_count += CountDirtyBytes(object, object_remote);
620 dirty_object_size_in_bytes += EntrySize(object);
621 dirty_objects.push_back(object_remote);
622 }
623
624 void AddFalseDirtyObject(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
625 ++false_dirty_object_count;
626 false_dirty_objects.push_back(object);
627 false_dirty_byte_count += EntrySize(object);
628 }
629
630 private:
631 // Go byte-by-byte and figure out what exactly got dirtied
632 static size_t CountDirtyBytes(mirror::Object* object1, mirror::Object* object2)
633 REQUIRES_SHARED(Locks::mutator_lock_) {
634 const uint8_t* cur1 = reinterpret_cast<const uint8_t*>(object1);
635 const uint8_t* cur2 = reinterpret_cast<const uint8_t*>(object2);
636 size_t dirty_bytes = 0;
637 size_t object_size = EntrySize(object1);
638 for (size_t i = 0; i < object_size; ++i) {
639 if (cur1[i] != cur2[i]) {
640 dirty_bytes++;
641 }
642 }
643 return dirty_bytes;
644 }
645 };
646
647 std::ostream& os_;
Jeff Haoc23b0c02017-07-27 18:19:38 -0700648 bool dump_dirty_objects_;
649 std::unordered_set<mirror::Object*> dirty_objects_;
David Sehrb4005f02017-06-20 19:11:40 -0700650 std::map<mirror::Class*, ClassData> class_data_;
651
652 DISALLOW_COPY_AND_ASSIGN(RegionSpecializedBase);
653};
654
655// Region analysis for ArtMethods.
David Sehra49e0532017-08-25 08:05:29 -0700656class ImgArtMethodVisitor : public ArtMethodVisitor {
657 public:
658 using ComputeDirtyFunc = std::function<void(ArtMethod*,
659 const uint8_t*,
660 const std::set<size_t>&)>;
Andreas Gampe68562142018-06-20 21:49:11 +0000661 ImgArtMethodVisitor(ComputeDirtyFunc dirty_func,
David Sehra49e0532017-08-25 08:05:29 -0700662 const uint8_t* begin_image_ptr,
663 const std::set<size_t>& dirty_pages) :
Andreas Gampebc802de2018-06-20 17:24:11 -0700664 dirty_func_(std::move(dirty_func)),
David Sehra49e0532017-08-25 08:05:29 -0700665 begin_image_ptr_(begin_image_ptr),
666 dirty_pages_(dirty_pages) { }
Roland Levillainf73caca2018-08-24 17:19:07 +0100667 ~ImgArtMethodVisitor() override { }
668 void Visit(ArtMethod* method) override {
David Sehra49e0532017-08-25 08:05:29 -0700669 dirty_func_(method, begin_image_ptr_, dirty_pages_);
670 }
671
672 private:
Andreas Gampebc802de2018-06-20 17:24:11 -0700673 const ComputeDirtyFunc dirty_func_;
David Sehra49e0532017-08-25 08:05:29 -0700674 const uint8_t* begin_image_ptr_;
675 const std::set<size_t>& dirty_pages_;
676};
677
678// Struct and functor for computing offsets of members of ArtMethods.
679// template <typename RegionType>
680struct MemberInfo {
681 template <typename T>
682 void operator() (const ArtMethod* method, const T* member_address, const std::string& name) {
683 // Check that member_address is a pointer inside *method.
684 DCHECK(reinterpret_cast<uintptr_t>(method) <= reinterpret_cast<uintptr_t>(member_address));
685 DCHECK(reinterpret_cast<uintptr_t>(member_address) + sizeof(T) <=
686 reinterpret_cast<uintptr_t>(method) + sizeof(ArtMethod));
687 size_t offset =
688 reinterpret_cast<uintptr_t>(member_address) - reinterpret_cast<uintptr_t>(method);
689 offset_to_name_size_.insert({offset, NameAndSize(sizeof(T), name)});
690 }
691
692 struct NameAndSize {
693 size_t size_;
694 std::string name_;
695 NameAndSize(size_t size, const std::string& name) : size_(size), name_(name) { }
696 NameAndSize() : size_(0), name_("INVALID") { }
697 };
698
699 std::map<size_t, NameAndSize> offset_to_name_size_;
700};
701
David Sehrb4005f02017-06-20 19:11:40 -0700702template<>
David Sehra49e0532017-08-25 08:05:29 -0700703class RegionSpecializedBase<ArtMethod> : public RegionCommon<ArtMethod> {
David Sehrb4005f02017-06-20 19:11:40 -0700704 public:
705 RegionSpecializedBase(std::ostream* os,
706 std::vector<uint8_t>* remote_contents,
707 std::vector<uint8_t>* zygote_contents,
708 const backtrace_map_t& boot_map,
David Sehra49e0532017-08-25 08:05:29 -0700709 const ImageHeader& image_header,
710 bool dump_dirty_objects ATTRIBUTE_UNUSED)
711 : RegionCommon<ArtMethod>(os, remote_contents, zygote_contents, boot_map, image_header),
712 os_(*os) {
713 // Prepare the table for offset to member lookups.
714 ArtMethod* art_method = reinterpret_cast<ArtMethod*>(&(*remote_contents)[0]);
715 art_method->VisitMembers(member_info_);
716 // Prepare the table for address to symbolic entry point names.
717 BuildEntryPointNames();
718 class_linker_ = Runtime::Current()->GetClassLinker();
David Sehrb4005f02017-06-20 19:11:40 -0700719 }
720
David Sehra49e0532017-08-25 08:05:29 -0700721 // Define a common public type name for use by RegionData.
722 using VisitorClass = ImgArtMethodVisitor;
723
724 void VisitEntries(VisitorClass* visitor,
725 uint8_t* base,
726 PointerSize pointer_size)
David Sehrb4005f02017-06-20 19:11:40 -0700727 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehra49e0532017-08-25 08:05:29 -0700728 RegionCommon<ArtMethod>::image_header_.VisitPackedArtMethods(visitor, base, pointer_size);
David Sehrb4005f02017-06-20 19:11:40 -0700729 }
730
731 void VisitEntry(ArtMethod* method ATTRIBUTE_UNUSED)
732 REQUIRES_SHARED(Locks::mutator_lock_) {
733 }
734
David Sehra49e0532017-08-25 08:05:29 -0700735 void AddCleanEntry(ArtMethod* method ATTRIBUTE_UNUSED) {
736 }
737
David Sehrb4005f02017-06-20 19:11:40 -0700738 void AddFalseDirtyEntry(ArtMethod* method)
739 REQUIRES_SHARED(Locks::mutator_lock_) {
740 RegionCommon<ArtMethod>::AddFalseDirtyEntry(method);
741 }
742
David Sehrb4005f02017-06-20 19:11:40 -0700743 void AddDirtyEntry(ArtMethod* method, ArtMethod* method_remote)
744 REQUIRES_SHARED(Locks::mutator_lock_) {
745 size_t entry_size = EntrySize(method);
746 ++different_entries_;
747 dirty_entry_bytes_ += entry_size;
748 // Increment counts for the fields that are dirty
749 const uint8_t* current = reinterpret_cast<const uint8_t*>(method);
750 const uint8_t* current_remote = reinterpret_cast<const uint8_t*>(method_remote);
751 // ArtMethods always log their dirty count and entries.
752 for (size_t i = 0; i < entry_size; ++i) {
753 if (current[i] != current_remote[i]) {
754 field_dirty_count_[i]++;
755 }
756 }
757 dirty_entries_.push_back(method);
758 }
759
David Sehra49e0532017-08-25 08:05:29 -0700760 void DiffEntryContents(ArtMethod* method,
761 uint8_t* remote_bytes,
762 const uint8_t* base_ptr,
763 bool log_dirty_objects ATTRIBUTE_UNUSED)
David Sehrb4005f02017-06-20 19:11:40 -0700764 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehra49e0532017-08-25 08:05:29 -0700765 const char* tabs = " ";
766 os_ << tabs << "ArtMethod " << ArtMethod::PrettyMethod(method) << "\n";
767
768 std::unordered_set<size_t> dirty_members;
769 // Examine the members comprising the ArtMethod, computing which members are dirty.
Andreas Gampeaad9d372018-09-18 15:58:47 -0700770 for (const std::pair<const size_t,
771 MemberInfo::NameAndSize>& p : member_info_.offset_to_name_size_) {
David Sehra49e0532017-08-25 08:05:29 -0700772 const size_t offset = p.first;
773 if (memcmp(base_ptr + offset, remote_bytes + offset, p.second.size_) != 0) {
774 dirty_members.insert(p.first);
775 }
776 }
777 // Dump different fields.
778 if (!dirty_members.empty()) {
779 os_ << tabs << "Dirty members " << dirty_members.size() << "\n";
780 for (size_t offset : dirty_members) {
781 const MemberInfo::NameAndSize& member_info = member_info_.offset_to_name_size_[offset];
782 os_ << tabs << member_info.name_
783 << " original=" << StringFromBytes(base_ptr + offset, member_info.size_)
784 << " remote=" << StringFromBytes(remote_bytes + offset, member_info.size_)
785 << "\n";
786 }
787 }
788 os_ << "\n";
789 }
790
791 void DumpDirtyObjects() REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehrb4005f02017-06-20 19:11:40 -0700792 }
793
794 void DumpDirtyEntries() REQUIRES_SHARED(Locks::mutator_lock_) {
795 DumpSamplesAndOffsetCount();
David Sehra49e0532017-08-25 08:05:29 -0700796 os_ << " offset to field map:\n";
Andreas Gampeaad9d372018-09-18 15:58:47 -0700797 for (const std::pair<const size_t,
798 MemberInfo::NameAndSize>& p : member_info_.offset_to_name_size_) {
David Sehra49e0532017-08-25 08:05:29 -0700799 const size_t offset = p.first;
800 const size_t size = p.second.size_;
801 os_ << StringPrintf(" %zu-%zu: ", offset, offset + size - 1)
802 << p.second.name_
803 << std::endl;
804 }
805
David Sehrb4005f02017-06-20 19:11:40 -0700806 os_ << " field contents:\n";
807 for (ArtMethod* method : dirty_entries_) {
808 // remote method
809 auto art_method = reinterpret_cast<ArtMethod*>(method);
810 // remote class
Vladimir Markod93e3742018-07-18 10:58:13 +0100811 ObjPtr<mirror::Class> remote_declaring_class =
David Sehrb4005f02017-06-20 19:11:40 -0700812 FixUpRemotePointer(art_method->GetDeclaringClass(),
813 *RegionCommon<ArtMethod>::remote_contents_,
814 RegionCommon<ArtMethod>::boot_map_);
815 // local class
Vladimir Markod93e3742018-07-18 10:58:13 +0100816 ObjPtr<mirror::Class> declaring_class =
David Sehrb4005f02017-06-20 19:11:40 -0700817 RemoteContentsPointerToLocal(remote_declaring_class,
818 *RegionCommon<ArtMethod>::remote_contents_,
819 RegionCommon<ArtMethod>::image_header_);
820 DumpOneArtMethod(art_method, declaring_class, remote_declaring_class);
821 }
822 }
823
824 void DumpFalseDirtyEntries() REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehra49e0532017-08-25 08:05:29 -0700825 os_ << "\n" << " False-dirty ArtMethods\n";
David Sehrb4005f02017-06-20 19:11:40 -0700826 os_ << " field contents:\n";
827 for (ArtMethod* method : false_dirty_entries_) {
828 // local class
Vladimir Markod93e3742018-07-18 10:58:13 +0100829 ObjPtr<mirror::Class> declaring_class = method->GetDeclaringClass();
David Sehrb4005f02017-06-20 19:11:40 -0700830 DumpOneArtMethod(method, declaring_class, nullptr);
831 }
832 }
833
834 void DumpCleanEntries() REQUIRES_SHARED(Locks::mutator_lock_) {
835 }
836
837 private:
838 std::ostream& os_;
David Sehra49e0532017-08-25 08:05:29 -0700839 MemberInfo member_info_;
840 std::map<const void*, std::string> entry_point_names_;
841 ClassLinker* class_linker_;
842
843 // Compute a map of addresses to names in the boot OAT file(s).
844 void BuildEntryPointNames() {
845 OatFileManager& oat_file_manager = Runtime::Current()->GetOatFileManager();
846 std::vector<const OatFile*> boot_oat_files = oat_file_manager.GetBootOatFiles();
847 for (const OatFile* oat_file : boot_oat_files) {
848 const OatHeader& oat_header = oat_file->GetOatHeader();
David Sehra49e0532017-08-25 08:05:29 -0700849 const void* jdl = oat_header.GetJniDlsymLookup();
850 if (jdl != nullptr) {
851 entry_point_names_[jdl] = "JniDlsymLookup (from boot oat file)";
852 }
853 const void* qgjt = oat_header.GetQuickGenericJniTrampoline();
854 if (qgjt != nullptr) {
855 entry_point_names_[qgjt] = "QuickGenericJniTrampoline (from boot oat file)";
856 }
857 const void* qrt = oat_header.GetQuickResolutionTrampoline();
858 if (qrt != nullptr) {
859 entry_point_names_[qrt] = "QuickResolutionTrampoline (from boot oat file)";
860 }
861 const void* qict = oat_header.GetQuickImtConflictTrampoline();
862 if (qict != nullptr) {
863 entry_point_names_[qict] = "QuickImtConflictTrampoline (from boot oat file)";
864 }
865 const void* q2ib = oat_header.GetQuickToInterpreterBridge();
866 if (q2ib != nullptr) {
867 entry_point_names_[q2ib] = "QuickToInterpreterBridge (from boot oat file)";
868 }
869 }
870 }
871
872 std::string StringFromBytes(const uint8_t* bytes, size_t size) {
873 switch (size) {
874 case 1:
875 return StringPrintf("%" PRIx8, *bytes);
876 case 2:
877 return StringPrintf("%" PRIx16, *reinterpret_cast<const uint16_t*>(bytes));
878 case 4:
879 case 8: {
880 // Compute an address if the bytes might contain one.
881 uint64_t intval;
882 if (size == 4) {
883 intval = *reinterpret_cast<const uint32_t*>(bytes);
884 } else {
885 intval = *reinterpret_cast<const uint64_t*>(bytes);
886 }
887 const void* addr = reinterpret_cast<const void*>(intval);
888 // Match the address against those that have Is* methods in the ClassLinker.
889 if (class_linker_->IsQuickToInterpreterBridge(addr)) {
890 return "QuickToInterpreterBridge";
891 } else if (class_linker_->IsQuickGenericJniStub(addr)) {
892 return "QuickGenericJniStub";
893 } else if (class_linker_->IsQuickResolutionStub(addr)) {
894 return "QuickResolutionStub";
895 } else if (class_linker_->IsJniDlsymLookupStub(addr)) {
896 return "JniDlsymLookupStub";
897 }
898 // Match the address against those that we saved from the boot OAT files.
899 if (entry_point_names_.find(addr) != entry_point_names_.end()) {
900 return entry_point_names_[addr];
901 }
902 return StringPrintf("%" PRIx64, intval);
903 }
904 default:
905 LOG(WARNING) << "Don't know how to convert " << size << " bytes to integer";
906 return "<UNKNOWN>";
907 }
908 }
David Sehrb4005f02017-06-20 19:11:40 -0700909
910 void DumpOneArtMethod(ArtMethod* art_method,
Vladimir Markod93e3742018-07-18 10:58:13 +0100911 ObjPtr<mirror::Class> declaring_class,
912 ObjPtr<mirror::Class> remote_declaring_class)
David Sehrb4005f02017-06-20 19:11:40 -0700913 REQUIRES_SHARED(Locks::mutator_lock_) {
914 PointerSize pointer_size = InstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
915 os_ << " " << reinterpret_cast<const void*>(art_method) << " ";
916 os_ << " entryPointFromJni: "
917 << reinterpret_cast<const void*>(art_method->GetDataPtrSize(pointer_size)) << ", ";
918 os_ << " entryPointFromQuickCompiledCode: "
919 << reinterpret_cast<const void*>(
920 art_method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size))
921 << ", ";
922 os_ << " isNative? " << (art_method->IsNative() ? "yes" : "no") << ", ";
David Sehra49e0532017-08-25 08:05:29 -0700923 // Null for runtime metionds.
924 if (declaring_class != nullptr) {
925 os_ << " class_status (local): " << declaring_class->GetStatus();
926 }
David Sehrb4005f02017-06-20 19:11:40 -0700927 if (remote_declaring_class != nullptr) {
928 os_ << ", class_status (remote): " << remote_declaring_class->GetStatus();
929 }
930 os_ << "\n";
931 }
932
933 DISALLOW_COPY_AND_ASSIGN(RegionSpecializedBase);
934};
935
936template <typename T>
937class RegionData : public RegionSpecializedBase<T> {
938 public:
939 RegionData(std::ostream* os,
940 std::vector<uint8_t>* remote_contents,
941 std::vector<uint8_t>* zygote_contents,
942 const backtrace_map_t& boot_map,
Jeff Haoc23b0c02017-07-27 18:19:38 -0700943 const ImageHeader& image_header,
944 bool dump_dirty_objects)
945 : RegionSpecializedBase<T>(os,
946 remote_contents,
947 zygote_contents,
948 boot_map,
949 image_header,
950 dump_dirty_objects),
951 os_(*os) {
David Sehrb4005f02017-06-20 19:11:40 -0700952 CHECK(remote_contents != nullptr);
953 CHECK(zygote_contents != nullptr);
954 }
955
956 // Walk over the type T entries in theregion between begin_image_ptr and end_image_ptr,
957 // collecting and reporting data regarding dirty, difference, etc.
958 void ProcessRegion(const MappingData& mapping_data,
959 RemoteProcesses remotes,
David Sehra49e0532017-08-25 08:05:29 -0700960 const uint8_t* begin_image_ptr)
David Sehrb4005f02017-06-20 19:11:40 -0700961 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehra49e0532017-08-25 08:05:29 -0700962 typename RegionSpecializedBase<T>::VisitorClass visitor(
963 [this](T* entry,
964 const uint8_t* begin_image_ptr,
965 const std::set<size_t>& dirty_page_set) REQUIRES_SHARED(Locks::mutator_lock_) {
966 this->ComputeEntryDirty(entry, begin_image_ptr, dirty_page_set);
967 },
968 begin_image_ptr,
969 mapping_data.dirty_page_set);
970 PointerSize pointer_size = InstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
971 RegionSpecializedBase<T>::VisitEntries(&visitor,
972 const_cast<uint8_t*>(begin_image_ptr),
973 pointer_size);
David Sehrb4005f02017-06-20 19:11:40 -0700974
975 // Looking at only dirty pages, figure out how many of those bytes belong to dirty entries.
976 // TODO: fix this now that there are multiple regions in a mapping.
977 float true_dirtied_percent =
978 RegionCommon<T>::GetDirtyEntryBytes() * 1.0f / (mapping_data.dirty_pages * kPageSize);
979
980 // Entry specific statistics.
981 os_ << RegionCommon<T>::GetDifferentEntryCount() << " different entries, \n "
982 << RegionCommon<T>::GetDirtyEntryBytes() << " different entry [bytes], \n "
983 << RegionCommon<T>::GetFalseDirtyEntryCount() << " false dirty entries,\n "
984 << RegionCommon<T>::GetFalseDirtyEntryBytes() << " false dirty entry [bytes], \n "
985 << true_dirtied_percent << " different entries-vs-total in a dirty page;\n "
Mathieu Chartier51e79652017-07-24 15:43:38 -0700986 << "\n";
David Sehrb4005f02017-06-20 19:11:40 -0700987
Mathieu Chartier51e79652017-07-24 15:43:38 -0700988 const uint8_t* base_ptr = begin_image_ptr;
David Sehrb4005f02017-06-20 19:11:40 -0700989 switch (remotes) {
990 case RemoteProcesses::kZygoteOnly:
991 os_ << " Zygote shared dirty entries: ";
992 break;
993 case RemoteProcesses::kImageAndZygote:
994 os_ << " Application dirty entries (private dirty): ";
Mathieu Chartier51e79652017-07-24 15:43:38 -0700995 // If we are dumping private dirty, diff against the zygote map to make it clearer what
996 // fields caused the page to be private dirty.
997 base_ptr = &RegionCommon<T>::zygote_contents_->operator[](0);
David Sehrb4005f02017-06-20 19:11:40 -0700998 break;
999 case RemoteProcesses::kImageOnly:
1000 os_ << " Application dirty entries (unknown whether private or shared dirty): ";
1001 break;
1002 }
Mathieu Chartier51e79652017-07-24 15:43:38 -07001003 DiffDirtyEntries(ProcessType::kRemote,
1004 begin_image_ptr,
1005 RegionCommon<T>::remote_contents_,
Jeff Haoc23b0c02017-07-27 18:19:38 -07001006 base_ptr,
Andreas Gampe9b031f72018-10-04 11:03:34 -07001007 /*log_dirty_objects=*/true);
Mathieu Chartier51e79652017-07-24 15:43:38 -07001008 // Print shared dirty after since it's less important.
1009 if (RegionCommon<T>::GetZygoteDirtyEntryCount() != 0) {
1010 // We only reach this point if both pids were specified. Furthermore,
1011 // entries are only displayed here if they differed in both the image
1012 // and the zygote, so they are probably private dirty.
1013 CHECK(remotes == RemoteProcesses::kImageAndZygote);
1014 os_ << "\n" << " Zygote dirty entries (probably shared dirty): ";
1015 DiffDirtyEntries(ProcessType::kZygote,
1016 begin_image_ptr,
1017 RegionCommon<T>::zygote_contents_,
Jeff Haoc23b0c02017-07-27 18:19:38 -07001018 begin_image_ptr,
Andreas Gampe9b031f72018-10-04 11:03:34 -07001019 /*log_dirty_objects=*/false);
Mathieu Chartier51e79652017-07-24 15:43:38 -07001020 }
Jeff Haoc23b0c02017-07-27 18:19:38 -07001021 RegionSpecializedBase<T>::DumpDirtyObjects();
David Sehrb4005f02017-06-20 19:11:40 -07001022 RegionSpecializedBase<T>::DumpDirtyEntries();
1023 RegionSpecializedBase<T>::DumpFalseDirtyEntries();
1024 RegionSpecializedBase<T>::DumpCleanEntries();
1025 }
1026
1027 private:
1028 std::ostream& os_;
1029
1030 void DiffDirtyEntries(ProcessType process_type,
1031 const uint8_t* begin_image_ptr,
Mathieu Chartier51e79652017-07-24 15:43:38 -07001032 std::vector<uint8_t>* contents,
Jeff Haoc23b0c02017-07-27 18:19:38 -07001033 const uint8_t* base_ptr,
1034 bool log_dirty_objects)
David Sehrb4005f02017-06-20 19:11:40 -07001035 REQUIRES_SHARED(Locks::mutator_lock_) {
1036 os_ << RegionCommon<T>::dirty_entries_.size() << "\n";
1037 const std::set<T*>& entries =
1038 (process_type == ProcessType::kZygote) ?
1039 RegionCommon<T>::zygote_dirty_entries_:
1040 RegionCommon<T>::image_dirty_entries_;
1041 for (T* entry : entries) {
1042 uint8_t* entry_bytes = reinterpret_cast<uint8_t*>(entry);
1043 ptrdiff_t offset = entry_bytes - begin_image_ptr;
1044 uint8_t* remote_bytes = &(*contents)[offset];
Jeff Haoc23b0c02017-07-27 18:19:38 -07001045 RegionSpecializedBase<T>::DiffEntryContents(entry,
1046 remote_bytes,
1047 &base_ptr[offset],
1048 log_dirty_objects);
David Sehrb4005f02017-06-20 19:11:40 -07001049 }
1050 }
1051
1052 void ComputeEntryDirty(T* entry,
1053 const uint8_t* begin_image_ptr,
1054 const std::set<size_t>& dirty_pages)
1055 REQUIRES_SHARED(Locks::mutator_lock_) {
1056 // Set up pointers in the remote and the zygote for comparison.
1057 uint8_t* current = reinterpret_cast<uint8_t*>(entry);
1058 ptrdiff_t offset = current - begin_image_ptr;
1059 T* entry_remote =
1060 reinterpret_cast<T*>(const_cast<uint8_t*>(&(*RegionCommon<T>::remote_contents_)[offset]));
Mathieu Chartier51e79652017-07-24 15:43:38 -07001061 const bool have_zygote = !RegionCommon<T>::zygote_contents_->empty();
David Sehrb4005f02017-06-20 19:11:40 -07001062 const uint8_t* current_zygote =
Mathieu Chartier51e79652017-07-24 15:43:38 -07001063 have_zygote ? &(*RegionCommon<T>::zygote_contents_)[offset] : nullptr;
David Sehrb4005f02017-06-20 19:11:40 -07001064 T* entry_zygote = reinterpret_cast<T*>(const_cast<uint8_t*>(current_zygote));
1065 // Visit and classify entries at the current location.
1066 RegionSpecializedBase<T>::VisitEntry(entry);
Mathieu Chartier51e79652017-07-24 15:43:38 -07001067
1068 // Test private dirty first.
1069 bool is_dirty = false;
1070 if (have_zygote) {
1071 bool private_dirty = EntriesDiffer(entry_zygote, entry_remote);
1072 if (private_dirty) {
1073 // Private dirty, app vs zygote.
1074 is_dirty = true;
David Sehrb4005f02017-06-20 19:11:40 -07001075 RegionCommon<T>::AddImageDirtyEntry(entry);
David Sehrb4005f02017-06-20 19:11:40 -07001076 }
Mathieu Chartier51e79652017-07-24 15:43:38 -07001077 if (EntriesDiffer(entry_zygote, entry)) {
1078 // Shared dirty, zygote vs image.
1079 is_dirty = true;
1080 RegionCommon<T>::AddZygoteDirtyEntry(entry);
1081 }
1082 } else if (EntriesDiffer(entry_remote, entry)) {
1083 // Shared or private dirty, app vs image.
1084 is_dirty = true;
1085 RegionCommon<T>::AddImageDirtyEntry(entry);
1086 }
1087 if (is_dirty) {
1088 // TODO: Add support dirty entries in zygote and image.
1089 RegionSpecializedBase<T>::AddDirtyEntry(entry, entry_remote);
David Sehrb4005f02017-06-20 19:11:40 -07001090 } else {
1091 RegionSpecializedBase<T>::AddCleanEntry(entry);
Mathieu Chartier51e79652017-07-24 15:43:38 -07001092 if (RegionCommon<T>::IsEntryOnDirtyPage(entry, dirty_pages)) {
1093 // This entry was either never mutated or got mutated back to the same value.
1094 // TODO: Do I want to distinguish a "different" vs a "dirty" page here?
1095 RegionSpecializedBase<T>::AddFalseDirtyEntry(entry);
1096 }
David Sehrb4005f02017-06-20 19:11:40 -07001097 }
1098 }
1099
1100 DISALLOW_COPY_AND_ASSIGN(RegionData);
1101};
1102
1103} // namespace
1104
1105
Igor Murashkin37743352014-11-13 14:38:00 -08001106class ImgDiagDumper {
1107 public:
1108 explicit ImgDiagDumper(std::ostream* os,
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001109 pid_t image_diff_pid,
Jeff Haoc23b0c02017-07-27 18:19:38 -07001110 pid_t zygote_diff_pid,
1111 bool dump_dirty_objects)
Igor Murashkin37743352014-11-13 14:38:00 -08001112 : os_(os),
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001113 image_diff_pid_(image_diff_pid),
David Sehr20e271a2017-06-14 13:02:14 -07001114 zygote_diff_pid_(zygote_diff_pid),
Jeff Haoc23b0c02017-07-27 18:19:38 -07001115 dump_dirty_objects_(dump_dirty_objects),
David Sehr20e271a2017-06-14 13:02:14 -07001116 zygote_pid_only_(false) {}
Igor Murashkin37743352014-11-13 14:38:00 -08001117
David Sehr50005a02017-06-21 13:24:21 -07001118 bool Init() {
Igor Murashkin37743352014-11-13 14:38:00 -08001119 std::ostream& os = *os_;
Mathieu Chartiercb044bc2016-04-01 13:56:41 -07001120
David Sehr50005a02017-06-21 13:24:21 -07001121 if (image_diff_pid_ < 0 && zygote_diff_pid_ < 0) {
1122 os << "Either --image-diff-pid or --zygote-diff-pid (or both) must be specified.\n";
1123 return false;
Igor Murashkin37743352014-11-13 14:38:00 -08001124 }
1125
David Sehr50005a02017-06-21 13:24:21 -07001126 // To avoid the combinations of command-line argument use cases:
1127 // If the user invoked with only --zygote-diff-pid, shuffle that to
1128 // image_diff_pid_, invalidate zygote_diff_pid_, and remember that
1129 // image_diff_pid_ is now special.
1130 if (image_diff_pid_ < 0) {
1131 image_diff_pid_ = zygote_diff_pid_;
1132 zygote_diff_pid_ = -1;
1133 zygote_pid_only_ = true;
David Sehr45de57f2017-06-21 05:03:22 +00001134 }
Igor Murashkin37743352014-11-13 14:38:00 -08001135
David Sehr45de57f2017-06-21 05:03:22 +00001136 {
1137 struct stat sts;
1138 std::string proc_pid_str =
1139 StringPrintf("/proc/%ld", static_cast<long>(image_diff_pid_)); // NOLINT [runtime/int]
1140 if (stat(proc_pid_str.c_str(), &sts) == -1) {
1141 os << "Process does not exist";
1142 return false;
Igor Murashkin37743352014-11-13 14:38:00 -08001143 }
1144 }
1145
Vladimir Marko1f146b72019-03-08 16:28:08 +00001146 auto open_proc_maps = [&os](pid_t pid, /*out*/ std::unique_ptr<BacktraceMap>* proc_maps) {
1147 // Open /proc/<pid>/maps to view memory maps.
1148 proc_maps->reset(BacktraceMap::Create(pid));
1149 if (*proc_maps == nullptr) {
1150 os << "Could not read backtrace maps for " << pid;
1151 return false;
David Sehr0627be32017-06-16 13:50:02 -07001152 }
Vladimir Marko1f146b72019-03-08 16:28:08 +00001153 return true;
1154 };
1155 auto open_file = [&os] (const char* file_name, /*out*/ std::unique_ptr<File>* file) {
1156 file->reset(OS::OpenFileForReading(file_name));
1157 if (*file == nullptr) {
1158 os << "Failed to open " << file_name << " for reading";
1159 return false;
1160 }
1161 return true;
1162 };
1163 auto open_mem_file = [&open_file](pid_t pid, /*out*/ std::unique_ptr<File>* mem_file) {
1164 // Open /proc/<pid>/mem and for reading remote contents.
1165 std::string mem_file_name =
1166 StringPrintf("/proc/%ld/mem", static_cast<long>(pid)); // NOLINT [runtime/int]
1167 return open_file(mem_file_name.c_str(), mem_file);
1168 };
1169 auto open_pagemap_file = [&open_file](pid_t pid, /*out*/ std::unique_ptr<File>* pagemap_file) {
1170 // Open /proc/<pid>/pagemap.
1171 std::string pagemap_file_name = StringPrintf(
1172 "/proc/%ld/pagemap", static_cast<long>(pid)); // NOLINT [runtime/int]
1173 return open_file(pagemap_file_name.c_str(), pagemap_file);
1174 };
David Sehr0627be32017-06-16 13:50:02 -07001175
Vladimir Marko1f146b72019-03-08 16:28:08 +00001176 // Open files for inspecting image memory.
1177 std::unique_ptr<BacktraceMap> image_proc_maps;
1178 std::unique_ptr<File> image_mem_file;
1179 std::unique_ptr<File> image_pagemap_file;
1180 if (!open_proc_maps(image_diff_pid_, &image_proc_maps) ||
1181 !open_mem_file(image_diff_pid_, &image_mem_file) ||
1182 !open_pagemap_file(image_diff_pid_, &image_pagemap_file)) {
David Sehr50005a02017-06-21 13:24:21 -07001183 return false;
1184 }
1185
Vladimir Marko1f146b72019-03-08 16:28:08 +00001186 // If zygote_diff_pid_ != -1, open files for inspecting zygote memory.
1187 std::unique_ptr<BacktraceMap> zygote_proc_maps;
1188 std::unique_ptr<File> zygote_mem_file;
1189 std::unique_ptr<File> zygote_pagemap_file;
David Sehr50005a02017-06-21 13:24:21 -07001190 if (zygote_diff_pid_ != -1) {
Vladimir Marko1f146b72019-03-08 16:28:08 +00001191 if (!open_proc_maps(zygote_diff_pid_, &zygote_proc_maps) ||
1192 !open_mem_file(zygote_diff_pid_, &zygote_mem_file) ||
1193 !open_pagemap_file(zygote_diff_pid_, &zygote_pagemap_file)) {
David Sehr50005a02017-06-21 13:24:21 -07001194 return false;
1195 }
1196 }
1197
Vladimir Marko1f146b72019-03-08 16:28:08 +00001198 std::unique_ptr<File> clean_pagemap_file;
1199 std::unique_ptr<File> kpageflags_file;
1200 std::unique_ptr<File> kpagecount_file;
1201 if (!open_file("/proc/self/pagemap", &clean_pagemap_file) ||
1202 !open_file("/proc/kpageflags", &kpageflags_file) ||
1203 !open_file("/proc/kpagecount", &kpagecount_file)) {
David Sehr50005a02017-06-21 13:24:21 -07001204 return false;
1205 }
1206
Vladimir Markod0430bf2019-03-18 10:54:17 +00001207 // Note: the boot image is not really clean but close enough.
1208 // For now, log pages found to be dirty.
1209 // TODO: Rewrite imgdiag to load boot image without creating a runtime.
1210 // FIXME: The following does not reliably detect dirty pages.
Vladimir Marko1f146b72019-03-08 16:28:08 +00001211 Runtime* runtime = Runtime::Current();
1212 CHECK(!runtime->ShouldRelocate());
1213 size_t total_dirty_pages = 0u;
1214 for (gc::space::ImageSpace* space : runtime->GetHeap()->GetBootImageSpaces()) {
1215 const ImageHeader& image_header = space->GetImageHeader();
1216 const uint8_t* image_begin = image_header.GetImageBegin();
1217 const uint8_t* image_end = AlignUp(image_begin + image_header.GetImageSize(), kPageSize);
1218 size_t virtual_page_idx_begin = reinterpret_cast<uintptr_t>(image_begin) / kPageSize;
1219 size_t virtual_page_idx_end = reinterpret_cast<uintptr_t>(image_end) / kPageSize;
1220 size_t num_virtual_pages = virtual_page_idx_end - virtual_page_idx_begin;
1221
1222 std::string error_msg;
1223 std::vector<uint64_t> page_frame_numbers(num_virtual_pages);
1224 if (!GetPageFrameNumbers(clean_pagemap_file.get(),
1225 virtual_page_idx_begin,
1226 ArrayRef<uint64_t>(page_frame_numbers),
1227 &error_msg)) {
1228 os << "Failed to get page frame numbers for image space " << space->GetImageLocation()
1229 << ", error: " << error_msg;
1230 return false;
1231 }
1232
1233 std::vector<uint64_t> page_flags(num_virtual_pages);
1234 if (!GetPageFlagsOrCounts(kpageflags_file.get(),
1235 ArrayRef<const uint64_t>(page_frame_numbers),
1236 ArrayRef<uint64_t>(page_flags),
1237 &error_msg)) {
1238 os << "Failed to get page flags for image space " << space->GetImageLocation()
1239 << ", error: " << error_msg;
1240 return false;
1241 }
1242
1243 size_t num_dirty_pages = 0u;
1244 std::optional<size_t> first_dirty_page;
1245 for (size_t i = 0u, size = page_flags.size(); i != size; ++i) {
1246 if (UNLIKELY((page_flags[i] & kPageFlagsDirtyMask) != 0u)) {
1247 ++num_dirty_pages;
1248 if (!first_dirty_page.has_value()) {
1249 first_dirty_page = i;
1250 }
1251 }
1252 }
1253 if (num_dirty_pages != 0u) {
1254 DCHECK(first_dirty_page.has_value());
1255 os << "Found " << num_dirty_pages << " dirty pages for " << space->GetImageLocation()
1256 << ", first dirty page: " << first_dirty_page.value_or(0u);
1257 total_dirty_pages += num_dirty_pages;
1258 }
1259 }
David Sehr50005a02017-06-21 13:24:21 -07001260
Vladimir Marko1f146b72019-03-08 16:28:08 +00001261 // Commit the mappings and files.
1262 image_proc_maps_ = std::move(image_proc_maps);
1263 image_mem_file_ = std::move(*image_mem_file);
1264 image_pagemap_file_ = std::move(*image_pagemap_file);
1265 if (zygote_diff_pid_ != -1) {
1266 zygote_proc_maps_ = std::move(zygote_proc_maps);
1267 zygote_mem_file_ = std::move(*zygote_mem_file);
1268 zygote_pagemap_file_ = std::move(*zygote_pagemap_file);
David Sehr50005a02017-06-21 13:24:21 -07001269 }
Vladimir Marko1f146b72019-03-08 16:28:08 +00001270 clean_pagemap_file_ = std::move(*clean_pagemap_file);
1271 kpageflags_file_ = std::move(*kpageflags_file);
1272 kpagecount_file_ = std::move(*kpagecount_file);
David Sehr50005a02017-06-21 13:24:21 -07001273
1274 return true;
1275 }
1276
Vladimir Marko1f146b72019-03-08 16:28:08 +00001277 bool Dump(const ImageHeader& image_header, const std::string& image_location)
1278 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr50005a02017-06-21 13:24:21 -07001279 std::ostream& os = *os_;
Vladimir Marko1f146b72019-03-08 16:28:08 +00001280 os << "IMAGE LOCATION: " << image_location << "\n\n";
David Sehr50005a02017-06-21 13:24:21 -07001281
Vladimir Marko1f146b72019-03-08 16:28:08 +00001282 os << "MAGIC: " << image_header.GetMagic() << "\n\n";
David Sehr50005a02017-06-21 13:24:21 -07001283
Vladimir Marko1f146b72019-03-08 16:28:08 +00001284 os << "IMAGE BEGIN: " << reinterpret_cast<void*>(image_header.GetImageBegin()) << "\n\n";
David Sehr50005a02017-06-21 13:24:21 -07001285
1286 PrintPidLine("IMAGE", image_diff_pid_);
1287 os << "\n\n";
1288 PrintPidLine("ZYGOTE", zygote_diff_pid_);
1289 bool ret = true;
1290 if (image_diff_pid_ >= 0 || zygote_diff_pid_ >= 0) {
Vladimir Marko1f146b72019-03-08 16:28:08 +00001291 ret = DumpImageDiff(image_header, image_location);
David Sehr50005a02017-06-21 13:24:21 -07001292 os << "\n\n";
1293 }
1294
1295 os << std::flush;
1296
1297 return ret;
1298 }
1299
1300 private:
Vladimir Marko1f146b72019-03-08 16:28:08 +00001301 bool DumpImageDiff(const ImageHeader& image_header, const std::string& image_location)
David Sehr50005a02017-06-21 13:24:21 -07001302 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko1f146b72019-03-08 16:28:08 +00001303 return DumpImageDiffMap(image_header, image_location);
David Sehr50005a02017-06-21 13:24:21 -07001304 }
1305
Vladimir Marko1f146b72019-03-08 16:28:08 +00001306 bool ComputeDirtyBytes(const ImageHeader& image_header,
1307 const uint8_t* image_begin,
1308 const backtrace_map_t& boot_map,
1309 const std::vector<uint8_t>& remote_contents,
1310 MappingData* mapping_data /*out*/) {
David Sehr50005a02017-06-21 13:24:21 -07001311 std::ostream& os = *os_;
1312
1313 size_t virtual_page_idx = 0; // Virtual page number (for an absolute memory address)
1314 size_t page_idx = 0; // Page index relative to 0
1315 size_t previous_page_idx = 0; // Previous page index relative to 0
1316
1317
1318 // Iterate through one page at a time. Boot map begin/end already implicitly aligned.
Vladimir Marko1f146b72019-03-08 16:28:08 +00001319 for (uintptr_t begin = boot_map.start; begin != boot_map.end; begin += kPageSize) {
1320 ptrdiff_t offset = begin - boot_map.start;
David Sehr50005a02017-06-21 13:24:21 -07001321
1322 // We treat the image header as part of the memory map for now
1323 // If we wanted to change this, we could pass base=start+sizeof(ImageHeader)
1324 // But it might still be interesting to see if any of the ImageHeader data mutated
Vladimir Marko1f146b72019-03-08 16:28:08 +00001325 const uint8_t* local_ptr = reinterpret_cast<const uint8_t*>(&image_header) + offset;
1326 const uint8_t* remote_ptr = &remote_contents[offset];
David Sehr50005a02017-06-21 13:24:21 -07001327
1328 if (memcmp(local_ptr, remote_ptr, kPageSize) != 0) {
David Sehrb4005f02017-06-20 19:11:40 -07001329 mapping_data->different_pages++;
David Sehr50005a02017-06-21 13:24:21 -07001330
1331 // Count the number of 32-bit integers that are different.
1332 for (size_t i = 0; i < kPageSize / sizeof(uint32_t); ++i) {
Vladimir Marko1f146b72019-03-08 16:28:08 +00001333 const uint32_t* remote_ptr_int32 = reinterpret_cast<const uint32_t*>(remote_ptr);
David Sehr50005a02017-06-21 13:24:21 -07001334 const uint32_t* local_ptr_int32 = reinterpret_cast<const uint32_t*>(local_ptr);
1335
1336 if (remote_ptr_int32[i] != local_ptr_int32[i]) {
David Sehrb4005f02017-06-20 19:11:40 -07001337 mapping_data->different_int32s++;
David Sehr50005a02017-06-21 13:24:21 -07001338 }
1339 }
1340 }
1341 }
1342
Mathieu Chartier728f8502017-07-28 17:35:30 -07001343 std::vector<size_t> private_dirty_pages_for_section(ImageHeader::kSectionCount, 0u);
1344
David Sehr50005a02017-06-21 13:24:21 -07001345 // Iterate through one byte at a time.
Vladimir Marko1f146b72019-03-08 16:28:08 +00001346 ptrdiff_t page_off_begin = image_header.GetImageBegin() - image_begin;
1347 for (uintptr_t begin = boot_map.start; begin != boot_map.end; ++begin) {
David Sehr50005a02017-06-21 13:24:21 -07001348 previous_page_idx = page_idx;
Vladimir Marko1f146b72019-03-08 16:28:08 +00001349 ptrdiff_t offset = begin - boot_map.start;
David Sehr50005a02017-06-21 13:24:21 -07001350
1351 // We treat the image header as part of the memory map for now
1352 // If we wanted to change this, we could pass base=start+sizeof(ImageHeader)
1353 // But it might still be interesting to see if any of the ImageHeader data mutated
Vladimir Marko1f146b72019-03-08 16:28:08 +00001354 const uint8_t* local_ptr = reinterpret_cast<const uint8_t*>(&image_header) + offset;
1355 const uint8_t* remote_ptr = &remote_contents[offset];
David Sehr50005a02017-06-21 13:24:21 -07001356
1357 virtual_page_idx = reinterpret_cast<uintptr_t>(local_ptr) / kPageSize;
1358
1359 // Calculate the page index, relative to the 0th page where the image begins
1360 page_idx = (offset + page_off_begin) / kPageSize;
1361 if (*local_ptr != *remote_ptr) {
1362 // Track number of bytes that are different
David Sehrb4005f02017-06-20 19:11:40 -07001363 mapping_data->different_bytes++;
David Sehr50005a02017-06-21 13:24:21 -07001364 }
1365
1366 // Independently count the # of dirty pages on the remote side
1367 size_t remote_virtual_page_idx = begin / kPageSize;
1368 if (previous_page_idx != page_idx) {
1369 uint64_t page_count = 0xC0FFEE;
1370 // TODO: virtual_page_idx needs to be from the same process
1371 std::string error_msg;
Vladimir Marko1f146b72019-03-08 16:28:08 +00001372 int dirtiness = (IsPageDirty(&image_pagemap_file_, // Image-diff-pid procmap
David Sehr50005a02017-06-21 13:24:21 -07001373 &clean_pagemap_file_, // Self procmap
1374 &kpageflags_file_,
1375 &kpagecount_file_,
1376 remote_virtual_page_idx, // potentially "dirty" page
1377 virtual_page_idx, // true "clean" page
1378 &page_count,
1379 &error_msg));
1380 if (dirtiness < 0) {
1381 os << error_msg;
1382 return false;
1383 } else if (dirtiness > 0) {
David Sehrb4005f02017-06-20 19:11:40 -07001384 mapping_data->dirty_pages++;
1385 mapping_data->dirty_page_set.insert(mapping_data->dirty_page_set.end(), virtual_page_idx);
David Sehr50005a02017-06-21 13:24:21 -07001386 }
1387
1388 bool is_dirty = dirtiness > 0;
1389 bool is_private = page_count == 1;
1390
1391 if (page_count == 1) {
David Sehrb4005f02017-06-20 19:11:40 -07001392 mapping_data->private_pages++;
David Sehr50005a02017-06-21 13:24:21 -07001393 }
1394
1395 if (is_dirty && is_private) {
David Sehrb4005f02017-06-20 19:11:40 -07001396 mapping_data->private_dirty_pages++;
Mathieu Chartier728f8502017-07-28 17:35:30 -07001397 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1398 const ImageHeader::ImageSections section = static_cast<ImageHeader::ImageSections>(i);
Vladimir Marko1f146b72019-03-08 16:28:08 +00001399 if (image_header.GetImageSection(section).Contains(offset)) {
Mathieu Chartier728f8502017-07-28 17:35:30 -07001400 ++private_dirty_pages_for_section[i];
1401 }
1402 }
David Sehr50005a02017-06-21 13:24:21 -07001403 }
1404 }
1405 }
David Sehrb4005f02017-06-20 19:11:40 -07001406 mapping_data->false_dirty_pages = mapping_data->dirty_pages - mapping_data->different_pages;
1407 // Print low-level (bytes, int32s, pages) statistics.
1408 os << mapping_data->different_bytes << " differing bytes,\n "
1409 << mapping_data->different_int32s << " differing int32s,\n "
1410 << mapping_data->different_pages << " differing pages,\n "
1411 << mapping_data->dirty_pages << " pages are dirty;\n "
1412 << mapping_data->false_dirty_pages << " pages are false dirty;\n "
1413 << mapping_data->private_pages << " pages are private;\n "
Mathieu Chartier728f8502017-07-28 17:35:30 -07001414 << mapping_data->private_dirty_pages << " pages are Private_Dirty\n "
1415 << "\n";
1416
1417 size_t total_private_dirty_pages = std::accumulate(private_dirty_pages_for_section.begin(),
1418 private_dirty_pages_for_section.end(),
1419 0u);
1420 os << "Image sections (total private dirty pages " << total_private_dirty_pages << ")\n";
1421 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1422 const ImageHeader::ImageSections section = static_cast<ImageHeader::ImageSections>(i);
Vladimir Marko1f146b72019-03-08 16:28:08 +00001423 os << section << " " << image_header.GetImageSection(section)
Mathieu Chartier728f8502017-07-28 17:35:30 -07001424 << " private dirty pages=" << private_dirty_pages_for_section[i] << "\n";
1425 }
1426 os << "\n";
David Sehrb4005f02017-06-20 19:11:40 -07001427
David Sehr50005a02017-06-21 13:24:21 -07001428 return true;
1429 }
1430
David Sehr50005a02017-06-21 13:24:21 -07001431 // Look at /proc/$pid/mem and only diff the things from there
Vladimir Marko1f146b72019-03-08 16:28:08 +00001432 bool DumpImageDiffMap(const ImageHeader& image_header, const std::string& image_location)
David Sehrb4005f02017-06-20 19:11:40 -07001433 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr50005a02017-06-21 13:24:21 -07001434 std::ostream& os = *os_;
Igor Murashkin37743352014-11-13 14:38:00 -08001435 std::string error_msg;
1436
Vladimir Marko1f146b72019-03-08 16:28:08 +00001437 std::string image_location_base_name = GetImageLocationBaseName(image_location);
1438 // FIXME: BacktraceMap should provide a const_iterator so that we can take `maps` as const&.
1439 auto find_boot_map = [&os, &image_location_base_name](BacktraceMap& maps, const char* tag)
1440 -> std::optional<backtrace_map_t> {
1441 // Find the memory map for the current boot image component.
1442 for (const backtrace_map_t* map : maps) {
1443 if (EndsWith(map->name, image_location_base_name)) {
1444 if ((map->flags & PROT_WRITE) != 0) {
1445 return *map;
1446 }
1447 // In actuality there's more than 1 map, but the second one is read-only.
1448 // The one we care about is the write-able map.
1449 // The readonly maps are guaranteed to be identical, so its not interesting to compare
1450 // them.
1451 }
1452 }
1453 os << "Could not find map for " << image_location_base_name << " in " << tag;
1454 return std::nullopt;
1455 };
1456
1457 // Find the current boot image mapping.
1458 std::optional<backtrace_map_t> maybe_boot_map = find_boot_map(*image_proc_maps_, "image");
1459 if (maybe_boot_map == std::nullopt) {
1460 return false;
1461 }
1462 backtrace_map_t boot_map = maybe_boot_map.value_or(backtrace_map_t{});
1463 // Sanity check boot_map_.
1464 CHECK(boot_map.end >= boot_map.start);
1465 // The size of the boot image mapping.
1466 size_t boot_map_size = boot_map.end - boot_map.start;
1467
1468 // If zygote_diff_pid_ != -1, check that the zygote boot map is the same.
1469 if (zygote_diff_pid_ != -1) {
1470 std::optional<backtrace_map_t> maybe_zygote_boot_map =
1471 find_boot_map(*zygote_proc_maps_, "zygote");
1472 if (maybe_zygote_boot_map == std::nullopt) {
1473 return false;
1474 }
1475 backtrace_map_t zygote_boot_map = maybe_zygote_boot_map.value_or(backtrace_map_t{});
1476 if (zygote_boot_map.start != boot_map.start || zygote_boot_map.end != boot_map.end) {
1477 os << "Zygote boot map does not match image boot map: "
1478 << "zygote begin " << reinterpret_cast<const void*>(zygote_boot_map.start)
1479 << ", zygote end " << reinterpret_cast<const void*>(zygote_boot_map.end)
1480 << ", image begin " << reinterpret_cast<const void*>(boot_map.start)
1481 << ", image end " << reinterpret_cast<const void*>(boot_map.end);
1482 return false;
1483 }
1484 }
1485
Igor Murashkin37743352014-11-13 14:38:00 -08001486 // Walk the bytes and diff against our boot image
Igor Murashkin37743352014-11-13 14:38:00 -08001487 os << "\nObserving boot image header at address "
Vladimir Marko1f146b72019-03-08 16:28:08 +00001488 << reinterpret_cast<const void*>(&image_header)
Igor Murashkin37743352014-11-13 14:38:00 -08001489 << "\n\n";
1490
Vladimir Marko1f146b72019-03-08 16:28:08 +00001491 const uint8_t* image_begin_unaligned = image_header.GetImageBegin();
1492 const uint8_t* image_end_unaligned = image_begin_unaligned + image_header.GetImageSize();
Igor Murashkin37743352014-11-13 14:38:00 -08001493
1494 // Adjust range to nearest page
1495 const uint8_t* image_begin = AlignDown(image_begin_unaligned, kPageSize);
1496 const uint8_t* image_end = AlignUp(image_end_unaligned, kPageSize);
1497
Vladimir Marko1f146b72019-03-08 16:28:08 +00001498 size_t image_size = image_end - image_begin;
1499 if (image_size != boot_map_size) {
1500 os << "Remote boot map size does not match local boot map size: "
1501 << "local size " << image_size
1502 << ", remote size " << boot_map_size;
1503 return false;
1504 }
1505
1506 // The contents of /proc/<image_diff_pid_>/maps.
1507 std::vector<uint8_t> remote_contents(boot_map_size);
1508 if (!image_mem_file_.PreadFully(remote_contents.data(), boot_map_size, boot_map.start)) {
1509 os << "Could not fully read file " << image_mem_file_.GetPath();
1510 return false;
1511 }
1512 // The contents of /proc/<zygote_diff_pid_>/maps.
1513 std::vector<uint8_t> zygote_contents;
1514 if (zygote_diff_pid_ != -1) {
1515 zygote_contents.resize(boot_map_size);
1516 if (!zygote_mem_file_.PreadFully(zygote_contents.data(), boot_map_size, boot_map.start)) {
1517 LOG(WARNING) << "Could not fully read zygote file " << zygote_mem_file_.GetPath();
1518 return false;
1519 }
1520 }
1521
1522 // FIXME: Because of ASLR, this check shall fail for most processes.
1523 // We need to update the entire diff to work with the ASLR. b/77856493
1524 if (reinterpret_cast<uintptr_t>(image_begin) > boot_map.start ||
1525 reinterpret_cast<uintptr_t>(image_end) < boot_map.end) {
Igor Murashkin37743352014-11-13 14:38:00 -08001526 // Sanity check that we aren't trying to read a completely different boot image
1527 os << "Remote boot map is out of range of local boot map: " <<
1528 "local begin " << reinterpret_cast<const void*>(image_begin) <<
1529 ", local end " << reinterpret_cast<const void*>(image_end) <<
Vladimir Marko1f146b72019-03-08 16:28:08 +00001530 ", remote begin " << reinterpret_cast<const void*>(boot_map.start) <<
1531 ", remote end " << reinterpret_cast<const void*>(boot_map.end);
Igor Murashkin37743352014-11-13 14:38:00 -08001532 return false;
1533 // If we wanted even more validation we could map the ImageHeader from the file
1534 }
1535
David Sehrb4005f02017-06-20 19:11:40 -07001536 MappingData mapping_data;
David Sehr45de57f2017-06-21 05:03:22 +00001537
Vladimir Marko1f146b72019-03-08 16:28:08 +00001538 os << "Mapping at [" << reinterpret_cast<void*>(boot_map.start) << ", "
1539 << reinterpret_cast<void*>(boot_map.end) << ") had:\n ";
1540 if (!ComputeDirtyBytes(image_header, image_begin, boot_map, remote_contents, &mapping_data)) {
David Sehr50005a02017-06-21 13:24:21 -07001541 return false;
Igor Murashkin37743352014-11-13 14:38:00 -08001542 }
David Sehrb4005f02017-06-20 19:11:40 -07001543 RemoteProcesses remotes;
David Sehr20e271a2017-06-14 13:02:14 -07001544 if (zygote_pid_only_) {
David Sehrb4005f02017-06-20 19:11:40 -07001545 remotes = RemoteProcesses::kZygoteOnly;
1546 } else if (zygote_diff_pid_ > 0) {
1547 remotes = RemoteProcesses::kImageAndZygote;
David Sehr20e271a2017-06-14 13:02:14 -07001548 } else {
David Sehrb4005f02017-06-20 19:11:40 -07001549 remotes = RemoteProcesses::kImageOnly;
Mathieu Chartiercb044bc2016-04-01 13:56:41 -07001550 }
1551
David Sehra49e0532017-08-25 08:05:29 -07001552 // Check all the mirror::Object entries in the image.
1553 RegionData<mirror::Object> object_region_data(os_,
Vladimir Marko1f146b72019-03-08 16:28:08 +00001554 &remote_contents,
1555 &zygote_contents,
1556 boot_map,
1557 image_header,
David Sehra49e0532017-08-25 08:05:29 -07001558 dump_dirty_objects_);
David Sehrb4005f02017-06-20 19:11:40 -07001559 object_region_data.ProcessRegion(mapping_data,
1560 remotes,
David Sehra49e0532017-08-25 08:05:29 -07001561 image_begin_unaligned);
Igor Murashkin37743352014-11-13 14:38:00 -08001562
David Sehra49e0532017-08-25 08:05:29 -07001563 // Check all the ArtMethod entries in the image.
1564 RegionData<ArtMethod> artmethod_region_data(os_,
Vladimir Marko1f146b72019-03-08 16:28:08 +00001565 &remote_contents,
1566 &zygote_contents,
1567 boot_map,
1568 image_header,
David Sehra49e0532017-08-25 08:05:29 -07001569 dump_dirty_objects_);
1570 artmethod_region_data.ProcessRegion(mapping_data,
1571 remotes,
1572 image_begin_unaligned);
Igor Murashkin37743352014-11-13 14:38:00 -08001573 return true;
1574 }
1575
Vladimir Marko1f146b72019-03-08 16:28:08 +00001576 // Note: On failure, `*page_frame_number` shall be clobbered.
Igor Murashkin37743352014-11-13 14:38:00 -08001577 static bool GetPageFrameNumber(File* page_map_file,
Vladimir Marko1f146b72019-03-08 16:28:08 +00001578 size_t virtual_page_index,
1579 /*out*/ uint64_t* page_frame_number,
1580 /*out*/ std::string* error_msg) {
Igor Murashkin37743352014-11-13 14:38:00 -08001581 CHECK(page_frame_number != nullptr);
Vladimir Marko1f146b72019-03-08 16:28:08 +00001582 return GetPageFrameNumbers(page_map_file,
1583 virtual_page_index,
1584 ArrayRef<uint64_t>(page_frame_number, 1u),
1585 error_msg);
1586 }
1587
1588 // Note: On failure, `page_frame_numbers[.]` shall be clobbered.
1589 static bool GetPageFrameNumbers(File* page_map_file,
1590 size_t virtual_page_index,
1591 /*out*/ ArrayRef<uint64_t> page_frame_numbers,
1592 /*out*/ std::string* error_msg) {
1593 CHECK(page_map_file != nullptr);
1594 CHECK_NE(page_frame_numbers.size(), 0u);
1595 CHECK(page_frame_numbers.data() != nullptr);
Igor Murashkin37743352014-11-13 14:38:00 -08001596 CHECK(error_msg != nullptr);
1597
Vladimir Marko1f146b72019-03-08 16:28:08 +00001598 // Read 64-bit entries from /proc/$pid/pagemap to get the physical page frame numbers.
1599 if (!page_map_file->PreadFully(page_frame_numbers.data(),
1600 page_frame_numbers.size() * kPageMapEntrySize,
1601 virtual_page_index * kPageMapEntrySize)) {
1602 *error_msg = StringPrintf("Failed to read the virtual page index entries from %s, error: %s",
1603 page_map_file->GetPath().c_str(),
1604 strerror(errno));
Igor Murashkin37743352014-11-13 14:38:00 -08001605 return false;
1606 }
1607
Vladimir Marko1f146b72019-03-08 16:28:08 +00001608 // Extract page frame numbers from pagemap entries.
1609 for (uint64_t& page_frame_number : page_frame_numbers) {
1610 page_frame_number &= kPageFrameNumberMask;
Igor Murashkin37743352014-11-13 14:38:00 -08001611 }
1612
Vladimir Marko1f146b72019-03-08 16:28:08 +00001613 return true;
1614 }
1615
1616 // Note: On failure, `page_flags_or_counts[.]` shall be clobbered.
1617 static bool GetPageFlagsOrCounts(File* kpage_file,
1618 ArrayRef<const uint64_t> page_frame_numbers,
1619 /*out*/ ArrayRef<uint64_t> page_flags_or_counts,
1620 /*out*/ std::string* error_msg) {
1621 static_assert(kPageFlagsEntrySize == kPageCountEntrySize, "entry size check");
1622 CHECK_NE(page_frame_numbers.size(), 0u);
1623 CHECK_EQ(page_flags_or_counts.size(), page_frame_numbers.size());
1624 CHECK(kpage_file != nullptr);
1625 CHECK(page_frame_numbers.data() != nullptr);
1626 CHECK(page_flags_or_counts.data() != nullptr);
1627 CHECK(error_msg != nullptr);
1628
1629 size_t size = page_frame_numbers.size();
1630 size_t i = 0;
1631 while (i != size) {
1632 size_t start = i;
1633 ++i;
1634 while (i != size && page_frame_numbers[i] - page_frame_numbers[start] == i - start) {
1635 ++i;
1636 }
1637 // Read 64-bit entries from /proc/kpageflags or /proc/kpagecount.
1638 if (!kpage_file->PreadFully(page_flags_or_counts.data() + start,
1639 (i - start) * kPageMapEntrySize,
1640 page_frame_numbers[start] * kPageFlagsEntrySize)) {
1641 *error_msg = StringPrintf("Failed to read the page flags or counts from %s, error: %s",
1642 kpage_file->GetPath().c_str(),
1643 strerror(errno));
1644 return false;
1645 }
1646 }
Igor Murashkin37743352014-11-13 14:38:00 -08001647
1648 return true;
1649 }
1650
1651 static int IsPageDirty(File* page_map_file,
David Sehr50005a02017-06-21 13:24:21 -07001652 File* clean_pagemap_file,
1653 File* kpageflags_file,
1654 File* kpagecount_file,
Igor Murashkin37743352014-11-13 14:38:00 -08001655 size_t virtual_page_idx,
1656 size_t clean_virtual_page_idx,
1657 // Out parameters:
1658 uint64_t* page_count, std::string* error_msg) {
1659 CHECK(page_map_file != nullptr);
David Sehr50005a02017-06-21 13:24:21 -07001660 CHECK(clean_pagemap_file != nullptr);
1661 CHECK_NE(page_map_file, clean_pagemap_file);
1662 CHECK(kpageflags_file != nullptr);
1663 CHECK(kpagecount_file != nullptr);
Igor Murashkin37743352014-11-13 14:38:00 -08001664 CHECK(page_count != nullptr);
1665 CHECK(error_msg != nullptr);
1666
1667 // Constants are from https://www.kernel.org/doc/Documentation/vm/pagemap.txt
1668
Igor Murashkin37743352014-11-13 14:38:00 -08001669 uint64_t page_frame_number = 0;
1670 if (!GetPageFrameNumber(page_map_file, virtual_page_idx, &page_frame_number, error_msg)) {
1671 return -1;
1672 }
1673
1674 uint64_t page_frame_number_clean = 0;
David Sehr50005a02017-06-21 13:24:21 -07001675 if (!GetPageFrameNumber(clean_pagemap_file, clean_virtual_page_idx, &page_frame_number_clean,
Igor Murashkin37743352014-11-13 14:38:00 -08001676 error_msg)) {
1677 return -1;
1678 }
1679
1680 // Read 64-bit entry from /proc/kpageflags to get the dirty bit for a page
1681 uint64_t kpage_flags_entry = 0;
David Sehr50005a02017-06-21 13:24:21 -07001682 if (!kpageflags_file->PreadFully(&kpage_flags_entry,
Igor Murashkin37743352014-11-13 14:38:00 -08001683 kPageFlagsEntrySize,
1684 page_frame_number * kPageFlagsEntrySize)) {
1685 *error_msg = StringPrintf("Failed to read the page flags from %s",
David Sehr50005a02017-06-21 13:24:21 -07001686 kpageflags_file->GetPath().c_str());
Igor Murashkin37743352014-11-13 14:38:00 -08001687 return -1;
1688 }
1689
1690 // Read 64-bit entyry from /proc/kpagecount to get mapping counts for a page
David Sehr50005a02017-06-21 13:24:21 -07001691 if (!kpagecount_file->PreadFully(page_count /*out*/,
Igor Murashkin37743352014-11-13 14:38:00 -08001692 kPageCountEntrySize,
1693 page_frame_number * kPageCountEntrySize)) {
1694 *error_msg = StringPrintf("Failed to read the page count from %s",
David Sehr50005a02017-06-21 13:24:21 -07001695 kpagecount_file->GetPath().c_str());
Igor Murashkin37743352014-11-13 14:38:00 -08001696 return -1;
1697 }
1698
1699 // There must be a page frame at the requested address.
1700 CHECK_EQ(kpage_flags_entry & kPageFlagsNoPageMask, 0u);
1701 // The page frame must be memory mapped
1702 CHECK_NE(kpage_flags_entry & kPageFlagsMmapMask, 0u);
1703
1704 // Page is dirty, i.e. has diverged from file, if the 4th bit is set to 1
1705 bool flags_dirty = (kpage_flags_entry & kPageFlagsDirtyMask) != 0;
1706
1707 // page_frame_number_clean must come from the *same* process
1708 // but a *different* mmap than page_frame_number
1709 if (flags_dirty) {
Vladimir Marko20af92f2019-03-06 16:18:56 +00001710 CHECK_NE(page_frame_number, page_frame_number_clean)
1711 << " count: " << *page_count << " flags: 0x" << std::hex << kpage_flags_entry;
Igor Murashkin37743352014-11-13 14:38:00 -08001712 }
1713
1714 return page_frame_number != page_frame_number_clean;
1715 }
1716
David Sehr50005a02017-06-21 13:24:21 -07001717 void PrintPidLine(const std::string& kind, pid_t pid) {
1718 if (pid < 0) {
1719 *os_ << kind << " DIFF PID: disabled\n\n";
1720 } else {
1721 *os_ << kind << " DIFF PID (" << pid << "): ";
1722 }
1723 }
1724
David Sehr50005a02017-06-21 13:24:21 -07001725 // Return suffix of the file path after the last /. (e.g. /foo/bar -> bar, bar -> bar)
1726 static std::string BaseName(const std::string& str) {
1727 size_t idx = str.rfind('/');
1728 if (idx == std::string::npos) {
1729 return str;
1730 }
1731
1732 return str.substr(idx + 1);
1733 }
1734
Igor Murashkin37743352014-11-13 14:38:00 -08001735 // Return the image location, stripped of any directories, e.g. "boot.art" or "core.art"
Vladimir Marko1f146b72019-03-08 16:28:08 +00001736 static std::string GetImageLocationBaseName(const std::string& image_location) {
1737 return BaseName(std::string(image_location));
Igor Murashkin37743352014-11-13 14:38:00 -08001738 }
1739
Vladimir Marko1f146b72019-03-08 16:28:08 +00001740 static constexpr size_t kPageMapEntrySize = sizeof(uint64_t);
1741 // bits 0-54 [in /proc/$pid/pagemap]
1742 static constexpr uint64_t kPageFrameNumberMask = (1ULL << 55) - 1;
1743
1744 static constexpr size_t kPageFlagsEntrySize = sizeof(uint64_t);
1745 static constexpr size_t kPageCountEntrySize = sizeof(uint64_t);
1746 static constexpr uint64_t kPageFlagsDirtyMask = (1ULL << 4); // in /proc/kpageflags
1747 static constexpr uint64_t kPageFlagsNoPageMask = (1ULL << 20); // in /proc/kpageflags
1748 static constexpr uint64_t kPageFlagsMmapMask = (1ULL << 11); // in /proc/kpageflags
1749
1750
Igor Murashkin37743352014-11-13 14:38:00 -08001751 std::ostream* os_;
Igor Murashkin37743352014-11-13 14:38:00 -08001752 pid_t image_diff_pid_; // Dump image diff against boot.art if pid is non-negative
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001753 pid_t zygote_diff_pid_; // Dump image diff against zygote boot.art if pid is non-negative
Jeff Haoc23b0c02017-07-27 18:19:38 -07001754 bool dump_dirty_objects_; // Adds dumping of objects that are dirty.
David Sehr20e271a2017-06-14 13:02:14 -07001755 bool zygote_pid_only_; // The user only specified a pid for the zygote.
Igor Murashkin37743352014-11-13 14:38:00 -08001756
David Sehr50005a02017-06-21 13:24:21 -07001757 // BacktraceMap used for finding the memory mapping of the image file.
Vladimir Marko1f146b72019-03-08 16:28:08 +00001758 std::unique_ptr<BacktraceMap> image_proc_maps_;
1759 // A File for reading /proc/<image_diff_pid_>/mem.
1760 File image_mem_file_;
1761 // A File for reading /proc/<image_diff_pid_>/pagemap.
1762 File image_pagemap_file_;
1763
1764 // BacktraceMap used for finding the memory mapping of the zygote image file.
1765 std::unique_ptr<BacktraceMap> zygote_proc_maps_;
1766 // A File for reading /proc/<zygote_diff_pid_>/mem.
1767 File zygote_mem_file_;
1768 // A File for reading /proc/<zygote_diff_pid_>/pagemap.
1769 File zygote_pagemap_file_;
1770
David Sehr50005a02017-06-21 13:24:21 -07001771 // A File for reading /proc/self/pagemap.
1772 File clean_pagemap_file_;
1773 // A File for reading /proc/kpageflags.
1774 File kpageflags_file_;
1775 // A File for reading /proc/kpagecount.
1776 File kpagecount_file_;
1777
Igor Murashkin37743352014-11-13 14:38:00 -08001778 DISALLOW_COPY_AND_ASSIGN(ImgDiagDumper);
1779};
1780
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001781static int DumpImage(Runtime* runtime,
1782 std::ostream* os,
1783 pid_t image_diff_pid,
Jeff Haoc23b0c02017-07-27 18:19:38 -07001784 pid_t zygote_diff_pid,
1785 bool dump_dirty_objects) {
Igor Murashkin37743352014-11-13 14:38:00 -08001786 ScopedObjectAccess soa(Thread::Current());
1787 gc::Heap* heap = runtime->GetHeap();
Vladimir Marko1f146b72019-03-08 16:28:08 +00001788 const std::vector<gc::space::ImageSpace*>& image_spaces = heap->GetBootImageSpaces();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001789 CHECK(!image_spaces.empty());
Vladimir Marko1f146b72019-03-08 16:28:08 +00001790 ImgDiagDumper img_diag_dumper(os,
1791 image_diff_pid,
1792 zygote_diff_pid,
1793 dump_dirty_objects);
1794 if (!img_diag_dumper.Init()) {
1795 return EXIT_FAILURE;
1796 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001797 for (gc::space::ImageSpace* image_space : image_spaces) {
1798 const ImageHeader& image_header = image_space->GetImageHeader();
1799 if (!image_header.IsValid()) {
1800 fprintf(stderr, "Invalid image header %s\n", image_space->GetImageLocation().c_str());
1801 return EXIT_FAILURE;
1802 }
1803
Vladimir Marko1f146b72019-03-08 16:28:08 +00001804 if (!img_diag_dumper.Dump(image_header, image_space->GetImageLocation())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001805 return EXIT_FAILURE;
1806 }
Igor Murashkin37743352014-11-13 14:38:00 -08001807 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001808 return EXIT_SUCCESS;
Igor Murashkin37743352014-11-13 14:38:00 -08001809}
1810
1811struct ImgDiagArgs : public CmdlineArgs {
1812 protected:
1813 using Base = CmdlineArgs;
1814
Vladimir Marko8581e2a2019-02-06 15:54:55 +00001815 ParseStatus ParseCustom(const char* raw_option,
1816 size_t raw_option_length,
1817 std::string* error_msg) override {
1818 DCHECK_EQ(strlen(raw_option), raw_option_length);
Igor Murashkin37743352014-11-13 14:38:00 -08001819 {
Vladimir Marko8581e2a2019-02-06 15:54:55 +00001820 ParseStatus base_parse = Base::ParseCustom(raw_option, raw_option_length, error_msg);
Igor Murashkin37743352014-11-13 14:38:00 -08001821 if (base_parse != kParseUnknownArgument) {
1822 return base_parse;
1823 }
1824 }
1825
Vladimir Marko8581e2a2019-02-06 15:54:55 +00001826 std::string_view option(raw_option, raw_option_length);
1827 if (StartsWith(option, "--image-diff-pid=")) {
1828 const char* image_diff_pid = raw_option + strlen("--image-diff-pid=");
Igor Murashkin37743352014-11-13 14:38:00 -08001829
Andreas Gampef9411702018-09-06 17:16:57 -07001830 if (!android::base::ParseInt(image_diff_pid, &image_diff_pid_)) {
Igor Murashkin37743352014-11-13 14:38:00 -08001831 *error_msg = "Image diff pid out of range";
1832 return kParseError;
1833 }
Vladimir Marko8581e2a2019-02-06 15:54:55 +00001834 } else if (StartsWith(option, "--zygote-diff-pid=")) {
1835 const char* zygote_diff_pid = raw_option + strlen("--zygote-diff-pid=");
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001836
Andreas Gampef9411702018-09-06 17:16:57 -07001837 if (!android::base::ParseInt(zygote_diff_pid, &zygote_diff_pid_)) {
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001838 *error_msg = "Zygote diff pid out of range";
1839 return kParseError;
1840 }
Jeff Haoc23b0c02017-07-27 18:19:38 -07001841 } else if (option == "--dump-dirty-objects") {
1842 dump_dirty_objects_ = true;
Igor Murashkin37743352014-11-13 14:38:00 -08001843 } else {
1844 return kParseUnknownArgument;
1845 }
1846
1847 return kParseOk;
1848 }
1849
Roland Levillainf73caca2018-08-24 17:19:07 +01001850 ParseStatus ParseChecks(std::string* error_msg) override {
Igor Murashkin37743352014-11-13 14:38:00 -08001851 // Perform the parent checks.
1852 ParseStatus parent_checks = Base::ParseChecks(error_msg);
1853 if (parent_checks != kParseOk) {
1854 return parent_checks;
1855 }
1856
1857 // Perform our own checks.
1858
1859 if (kill(image_diff_pid_,
1860 /*sig*/0) != 0) { // No signal is sent, perform error-checking only.
1861 // Check if the pid exists before proceeding.
1862 if (errno == ESRCH) {
1863 *error_msg = "Process specified does not exist";
1864 } else {
1865 *error_msg = StringPrintf("Failed to check process status: %s", strerror(errno));
1866 }
1867 return kParseError;
Andreas Gampe8fae4b52017-09-27 20:04:47 -07001868 } else if (instruction_set_ != InstructionSet::kNone && instruction_set_ != kRuntimeISA) {
Igor Murashkin37743352014-11-13 14:38:00 -08001869 // Don't allow different ISAs since the images are ISA-specific.
1870 // Right now the code assumes both the runtime ISA and the remote ISA are identical.
1871 *error_msg = "Must use the default runtime ISA; changing ISA is not supported.";
1872 return kParseError;
1873 }
1874
1875 return kParseOk;
1876 }
1877
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001878 std::string GetUsage() const override {
Igor Murashkin37743352014-11-13 14:38:00 -08001879 std::string usage;
1880
1881 usage +=
1882 "Usage: imgdiag [options] ...\n"
1883 " Example: imgdiag --image-diff-pid=$(pidof dex2oat)\n"
1884 " Example: adb shell imgdiag --image-diff-pid=$(pid zygote)\n"
1885 "\n";
1886
1887 usage += Base::GetUsage();
1888
1889 usage += // Optional.
1890 " --image-diff-pid=<pid>: provide the PID of a process whose boot.art you want to diff.\n"
1891 " Example: --image-diff-pid=$(pid zygote)\n"
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001892 " --zygote-diff-pid=<pid>: provide the PID of the zygote whose boot.art you want to diff "
1893 "against.\n"
1894 " Example: --zygote-diff-pid=$(pid zygote)\n"
Jeff Haoc23b0c02017-07-27 18:19:38 -07001895 " --dump-dirty-objects: additionally output dirty objects of interest.\n"
Igor Murashkin37743352014-11-13 14:38:00 -08001896 "\n";
1897
1898 return usage;
1899 }
1900
1901 public:
1902 pid_t image_diff_pid_ = -1;
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001903 pid_t zygote_diff_pid_ = -1;
Jeff Haoc23b0c02017-07-27 18:19:38 -07001904 bool dump_dirty_objects_ = false;
Igor Murashkin37743352014-11-13 14:38:00 -08001905};
1906
1907struct ImgDiagMain : public CmdlineMain<ImgDiagArgs> {
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001908 bool ExecuteWithRuntime(Runtime* runtime) override {
Igor Murashkin37743352014-11-13 14:38:00 -08001909 CHECK(args_ != nullptr);
1910
1911 return DumpImage(runtime,
Igor Murashkin37743352014-11-13 14:38:00 -08001912 args_->os_,
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001913 args_->image_diff_pid_,
Jeff Haoc23b0c02017-07-27 18:19:38 -07001914 args_->zygote_diff_pid_,
1915 args_->dump_dirty_objects_) == EXIT_SUCCESS;
Igor Murashkin37743352014-11-13 14:38:00 -08001916 }
1917};
1918
1919} // namespace art
1920
1921int main(int argc, char** argv) {
1922 art::ImgDiagMain main;
1923 return main.Main(argc, argv);
1924}