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