blob: f307cbc4f5f7d5927e9acf64d0a6e1d0b33b88ee [file] [log] [blame]
Igor Murashkin37743352014-11-13 14:38:00 -08001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <stdio.h>
18#include <stdlib.h>
19
20#include <fstream>
Andreas Gampe7ad71d02016-04-04 13:49:18 -070021#include <functional>
Igor Murashkin37743352014-11-13 14:38:00 -080022#include <iostream>
23#include <string>
24#include <vector>
25#include <set>
26#include <map>
Mathieu Chartiercb044bc2016-04-01 13:56:41 -070027#include <unordered_set>
Igor Murashkin37743352014-11-13 14:38:00 -080028
Andreas Gampe46ee31b2016-12-14 10:11:49 -080029#include "android-base/stringprintf.h"
30
Mathieu Chartiere401d142015-04-22 13:56:20 -070031#include "art_method-inl.h"
Igor Murashkin37743352014-11-13 14:38:00 -080032#include "base/unix_file/fd_file.h"
Igor Murashkin37743352014-11-13 14:38:00 -080033#include "gc/space/image_space.h"
34#include "gc/heap.h"
35#include "mirror/class-inl.h"
36#include "mirror/object-inl.h"
Igor Murashkin37743352014-11-13 14:38:00 -080037#include "image.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070038#include "scoped_thread_state_change-inl.h"
Igor Murashkin37743352014-11-13 14:38:00 -080039#include "os.h"
Igor Murashkin37743352014-11-13 14:38:00 -080040
41#include "cmdline.h"
42#include "backtrace/BacktraceMap.h"
43
44#include <sys/stat.h>
45#include <sys/types.h>
46#include <signal.h>
47
48namespace art {
49
Andreas Gampe46ee31b2016-12-14 10:11:49 -080050using android::base::StringPrintf;
51
Igor Murashkin37743352014-11-13 14:38:00 -080052class ImgDiagDumper {
53 public:
54 explicit ImgDiagDumper(std::ostream* os,
Mathieu Chartiercb044bc2016-04-01 13:56:41 -070055 const ImageHeader& image_header,
56 const std::string& image_location,
Mathieu Chartierc5196cd2016-04-08 14:08:37 -070057 pid_t image_diff_pid,
58 pid_t zygote_diff_pid)
Igor Murashkin37743352014-11-13 14:38:00 -080059 : os_(os),
60 image_header_(image_header),
61 image_location_(image_location),
Mathieu Chartierc5196cd2016-04-08 14:08:37 -070062 image_diff_pid_(image_diff_pid),
63 zygote_diff_pid_(zygote_diff_pid) {}
Igor Murashkin37743352014-11-13 14:38:00 -080064
Andreas Gampebdf7f1c2016-08-30 16:38:47 -070065 bool Dump() REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin37743352014-11-13 14:38:00 -080066 std::ostream& os = *os_;
Mathieu Chartiercb044bc2016-04-01 13:56:41 -070067 os << "IMAGE LOCATION: " << image_location_ << "\n\n";
68
Igor Murashkin37743352014-11-13 14:38:00 -080069 os << "MAGIC: " << image_header_.GetMagic() << "\n\n";
70
71 os << "IMAGE BEGIN: " << reinterpret_cast<void*>(image_header_.GetImageBegin()) << "\n\n";
72
73 bool ret = true;
74 if (image_diff_pid_ >= 0) {
75 os << "IMAGE DIFF PID (" << image_diff_pid_ << "): ";
Mathieu Chartierc5196cd2016-04-08 14:08:37 -070076 ret = DumpImageDiff(image_diff_pid_, zygote_diff_pid_);
Igor Murashkin37743352014-11-13 14:38:00 -080077 os << "\n\n";
78 } else {
79 os << "IMAGE DIFF PID: disabled\n\n";
80 }
81
82 os << std::flush;
83
84 return ret;
85 }
86
87 private:
88 static bool EndsWith(const std::string& str, const std::string& suffix) {
89 return str.size() >= suffix.size() &&
90 str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
91 }
92
93 // Return suffix of the file path after the last /. (e.g. /foo/bar -> bar, bar -> bar)
94 static std::string BaseName(const std::string& str) {
Andreas Gampeca620d72016-11-08 08:09:33 -080095 size_t idx = str.rfind('/');
Igor Murashkin37743352014-11-13 14:38:00 -080096 if (idx == std::string::npos) {
97 return str;
98 }
99
100 return str.substr(idx + 1);
101 }
102
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700103 bool DumpImageDiff(pid_t image_diff_pid, pid_t zygote_diff_pid)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700104 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin37743352014-11-13 14:38:00 -0800105 std::ostream& os = *os_;
106
107 {
108 struct stat sts;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700109 std::string proc_pid_str =
110 StringPrintf("/proc/%ld", static_cast<long>(image_diff_pid)); // NOLINT [runtime/int]
Igor Murashkin37743352014-11-13 14:38:00 -0800111 if (stat(proc_pid_str.c_str(), &sts) == -1) {
112 os << "Process does not exist";
113 return false;
114 }
115 }
116
117 // Open /proc/$pid/maps to view memory maps
118 auto proc_maps = std::unique_ptr<BacktraceMap>(BacktraceMap::Create(image_diff_pid));
119 if (proc_maps == nullptr) {
120 os << "Could not read backtrace maps";
121 return false;
122 }
123
124 bool found_boot_map = false;
125 backtrace_map_t boot_map = backtrace_map_t();
126 // Find the memory map only for boot.art
127 for (const backtrace_map_t& map : *proc_maps) {
128 if (EndsWith(map.name, GetImageLocationBaseName())) {
129 if ((map.flags & PROT_WRITE) != 0) {
130 boot_map = map;
131 found_boot_map = true;
132 break;
133 }
134 // In actuality there's more than 1 map, but the second one is read-only.
135 // The one we care about is the write-able map.
136 // The readonly maps are guaranteed to be identical, so its not interesting to compare
137 // them.
138 }
139 }
140
141 if (!found_boot_map) {
142 os << "Could not find map for " << GetImageLocationBaseName();
143 return false;
144 }
145
146 // Future idea: diff against zygote so we can ignore the shared dirty pages.
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700147 return DumpImageDiffMap(image_diff_pid, zygote_diff_pid, boot_map);
Igor Murashkin37743352014-11-13 14:38:00 -0800148 }
149
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700150 static std::string PrettyFieldValue(ArtField* field, mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700151 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700152 std::ostringstream oss;
153 switch (field->GetTypeAsPrimitiveType()) {
154 case Primitive::kPrimNot: {
155 oss << obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
156 field->GetOffset());
157 break;
158 }
159 case Primitive::kPrimBoolean: {
160 oss << static_cast<bool>(obj->GetFieldBoolean<kVerifyNone>(field->GetOffset()));
161 break;
162 }
163 case Primitive::kPrimByte: {
164 oss << static_cast<int32_t>(obj->GetFieldByte<kVerifyNone>(field->GetOffset()));
165 break;
166 }
167 case Primitive::kPrimChar: {
168 oss << obj->GetFieldChar<kVerifyNone>(field->GetOffset());
169 break;
170 }
171 case Primitive::kPrimShort: {
172 oss << obj->GetFieldShort<kVerifyNone>(field->GetOffset());
173 break;
174 }
175 case Primitive::kPrimInt: {
176 oss << obj->GetField32<kVerifyNone>(field->GetOffset());
177 break;
178 }
179 case Primitive::kPrimLong: {
180 oss << obj->GetField64<kVerifyNone>(field->GetOffset());
181 break;
182 }
183 case Primitive::kPrimFloat: {
184 oss << obj->GetField32<kVerifyNone>(field->GetOffset());
185 break;
186 }
187 case Primitive::kPrimDouble: {
188 oss << obj->GetField64<kVerifyNone>(field->GetOffset());
189 break;
190 }
191 case Primitive::kPrimVoid: {
192 oss << "void";
193 break;
194 }
195 }
196 return oss.str();
197 }
198
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700199 // Aggregate and detail class data from an image diff.
200 struct ClassData {
201 int dirty_object_count = 0;
202
203 // Track only the byte-per-byte dirtiness (in bytes)
204 int dirty_object_byte_count = 0;
205
206 // Track the object-by-object dirtiness (in bytes)
207 int dirty_object_size_in_bytes = 0;
208
209 int clean_object_count = 0;
210
211 std::string descriptor;
212
213 int false_dirty_byte_count = 0;
214 int false_dirty_object_count = 0;
215 std::vector<mirror::Object*> false_dirty_objects;
216
217 // Remote pointers to dirty objects
218 std::vector<mirror::Object*> dirty_objects;
219 };
220
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700221 void DiffObjectContents(mirror::Object* obj,
222 uint8_t* remote_bytes,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700223 std::ostream& os) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700224 const char* tabs = " ";
225 // Attempt to find fields for all dirty bytes.
226 mirror::Class* klass = obj->GetClass();
227 if (obj->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700228 os << tabs << "Class " << mirror::Class::PrettyClass(obj->AsClass()) << " " << obj << "\n";
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700229 } else {
David Sehr709b0702016-10-13 09:12:37 -0700230 os << tabs << "Instance of " << mirror::Class::PrettyClass(klass) << " " << obj << "\n";
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700231 }
232
233 std::unordered_set<ArtField*> dirty_instance_fields;
234 std::unordered_set<ArtField*> dirty_static_fields;
235 const uint8_t* obj_bytes = reinterpret_cast<const uint8_t*>(obj);
236 mirror::Object* remote_obj = reinterpret_cast<mirror::Object*>(remote_bytes);
237 for (size_t i = 0, count = obj->SizeOf(); i < count; ++i) {
238 if (obj_bytes[i] != remote_bytes[i]) {
239 ArtField* field = ArtField::FindInstanceFieldWithOffset</*exact*/false>(klass, i);
240 if (field != nullptr) {
241 dirty_instance_fields.insert(field);
242 } else if (obj->IsClass()) {
243 field = ArtField::FindStaticFieldWithOffset</*exact*/false>(obj->AsClass(), i);
244 if (field != nullptr) {
245 dirty_static_fields.insert(field);
246 }
247 }
248 if (field == nullptr) {
249 if (klass->IsArrayClass()) {
250 mirror::Class* component_type = klass->GetComponentType();
251 Primitive::Type primitive_type = component_type->GetPrimitiveType();
252 size_t component_size = Primitive::ComponentSize(primitive_type);
253 size_t data_offset = mirror::Array::DataOffset(component_size).Uint32Value();
254 if (i >= data_offset) {
255 os << tabs << "Dirty array element " << (i - data_offset) / component_size << "\n";
256 // Skip to next element to prevent spam.
257 i += component_size - 1;
258 continue;
259 }
260 }
261 os << tabs << "No field for byte offset " << i << "\n";
262 }
263 }
264 }
265 // Dump different fields. TODO: Dump field contents.
266 if (!dirty_instance_fields.empty()) {
267 os << tabs << "Dirty instance fields " << dirty_instance_fields.size() << "\n";
268 for (ArtField* field : dirty_instance_fields) {
David Sehr709b0702016-10-13 09:12:37 -0700269 os << tabs << ArtField::PrettyField(field)
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700270 << " original=" << PrettyFieldValue(field, obj)
271 << " remote=" << PrettyFieldValue(field, remote_obj) << "\n";
272 }
273 }
274 if (!dirty_static_fields.empty()) {
275 os << tabs << "Dirty static fields " << dirty_static_fields.size() << "\n";
276 for (ArtField* field : dirty_static_fields) {
David Sehr709b0702016-10-13 09:12:37 -0700277 os << tabs << ArtField::PrettyField(field)
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700278 << " original=" << PrettyFieldValue(field, obj)
279 << " remote=" << PrettyFieldValue(field, remote_obj) << "\n";
280 }
281 }
282 os << "\n";
283 }
284
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700285 // Look at /proc/$pid/mem and only diff the things from there
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700286 bool DumpImageDiffMap(pid_t image_diff_pid,
287 pid_t zygote_diff_pid,
288 const backtrace_map_t& boot_map)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700289 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin37743352014-11-13 14:38:00 -0800290 std::ostream& os = *os_;
Andreas Gampe542451c2016-07-26 09:02:02 -0700291 const PointerSize pointer_size = InstructionSetPointerSize(
Igor Murashkin37743352014-11-13 14:38:00 -0800292 Runtime::Current()->GetInstructionSet());
293
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700294 std::string file_name =
295 StringPrintf("/proc/%ld/mem", static_cast<long>(image_diff_pid)); // NOLINT [runtime/int]
Igor Murashkin37743352014-11-13 14:38:00 -0800296
297 size_t boot_map_size = boot_map.end - boot_map.start;
298
299 // Open /proc/$pid/mem as a file
300 auto map_file = std::unique_ptr<File>(OS::OpenFileForReading(file_name.c_str()));
301 if (map_file == nullptr) {
302 os << "Failed to open " << file_name << " for reading";
303 return false;
304 }
305
306 // Memory-map /proc/$pid/mem subset from the boot map
307 CHECK(boot_map.end >= boot_map.start);
308
309 std::string error_msg;
310
311 // Walk the bytes and diff against our boot image
Andreas Gampe8994a042015-12-30 19:03:17 +0000312 const ImageHeader& boot_image_header = image_header_;
Igor Murashkin37743352014-11-13 14:38:00 -0800313
314 os << "\nObserving boot image header at address "
315 << reinterpret_cast<const void*>(&boot_image_header)
316 << "\n\n";
317
318 const uint8_t* image_begin_unaligned = boot_image_header.GetImageBegin();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700319 const uint8_t* image_mirror_end_unaligned = image_begin_unaligned +
Mathieu Chartiere401d142015-04-22 13:56:20 -0700320 boot_image_header.GetImageSection(ImageHeader::kSectionObjects).Size();
321 const uint8_t* image_end_unaligned = image_begin_unaligned + boot_image_header.GetImageSize();
Igor Murashkin37743352014-11-13 14:38:00 -0800322
323 // Adjust range to nearest page
324 const uint8_t* image_begin = AlignDown(image_begin_unaligned, kPageSize);
325 const uint8_t* image_end = AlignUp(image_end_unaligned, kPageSize);
326
327 ptrdiff_t page_off_begin = boot_image_header.GetImageBegin() - image_begin;
328
329 if (reinterpret_cast<uintptr_t>(image_begin) > boot_map.start ||
330 reinterpret_cast<uintptr_t>(image_end) < boot_map.end) {
331 // Sanity check that we aren't trying to read a completely different boot image
332 os << "Remote boot map is out of range of local boot map: " <<
333 "local begin " << reinterpret_cast<const void*>(image_begin) <<
334 ", local end " << reinterpret_cast<const void*>(image_end) <<
335 ", remote begin " << reinterpret_cast<const void*>(boot_map.start) <<
336 ", remote end " << reinterpret_cast<const void*>(boot_map.end);
337 return false;
338 // If we wanted even more validation we could map the ImageHeader from the file
339 }
340
341 std::vector<uint8_t> remote_contents(boot_map_size);
342 if (!map_file->PreadFully(&remote_contents[0], boot_map_size, boot_map.start)) {
343 os << "Could not fully read file " << file_name;
344 return false;
345 }
346
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700347 std::vector<uint8_t> zygote_contents;
348 std::unique_ptr<File> zygote_map_file;
349 if (zygote_diff_pid != -1) {
350 std::string zygote_file_name =
351 StringPrintf("/proc/%ld/mem", static_cast<long>(zygote_diff_pid)); // NOLINT [runtime/int]
352 zygote_map_file.reset(OS::OpenFileForReading(zygote_file_name.c_str()));
353 // The boot map should be at the same address.
354 zygote_contents.resize(boot_map_size);
355 if (!zygote_map_file->PreadFully(&zygote_contents[0], boot_map_size, boot_map.start)) {
356 LOG(WARNING) << "Could not fully read zygote file " << zygote_file_name;
357 zygote_contents.clear();
358 }
359 }
360
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700361 std::string page_map_file_name = StringPrintf(
362 "/proc/%ld/pagemap", static_cast<long>(image_diff_pid)); // NOLINT [runtime/int]
Igor Murashkin37743352014-11-13 14:38:00 -0800363 auto page_map_file = std::unique_ptr<File>(OS::OpenFileForReading(page_map_file_name.c_str()));
364 if (page_map_file == nullptr) {
365 os << "Failed to open " << page_map_file_name << " for reading: " << strerror(errno);
366 return false;
367 }
368
369 // Not truly clean, mmap-ing boot.art again would be more pristine, but close enough
370 const char* clean_page_map_file_name = "/proc/self/pagemap";
371 auto clean_page_map_file = std::unique_ptr<File>(
372 OS::OpenFileForReading(clean_page_map_file_name));
373 if (clean_page_map_file == nullptr) {
374 os << "Failed to open " << clean_page_map_file_name << " for reading: " << strerror(errno);
375 return false;
376 }
377
378 auto kpage_flags_file = std::unique_ptr<File>(OS::OpenFileForReading("/proc/kpageflags"));
379 if (kpage_flags_file == nullptr) {
380 os << "Failed to open /proc/kpageflags for reading: " << strerror(errno);
381 return false;
382 }
383
384 auto kpage_count_file = std::unique_ptr<File>(OS::OpenFileForReading("/proc/kpagecount"));
385 if (kpage_count_file == nullptr) {
386 os << "Failed to open /proc/kpagecount for reading:" << strerror(errno);
387 return false;
388 }
389
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700390 // Set of the remote virtual page indices that are dirty
391 std::set<size_t> dirty_page_set_remote;
392 // Set of the local virtual page indices that are dirty
393 std::set<size_t> dirty_page_set_local;
Igor Murashkin37743352014-11-13 14:38:00 -0800394
395 size_t different_int32s = 0;
396 size_t different_bytes = 0;
397 size_t different_pages = 0;
398 size_t virtual_page_idx = 0; // Virtual page number (for an absolute memory address)
399 size_t page_idx = 0; // Page index relative to 0
400 size_t previous_page_idx = 0; // Previous page index relative to 0
401 size_t dirty_pages = 0;
402 size_t private_pages = 0;
403 size_t private_dirty_pages = 0;
404
405 // Iterate through one page at a time. Boot map begin/end already implicitly aligned.
406 for (uintptr_t begin = boot_map.start; begin != boot_map.end; begin += kPageSize) {
407 ptrdiff_t offset = begin - boot_map.start;
408
409 // We treat the image header as part of the memory map for now
410 // If we wanted to change this, we could pass base=start+sizeof(ImageHeader)
411 // But it might still be interesting to see if any of the ImageHeader data mutated
412 const uint8_t* local_ptr = reinterpret_cast<const uint8_t*>(&boot_image_header) + offset;
413 uint8_t* remote_ptr = &remote_contents[offset];
414
415 if (memcmp(local_ptr, remote_ptr, kPageSize) != 0) {
416 different_pages++;
417
418 // Count the number of 32-bit integers that are different.
419 for (size_t i = 0; i < kPageSize / sizeof(uint32_t); ++i) {
420 uint32_t* remote_ptr_int32 = reinterpret_cast<uint32_t*>(remote_ptr);
421 const uint32_t* local_ptr_int32 = reinterpret_cast<const uint32_t*>(local_ptr);
422
423 if (remote_ptr_int32[i] != local_ptr_int32[i]) {
424 different_int32s++;
425 }
426 }
427 }
428 }
429
430 // Iterate through one byte at a time.
431 for (uintptr_t begin = boot_map.start; begin != boot_map.end; ++begin) {
432 previous_page_idx = page_idx;
433 ptrdiff_t offset = begin - boot_map.start;
434
435 // We treat the image header as part of the memory map for now
436 // If we wanted to change this, we could pass base=start+sizeof(ImageHeader)
437 // But it might still be interesting to see if any of the ImageHeader data mutated
438 const uint8_t* local_ptr = reinterpret_cast<const uint8_t*>(&boot_image_header) + offset;
439 uint8_t* remote_ptr = &remote_contents[offset];
440
441 virtual_page_idx = reinterpret_cast<uintptr_t>(local_ptr) / kPageSize;
442
443 // Calculate the page index, relative to the 0th page where the image begins
444 page_idx = (offset + page_off_begin) / kPageSize;
445 if (*local_ptr != *remote_ptr) {
446 // Track number of bytes that are different
447 different_bytes++;
448 }
449
450 // Independently count the # of dirty pages on the remote side
451 size_t remote_virtual_page_idx = begin / kPageSize;
452 if (previous_page_idx != page_idx) {
453 uint64_t page_count = 0xC0FFEE;
454 // TODO: virtual_page_idx needs to be from the same process
455 int dirtiness = (IsPageDirty(page_map_file.get(), // Image-diff-pid procmap
456 clean_page_map_file.get(), // Self procmap
457 kpage_flags_file.get(),
458 kpage_count_file.get(),
459 remote_virtual_page_idx, // potentially "dirty" page
460 virtual_page_idx, // true "clean" page
461 &page_count,
462 &error_msg));
463 if (dirtiness < 0) {
464 os << error_msg;
465 return false;
466 } else if (dirtiness > 0) {
467 dirty_pages++;
468 dirty_page_set_remote.insert(dirty_page_set_remote.end(), remote_virtual_page_idx);
469 dirty_page_set_local.insert(dirty_page_set_local.end(), virtual_page_idx);
470 }
471
472 bool is_dirty = dirtiness > 0;
473 bool is_private = page_count == 1;
474
475 if (page_count == 1) {
476 private_pages++;
477 }
478
479 if (is_dirty && is_private) {
480 private_dirty_pages++;
481 }
482 }
483 }
484
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700485 std::map<mirror::Class*, ClassData> class_data;
486
Igor Murashkin37743352014-11-13 14:38:00 -0800487 // Walk each object in the remote image space and compare it against ours
488 size_t different_objects = 0;
Igor Murashkin37743352014-11-13 14:38:00 -0800489
490 std::map<off_t /* field offset */, int /* count */> art_method_field_dirty_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700491 std::vector<ArtMethod*> art_method_dirty_objects;
Igor Murashkin37743352014-11-13 14:38:00 -0800492
493 std::map<off_t /* field offset */, int /* count */> class_field_dirty_count;
494 std::vector<mirror::Class*> class_dirty_objects;
495
496 // List of local objects that are clean, but located on dirty pages.
497 std::vector<mirror::Object*> false_dirty_objects;
Igor Murashkin37743352014-11-13 14:38:00 -0800498 size_t false_dirty_object_bytes = 0;
499
Igor Murashkin37743352014-11-13 14:38:00 -0800500 // Look up remote classes by their descriptor
501 std::map<std::string, mirror::Class*> remote_class_map;
502 // Look up local classes by their descriptor
503 std::map<std::string, mirror::Class*> local_class_map;
504
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700505 // Objects that are dirty against the image (possibly shared or private dirty).
506 std::set<mirror::Object*> image_dirty_objects;
507
508 // Objects that are dirty against the zygote (probably private dirty).
509 std::set<mirror::Object*> zygote_dirty_objects;
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700510
Igor Murashkin37743352014-11-13 14:38:00 -0800511 size_t dirty_object_bytes = 0;
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700512 const uint8_t* begin_image_ptr = image_begin_unaligned;
513 const uint8_t* end_image_ptr = image_mirror_end_unaligned;
Igor Murashkin37743352014-11-13 14:38:00 -0800514
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700515 const uint8_t* current = begin_image_ptr + RoundUp(sizeof(ImageHeader), kObjectAlignment);
516 while (reinterpret_cast<uintptr_t>(current) < reinterpret_cast<uintptr_t>(end_image_ptr)) {
517 CHECK_ALIGNED(current, kObjectAlignment);
518 mirror::Object* obj = reinterpret_cast<mirror::Object*>(const_cast<uint8_t*>(current));
Igor Murashkin37743352014-11-13 14:38:00 -0800519
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700520 // Sanity check that we are reading a real object
521 CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700522 if (kUseBakerReadBarrier) {
523 obj->AssertReadBarrierState();
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700524 }
525
526 // Iterate every page this object belongs to
527 bool on_dirty_page = false;
528 size_t page_off = 0;
529 size_t current_page_idx;
530 uintptr_t object_address;
531 do {
532 object_address = reinterpret_cast<uintptr_t>(current);
533 current_page_idx = object_address / kPageSize + page_off;
534
535 if (dirty_page_set_local.find(current_page_idx) != dirty_page_set_local.end()) {
536 // This object is on a dirty page
537 on_dirty_page = true;
Igor Murashkin37743352014-11-13 14:38:00 -0800538 }
539
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700540 page_off++;
541 } while ((current_page_idx * kPageSize) <
542 RoundUp(object_address + obj->SizeOf(), kObjectAlignment));
Igor Murashkin37743352014-11-13 14:38:00 -0800543
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700544 mirror::Class* klass = obj->GetClass();
545
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700546 // Check against the other object and see if they are different
547 ptrdiff_t offset = current - begin_image_ptr;
548 const uint8_t* current_remote = &remote_contents[offset];
549 mirror::Object* remote_obj = reinterpret_cast<mirror::Object*>(
550 const_cast<uint8_t*>(current_remote));
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700551
552 bool different_image_object = memcmp(current, current_remote, obj->SizeOf()) != 0;
553 if (different_image_object) {
554 bool different_zygote_object = false;
555 if (!zygote_contents.empty()) {
556 const uint8_t* zygote_ptr = &zygote_contents[offset];
557 different_zygote_object = memcmp(current, zygote_ptr, obj->SizeOf()) != 0;
558 }
559 if (different_zygote_object) {
560 // Different from zygote.
561 zygote_dirty_objects.insert(obj);
562 } else {
563 // Just different from iamge.
564 image_dirty_objects.insert(obj);
565 }
566
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700567 different_objects++;
568 dirty_object_bytes += obj->SizeOf();
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700569
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700570 ++class_data[klass].dirty_object_count;
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700571
572 // Go byte-by-byte and figure out what exactly got dirtied
573 size_t dirty_byte_count_per_object = 0;
574 for (size_t i = 0; i < obj->SizeOf(); ++i) {
575 if (current[i] != current_remote[i]) {
576 dirty_byte_count_per_object++;
Igor Murashkin37743352014-11-13 14:38:00 -0800577 }
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700578 }
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700579 class_data[klass].dirty_object_byte_count += dirty_byte_count_per_object;
580 class_data[klass].dirty_object_size_in_bytes += obj->SizeOf();
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700581 class_data[klass].dirty_objects.push_back(remote_obj);
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700582 } else {
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700583 ++class_data[klass].clean_object_count;
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700584 }
Igor Murashkin37743352014-11-13 14:38:00 -0800585
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700586 std::string descriptor = GetClassDescriptor(klass);
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700587 if (different_image_object) {
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700588 if (klass->IsClassClass()) {
589 // this is a "Class"
590 mirror::Class* obj_as_class = reinterpret_cast<mirror::Class*>(remote_obj);
Igor Murashkin37743352014-11-13 14:38:00 -0800591
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700592 // print the fields that are dirty
Igor Murashkin37743352014-11-13 14:38:00 -0800593 for (size_t i = 0; i < obj->SizeOf(); ++i) {
594 if (current[i] != current_remote[i]) {
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700595 class_field_dirty_count[i]++;
Igor Murashkin37743352014-11-13 14:38:00 -0800596 }
597 }
Igor Murashkin37743352014-11-13 14:38:00 -0800598
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700599 class_dirty_objects.push_back(obj_as_class);
600 } else if (strcmp(descriptor.c_str(), "Ljava/lang/reflect/ArtMethod;") == 0) {
601 // this is an ArtMethod
602 ArtMethod* art_method = reinterpret_cast<ArtMethod*>(remote_obj);
Igor Murashkin37743352014-11-13 14:38:00 -0800603
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700604 // print the fields that are dirty
605 for (size_t i = 0; i < obj->SizeOf(); ++i) {
606 if (current[i] != current_remote[i]) {
607 art_method_field_dirty_count[i]++;
Igor Murashkin37743352014-11-13 14:38:00 -0800608 }
Igor Murashkin37743352014-11-13 14:38:00 -0800609 }
Igor Murashkin37743352014-11-13 14:38:00 -0800610
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700611 art_method_dirty_objects.push_back(art_method);
Igor Murashkin37743352014-11-13 14:38:00 -0800612 }
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700613 } else if (on_dirty_page) {
614 // This object was either never mutated or got mutated back to the same value.
615 // TODO: Do I want to distinguish a "different" vs a "dirty" page here?
616 false_dirty_objects.push_back(obj);
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700617 class_data[klass].false_dirty_objects.push_back(obj);
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700618 false_dirty_object_bytes += obj->SizeOf();
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700619 class_data[obj->GetClass()].false_dirty_byte_count += obj->SizeOf();
620 class_data[obj->GetClass()].false_dirty_object_count += 1;
Igor Murashkin37743352014-11-13 14:38:00 -0800621 }
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700622
623 if (strcmp(descriptor.c_str(), "Ljava/lang/Class;") == 0) {
624 local_class_map[descriptor] = reinterpret_cast<mirror::Class*>(obj);
625 remote_class_map[descriptor] = reinterpret_cast<mirror::Class*>(remote_obj);
626 }
627
628 // Unconditionally store the class descriptor in case we need it later
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700629 class_data[klass].descriptor = descriptor;
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700630 current += RoundUp(obj->SizeOf(), kObjectAlignment);
Igor Murashkin37743352014-11-13 14:38:00 -0800631 }
632
633 // Looking at only dirty pages, figure out how many of those bytes belong to dirty objects.
634 float true_dirtied_percent = dirty_object_bytes * 1.0f / (dirty_pages * kPageSize);
635 size_t false_dirty_pages = dirty_pages - different_pages;
636
637 os << "Mapping at [" << reinterpret_cast<void*>(boot_map.start) << ", "
638 << reinterpret_cast<void*>(boot_map.end) << ") had: \n "
639 << different_bytes << " differing bytes, \n "
640 << different_int32s << " differing int32s, \n "
641 << different_objects << " different objects, \n "
642 << dirty_object_bytes << " different object [bytes], \n "
643 << false_dirty_objects.size() << " false dirty objects,\n "
644 << false_dirty_object_bytes << " false dirty object [bytes], \n "
645 << true_dirtied_percent << " different objects-vs-total in a dirty page;\n "
646 << different_pages << " different pages; \n "
647 << dirty_pages << " pages are dirty; \n "
648 << false_dirty_pages << " pages are false dirty; \n "
649 << private_pages << " pages are private; \n "
650 << private_dirty_pages << " pages are Private_Dirty\n "
651 << "";
652
653 // vector of pairs (int count, Class*)
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700654 auto dirty_object_class_values = SortByValueDesc<mirror::Class*, int, ClassData>(
655 class_data, [](const ClassData& d) { return d.dirty_object_count; });
656 auto clean_object_class_values = SortByValueDesc<mirror::Class*, int, ClassData>(
657 class_data, [](const ClassData& d) { return d.clean_object_count; });
Igor Murashkin37743352014-11-13 14:38:00 -0800658
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700659 if (!zygote_dirty_objects.empty()) {
660 os << "\n" << " Dirty objects compared to zygote (probably private dirty): "
661 << zygote_dirty_objects.size() << "\n";
662 for (mirror::Object* obj : zygote_dirty_objects) {
663 const uint8_t* obj_bytes = reinterpret_cast<const uint8_t*>(obj);
664 ptrdiff_t offset = obj_bytes - begin_image_ptr;
665 uint8_t* remote_bytes = &zygote_contents[offset];
666 DiffObjectContents(obj, remote_bytes, os);
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700667 }
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700668 }
669 os << "\n" << " Dirty objects compared to image (private or shared dirty): "
670 << image_dirty_objects.size() << "\n";
671 for (mirror::Object* obj : image_dirty_objects) {
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700672 const uint8_t* obj_bytes = reinterpret_cast<const uint8_t*>(obj);
673 ptrdiff_t offset = obj_bytes - begin_image_ptr;
674 uint8_t* remote_bytes = &remote_contents[offset];
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700675 DiffObjectContents(obj, remote_bytes, os);
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700676 }
677
Igor Murashkin37743352014-11-13 14:38:00 -0800678 os << "\n" << " Dirty object count by class:\n";
679 for (const auto& vk_pair : dirty_object_class_values) {
680 int dirty_object_count = vk_pair.first;
681 mirror::Class* klass = vk_pair.second;
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700682 int object_sizes = class_data[klass].dirty_object_size_in_bytes;
683 float avg_dirty_bytes_per_class =
684 class_data[klass].dirty_object_byte_count * 1.0f / object_sizes;
Igor Murashkin37743352014-11-13 14:38:00 -0800685 float avg_object_size = object_sizes * 1.0f / dirty_object_count;
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700686 const std::string& descriptor = class_data[klass].descriptor;
David Sehr709b0702016-10-13 09:12:37 -0700687 os << " " << mirror::Class::PrettyClass(klass) << " ("
Igor Murashkin37743352014-11-13 14:38:00 -0800688 << "objects: " << dirty_object_count << ", "
689 << "avg dirty bytes: " << avg_dirty_bytes_per_class << ", "
690 << "avg object size: " << avg_object_size << ", "
691 << "class descriptor: '" << descriptor << "'"
692 << ")\n";
693
694 constexpr size_t kMaxAddressPrint = 5;
695 if (strcmp(descriptor.c_str(), "Ljava/lang/reflect/ArtMethod;") == 0) {
696 os << " sample object addresses: ";
697 for (size_t i = 0; i < art_method_dirty_objects.size() && i < kMaxAddressPrint; ++i) {
698 auto art_method = art_method_dirty_objects[i];
699
700 os << reinterpret_cast<void*>(art_method) << ", ";
701 }
702 os << "\n";
703
704 os << " dirty byte +offset:count list = ";
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700705 auto art_method_field_dirty_count_sorted =
706 SortByValueDesc<off_t, int, int>(art_method_field_dirty_count);
Igor Murashkin37743352014-11-13 14:38:00 -0800707 for (auto pair : art_method_field_dirty_count_sorted) {
708 off_t offset = pair.second;
709 int count = pair.first;
710
711 os << "+" << offset << ":" << count << ", ";
712 }
713
714 os << "\n";
715
716 os << " field contents:\n";
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700717 const auto& dirty_objects_list = class_data[klass].dirty_objects;
Igor Murashkin37743352014-11-13 14:38:00 -0800718 for (mirror::Object* obj : dirty_objects_list) {
719 // remote method
Mathieu Chartiere401d142015-04-22 13:56:20 -0700720 auto art_method = reinterpret_cast<ArtMethod*>(obj);
Igor Murashkin37743352014-11-13 14:38:00 -0800721
722 // remote class
723 mirror::Class* remote_declaring_class =
724 FixUpRemotePointer(art_method->GetDeclaringClass(), remote_contents, boot_map);
725
726 // local class
727 mirror::Class* declaring_class =
728 RemoteContentsPointerToLocal(remote_declaring_class,
729 remote_contents,
730 boot_image_header);
731
732 os << " " << reinterpret_cast<void*>(obj) << " ";
733 os << " entryPointFromJni: "
734 << reinterpret_cast<const void*>(
Andreas Gampe75f08852016-07-19 08:06:07 -0700735 art_method->GetDataPtrSize(pointer_size)) << ", ";
Igor Murashkin37743352014-11-13 14:38:00 -0800736 os << " entryPointFromQuickCompiledCode: "
737 << reinterpret_cast<const void*>(
738 art_method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size))
739 << ", ";
740 os << " isNative? " << (art_method->IsNative() ? "yes" : "no") << ", ";
741 os << " class_status (local): " << declaring_class->GetStatus();
742 os << " class_status (remote): " << remote_declaring_class->GetStatus();
743 os << "\n";
744 }
745 }
746 if (strcmp(descriptor.c_str(), "Ljava/lang/Class;") == 0) {
747 os << " sample object addresses: ";
748 for (size_t i = 0; i < class_dirty_objects.size() && i < kMaxAddressPrint; ++i) {
749 auto class_ptr = class_dirty_objects[i];
750
751 os << reinterpret_cast<void*>(class_ptr) << ", ";
752 }
753 os << "\n";
754
755 os << " dirty byte +offset:count list = ";
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700756 auto class_field_dirty_count_sorted =
757 SortByValueDesc<off_t, int, int>(class_field_dirty_count);
Igor Murashkin37743352014-11-13 14:38:00 -0800758 for (auto pair : class_field_dirty_count_sorted) {
759 off_t offset = pair.second;
760 int count = pair.first;
761
762 os << "+" << offset << ":" << count << ", ";
763 }
764 os << "\n";
765
766 os << " field contents:\n";
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700767 const auto& dirty_objects_list = class_data[klass].dirty_objects;
Igor Murashkin37743352014-11-13 14:38:00 -0800768 for (mirror::Object* obj : dirty_objects_list) {
769 // remote class object
770 auto remote_klass = reinterpret_cast<mirror::Class*>(obj);
771
772 // local class object
773 auto local_klass = RemoteContentsPointerToLocal(remote_klass,
774 remote_contents,
775 boot_image_header);
776
777 os << " " << reinterpret_cast<void*>(obj) << " ";
778 os << " class_status (remote): " << remote_klass->GetStatus() << ", ";
779 os << " class_status (local): " << local_klass->GetStatus();
780 os << "\n";
781 }
782 }
783 }
784
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700785 auto false_dirty_object_class_values = SortByValueDesc<mirror::Class*, int, ClassData>(
786 class_data, [](const ClassData& d) { return d.false_dirty_object_count; });
Igor Murashkin37743352014-11-13 14:38:00 -0800787
788 os << "\n" << " False-dirty object count by class:\n";
789 for (const auto& vk_pair : false_dirty_object_class_values) {
790 int object_count = vk_pair.first;
791 mirror::Class* klass = vk_pair.second;
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700792 int object_sizes = class_data[klass].false_dirty_byte_count;
Igor Murashkin37743352014-11-13 14:38:00 -0800793 float avg_object_size = object_sizes * 1.0f / object_count;
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700794 const std::string& descriptor = class_data[klass].descriptor;
David Sehr709b0702016-10-13 09:12:37 -0700795 os << " " << mirror::Class::PrettyClass(klass) << " ("
Igor Murashkin37743352014-11-13 14:38:00 -0800796 << "objects: " << object_count << ", "
797 << "avg object size: " << avg_object_size << ", "
798 << "total bytes: " << object_sizes << ", "
799 << "class descriptor: '" << descriptor << "'"
800 << ")\n";
801
802 if (strcmp(descriptor.c_str(), "Ljava/lang/reflect/ArtMethod;") == 0) {
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700803 auto& art_method_false_dirty_objects = class_data[klass].false_dirty_objects;
Igor Murashkin37743352014-11-13 14:38:00 -0800804
805 os << " field contents:\n";
806 for (mirror::Object* obj : art_method_false_dirty_objects) {
807 // local method
Mathieu Chartiere401d142015-04-22 13:56:20 -0700808 auto art_method = reinterpret_cast<ArtMethod*>(obj);
Igor Murashkin37743352014-11-13 14:38:00 -0800809
810 // local class
811 mirror::Class* declaring_class = art_method->GetDeclaringClass();
812
813 os << " " << reinterpret_cast<void*>(obj) << " ";
814 os << " entryPointFromJni: "
815 << reinterpret_cast<const void*>(
Andreas Gampe75f08852016-07-19 08:06:07 -0700816 art_method->GetDataPtrSize(pointer_size)) << ", ";
Igor Murashkin37743352014-11-13 14:38:00 -0800817 os << " entryPointFromQuickCompiledCode: "
818 << reinterpret_cast<const void*>(
819 art_method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size))
820 << ", ";
821 os << " isNative? " << (art_method->IsNative() ? "yes" : "no") << ", ";
822 os << " class_status (local): " << declaring_class->GetStatus();
823 os << "\n";
824 }
825 }
826 }
827
828 os << "\n" << " Clean object count by class:\n";
829 for (const auto& vk_pair : clean_object_class_values) {
David Sehr709b0702016-10-13 09:12:37 -0700830 os << " " << mirror::Class::PrettyClass(vk_pair.second) << " (" << vk_pair.first << ")\n";
Igor Murashkin37743352014-11-13 14:38:00 -0800831 }
832
833 return true;
834 }
835
836 // Fixup a remote pointer that we read from a foreign boot.art to point to our own memory.
837 // Returned pointer will point to inside of remote_contents.
838 template <typename T>
839 static T* FixUpRemotePointer(T* remote_ptr,
840 std::vector<uint8_t>& remote_contents,
841 const backtrace_map_t& boot_map) {
842 if (remote_ptr == nullptr) {
843 return nullptr;
844 }
845
846 uintptr_t remote = reinterpret_cast<uintptr_t>(remote_ptr);
847
848 CHECK_LE(boot_map.start, remote);
849 CHECK_GT(boot_map.end, remote);
850
851 off_t boot_offset = remote - boot_map.start;
852
853 return reinterpret_cast<T*>(&remote_contents[boot_offset]);
854 }
855
856 template <typename T>
857 static T* RemoteContentsPointerToLocal(T* remote_ptr,
858 std::vector<uint8_t>& remote_contents,
859 const ImageHeader& image_header) {
860 if (remote_ptr == nullptr) {
861 return nullptr;
862 }
863
864 uint8_t* remote = reinterpret_cast<uint8_t*>(remote_ptr);
865 ptrdiff_t boot_offset = remote - &remote_contents[0];
866
867 const uint8_t* local_ptr = reinterpret_cast<const uint8_t*>(&image_header) + boot_offset;
868
869 return reinterpret_cast<T*>(const_cast<uint8_t*>(local_ptr));
870 }
871
872 static std::string GetClassDescriptor(mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700873 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin37743352014-11-13 14:38:00 -0800874 CHECK(klass != nullptr);
875
876 std::string descriptor;
877 const char* descriptor_str = klass->GetDescriptor(&descriptor);
878
879 return std::string(descriptor_str);
880 }
881
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700882 template <typename K, typename V, typename D>
883 static std::vector<std::pair<V, K>> SortByValueDesc(
884 const std::map<K, D> map,
885 std::function<V(const D&)> value_mapper = [](const D& d) { return static_cast<V>(d); }) {
Igor Murashkin37743352014-11-13 14:38:00 -0800886 // Store value->key so that we can use the default sort from pair which
887 // sorts by value first and then key
888 std::vector<std::pair<V, K>> value_key_vector;
889
890 for (const auto& kv_pair : map) {
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700891 value_key_vector.push_back(std::make_pair(value_mapper(kv_pair.second), kv_pair.first));
Igor Murashkin37743352014-11-13 14:38:00 -0800892 }
893
894 // Sort in reverse (descending order)
895 std::sort(value_key_vector.rbegin(), value_key_vector.rend());
896 return value_key_vector;
897 }
898
899 static bool GetPageFrameNumber(File* page_map_file,
900 size_t virtual_page_index,
901 uint64_t* page_frame_number,
902 std::string* error_msg) {
903 CHECK(page_map_file != nullptr);
904 CHECK(page_frame_number != nullptr);
905 CHECK(error_msg != nullptr);
906
907 constexpr size_t kPageMapEntrySize = sizeof(uint64_t);
908 constexpr uint64_t kPageFrameNumberMask = (1ULL << 55) - 1; // bits 0-54 [in /proc/$pid/pagemap]
909 constexpr uint64_t kPageSoftDirtyMask = (1ULL << 55); // bit 55 [in /proc/$pid/pagemap]
910
911 uint64_t page_map_entry = 0;
912
913 // Read 64-bit entry from /proc/$pid/pagemap to get the physical page frame number
914 if (!page_map_file->PreadFully(&page_map_entry, kPageMapEntrySize,
915 virtual_page_index * kPageMapEntrySize)) {
916 *error_msg = StringPrintf("Failed to read the virtual page index entry from %s",
917 page_map_file->GetPath().c_str());
918 return false;
919 }
920
921 // TODO: seems useless, remove this.
922 bool soft_dirty = (page_map_entry & kPageSoftDirtyMask) != 0;
923 if ((false)) {
924 LOG(VERBOSE) << soft_dirty; // Suppress unused warning
925 UNREACHABLE();
926 }
927
928 *page_frame_number = page_map_entry & kPageFrameNumberMask;
929
930 return true;
931 }
932
933 static int IsPageDirty(File* page_map_file,
934 File* clean_page_map_file,
935 File* kpage_flags_file,
936 File* kpage_count_file,
937 size_t virtual_page_idx,
938 size_t clean_virtual_page_idx,
939 // Out parameters:
940 uint64_t* page_count, std::string* error_msg) {
941 CHECK(page_map_file != nullptr);
942 CHECK(clean_page_map_file != nullptr);
943 CHECK_NE(page_map_file, clean_page_map_file);
944 CHECK(kpage_flags_file != nullptr);
945 CHECK(kpage_count_file != nullptr);
946 CHECK(page_count != nullptr);
947 CHECK(error_msg != nullptr);
948
949 // Constants are from https://www.kernel.org/doc/Documentation/vm/pagemap.txt
950
951 constexpr size_t kPageFlagsEntrySize = sizeof(uint64_t);
952 constexpr size_t kPageCountEntrySize = sizeof(uint64_t);
953 constexpr uint64_t kPageFlagsDirtyMask = (1ULL << 4); // in /proc/kpageflags
954 constexpr uint64_t kPageFlagsNoPageMask = (1ULL << 20); // in /proc/kpageflags
955 constexpr uint64_t kPageFlagsMmapMask = (1ULL << 11); // in /proc/kpageflags
956
957 uint64_t page_frame_number = 0;
958 if (!GetPageFrameNumber(page_map_file, virtual_page_idx, &page_frame_number, error_msg)) {
959 return -1;
960 }
961
962 uint64_t page_frame_number_clean = 0;
963 if (!GetPageFrameNumber(clean_page_map_file, clean_virtual_page_idx, &page_frame_number_clean,
964 error_msg)) {
965 return -1;
966 }
967
968 // Read 64-bit entry from /proc/kpageflags to get the dirty bit for a page
969 uint64_t kpage_flags_entry = 0;
970 if (!kpage_flags_file->PreadFully(&kpage_flags_entry,
971 kPageFlagsEntrySize,
972 page_frame_number * kPageFlagsEntrySize)) {
973 *error_msg = StringPrintf("Failed to read the page flags from %s",
974 kpage_flags_file->GetPath().c_str());
975 return -1;
976 }
977
978 // Read 64-bit entyry from /proc/kpagecount to get mapping counts for a page
979 if (!kpage_count_file->PreadFully(page_count /*out*/,
980 kPageCountEntrySize,
981 page_frame_number * kPageCountEntrySize)) {
982 *error_msg = StringPrintf("Failed to read the page count from %s",
983 kpage_count_file->GetPath().c_str());
984 return -1;
985 }
986
987 // There must be a page frame at the requested address.
988 CHECK_EQ(kpage_flags_entry & kPageFlagsNoPageMask, 0u);
989 // The page frame must be memory mapped
990 CHECK_NE(kpage_flags_entry & kPageFlagsMmapMask, 0u);
991
992 // Page is dirty, i.e. has diverged from file, if the 4th bit is set to 1
993 bool flags_dirty = (kpage_flags_entry & kPageFlagsDirtyMask) != 0;
994
995 // page_frame_number_clean must come from the *same* process
996 // but a *different* mmap than page_frame_number
997 if (flags_dirty) {
998 CHECK_NE(page_frame_number, page_frame_number_clean);
999 }
1000
1001 return page_frame_number != page_frame_number_clean;
1002 }
1003
Igor Murashkin37743352014-11-13 14:38:00 -08001004 private:
1005 // Return the image location, stripped of any directories, e.g. "boot.art" or "core.art"
1006 std::string GetImageLocationBaseName() const {
1007 return BaseName(std::string(image_location_));
1008 }
1009
1010 std::ostream* os_;
1011 const ImageHeader& image_header_;
Andreas Gampe8994a042015-12-30 19:03:17 +00001012 const std::string image_location_;
Igor Murashkin37743352014-11-13 14:38:00 -08001013 pid_t image_diff_pid_; // Dump image diff against boot.art if pid is non-negative
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001014 pid_t zygote_diff_pid_; // Dump image diff against zygote boot.art if pid is non-negative
Igor Murashkin37743352014-11-13 14:38:00 -08001015
1016 DISALLOW_COPY_AND_ASSIGN(ImgDiagDumper);
1017};
1018
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001019static int DumpImage(Runtime* runtime,
1020 std::ostream* os,
1021 pid_t image_diff_pid,
1022 pid_t zygote_diff_pid) {
Igor Murashkin37743352014-11-13 14:38:00 -08001023 ScopedObjectAccess soa(Thread::Current());
1024 gc::Heap* heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001025 std::vector<gc::space::ImageSpace*> image_spaces = heap->GetBootImageSpaces();
1026 CHECK(!image_spaces.empty());
1027 for (gc::space::ImageSpace* image_space : image_spaces) {
1028 const ImageHeader& image_header = image_space->GetImageHeader();
1029 if (!image_header.IsValid()) {
1030 fprintf(stderr, "Invalid image header %s\n", image_space->GetImageLocation().c_str());
1031 return EXIT_FAILURE;
1032 }
1033
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001034 ImgDiagDumper img_diag_dumper(os,
1035 image_header,
1036 image_space->GetImageLocation(),
1037 image_diff_pid,
1038 zygote_diff_pid);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001039 if (!img_diag_dumper.Dump()) {
1040 return EXIT_FAILURE;
1041 }
Igor Murashkin37743352014-11-13 14:38:00 -08001042 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001043 return EXIT_SUCCESS;
Igor Murashkin37743352014-11-13 14:38:00 -08001044}
1045
1046struct ImgDiagArgs : public CmdlineArgs {
1047 protected:
1048 using Base = CmdlineArgs;
1049
1050 virtual ParseStatus ParseCustom(const StringPiece& option,
1051 std::string* error_msg) OVERRIDE {
1052 {
1053 ParseStatus base_parse = Base::ParseCustom(option, error_msg);
1054 if (base_parse != kParseUnknownArgument) {
1055 return base_parse;
1056 }
1057 }
1058
1059 if (option.starts_with("--image-diff-pid=")) {
1060 const char* image_diff_pid = option.substr(strlen("--image-diff-pid=")).data();
1061
1062 if (!ParseInt(image_diff_pid, &image_diff_pid_)) {
1063 *error_msg = "Image diff pid out of range";
1064 return kParseError;
1065 }
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001066 } else if (option.starts_with("--zygote-diff-pid=")) {
1067 const char* zygote_diff_pid = option.substr(strlen("--zygote-diff-pid=")).data();
1068
1069 if (!ParseInt(zygote_diff_pid, &zygote_diff_pid_)) {
1070 *error_msg = "Zygote diff pid out of range";
1071 return kParseError;
1072 }
Igor Murashkin37743352014-11-13 14:38:00 -08001073 } else {
1074 return kParseUnknownArgument;
1075 }
1076
1077 return kParseOk;
1078 }
1079
1080 virtual ParseStatus ParseChecks(std::string* error_msg) OVERRIDE {
1081 // Perform the parent checks.
1082 ParseStatus parent_checks = Base::ParseChecks(error_msg);
1083 if (parent_checks != kParseOk) {
1084 return parent_checks;
1085 }
1086
1087 // Perform our own checks.
1088
1089 if (kill(image_diff_pid_,
1090 /*sig*/0) != 0) { // No signal is sent, perform error-checking only.
1091 // Check if the pid exists before proceeding.
1092 if (errno == ESRCH) {
1093 *error_msg = "Process specified does not exist";
1094 } else {
1095 *error_msg = StringPrintf("Failed to check process status: %s", strerror(errno));
1096 }
1097 return kParseError;
1098 } else if (instruction_set_ != kRuntimeISA) {
1099 // Don't allow different ISAs since the images are ISA-specific.
1100 // Right now the code assumes both the runtime ISA and the remote ISA are identical.
1101 *error_msg = "Must use the default runtime ISA; changing ISA is not supported.";
1102 return kParseError;
1103 }
1104
1105 return kParseOk;
1106 }
1107
1108 virtual std::string GetUsage() const {
1109 std::string usage;
1110
1111 usage +=
1112 "Usage: imgdiag [options] ...\n"
1113 " Example: imgdiag --image-diff-pid=$(pidof dex2oat)\n"
1114 " Example: adb shell imgdiag --image-diff-pid=$(pid zygote)\n"
1115 "\n";
1116
1117 usage += Base::GetUsage();
1118
1119 usage += // Optional.
1120 " --image-diff-pid=<pid>: provide the PID of a process whose boot.art you want to diff.\n"
1121 " Example: --image-diff-pid=$(pid zygote)\n"
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001122 " --zygote-diff-pid=<pid>: provide the PID of the zygote whose boot.art you want to diff "
1123 "against.\n"
1124 " Example: --zygote-diff-pid=$(pid zygote)\n"
Igor Murashkin37743352014-11-13 14:38:00 -08001125 "\n";
1126
1127 return usage;
1128 }
1129
1130 public:
1131 pid_t image_diff_pid_ = -1;
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001132 pid_t zygote_diff_pid_ = -1;
Igor Murashkin37743352014-11-13 14:38:00 -08001133};
1134
1135struct ImgDiagMain : public CmdlineMain<ImgDiagArgs> {
1136 virtual bool ExecuteWithRuntime(Runtime* runtime) {
1137 CHECK(args_ != nullptr);
1138
1139 return DumpImage(runtime,
Igor Murashkin37743352014-11-13 14:38:00 -08001140 args_->os_,
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001141 args_->image_diff_pid_,
1142 args_->zygote_diff_pid_) == EXIT_SUCCESS;
Igor Murashkin37743352014-11-13 14:38:00 -08001143 }
1144};
1145
1146} // namespace art
1147
1148int main(int argc, char** argv) {
1149 art::ImgDiagMain main;
1150 return main.Main(argc, argv);
1151}