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