blob: 9b57ecbbff7c691c037e15497980f4758949b921 [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>
21#include <iostream>
22#include <string>
23#include <vector>
24#include <set>
25#include <map>
26
27#include "base/unix_file/fd_file.h"
28#include "base/stringprintf.h"
29#include "gc/space/image_space.h"
30#include "gc/heap.h"
31#include "mirror/class-inl.h"
32#include "mirror/object-inl.h"
33#include "mirror/art_method-inl.h"
34#include "image.h"
35#include "scoped_thread_state_change.h"
36#include "os.h"
37#include "gc_map.h"
38
39#include "cmdline.h"
40#include "backtrace/BacktraceMap.h"
41
42#include <sys/stat.h>
43#include <sys/types.h>
44#include <signal.h>
45
46namespace art {
47
48class ImgDiagDumper {
49 public:
50 explicit ImgDiagDumper(std::ostream* os,
51 const ImageHeader& image_header,
52 const char* image_location,
53 pid_t image_diff_pid)
54 : os_(os),
55 image_header_(image_header),
56 image_location_(image_location),
57 image_diff_pid_(image_diff_pid) {}
58
59 bool Dump() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
60 std::ostream& os = *os_;
61 os << "MAGIC: " << image_header_.GetMagic() << "\n\n";
62
63 os << "IMAGE BEGIN: " << reinterpret_cast<void*>(image_header_.GetImageBegin()) << "\n\n";
64
65 bool ret = true;
66 if (image_diff_pid_ >= 0) {
67 os << "IMAGE DIFF PID (" << image_diff_pid_ << "): ";
68 ret = DumpImageDiff(image_diff_pid_);
69 os << "\n\n";
70 } else {
71 os << "IMAGE DIFF PID: disabled\n\n";
72 }
73
74 os << std::flush;
75
76 return ret;
77 }
78
79 private:
80 static bool EndsWith(const std::string& str, const std::string& suffix) {
81 return str.size() >= suffix.size() &&
82 str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
83 }
84
85 // Return suffix of the file path after the last /. (e.g. /foo/bar -> bar, bar -> bar)
86 static std::string BaseName(const std::string& str) {
87 size_t idx = str.rfind("/");
88 if (idx == std::string::npos) {
89 return str;
90 }
91
92 return str.substr(idx + 1);
93 }
94
95 bool DumpImageDiff(pid_t image_diff_pid) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
96 std::ostream& os = *os_;
97
98 {
99 struct stat sts;
100 std::string proc_pid_str = StringPrintf("/proc/%ld", static_cast<long>(image_diff_pid)); // NOLINT [runtime/int]
101 if (stat(proc_pid_str.c_str(), &sts) == -1) {
102 os << "Process does not exist";
103 return false;
104 }
105 }
106
107 // Open /proc/$pid/maps to view memory maps
108 auto proc_maps = std::unique_ptr<BacktraceMap>(BacktraceMap::Create(image_diff_pid));
109 if (proc_maps == nullptr) {
110 os << "Could not read backtrace maps";
111 return false;
112 }
113
114 bool found_boot_map = false;
115 backtrace_map_t boot_map = backtrace_map_t();
116 // Find the memory map only for boot.art
117 for (const backtrace_map_t& map : *proc_maps) {
118 if (EndsWith(map.name, GetImageLocationBaseName())) {
119 if ((map.flags & PROT_WRITE) != 0) {
120 boot_map = map;
121 found_boot_map = true;
122 break;
123 }
124 // In actuality there's more than 1 map, but the second one is read-only.
125 // The one we care about is the write-able map.
126 // The readonly maps are guaranteed to be identical, so its not interesting to compare
127 // them.
128 }
129 }
130
131 if (!found_boot_map) {
132 os << "Could not find map for " << GetImageLocationBaseName();
133 return false;
134 }
135
136 // Future idea: diff against zygote so we can ignore the shared dirty pages.
137 return DumpImageDiffMap(image_diff_pid, boot_map);
138 }
139
140 // Look at /proc/$pid/mem and only diff the things from there
141 bool DumpImageDiffMap(pid_t image_diff_pid, const backtrace_map_t& boot_map)
142 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
143 std::ostream& os = *os_;
144 const size_t pointer_size = InstructionSetPointerSize(
145 Runtime::Current()->GetInstructionSet());
146
147 std::string file_name = StringPrintf("/proc/%ld/mem", static_cast<long>(image_diff_pid)); // NOLINT [runtime/int]
148
149 size_t boot_map_size = boot_map.end - boot_map.start;
150
151 // Open /proc/$pid/mem as a file
152 auto map_file = std::unique_ptr<File>(OS::OpenFileForReading(file_name.c_str()));
153 if (map_file == nullptr) {
154 os << "Failed to open " << file_name << " for reading";
155 return false;
156 }
157
158 // Memory-map /proc/$pid/mem subset from the boot map
159 CHECK(boot_map.end >= boot_map.start);
160
161 std::string error_msg;
162
163 // Walk the bytes and diff against our boot image
164 const ImageHeader& boot_image_header = GetBootImageHeader();
165
166 os << "\nObserving boot image header at address "
167 << reinterpret_cast<const void*>(&boot_image_header)
168 << "\n\n";
169
170 const uint8_t* image_begin_unaligned = boot_image_header.GetImageBegin();
171 const uint8_t* image_end_unaligned = image_begin_unaligned + boot_image_header.GetImageSize();
172
173 // Adjust range to nearest page
174 const uint8_t* image_begin = AlignDown(image_begin_unaligned, kPageSize);
175 const uint8_t* image_end = AlignUp(image_end_unaligned, kPageSize);
176
177 ptrdiff_t page_off_begin = boot_image_header.GetImageBegin() - image_begin;
178
179 if (reinterpret_cast<uintptr_t>(image_begin) > boot_map.start ||
180 reinterpret_cast<uintptr_t>(image_end) < boot_map.end) {
181 // Sanity check that we aren't trying to read a completely different boot image
182 os << "Remote boot map is out of range of local boot map: " <<
183 "local begin " << reinterpret_cast<const void*>(image_begin) <<
184 ", local end " << reinterpret_cast<const void*>(image_end) <<
185 ", remote begin " << reinterpret_cast<const void*>(boot_map.start) <<
186 ", remote end " << reinterpret_cast<const void*>(boot_map.end);
187 return false;
188 // If we wanted even more validation we could map the ImageHeader from the file
189 }
190
191 std::vector<uint8_t> remote_contents(boot_map_size);
192 if (!map_file->PreadFully(&remote_contents[0], boot_map_size, boot_map.start)) {
193 os << "Could not fully read file " << file_name;
194 return false;
195 }
196
197 std::string page_map_file_name = StringPrintf("/proc/%ld/pagemap",
198 static_cast<long>(image_diff_pid)); // NOLINT [runtime/int]
199 auto page_map_file = std::unique_ptr<File>(OS::OpenFileForReading(page_map_file_name.c_str()));
200 if (page_map_file == nullptr) {
201 os << "Failed to open " << page_map_file_name << " for reading: " << strerror(errno);
202 return false;
203 }
204
205 // Not truly clean, mmap-ing boot.art again would be more pristine, but close enough
206 const char* clean_page_map_file_name = "/proc/self/pagemap";
207 auto clean_page_map_file = std::unique_ptr<File>(
208 OS::OpenFileForReading(clean_page_map_file_name));
209 if (clean_page_map_file == nullptr) {
210 os << "Failed to open " << clean_page_map_file_name << " for reading: " << strerror(errno);
211 return false;
212 }
213
214 auto kpage_flags_file = std::unique_ptr<File>(OS::OpenFileForReading("/proc/kpageflags"));
215 if (kpage_flags_file == nullptr) {
216 os << "Failed to open /proc/kpageflags for reading: " << strerror(errno);
217 return false;
218 }
219
220 auto kpage_count_file = std::unique_ptr<File>(OS::OpenFileForReading("/proc/kpagecount"));
221 if (kpage_count_file == nullptr) {
222 os << "Failed to open /proc/kpagecount for reading:" << strerror(errno);
223 return false;
224 }
225
226 std::set<size_t> dirty_page_set_remote; // Set of the remote virtual page indices that are dirty
227 std::set<size_t> dirty_page_set_local; // Set of the local virtual page indices that are dirty
228
229 size_t different_int32s = 0;
230 size_t different_bytes = 0;
231 size_t different_pages = 0;
232 size_t virtual_page_idx = 0; // Virtual page number (for an absolute memory address)
233 size_t page_idx = 0; // Page index relative to 0
234 size_t previous_page_idx = 0; // Previous page index relative to 0
235 size_t dirty_pages = 0;
236 size_t private_pages = 0;
237 size_t private_dirty_pages = 0;
238
239 // Iterate through one page at a time. Boot map begin/end already implicitly aligned.
240 for (uintptr_t begin = boot_map.start; begin != boot_map.end; begin += kPageSize) {
241 ptrdiff_t offset = begin - boot_map.start;
242
243 // We treat the image header as part of the memory map for now
244 // If we wanted to change this, we could pass base=start+sizeof(ImageHeader)
245 // But it might still be interesting to see if any of the ImageHeader data mutated
246 const uint8_t* local_ptr = reinterpret_cast<const uint8_t*>(&boot_image_header) + offset;
247 uint8_t* remote_ptr = &remote_contents[offset];
248
249 if (memcmp(local_ptr, remote_ptr, kPageSize) != 0) {
250 different_pages++;
251
252 // Count the number of 32-bit integers that are different.
253 for (size_t i = 0; i < kPageSize / sizeof(uint32_t); ++i) {
254 uint32_t* remote_ptr_int32 = reinterpret_cast<uint32_t*>(remote_ptr);
255 const uint32_t* local_ptr_int32 = reinterpret_cast<const uint32_t*>(local_ptr);
256
257 if (remote_ptr_int32[i] != local_ptr_int32[i]) {
258 different_int32s++;
259 }
260 }
261 }
262 }
263
264 // Iterate through one byte at a time.
265 for (uintptr_t begin = boot_map.start; begin != boot_map.end; ++begin) {
266 previous_page_idx = page_idx;
267 ptrdiff_t offset = begin - boot_map.start;
268
269 // We treat the image header as part of the memory map for now
270 // If we wanted to change this, we could pass base=start+sizeof(ImageHeader)
271 // But it might still be interesting to see if any of the ImageHeader data mutated
272 const uint8_t* local_ptr = reinterpret_cast<const uint8_t*>(&boot_image_header) + offset;
273 uint8_t* remote_ptr = &remote_contents[offset];
274
275 virtual_page_idx = reinterpret_cast<uintptr_t>(local_ptr) / kPageSize;
276
277 // Calculate the page index, relative to the 0th page where the image begins
278 page_idx = (offset + page_off_begin) / kPageSize;
279 if (*local_ptr != *remote_ptr) {
280 // Track number of bytes that are different
281 different_bytes++;
282 }
283
284 // Independently count the # of dirty pages on the remote side
285 size_t remote_virtual_page_idx = begin / kPageSize;
286 if (previous_page_idx != page_idx) {
287 uint64_t page_count = 0xC0FFEE;
288 // TODO: virtual_page_idx needs to be from the same process
289 int dirtiness = (IsPageDirty(page_map_file.get(), // Image-diff-pid procmap
290 clean_page_map_file.get(), // Self procmap
291 kpage_flags_file.get(),
292 kpage_count_file.get(),
293 remote_virtual_page_idx, // potentially "dirty" page
294 virtual_page_idx, // true "clean" page
295 &page_count,
296 &error_msg));
297 if (dirtiness < 0) {
298 os << error_msg;
299 return false;
300 } else if (dirtiness > 0) {
301 dirty_pages++;
302 dirty_page_set_remote.insert(dirty_page_set_remote.end(), remote_virtual_page_idx);
303 dirty_page_set_local.insert(dirty_page_set_local.end(), virtual_page_idx);
304 }
305
306 bool is_dirty = dirtiness > 0;
307 bool is_private = page_count == 1;
308
309 if (page_count == 1) {
310 private_pages++;
311 }
312
313 if (is_dirty && is_private) {
314 private_dirty_pages++;
315 }
316 }
317 }
318
319 // Walk each object in the remote image space and compare it against ours
320 size_t different_objects = 0;
321 std::map<mirror::Class*, int /*count*/> dirty_object_class_map;
322 // Track only the byte-per-byte dirtiness (in bytes)
323 std::map<mirror::Class*, int /*byte_count*/> dirty_object_byte_count;
324 // Track the object-by-object dirtiness (in bytes)
325 std::map<mirror::Class*, int /*byte_count*/> dirty_object_size_in_bytes;
326 std::map<mirror::Class*, int /*count*/> clean_object_class_map;
327
328 std::map<mirror::Class*, std::string> class_to_descriptor_map;
329
330 std::map<off_t /* field offset */, int /* count */> art_method_field_dirty_count;
331 std::vector<mirror::ArtMethod*> art_method_dirty_objects;
332
333 std::map<off_t /* field offset */, int /* count */> class_field_dirty_count;
334 std::vector<mirror::Class*> class_dirty_objects;
335
336 // List of local objects that are clean, but located on dirty pages.
337 std::vector<mirror::Object*> false_dirty_objects;
338 std::map<mirror::Class*, int /*byte_count*/> false_dirty_byte_count;
339 std::map<mirror::Class*, int /*object_count*/> false_dirty_object_count;
340 std::map<mirror::Class*, std::vector<mirror::Object*>> false_dirty_objects_map;
341 size_t false_dirty_object_bytes = 0;
342
343 // Remote pointers to dirty objects
344 std::map<mirror::Class*, std::vector<mirror::Object*>> dirty_objects_by_class;
345 // Look up remote classes by their descriptor
346 std::map<std::string, mirror::Class*> remote_class_map;
347 // Look up local classes by their descriptor
348 std::map<std::string, mirror::Class*> local_class_map;
349
350 size_t dirty_object_bytes = 0;
351 {
352 const uint8_t* begin_image_ptr = image_begin_unaligned;
353 const uint8_t* end_image_ptr = image_end_unaligned;
354
355 const uint8_t* current = begin_image_ptr + RoundUp(sizeof(ImageHeader), kObjectAlignment);
356 while (reinterpret_cast<const uintptr_t>(current)
357 < reinterpret_cast<const uintptr_t>(end_image_ptr)) {
358 CHECK_ALIGNED(current, kObjectAlignment);
359 mirror::Object* obj = reinterpret_cast<mirror::Object*>(const_cast<uint8_t*>(current));
360
361 // Sanity check that we are reading a real object
362 CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
363 if (kUseBakerOrBrooksReadBarrier) {
364 obj->AssertReadBarrierPointer();
365 }
366
367 // Iterate every page this object belongs to
368 bool on_dirty_page = false;
369 size_t page_off = 0;
370 size_t current_page_idx;
371 uintptr_t object_address;
372 do {
373 object_address = reinterpret_cast<uintptr_t>(current);
374 current_page_idx = object_address / kPageSize + page_off;
375
376 if (dirty_page_set_local.find(current_page_idx) != dirty_page_set_local.end()) {
377 // This object is on a dirty page
378 on_dirty_page = true;
379 }
380
381 page_off++;
382 } while ((current_page_idx * kPageSize) <
383 RoundUp(object_address + obj->SizeOf(), kObjectAlignment));
384
385 mirror::Class* klass = obj->GetClass();
386
387 bool different_object = false;
388
389 // Check against the other object and see if they are different
390 ptrdiff_t offset = current - begin_image_ptr;
391 const uint8_t* current_remote = &remote_contents[offset];
392 mirror::Object* remote_obj = reinterpret_cast<mirror::Object*>(
393 const_cast<uint8_t*>(current_remote));
394 if (memcmp(current, current_remote, obj->SizeOf()) != 0) {
395 different_objects++;
396 dirty_object_bytes += obj->SizeOf();
397
398 ++dirty_object_class_map[klass];
399
400 // Go byte-by-byte and figure out what exactly got dirtied
401 size_t dirty_byte_count_per_object = 0;
402 for (size_t i = 0; i < obj->SizeOf(); ++i) {
403 if (current[i] != current_remote[i]) {
404 dirty_byte_count_per_object++;
405 }
406 }
407 dirty_object_byte_count[klass] += dirty_byte_count_per_object;
408 dirty_object_size_in_bytes[klass] += obj->SizeOf();
409
410 different_object = true;
411
412 dirty_objects_by_class[klass].push_back(remote_obj);
413 } else {
414 ++clean_object_class_map[klass];
415 }
416
417 std::string descriptor = GetClassDescriptor(klass);
418 if (different_object) {
419 if (strcmp(descriptor.c_str(), "Ljava/lang/Class;") == 0) {
420 // this is a "Class"
421 mirror::Class* obj_as_class = reinterpret_cast<mirror::Class*>(remote_obj);
422
423 // print the fields that are dirty
424 for (size_t i = 0; i < obj->SizeOf(); ++i) {
425 if (current[i] != current_remote[i]) {
426 class_field_dirty_count[i]++;
427 }
428 }
429
430 class_dirty_objects.push_back(obj_as_class);
431 } else if (strcmp(descriptor.c_str(), "Ljava/lang/reflect/ArtMethod;") == 0) {
432 // this is an ArtMethod
433 mirror::ArtMethod* art_method = reinterpret_cast<mirror::ArtMethod*>(remote_obj);
434
435 // print the fields that are dirty
436 for (size_t i = 0; i < obj->SizeOf(); ++i) {
437 if (current[i] != current_remote[i]) {
438 art_method_field_dirty_count[i]++;
439 }
440 }
441
442 art_method_dirty_objects.push_back(art_method);
443 }
444 } else if (on_dirty_page) {
445 // This object was either never mutated or got mutated back to the same value.
446 // TODO: Do I want to distinguish a "different" vs a "dirty" page here?
447 false_dirty_objects.push_back(obj);
448 false_dirty_objects_map[klass].push_back(obj);
449 false_dirty_object_bytes += obj->SizeOf();
450 false_dirty_byte_count[obj->GetClass()] += obj->SizeOf();
451 false_dirty_object_count[obj->GetClass()] += 1;
452 }
453
454 if (strcmp(descriptor.c_str(), "Ljava/lang/Class;") == 0) {
455 local_class_map[descriptor] = reinterpret_cast<mirror::Class*>(obj);
456 remote_class_map[descriptor] = reinterpret_cast<mirror::Class*>(remote_obj);
457 }
458
459 // Unconditionally store the class descriptor in case we need it later
460 class_to_descriptor_map[klass] = descriptor;
461 current += RoundUp(obj->SizeOf(), kObjectAlignment);
462 }
463 }
464
465 // Looking at only dirty pages, figure out how many of those bytes belong to dirty objects.
466 float true_dirtied_percent = dirty_object_bytes * 1.0f / (dirty_pages * kPageSize);
467 size_t false_dirty_pages = dirty_pages - different_pages;
468
469 os << "Mapping at [" << reinterpret_cast<void*>(boot_map.start) << ", "
470 << reinterpret_cast<void*>(boot_map.end) << ") had: \n "
471 << different_bytes << " differing bytes, \n "
472 << different_int32s << " differing int32s, \n "
473 << different_objects << " different objects, \n "
474 << dirty_object_bytes << " different object [bytes], \n "
475 << false_dirty_objects.size() << " false dirty objects,\n "
476 << false_dirty_object_bytes << " false dirty object [bytes], \n "
477 << true_dirtied_percent << " different objects-vs-total in a dirty page;\n "
478 << different_pages << " different pages; \n "
479 << dirty_pages << " pages are dirty; \n "
480 << false_dirty_pages << " pages are false dirty; \n "
481 << private_pages << " pages are private; \n "
482 << private_dirty_pages << " pages are Private_Dirty\n "
483 << "";
484
485 // vector of pairs (int count, Class*)
486 auto dirty_object_class_values = SortByValueDesc(dirty_object_class_map);
487 auto clean_object_class_values = SortByValueDesc(clean_object_class_map);
488
489 os << "\n" << " Dirty object count by class:\n";
490 for (const auto& vk_pair : dirty_object_class_values) {
491 int dirty_object_count = vk_pair.first;
492 mirror::Class* klass = vk_pair.second;
493 int object_sizes = dirty_object_size_in_bytes[klass];
494 float avg_dirty_bytes_per_class = dirty_object_byte_count[klass] * 1.0f / object_sizes;
495 float avg_object_size = object_sizes * 1.0f / dirty_object_count;
496 const std::string& descriptor = class_to_descriptor_map[klass];
497 os << " " << PrettyClass(klass) << " ("
498 << "objects: " << dirty_object_count << ", "
499 << "avg dirty bytes: " << avg_dirty_bytes_per_class << ", "
500 << "avg object size: " << avg_object_size << ", "
501 << "class descriptor: '" << descriptor << "'"
502 << ")\n";
503
504 constexpr size_t kMaxAddressPrint = 5;
505 if (strcmp(descriptor.c_str(), "Ljava/lang/reflect/ArtMethod;") == 0) {
506 os << " sample object addresses: ";
507 for (size_t i = 0; i < art_method_dirty_objects.size() && i < kMaxAddressPrint; ++i) {
508 auto art_method = art_method_dirty_objects[i];
509
510 os << reinterpret_cast<void*>(art_method) << ", ";
511 }
512 os << "\n";
513
514 os << " dirty byte +offset:count list = ";
515 auto art_method_field_dirty_count_sorted = SortByValueDesc(art_method_field_dirty_count);
516 for (auto pair : art_method_field_dirty_count_sorted) {
517 off_t offset = pair.second;
518 int count = pair.first;
519
520 os << "+" << offset << ":" << count << ", ";
521 }
522
523 os << "\n";
524
525 os << " field contents:\n";
526 const auto& dirty_objects_list = dirty_objects_by_class[klass];
527 for (mirror::Object* obj : dirty_objects_list) {
528 // remote method
529 auto art_method = reinterpret_cast<mirror::ArtMethod*>(obj);
530
531 // remote class
532 mirror::Class* remote_declaring_class =
533 FixUpRemotePointer(art_method->GetDeclaringClass(), remote_contents, boot_map);
534
535 // local class
536 mirror::Class* declaring_class =
537 RemoteContentsPointerToLocal(remote_declaring_class,
538 remote_contents,
539 boot_image_header);
540
541 os << " " << reinterpret_cast<void*>(obj) << " ";
542 os << " entryPointFromJni: "
543 << reinterpret_cast<const void*>(
544 art_method->GetEntryPointFromJniPtrSize(pointer_size)) << ", ";
545 os << " entryPointFromInterpreter: "
546 << reinterpret_cast<const void*>(
547 art_method->GetEntryPointFromInterpreterPtrSize<kVerifyNone>(pointer_size))
548 << ", ";
549 os << " entryPointFromQuickCompiledCode: "
550 << reinterpret_cast<const void*>(
551 art_method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size))
552 << ", ";
553 os << " isNative? " << (art_method->IsNative() ? "yes" : "no") << ", ";
554 os << " class_status (local): " << declaring_class->GetStatus();
555 os << " class_status (remote): " << remote_declaring_class->GetStatus();
556 os << "\n";
557 }
558 }
559 if (strcmp(descriptor.c_str(), "Ljava/lang/Class;") == 0) {
560 os << " sample object addresses: ";
561 for (size_t i = 0; i < class_dirty_objects.size() && i < kMaxAddressPrint; ++i) {
562 auto class_ptr = class_dirty_objects[i];
563
564 os << reinterpret_cast<void*>(class_ptr) << ", ";
565 }
566 os << "\n";
567
568 os << " dirty byte +offset:count list = ";
569 auto class_field_dirty_count_sorted = SortByValueDesc(class_field_dirty_count);
570 for (auto pair : class_field_dirty_count_sorted) {
571 off_t offset = pair.second;
572 int count = pair.first;
573
574 os << "+" << offset << ":" << count << ", ";
575 }
576 os << "\n";
577
578 os << " field contents:\n";
579 const auto& dirty_objects_list = dirty_objects_by_class[klass];
580 for (mirror::Object* obj : dirty_objects_list) {
581 // remote class object
582 auto remote_klass = reinterpret_cast<mirror::Class*>(obj);
583
584 // local class object
585 auto local_klass = RemoteContentsPointerToLocal(remote_klass,
586 remote_contents,
587 boot_image_header);
588
589 os << " " << reinterpret_cast<void*>(obj) << " ";
590 os << " class_status (remote): " << remote_klass->GetStatus() << ", ";
591 os << " class_status (local): " << local_klass->GetStatus();
592 os << "\n";
593 }
594 }
595 }
596
597 auto false_dirty_object_class_values = SortByValueDesc(false_dirty_object_count);
598
599 os << "\n" << " False-dirty object count by class:\n";
600 for (const auto& vk_pair : false_dirty_object_class_values) {
601 int object_count = vk_pair.first;
602 mirror::Class* klass = vk_pair.second;
603 int object_sizes = false_dirty_byte_count[klass];
604 float avg_object_size = object_sizes * 1.0f / object_count;
605 const std::string& descriptor = class_to_descriptor_map[klass];
606 os << " " << PrettyClass(klass) << " ("
607 << "objects: " << object_count << ", "
608 << "avg object size: " << avg_object_size << ", "
609 << "total bytes: " << object_sizes << ", "
610 << "class descriptor: '" << descriptor << "'"
611 << ")\n";
612
613 if (strcmp(descriptor.c_str(), "Ljava/lang/reflect/ArtMethod;") == 0) {
614 auto& art_method_false_dirty_objects = false_dirty_objects_map[klass];
615
616 os << " field contents:\n";
617 for (mirror::Object* obj : art_method_false_dirty_objects) {
618 // local method
619 auto art_method = reinterpret_cast<mirror::ArtMethod*>(obj);
620
621 // local class
622 mirror::Class* declaring_class = art_method->GetDeclaringClass();
623
624 os << " " << reinterpret_cast<void*>(obj) << " ";
625 os << " entryPointFromJni: "
626 << reinterpret_cast<const void*>(
627 art_method->GetEntryPointFromJniPtrSize(pointer_size)) << ", ";
628 os << " entryPointFromInterpreter: "
629 << reinterpret_cast<const void*>(
630 art_method->GetEntryPointFromInterpreterPtrSize<kVerifyNone>(pointer_size))
631 << ", ";
632 os << " entryPointFromQuickCompiledCode: "
633 << reinterpret_cast<const void*>(
634 art_method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size))
635 << ", ";
636 os << " isNative? " << (art_method->IsNative() ? "yes" : "no") << ", ";
637 os << " class_status (local): " << declaring_class->GetStatus();
638 os << "\n";
639 }
640 }
641 }
642
643 os << "\n" << " Clean object count by class:\n";
644 for (const auto& vk_pair : clean_object_class_values) {
645 os << " " << PrettyClass(vk_pair.second) << " (" << vk_pair.first << ")\n";
646 }
647
648 return true;
649 }
650
651 // Fixup a remote pointer that we read from a foreign boot.art to point to our own memory.
652 // Returned pointer will point to inside of remote_contents.
653 template <typename T>
654 static T* FixUpRemotePointer(T* remote_ptr,
655 std::vector<uint8_t>& remote_contents,
656 const backtrace_map_t& boot_map) {
657 if (remote_ptr == nullptr) {
658 return nullptr;
659 }
660
661 uintptr_t remote = reinterpret_cast<uintptr_t>(remote_ptr);
662
663 CHECK_LE(boot_map.start, remote);
664 CHECK_GT(boot_map.end, remote);
665
666 off_t boot_offset = remote - boot_map.start;
667
668 return reinterpret_cast<T*>(&remote_contents[boot_offset]);
669 }
670
671 template <typename T>
672 static T* RemoteContentsPointerToLocal(T* remote_ptr,
673 std::vector<uint8_t>& remote_contents,
674 const ImageHeader& image_header) {
675 if (remote_ptr == nullptr) {
676 return nullptr;
677 }
678
679 uint8_t* remote = reinterpret_cast<uint8_t*>(remote_ptr);
680 ptrdiff_t boot_offset = remote - &remote_contents[0];
681
682 const uint8_t* local_ptr = reinterpret_cast<const uint8_t*>(&image_header) + boot_offset;
683
684 return reinterpret_cast<T*>(const_cast<uint8_t*>(local_ptr));
685 }
686
687 static std::string GetClassDescriptor(mirror::Class* klass)
688 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
689 CHECK(klass != nullptr);
690
691 std::string descriptor;
692 const char* descriptor_str = klass->GetDescriptor(&descriptor);
693
694 return std::string(descriptor_str);
695 }
696
697 template <typename K, typename V>
698 static std::vector<std::pair<V, K>> SortByValueDesc(const std::map<K, V> map) {
699 // Store value->key so that we can use the default sort from pair which
700 // sorts by value first and then key
701 std::vector<std::pair<V, K>> value_key_vector;
702
703 for (const auto& kv_pair : map) {
704 value_key_vector.push_back(std::make_pair(kv_pair.second, kv_pair.first));
705 }
706
707 // Sort in reverse (descending order)
708 std::sort(value_key_vector.rbegin(), value_key_vector.rend());
709 return value_key_vector;
710 }
711
712 static bool GetPageFrameNumber(File* page_map_file,
713 size_t virtual_page_index,
714 uint64_t* page_frame_number,
715 std::string* error_msg) {
716 CHECK(page_map_file != nullptr);
717 CHECK(page_frame_number != nullptr);
718 CHECK(error_msg != nullptr);
719
720 constexpr size_t kPageMapEntrySize = sizeof(uint64_t);
721 constexpr uint64_t kPageFrameNumberMask = (1ULL << 55) - 1; // bits 0-54 [in /proc/$pid/pagemap]
722 constexpr uint64_t kPageSoftDirtyMask = (1ULL << 55); // bit 55 [in /proc/$pid/pagemap]
723
724 uint64_t page_map_entry = 0;
725
726 // Read 64-bit entry from /proc/$pid/pagemap to get the physical page frame number
727 if (!page_map_file->PreadFully(&page_map_entry, kPageMapEntrySize,
728 virtual_page_index * kPageMapEntrySize)) {
729 *error_msg = StringPrintf("Failed to read the virtual page index entry from %s",
730 page_map_file->GetPath().c_str());
731 return false;
732 }
733
734 // TODO: seems useless, remove this.
735 bool soft_dirty = (page_map_entry & kPageSoftDirtyMask) != 0;
736 if ((false)) {
737 LOG(VERBOSE) << soft_dirty; // Suppress unused warning
738 UNREACHABLE();
739 }
740
741 *page_frame_number = page_map_entry & kPageFrameNumberMask;
742
743 return true;
744 }
745
746 static int IsPageDirty(File* page_map_file,
747 File* clean_page_map_file,
748 File* kpage_flags_file,
749 File* kpage_count_file,
750 size_t virtual_page_idx,
751 size_t clean_virtual_page_idx,
752 // Out parameters:
753 uint64_t* page_count, std::string* error_msg) {
754 CHECK(page_map_file != nullptr);
755 CHECK(clean_page_map_file != nullptr);
756 CHECK_NE(page_map_file, clean_page_map_file);
757 CHECK(kpage_flags_file != nullptr);
758 CHECK(kpage_count_file != nullptr);
759 CHECK(page_count != nullptr);
760 CHECK(error_msg != nullptr);
761
762 // Constants are from https://www.kernel.org/doc/Documentation/vm/pagemap.txt
763
764 constexpr size_t kPageFlagsEntrySize = sizeof(uint64_t);
765 constexpr size_t kPageCountEntrySize = sizeof(uint64_t);
766 constexpr uint64_t kPageFlagsDirtyMask = (1ULL << 4); // in /proc/kpageflags
767 constexpr uint64_t kPageFlagsNoPageMask = (1ULL << 20); // in /proc/kpageflags
768 constexpr uint64_t kPageFlagsMmapMask = (1ULL << 11); // in /proc/kpageflags
769
770 uint64_t page_frame_number = 0;
771 if (!GetPageFrameNumber(page_map_file, virtual_page_idx, &page_frame_number, error_msg)) {
772 return -1;
773 }
774
775 uint64_t page_frame_number_clean = 0;
776 if (!GetPageFrameNumber(clean_page_map_file, clean_virtual_page_idx, &page_frame_number_clean,
777 error_msg)) {
778 return -1;
779 }
780
781 // Read 64-bit entry from /proc/kpageflags to get the dirty bit for a page
782 uint64_t kpage_flags_entry = 0;
783 if (!kpage_flags_file->PreadFully(&kpage_flags_entry,
784 kPageFlagsEntrySize,
785 page_frame_number * kPageFlagsEntrySize)) {
786 *error_msg = StringPrintf("Failed to read the page flags from %s",
787 kpage_flags_file->GetPath().c_str());
788 return -1;
789 }
790
791 // Read 64-bit entyry from /proc/kpagecount to get mapping counts for a page
792 if (!kpage_count_file->PreadFully(page_count /*out*/,
793 kPageCountEntrySize,
794 page_frame_number * kPageCountEntrySize)) {
795 *error_msg = StringPrintf("Failed to read the page count from %s",
796 kpage_count_file->GetPath().c_str());
797 return -1;
798 }
799
800 // There must be a page frame at the requested address.
801 CHECK_EQ(kpage_flags_entry & kPageFlagsNoPageMask, 0u);
802 // The page frame must be memory mapped
803 CHECK_NE(kpage_flags_entry & kPageFlagsMmapMask, 0u);
804
805 // Page is dirty, i.e. has diverged from file, if the 4th bit is set to 1
806 bool flags_dirty = (kpage_flags_entry & kPageFlagsDirtyMask) != 0;
807
808 // page_frame_number_clean must come from the *same* process
809 // but a *different* mmap than page_frame_number
810 if (flags_dirty) {
811 CHECK_NE(page_frame_number, page_frame_number_clean);
812 }
813
814 return page_frame_number != page_frame_number_clean;
815 }
816
817 static const ImageHeader& GetBootImageHeader() {
818 gc::Heap* heap = Runtime::Current()->GetHeap();
819 gc::space::ImageSpace* image_space = heap->GetImageSpace();
820 CHECK(image_space != nullptr);
821 const ImageHeader& image_header = image_space->GetImageHeader();
822 return image_header;
823 }
824
825 private:
826 // Return the image location, stripped of any directories, e.g. "boot.art" or "core.art"
827 std::string GetImageLocationBaseName() const {
828 return BaseName(std::string(image_location_));
829 }
830
831 std::ostream* os_;
832 const ImageHeader& image_header_;
833 const char* image_location_;
834 pid_t image_diff_pid_; // Dump image diff against boot.art if pid is non-negative
835
836 DISALLOW_COPY_AND_ASSIGN(ImgDiagDumper);
837};
838
839static int DumpImage(Runtime* runtime, const char* image_location,
840 std::ostream* os, pid_t image_diff_pid) {
841 ScopedObjectAccess soa(Thread::Current());
842 gc::Heap* heap = runtime->GetHeap();
843 gc::space::ImageSpace* image_space = heap->GetImageSpace();
844 CHECK(image_space != nullptr);
845 const ImageHeader& image_header = image_space->GetImageHeader();
846 if (!image_header.IsValid()) {
847 fprintf(stderr, "Invalid image header %s\n", image_location);
848 return EXIT_FAILURE;
849 }
850
851 ImgDiagDumper img_diag_dumper(os, image_header, image_location, image_diff_pid);
852
853 bool success = img_diag_dumper.Dump();
854 return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
855}
856
857struct ImgDiagArgs : public CmdlineArgs {
858 protected:
859 using Base = CmdlineArgs;
860
861 virtual ParseStatus ParseCustom(const StringPiece& option,
862 std::string* error_msg) OVERRIDE {
863 {
864 ParseStatus base_parse = Base::ParseCustom(option, error_msg);
865 if (base_parse != kParseUnknownArgument) {
866 return base_parse;
867 }
868 }
869
870 if (option.starts_with("--image-diff-pid=")) {
871 const char* image_diff_pid = option.substr(strlen("--image-diff-pid=")).data();
872
873 if (!ParseInt(image_diff_pid, &image_diff_pid_)) {
874 *error_msg = "Image diff pid out of range";
875 return kParseError;
876 }
877 } else {
878 return kParseUnknownArgument;
879 }
880
881 return kParseOk;
882 }
883
884 virtual ParseStatus ParseChecks(std::string* error_msg) OVERRIDE {
885 // Perform the parent checks.
886 ParseStatus parent_checks = Base::ParseChecks(error_msg);
887 if (parent_checks != kParseOk) {
888 return parent_checks;
889 }
890
891 // Perform our own checks.
892
893 if (kill(image_diff_pid_,
894 /*sig*/0) != 0) { // No signal is sent, perform error-checking only.
895 // Check if the pid exists before proceeding.
896 if (errno == ESRCH) {
897 *error_msg = "Process specified does not exist";
898 } else {
899 *error_msg = StringPrintf("Failed to check process status: %s", strerror(errno));
900 }
901 return kParseError;
902 } else if (instruction_set_ != kRuntimeISA) {
903 // Don't allow different ISAs since the images are ISA-specific.
904 // Right now the code assumes both the runtime ISA and the remote ISA are identical.
905 *error_msg = "Must use the default runtime ISA; changing ISA is not supported.";
906 return kParseError;
907 }
908
909 return kParseOk;
910 }
911
912 virtual std::string GetUsage() const {
913 std::string usage;
914
915 usage +=
916 "Usage: imgdiag [options] ...\n"
917 " Example: imgdiag --image-diff-pid=$(pidof dex2oat)\n"
918 " Example: adb shell imgdiag --image-diff-pid=$(pid zygote)\n"
919 "\n";
920
921 usage += Base::GetUsage();
922
923 usage += // Optional.
924 " --image-diff-pid=<pid>: provide the PID of a process whose boot.art you want to diff.\n"
925 " Example: --image-diff-pid=$(pid zygote)\n"
926 "\n";
927
928 return usage;
929 }
930
931 public:
932 pid_t image_diff_pid_ = -1;
933};
934
935struct ImgDiagMain : public CmdlineMain<ImgDiagArgs> {
936 virtual bool ExecuteWithRuntime(Runtime* runtime) {
937 CHECK(args_ != nullptr);
938
939 return DumpImage(runtime,
940 args_->boot_image_location_,
941 args_->os_,
942 args_->image_diff_pid_) == EXIT_SUCCESS;
943 }
944};
945
946} // namespace art
947
948int main(int argc, char** argv) {
949 art::ImgDiagMain main;
950 return main.Main(argc, argv);
951}