blob: e3b11951e3c23349840b5cd83cc60fc548dfd208 [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
Andreas Gampea1d2f952017-04-20 22:53:58 -070031#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070032#include "art_method-inl.h"
Igor Murashkin37743352014-11-13 14:38:00 -080033#include "base/unix_file/fd_file.h"
Igor Murashkin37743352014-11-13 14:38:00 -080034#include "gc/space/image_space.h"
35#include "gc/heap.h"
36#include "mirror/class-inl.h"
37#include "mirror/object-inl.h"
Igor Murashkin37743352014-11-13 14:38:00 -080038#include "image.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070039#include "scoped_thread_state_change-inl.h"
Igor Murashkin37743352014-11-13 14:38:00 -080040#include "os.h"
Igor Murashkin37743352014-11-13 14:38:00 -080041
42#include "cmdline.h"
43#include "backtrace/BacktraceMap.h"
44
45#include <sys/stat.h>
46#include <sys/types.h>
47#include <signal.h>
48
49namespace art {
50
Andreas Gampe46ee31b2016-12-14 10:11:49 -080051using android::base::StringPrintf;
52
Igor Murashkin37743352014-11-13 14:38:00 -080053class ImgDiagDumper {
54 public:
55 explicit ImgDiagDumper(std::ostream* os,
Mathieu Chartiercb044bc2016-04-01 13:56:41 -070056 const ImageHeader& image_header,
57 const std::string& image_location,
Mathieu Chartierc5196cd2016-04-08 14:08:37 -070058 pid_t image_diff_pid,
59 pid_t zygote_diff_pid)
Igor Murashkin37743352014-11-13 14:38:00 -080060 : os_(os),
61 image_header_(image_header),
62 image_location_(image_location),
Mathieu Chartierc5196cd2016-04-08 14:08:37 -070063 image_diff_pid_(image_diff_pid),
David Sehr20e271a2017-06-14 13:02:14 -070064 zygote_diff_pid_(zygote_diff_pid),
65 zygote_pid_only_(false) {}
Igor Murashkin37743352014-11-13 14:38:00 -080066
Andreas Gampebdf7f1c2016-08-30 16:38:47 -070067 bool Dump() REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin37743352014-11-13 14:38:00 -080068 std::ostream& os = *os_;
Mathieu Chartiercb044bc2016-04-01 13:56:41 -070069 os << "IMAGE LOCATION: " << image_location_ << "\n\n";
70
Igor Murashkin37743352014-11-13 14:38:00 -080071 os << "MAGIC: " << image_header_.GetMagic() << "\n\n";
72
73 os << "IMAGE BEGIN: " << reinterpret_cast<void*>(image_header_.GetImageBegin()) << "\n\n";
74
David Sehr20e271a2017-06-14 13:02:14 -070075 PrintPidLine("IMAGE", image_diff_pid_);
76 os << "\n\n";
77 PrintPidLine("ZYGOTE", zygote_diff_pid_);
Igor Murashkin37743352014-11-13 14:38:00 -080078 bool ret = true;
David Sehr20e271a2017-06-14 13:02:14 -070079 if (image_diff_pid_ >= 0 || zygote_diff_pid_ >= 0) {
80 if (image_diff_pid_ < 0) {
81 image_diff_pid_ = zygote_diff_pid_;
82 zygote_diff_pid_ = -1;
83 zygote_pid_only_ = true;
84 }
85 ret = DumpImageDiff();
Igor Murashkin37743352014-11-13 14:38:00 -080086 os << "\n\n";
Igor Murashkin37743352014-11-13 14:38:00 -080087 }
88
89 os << std::flush;
90
91 return ret;
92 }
93
94 private:
David Sehr45de57f2017-06-21 05:03:22 +000095 void PrintPidLine(const std::string& kind, pid_t pid) {
96 if (pid < 0) {
97 *os_ << kind << " DIFF PID: disabled\n\n";
98 } else {
99 *os_ << kind << " DIFF PID (" << pid << "): ";
100 }
101 }
102
103 static bool EndsWith(const std::string& str, const std::string& suffix) {
104 return str.size() >= suffix.size() &&
105 str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
106 }
107
108 // Return suffix of the file path after the last /. (e.g. /foo/bar -> bar, bar -> bar)
109 static std::string BaseName(const std::string& str) {
110 size_t idx = str.rfind('/');
111 if (idx == std::string::npos) {
112 return str;
113 }
114
115 return str.substr(idx + 1);
116 }
117
David Sehr20e271a2017-06-14 13:02:14 -0700118 bool DumpImageDiff()
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700119 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin37743352014-11-13 14:38:00 -0800120 std::ostream& os = *os_;
121
David Sehr45de57f2017-06-21 05:03:22 +0000122 {
123 struct stat sts;
124 std::string proc_pid_str =
125 StringPrintf("/proc/%ld", static_cast<long>(image_diff_pid_)); // NOLINT [runtime/int]
126 if (stat(proc_pid_str.c_str(), &sts) == -1) {
127 os << "Process does not exist";
128 return false;
Igor Murashkin37743352014-11-13 14:38:00 -0800129 }
130 }
131
David Sehr45de57f2017-06-21 05:03:22 +0000132 // Open /proc/$pid/maps to view memory maps
133 auto proc_maps = std::unique_ptr<BacktraceMap>(BacktraceMap::Create(image_diff_pid_));
134 if (proc_maps == nullptr) {
135 os << "Could not read backtrace maps";
136 return false;
137 }
Igor Murashkin37743352014-11-13 14:38:00 -0800138
David Sehr45de57f2017-06-21 05:03:22 +0000139 bool found_boot_map = false;
140 backtrace_map_t boot_map = backtrace_map_t();
141 // Find the memory map only for boot.art
142 for (const backtrace_map_t& map : *proc_maps) {
143 if (EndsWith(map.name, GetImageLocationBaseName())) {
144 if ((map.flags & PROT_WRITE) != 0) {
145 boot_map = map;
146 found_boot_map = true;
147 break;
David Sehr0627be32017-06-16 13:50:02 -0700148 }
David Sehr45de57f2017-06-21 05:03:22 +0000149 // In actuality there's more than 1 map, but the second one is read-only.
150 // The one we care about is the write-able map.
151 // The readonly maps are guaranteed to be identical, so its not interesting to compare
152 // them.
David Sehr0627be32017-06-16 13:50:02 -0700153 }
154 }
David Sehr0627be32017-06-16 13:50:02 -0700155
David Sehr45de57f2017-06-21 05:03:22 +0000156 if (!found_boot_map) {
157 os << "Could not find map for " << GetImageLocationBaseName();
158 return false;
159 }
David Sehr0627be32017-06-16 13:50:02 -0700160
David Sehr45de57f2017-06-21 05:03:22 +0000161 // Future idea: diff against zygote so we can ignore the shared dirty pages.
162 return DumpImageDiffMap(boot_map);
Igor Murashkin37743352014-11-13 14:38:00 -0800163 }
164
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700165 static std::string PrettyFieldValue(ArtField* field, mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700166 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700167 std::ostringstream oss;
168 switch (field->GetTypeAsPrimitiveType()) {
169 case Primitive::kPrimNot: {
170 oss << obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
171 field->GetOffset());
172 break;
173 }
174 case Primitive::kPrimBoolean: {
175 oss << static_cast<bool>(obj->GetFieldBoolean<kVerifyNone>(field->GetOffset()));
176 break;
177 }
178 case Primitive::kPrimByte: {
179 oss << static_cast<int32_t>(obj->GetFieldByte<kVerifyNone>(field->GetOffset()));
180 break;
181 }
182 case Primitive::kPrimChar: {
183 oss << obj->GetFieldChar<kVerifyNone>(field->GetOffset());
184 break;
185 }
186 case Primitive::kPrimShort: {
187 oss << obj->GetFieldShort<kVerifyNone>(field->GetOffset());
188 break;
189 }
190 case Primitive::kPrimInt: {
191 oss << obj->GetField32<kVerifyNone>(field->GetOffset());
192 break;
193 }
194 case Primitive::kPrimLong: {
195 oss << obj->GetField64<kVerifyNone>(field->GetOffset());
196 break;
197 }
198 case Primitive::kPrimFloat: {
199 oss << obj->GetField32<kVerifyNone>(field->GetOffset());
200 break;
201 }
202 case Primitive::kPrimDouble: {
203 oss << obj->GetField64<kVerifyNone>(field->GetOffset());
204 break;
205 }
206 case Primitive::kPrimVoid: {
207 oss << "void";
208 break;
209 }
210 }
211 return oss.str();
212 }
213
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700214 // Aggregate and detail class data from an image diff.
215 struct ClassData {
David Sehr45de57f2017-06-21 05:03:22 +0000216 int dirty_object_count = 0;
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700217
218 // Track only the byte-per-byte dirtiness (in bytes)
David Sehr45de57f2017-06-21 05:03:22 +0000219 int dirty_object_byte_count = 0;
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700220
221 // Track the object-by-object dirtiness (in bytes)
David Sehr45de57f2017-06-21 05:03:22 +0000222 int dirty_object_size_in_bytes = 0;
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700223
David Sehr45de57f2017-06-21 05:03:22 +0000224 int clean_object_count = 0;
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700225
226 std::string descriptor;
227
David Sehr45de57f2017-06-21 05:03:22 +0000228 int false_dirty_byte_count = 0;
229 int false_dirty_object_count = 0;
230 std::vector<mirror::Object*> false_dirty_objects;
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700231
232 // Remote pointers to dirty objects
David Sehr45de57f2017-06-21 05:03:22 +0000233 std::vector<mirror::Object*> dirty_objects;
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700234 };
235
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700236 void DiffObjectContents(mirror::Object* obj,
237 uint8_t* remote_bytes,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700238 std::ostream& os) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700239 const char* tabs = " ";
240 // Attempt to find fields for all dirty bytes.
241 mirror::Class* klass = obj->GetClass();
242 if (obj->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700243 os << tabs << "Class " << mirror::Class::PrettyClass(obj->AsClass()) << " " << obj << "\n";
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700244 } else {
David Sehr709b0702016-10-13 09:12:37 -0700245 os << tabs << "Instance of " << mirror::Class::PrettyClass(klass) << " " << obj << "\n";
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700246 }
247
248 std::unordered_set<ArtField*> dirty_instance_fields;
249 std::unordered_set<ArtField*> dirty_static_fields;
250 const uint8_t* obj_bytes = reinterpret_cast<const uint8_t*>(obj);
251 mirror::Object* remote_obj = reinterpret_cast<mirror::Object*>(remote_bytes);
252 for (size_t i = 0, count = obj->SizeOf(); i < count; ++i) {
253 if (obj_bytes[i] != remote_bytes[i]) {
254 ArtField* field = ArtField::FindInstanceFieldWithOffset</*exact*/false>(klass, i);
255 if (field != nullptr) {
256 dirty_instance_fields.insert(field);
257 } else if (obj->IsClass()) {
258 field = ArtField::FindStaticFieldWithOffset</*exact*/false>(obj->AsClass(), i);
259 if (field != nullptr) {
260 dirty_static_fields.insert(field);
261 }
262 }
263 if (field == nullptr) {
264 if (klass->IsArrayClass()) {
265 mirror::Class* component_type = klass->GetComponentType();
266 Primitive::Type primitive_type = component_type->GetPrimitiveType();
267 size_t component_size = Primitive::ComponentSize(primitive_type);
268 size_t data_offset = mirror::Array::DataOffset(component_size).Uint32Value();
269 if (i >= data_offset) {
270 os << tabs << "Dirty array element " << (i - data_offset) / component_size << "\n";
271 // Skip to next element to prevent spam.
272 i += component_size - 1;
273 continue;
274 }
275 }
276 os << tabs << "No field for byte offset " << i << "\n";
277 }
278 }
279 }
280 // Dump different fields. TODO: Dump field contents.
281 if (!dirty_instance_fields.empty()) {
282 os << tabs << "Dirty instance fields " << dirty_instance_fields.size() << "\n";
283 for (ArtField* field : dirty_instance_fields) {
David Sehr709b0702016-10-13 09:12:37 -0700284 os << tabs << ArtField::PrettyField(field)
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700285 << " original=" << PrettyFieldValue(field, obj)
286 << " remote=" << PrettyFieldValue(field, remote_obj) << "\n";
287 }
288 }
289 if (!dirty_static_fields.empty()) {
290 os << tabs << "Dirty static fields " << dirty_static_fields.size() << "\n";
291 for (ArtField* field : dirty_static_fields) {
David Sehr709b0702016-10-13 09:12:37 -0700292 os << tabs << ArtField::PrettyField(field)
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700293 << " original=" << PrettyFieldValue(field, obj)
294 << " remote=" << PrettyFieldValue(field, remote_obj) << "\n";
295 }
296 }
297 os << "\n";
298 }
299
David Sehr0627be32017-06-16 13:50:02 -0700300 // Look at /proc/$pid/mem and only diff the things from there
David Sehr45de57f2017-06-21 05:03:22 +0000301 bool DumpImageDiffMap(const backtrace_map_t& boot_map)
David Sehr0627be32017-06-16 13:50:02 -0700302 REQUIRES_SHARED(Locks::mutator_lock_) {
303 std::ostream& os = *os_;
David Sehr45de57f2017-06-21 05:03:22 +0000304 const PointerSize pointer_size = InstructionSetPointerSize(
305 Runtime::Current()->GetInstructionSet());
306
307 std::string file_name =
308 StringPrintf("/proc/%ld/mem", static_cast<long>(image_diff_pid_)); // NOLINT [runtime/int]
309
310 size_t boot_map_size = boot_map.end - boot_map.start;
311
312 // Open /proc/$pid/mem as a file
313 auto map_file = std::unique_ptr<File>(OS::OpenFileForReading(file_name.c_str()));
314 if (map_file == nullptr) {
315 os << "Failed to open " << file_name << " for reading";
316 return false;
317 }
318
319 // Memory-map /proc/$pid/mem subset from the boot map
320 CHECK(boot_map.end >= boot_map.start);
321
Igor Murashkin37743352014-11-13 14:38:00 -0800322 std::string error_msg;
323
324 // Walk the bytes and diff against our boot image
David Sehr45de57f2017-06-21 05:03:22 +0000325 const ImageHeader& boot_image_header = image_header_;
326
Igor Murashkin37743352014-11-13 14:38:00 -0800327 os << "\nObserving boot image header at address "
David Sehr45de57f2017-06-21 05:03:22 +0000328 << reinterpret_cast<const void*>(&boot_image_header)
Igor Murashkin37743352014-11-13 14:38:00 -0800329 << "\n\n";
330
David Sehr45de57f2017-06-21 05:03:22 +0000331 const uint8_t* image_begin_unaligned = boot_image_header.GetImageBegin();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700332 const uint8_t* image_mirror_end_unaligned = image_begin_unaligned +
David Sehr45de57f2017-06-21 05:03:22 +0000333 boot_image_header.GetImageSection(ImageHeader::kSectionObjects).Size();
334 const uint8_t* image_end_unaligned = image_begin_unaligned + boot_image_header.GetImageSize();
Igor Murashkin37743352014-11-13 14:38:00 -0800335
336 // Adjust range to nearest page
337 const uint8_t* image_begin = AlignDown(image_begin_unaligned, kPageSize);
338 const uint8_t* image_end = AlignUp(image_end_unaligned, kPageSize);
339
David Sehr45de57f2017-06-21 05:03:22 +0000340 ptrdiff_t page_off_begin = boot_image_header.GetImageBegin() - image_begin;
341
342 if (reinterpret_cast<uintptr_t>(image_begin) > boot_map.start ||
343 reinterpret_cast<uintptr_t>(image_end) < boot_map.end) {
Igor Murashkin37743352014-11-13 14:38:00 -0800344 // Sanity check that we aren't trying to read a completely different boot image
345 os << "Remote boot map is out of range of local boot map: " <<
346 "local begin " << reinterpret_cast<const void*>(image_begin) <<
347 ", local end " << reinterpret_cast<const void*>(image_end) <<
David Sehr45de57f2017-06-21 05:03:22 +0000348 ", remote begin " << reinterpret_cast<const void*>(boot_map.start) <<
349 ", remote end " << reinterpret_cast<const void*>(boot_map.end);
Igor Murashkin37743352014-11-13 14:38:00 -0800350 return false;
351 // If we wanted even more validation we could map the ImageHeader from the file
352 }
353
David Sehr45de57f2017-06-21 05:03:22 +0000354 std::vector<uint8_t> remote_contents(boot_map_size);
355 if (!map_file->PreadFully(&remote_contents[0], boot_map_size, boot_map.start)) {
356 os << "Could not fully read file " << file_name;
357 return false;
358 }
Igor Murashkin37743352014-11-13 14:38:00 -0800359
David Sehr45de57f2017-06-21 05:03:22 +0000360 std::vector<uint8_t> zygote_contents;
361 std::unique_ptr<File> zygote_map_file;
362 if (zygote_diff_pid_ != -1) {
363 std::string zygote_file_name =
364 StringPrintf("/proc/%ld/mem", static_cast<long>(zygote_diff_pid_)); // NOLINT [runtime/int]
365 zygote_map_file.reset(OS::OpenFileForReading(zygote_file_name.c_str()));
366 // The boot map should be at the same address.
367 zygote_contents.resize(boot_map_size);
368 if (!zygote_map_file->PreadFully(&zygote_contents[0], boot_map_size, boot_map.start)) {
369 LOG(WARNING) << "Could not fully read zygote file " << zygote_file_name;
370 zygote_contents.clear();
371 }
372 }
373
374 std::string page_map_file_name = StringPrintf(
375 "/proc/%ld/pagemap", static_cast<long>(image_diff_pid_)); // NOLINT [runtime/int]
376 auto page_map_file = std::unique_ptr<File>(OS::OpenFileForReading(page_map_file_name.c_str()));
377 if (page_map_file == nullptr) {
378 os << "Failed to open " << page_map_file_name << " for reading: " << strerror(errno);
379 return false;
380 }
381
382 // Not truly clean, mmap-ing boot.art again would be more pristine, but close enough
383 const char* clean_page_map_file_name = "/proc/self/pagemap";
384 auto clean_page_map_file = std::unique_ptr<File>(
385 OS::OpenFileForReading(clean_page_map_file_name));
386 if (clean_page_map_file == nullptr) {
387 os << "Failed to open " << clean_page_map_file_name << " for reading: " << strerror(errno);
388 return false;
389 }
390
391 auto kpage_flags_file = std::unique_ptr<File>(OS::OpenFileForReading("/proc/kpageflags"));
392 if (kpage_flags_file == nullptr) {
393 os << "Failed to open /proc/kpageflags for reading: " << strerror(errno);
394 return false;
395 }
396
397 auto kpage_count_file = std::unique_ptr<File>(OS::OpenFileForReading("/proc/kpagecount"));
398 if (kpage_count_file == nullptr) {
399 os << "Failed to open /proc/kpagecount for reading:" << strerror(errno);
400 return false;
401 }
402
403 // Set of the remote virtual page indices that are dirty
404 std::set<size_t> dirty_page_set_remote;
David Sehr0627be32017-06-16 13:50:02 -0700405 // Set of the local virtual page indices that are dirty
406 std::set<size_t> dirty_page_set_local;
Igor Murashkin37743352014-11-13 14:38:00 -0800407
David Sehr45de57f2017-06-21 05:03:22 +0000408 size_t different_int32s = 0;
409 size_t different_bytes = 0;
410 size_t different_pages = 0;
411 size_t virtual_page_idx = 0; // Virtual page number (for an absolute memory address)
412 size_t page_idx = 0; // Page index relative to 0
413 size_t previous_page_idx = 0; // Previous page index relative to 0
414 size_t dirty_pages = 0;
415 size_t private_pages = 0;
416 size_t private_dirty_pages = 0;
417
418 // Iterate through one page at a time. Boot map begin/end already implicitly aligned.
419 for (uintptr_t begin = boot_map.start; begin != boot_map.end; begin += kPageSize) {
420 ptrdiff_t offset = begin - boot_map.start;
421
422 // We treat the image header as part of the memory map for now
423 // If we wanted to change this, we could pass base=start+sizeof(ImageHeader)
424 // But it might still be interesting to see if any of the ImageHeader data mutated
425 const uint8_t* local_ptr = reinterpret_cast<const uint8_t*>(&boot_image_header) + offset;
426 uint8_t* remote_ptr = &remote_contents[offset];
427
428 if (memcmp(local_ptr, remote_ptr, kPageSize) != 0) {
429 different_pages++;
430
431 // Count the number of 32-bit integers that are different.
432 for (size_t i = 0; i < kPageSize / sizeof(uint32_t); ++i) {
433 uint32_t* remote_ptr_int32 = reinterpret_cast<uint32_t*>(remote_ptr);
434 const uint32_t* local_ptr_int32 = reinterpret_cast<const uint32_t*>(local_ptr);
435
436 if (remote_ptr_int32[i] != local_ptr_int32[i]) {
437 different_int32s++;
438 }
439 }
440 }
441 }
442
443 // Iterate through one byte at a time.
444 for (uintptr_t begin = boot_map.start; begin != boot_map.end; ++begin) {
445 previous_page_idx = page_idx;
446 ptrdiff_t offset = begin - boot_map.start;
447
448 // We treat the image header as part of the memory map for now
449 // If we wanted to change this, we could pass base=start+sizeof(ImageHeader)
450 // But it might still be interesting to see if any of the ImageHeader data mutated
451 const uint8_t* local_ptr = reinterpret_cast<const uint8_t*>(&boot_image_header) + offset;
452 uint8_t* remote_ptr = &remote_contents[offset];
453
454 virtual_page_idx = reinterpret_cast<uintptr_t>(local_ptr) / kPageSize;
455
456 // Calculate the page index, relative to the 0th page where the image begins
457 page_idx = (offset + page_off_begin) / kPageSize;
458 if (*local_ptr != *remote_ptr) {
459 // Track number of bytes that are different
460 different_bytes++;
461 }
462
463 // Independently count the # of dirty pages on the remote side
464 size_t remote_virtual_page_idx = begin / kPageSize;
465 if (previous_page_idx != page_idx) {
466 uint64_t page_count = 0xC0FFEE;
467 // TODO: virtual_page_idx needs to be from the same process
468 int dirtiness = (IsPageDirty(page_map_file.get(), // Image-diff-pid procmap
469 clean_page_map_file.get(), // Self procmap
470 kpage_flags_file.get(),
471 kpage_count_file.get(),
472 remote_virtual_page_idx, // potentially "dirty" page
473 virtual_page_idx, // true "clean" page
474 &page_count,
475 &error_msg));
476 if (dirtiness < 0) {
477 os << error_msg;
478 return false;
479 } else if (dirtiness > 0) {
480 dirty_pages++;
481 dirty_page_set_remote.insert(dirty_page_set_remote.end(), remote_virtual_page_idx);
482 dirty_page_set_local.insert(dirty_page_set_local.end(), virtual_page_idx);
483 }
484
485 bool is_dirty = dirtiness > 0;
486 bool is_private = page_count == 1;
487
488 if (page_count == 1) {
489 private_pages++;
490 }
491
492 if (is_dirty && is_private) {
493 private_dirty_pages++;
494 }
495 }
Igor Murashkin37743352014-11-13 14:38:00 -0800496 }
497
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700498 std::map<mirror::Class*, ClassData> class_data;
499
Igor Murashkin37743352014-11-13 14:38:00 -0800500 // Walk each object in the remote image space and compare it against ours
David Sehr45de57f2017-06-21 05:03:22 +0000501 size_t different_objects = 0;
502
Igor Murashkin37743352014-11-13 14:38:00 -0800503 std::map<off_t /* field offset */, int /* count */> art_method_field_dirty_count;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700504 std::vector<ArtMethod*> art_method_dirty_objects;
Igor Murashkin37743352014-11-13 14:38:00 -0800505
David Sehr45de57f2017-06-21 05:03:22 +0000506 std::map<off_t /* field offset */, int /* count */> class_field_dirty_count;
507 std::vector<mirror::Class*> class_dirty_objects;
Igor Murashkin37743352014-11-13 14:38:00 -0800508
David Sehr45de57f2017-06-21 05:03:22 +0000509 // List of local objects that are clean, but located on dirty pages.
510 std::vector<mirror::Object*> false_dirty_objects;
511 size_t false_dirty_object_bytes = 0;
Igor Murashkin37743352014-11-13 14:38:00 -0800512
Igor Murashkin37743352014-11-13 14:38:00 -0800513 // Look up remote classes by their descriptor
514 std::map<std::string, mirror::Class*> remote_class_map;
515 // Look up local classes by their descriptor
516 std::map<std::string, mirror::Class*> local_class_map;
517
David Sehr45de57f2017-06-21 05:03:22 +0000518 // Image dirty objects
519 // If zygote_pid_only_ == true, these are shared dirty objects in the zygote.
520 // If zygote_pid_only_ == false, these are private dirty objects in the application.
521 std::set<mirror::Object*> image_dirty_objects;
522
523 // Zygote dirty objects (probably private dirty).
524 // We only add objects here if they differed in both the image and the zygote, so
525 // they are probably private dirty.
526 std::set<mirror::Object*> zygote_dirty_objects;
527
528 size_t dirty_object_bytes = 0;
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700529 const uint8_t* begin_image_ptr = image_begin_unaligned;
530 const uint8_t* end_image_ptr = image_mirror_end_unaligned;
Igor Murashkin37743352014-11-13 14:38:00 -0800531
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700532 const uint8_t* current = begin_image_ptr + RoundUp(sizeof(ImageHeader), kObjectAlignment);
533 while (reinterpret_cast<uintptr_t>(current) < reinterpret_cast<uintptr_t>(end_image_ptr)) {
534 CHECK_ALIGNED(current, kObjectAlignment);
535 mirror::Object* obj = reinterpret_cast<mirror::Object*>(const_cast<uint8_t*>(current));
Igor Murashkin37743352014-11-13 14:38:00 -0800536
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700537 // Sanity check that we are reading a real object
538 CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700539 if (kUseBakerReadBarrier) {
540 obj->AssertReadBarrierState();
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700541 }
542
David Sehr45de57f2017-06-21 05:03:22 +0000543 // Iterate every page this object belongs to
544 bool on_dirty_page = false;
545 size_t page_off = 0;
546 size_t current_page_idx;
547 uintptr_t object_address;
548 do {
549 object_address = reinterpret_cast<uintptr_t>(current);
550 current_page_idx = object_address / kPageSize + page_off;
551
552 if (dirty_page_set_local.find(current_page_idx) != dirty_page_set_local.end()) {
553 // This object is on a dirty page
554 on_dirty_page = true;
555 }
556
557 page_off++;
558 } while ((current_page_idx * kPageSize) <
559 RoundUp(object_address + obj->SizeOf(), kObjectAlignment));
560
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700561 mirror::Class* klass = obj->GetClass();
562
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700563 // Check against the other object and see if they are different
564 ptrdiff_t offset = current - begin_image_ptr;
David Sehr45de57f2017-06-21 05:03:22 +0000565 const uint8_t* current_remote = &remote_contents[offset];
566 mirror::Object* remote_obj = reinterpret_cast<mirror::Object*>(
567 const_cast<uint8_t*>(current_remote));
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700568
David Sehr45de57f2017-06-21 05:03:22 +0000569 bool different_image_object = memcmp(current, current_remote, obj->SizeOf()) != 0;
570 if (different_image_object) {
571 bool different_zygote_object = false;
572 if (!zygote_contents.empty()) {
573 const uint8_t* zygote_ptr = &zygote_contents[offset];
574 different_zygote_object = memcmp(current, zygote_ptr, obj->SizeOf()) != 0;
575 }
576 if (different_zygote_object) {
577 // Different from zygote.
578 zygote_dirty_objects.insert(obj);
579 } else {
580 // Just different from image.
581 image_dirty_objects.insert(obj);
582 }
583
584 different_objects++;
585 dirty_object_bytes += obj->SizeOf();
586
587 ++class_data[klass].dirty_object_count;
588
589 // Go byte-by-byte and figure out what exactly got dirtied
590 size_t dirty_byte_count_per_object = 0;
591 for (size_t i = 0; i < obj->SizeOf(); ++i) {
592 if (current[i] != current_remote[i]) {
593 dirty_byte_count_per_object++;
594 }
595 }
596 class_data[klass].dirty_object_byte_count += dirty_byte_count_per_object;
597 class_data[klass].dirty_object_size_in_bytes += obj->SizeOf();
598 class_data[klass].dirty_objects.push_back(remote_obj);
599 } else {
600 ++class_data[klass].clean_object_count;
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700601 }
Igor Murashkin37743352014-11-13 14:38:00 -0800602
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700603 std::string descriptor = GetClassDescriptor(klass);
David Sehr45de57f2017-06-21 05:03:22 +0000604 if (different_image_object) {
605 if (klass->IsClassClass()) {
606 // this is a "Class"
607 mirror::Class* obj_as_class = reinterpret_cast<mirror::Class*>(remote_obj);
608
609 // print the fields that are dirty
610 for (size_t i = 0; i < obj->SizeOf(); ++i) {
611 if (current[i] != current_remote[i]) {
612 class_field_dirty_count[i]++;
613 }
614 }
615
616 class_dirty_objects.push_back(obj_as_class);
617 } else if (strcmp(descriptor.c_str(), "Ljava/lang/reflect/ArtMethod;") == 0) {
618 // this is an ArtMethod
619 ArtMethod* art_method = reinterpret_cast<ArtMethod*>(remote_obj);
620
621 // print the fields that are dirty
622 for (size_t i = 0; i < obj->SizeOf(); ++i) {
623 if (current[i] != current_remote[i]) {
624 art_method_field_dirty_count[i]++;
625 }
626 }
627
628 art_method_dirty_objects.push_back(art_method);
629 }
630 } else if (on_dirty_page) {
631 // This object was either never mutated or got mutated back to the same value.
632 // TODO: Do I want to distinguish a "different" vs a "dirty" page here?
633 false_dirty_objects.push_back(obj);
634 class_data[klass].false_dirty_objects.push_back(obj);
635 false_dirty_object_bytes += obj->SizeOf();
636 class_data[obj->GetClass()].false_dirty_byte_count += obj->SizeOf();
637 class_data[obj->GetClass()].false_dirty_object_count += 1;
638 }
639
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700640 if (strcmp(descriptor.c_str(), "Ljava/lang/Class;") == 0) {
641 local_class_map[descriptor] = reinterpret_cast<mirror::Class*>(obj);
642 remote_class_map[descriptor] = reinterpret_cast<mirror::Class*>(remote_obj);
643 }
644
645 // Unconditionally store the class descriptor in case we need it later
David Sehr45de57f2017-06-21 05:03:22 +0000646 class_data[klass].descriptor = descriptor;
647 current += RoundUp(obj->SizeOf(), kObjectAlignment);
Igor Murashkin37743352014-11-13 14:38:00 -0800648 }
649
650 // Looking at only dirty pages, figure out how many of those bytes belong to dirty objects.
David Sehr45de57f2017-06-21 05:03:22 +0000651 float true_dirtied_percent = dirty_object_bytes * 1.0f / (dirty_pages * kPageSize);
Igor Murashkin37743352014-11-13 14:38:00 -0800652 size_t false_dirty_pages = dirty_pages - different_pages;
653
David Sehr45de57f2017-06-21 05:03:22 +0000654 os << "Mapping at [" << reinterpret_cast<void*>(boot_map.start) << ", "
655 << reinterpret_cast<void*>(boot_map.end) << ") had: \n "
Igor Murashkin37743352014-11-13 14:38:00 -0800656 << different_bytes << " differing bytes, \n "
657 << different_int32s << " differing int32s, \n "
David Sehr45de57f2017-06-21 05:03:22 +0000658 << different_objects << " different objects, \n "
659 << dirty_object_bytes << " different object [bytes], \n "
660 << false_dirty_objects.size() << " false dirty objects,\n "
661 << false_dirty_object_bytes << " false dirty object [bytes], \n "
Igor Murashkin37743352014-11-13 14:38:00 -0800662 << true_dirtied_percent << " different objects-vs-total in a dirty page;\n "
663 << different_pages << " different pages; \n "
664 << dirty_pages << " pages are dirty; \n "
665 << false_dirty_pages << " pages are false dirty; \n "
666 << private_pages << " pages are private; \n "
667 << private_dirty_pages << " pages are Private_Dirty\n "
668 << "";
669
670 // vector of pairs (int count, Class*)
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700671 auto dirty_object_class_values = SortByValueDesc<mirror::Class*, int, ClassData>(
672 class_data, [](const ClassData& d) { return d.dirty_object_count; });
673 auto clean_object_class_values = SortByValueDesc<mirror::Class*, int, ClassData>(
674 class_data, [](const ClassData& d) { return d.clean_object_count; });
Igor Murashkin37743352014-11-13 14:38:00 -0800675
David Sehr45de57f2017-06-21 05:03:22 +0000676 if (!zygote_dirty_objects.empty()) {
David Sehr20e271a2017-06-14 13:02:14 -0700677 // We only reach this point if both pids were specified. Furthermore,
678 // objects are only displayed here if they differed in both the image
679 // and the zygote, so they are probably private dirty.
680 CHECK(image_diff_pid_ > 0 && zygote_diff_pid_ > 0);
681 os << "\n" << " Zygote dirty objects (probably shared dirty): "
David Sehr45de57f2017-06-21 05:03:22 +0000682 << zygote_dirty_objects.size() << "\n";
683 for (mirror::Object* obj : zygote_dirty_objects) {
684 const uint8_t* obj_bytes = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700685 ptrdiff_t offset = obj_bytes - begin_image_ptr;
David Sehr45de57f2017-06-21 05:03:22 +0000686 uint8_t* remote_bytes = &zygote_contents[offset];
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700687 DiffObjectContents(obj, remote_bytes, os);
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700688 }
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700689 }
David Sehr20e271a2017-06-14 13:02:14 -0700690 os << "\n";
691 if (zygote_pid_only_) {
David Sehr41d8eee2017-06-15 11:11:32 -0700692 // image_diff_pid_ is the zygote process.
693 os << " Zygote shared dirty objects: ";
David Sehr20e271a2017-06-14 13:02:14 -0700694 } else {
David Sehr41d8eee2017-06-15 11:11:32 -0700695 // image_diff_pid_ is actually the image (application) process.
696 if (zygote_diff_pid_ > 0) {
697 os << " Application dirty objects (private dirty): ";
698 } else {
699 os << " Application dirty objects (unknown whether private or shared dirty): ";
700 }
David Sehr20e271a2017-06-14 13:02:14 -0700701 }
David Sehr45de57f2017-06-21 05:03:22 +0000702 os << image_dirty_objects.size() << "\n";
703 for (mirror::Object* obj : image_dirty_objects) {
704 const uint8_t* obj_bytes = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700705 ptrdiff_t offset = obj_bytes - begin_image_ptr;
David Sehr45de57f2017-06-21 05:03:22 +0000706 uint8_t* remote_bytes = &remote_contents[offset];
Mathieu Chartierc5196cd2016-04-08 14:08:37 -0700707 DiffObjectContents(obj, remote_bytes, os);
Mathieu Chartiercb044bc2016-04-01 13:56:41 -0700708 }
709
Igor Murashkin37743352014-11-13 14:38:00 -0800710 os << "\n" << " Dirty object count by class:\n";
711 for (const auto& vk_pair : dirty_object_class_values) {
712 int dirty_object_count = vk_pair.first;
713 mirror::Class* klass = vk_pair.second;
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700714 int object_sizes = class_data[klass].dirty_object_size_in_bytes;
715 float avg_dirty_bytes_per_class =
716 class_data[klass].dirty_object_byte_count * 1.0f / object_sizes;
Igor Murashkin37743352014-11-13 14:38:00 -0800717 float avg_object_size = object_sizes * 1.0f / dirty_object_count;
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700718 const std::string& descriptor = class_data[klass].descriptor;
David Sehr709b0702016-10-13 09:12:37 -0700719 os << " " << mirror::Class::PrettyClass(klass) << " ("
Igor Murashkin37743352014-11-13 14:38:00 -0800720 << "objects: " << dirty_object_count << ", "
721 << "avg dirty bytes: " << avg_dirty_bytes_per_class << ", "
722 << "avg object size: " << avg_object_size << ", "
723 << "class descriptor: '" << descriptor << "'"
724 << ")\n";
725
726 constexpr size_t kMaxAddressPrint = 5;
727 if (strcmp(descriptor.c_str(), "Ljava/lang/reflect/ArtMethod;") == 0) {
728 os << " sample object addresses: ";
729 for (size_t i = 0; i < art_method_dirty_objects.size() && i < kMaxAddressPrint; ++i) {
730 auto art_method = art_method_dirty_objects[i];
731
732 os << reinterpret_cast<void*>(art_method) << ", ";
733 }
734 os << "\n";
735
736 os << " dirty byte +offset:count list = ";
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700737 auto art_method_field_dirty_count_sorted =
738 SortByValueDesc<off_t, int, int>(art_method_field_dirty_count);
Igor Murashkin37743352014-11-13 14:38:00 -0800739 for (auto pair : art_method_field_dirty_count_sorted) {
740 off_t offset = pair.second;
741 int count = pair.first;
742
743 os << "+" << offset << ":" << count << ", ";
744 }
745
746 os << "\n";
747
748 os << " field contents:\n";
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700749 const auto& dirty_objects_list = class_data[klass].dirty_objects;
David Sehr45de57f2017-06-21 05:03:22 +0000750 for (mirror::Object* obj : dirty_objects_list) {
Igor Murashkin37743352014-11-13 14:38:00 -0800751 // remote method
Mathieu Chartiere401d142015-04-22 13:56:20 -0700752 auto art_method = reinterpret_cast<ArtMethod*>(obj);
Igor Murashkin37743352014-11-13 14:38:00 -0800753
754 // remote class
755 mirror::Class* remote_declaring_class =
David Sehr45de57f2017-06-21 05:03:22 +0000756 FixUpRemotePointer(art_method->GetDeclaringClass(), remote_contents, boot_map);
Igor Murashkin37743352014-11-13 14:38:00 -0800757
758 // local class
759 mirror::Class* declaring_class =
David Sehr45de57f2017-06-21 05:03:22 +0000760 RemoteContentsPointerToLocal(remote_declaring_class,
761 remote_contents,
762 boot_image_header);
Igor Murashkin37743352014-11-13 14:38:00 -0800763
764 os << " " << reinterpret_cast<void*>(obj) << " ";
765 os << " entryPointFromJni: "
766 << reinterpret_cast<const void*>(
David Sehr45de57f2017-06-21 05:03:22 +0000767 art_method->GetDataPtrSize(pointer_size)) << ", ";
Igor Murashkin37743352014-11-13 14:38:00 -0800768 os << " entryPointFromQuickCompiledCode: "
769 << reinterpret_cast<const void*>(
David Sehr45de57f2017-06-21 05:03:22 +0000770 art_method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size))
Igor Murashkin37743352014-11-13 14:38:00 -0800771 << ", ";
772 os << " isNative? " << (art_method->IsNative() ? "yes" : "no") << ", ";
773 os << " class_status (local): " << declaring_class->GetStatus();
774 os << " class_status (remote): " << remote_declaring_class->GetStatus();
775 os << "\n";
776 }
777 }
778 if (strcmp(descriptor.c_str(), "Ljava/lang/Class;") == 0) {
779 os << " sample object addresses: ";
780 for (size_t i = 0; i < class_dirty_objects.size() && i < kMaxAddressPrint; ++i) {
781 auto class_ptr = class_dirty_objects[i];
782
David Sehr45de57f2017-06-21 05:03:22 +0000783 os << reinterpret_cast<void*>(class_ptr) << ", ";
Igor Murashkin37743352014-11-13 14:38:00 -0800784 }
785 os << "\n";
786
787 os << " dirty byte +offset:count list = ";
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700788 auto class_field_dirty_count_sorted =
David Sehr45de57f2017-06-21 05:03:22 +0000789 SortByValueDesc<off_t, int, int>(class_field_dirty_count);
Igor Murashkin37743352014-11-13 14:38:00 -0800790 for (auto pair : class_field_dirty_count_sorted) {
791 off_t offset = pair.second;
792 int count = pair.first;
793
794 os << "+" << offset << ":" << count << ", ";
795 }
796 os << "\n";
797
798 os << " field contents:\n";
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700799 const auto& dirty_objects_list = class_data[klass].dirty_objects;
David Sehr45de57f2017-06-21 05:03:22 +0000800 for (mirror::Object* obj : dirty_objects_list) {
Igor Murashkin37743352014-11-13 14:38:00 -0800801 // remote class object
802 auto remote_klass = reinterpret_cast<mirror::Class*>(obj);
803
804 // local class object
805 auto local_klass = RemoteContentsPointerToLocal(remote_klass,
David Sehr45de57f2017-06-21 05:03:22 +0000806 remote_contents,
807 boot_image_header);
Igor Murashkin37743352014-11-13 14:38:00 -0800808
David Sehr45de57f2017-06-21 05:03:22 +0000809 os << " " << reinterpret_cast<void*>(obj) << " ";
Igor Murashkin37743352014-11-13 14:38:00 -0800810 os << " class_status (remote): " << remote_klass->GetStatus() << ", ";
811 os << " class_status (local): " << local_klass->GetStatus();
812 os << "\n";
813 }
814 }
815 }
816
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700817 auto false_dirty_object_class_values = SortByValueDesc<mirror::Class*, int, ClassData>(
818 class_data, [](const ClassData& d) { return d.false_dirty_object_count; });
Igor Murashkin37743352014-11-13 14:38:00 -0800819
820 os << "\n" << " False-dirty object count by class:\n";
821 for (const auto& vk_pair : false_dirty_object_class_values) {
822 int object_count = vk_pair.first;
823 mirror::Class* klass = vk_pair.second;
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700824 int object_sizes = class_data[klass].false_dirty_byte_count;
Igor Murashkin37743352014-11-13 14:38:00 -0800825 float avg_object_size = object_sizes * 1.0f / object_count;
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700826 const std::string& descriptor = class_data[klass].descriptor;
David Sehr709b0702016-10-13 09:12:37 -0700827 os << " " << mirror::Class::PrettyClass(klass) << " ("
Igor Murashkin37743352014-11-13 14:38:00 -0800828 << "objects: " << object_count << ", "
829 << "avg object size: " << avg_object_size << ", "
830 << "total bytes: " << object_sizes << ", "
831 << "class descriptor: '" << descriptor << "'"
832 << ")\n";
833
834 if (strcmp(descriptor.c_str(), "Ljava/lang/reflect/ArtMethod;") == 0) {
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700835 auto& art_method_false_dirty_objects = class_data[klass].false_dirty_objects;
Igor Murashkin37743352014-11-13 14:38:00 -0800836
837 os << " field contents:\n";
David Sehr45de57f2017-06-21 05:03:22 +0000838 for (mirror::Object* obj : art_method_false_dirty_objects) {
Igor Murashkin37743352014-11-13 14:38:00 -0800839 // local method
Mathieu Chartiere401d142015-04-22 13:56:20 -0700840 auto art_method = reinterpret_cast<ArtMethod*>(obj);
Igor Murashkin37743352014-11-13 14:38:00 -0800841
842 // local class
843 mirror::Class* declaring_class = art_method->GetDeclaringClass();
844
David Sehr45de57f2017-06-21 05:03:22 +0000845 os << " " << reinterpret_cast<void*>(obj) << " ";
Igor Murashkin37743352014-11-13 14:38:00 -0800846 os << " entryPointFromJni: "
847 << reinterpret_cast<const void*>(
David Sehr45de57f2017-06-21 05:03:22 +0000848 art_method->GetDataPtrSize(pointer_size)) << ", ";
Igor Murashkin37743352014-11-13 14:38:00 -0800849 os << " entryPointFromQuickCompiledCode: "
850 << reinterpret_cast<const void*>(
David Sehr45de57f2017-06-21 05:03:22 +0000851 art_method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size))
Igor Murashkin37743352014-11-13 14:38:00 -0800852 << ", ";
853 os << " isNative? " << (art_method->IsNative() ? "yes" : "no") << ", ";
854 os << " class_status (local): " << declaring_class->GetStatus();
855 os << "\n";
856 }
857 }
858 }
859
860 os << "\n" << " Clean object count by class:\n";
861 for (const auto& vk_pair : clean_object_class_values) {
David Sehr709b0702016-10-13 09:12:37 -0700862 os << " " << mirror::Class::PrettyClass(vk_pair.second) << " (" << vk_pair.first << ")\n";
Igor Murashkin37743352014-11-13 14:38:00 -0800863 }
864
865 return true;
866 }
867
868 // Fixup a remote pointer that we read from a foreign boot.art to point to our own memory.
869 // Returned pointer will point to inside of remote_contents.
870 template <typename T>
871 static T* FixUpRemotePointer(T* remote_ptr,
872 std::vector<uint8_t>& remote_contents,
873 const backtrace_map_t& boot_map) {
874 if (remote_ptr == nullptr) {
875 return nullptr;
876 }
877
878 uintptr_t remote = reinterpret_cast<uintptr_t>(remote_ptr);
879
880 CHECK_LE(boot_map.start, remote);
881 CHECK_GT(boot_map.end, remote);
882
883 off_t boot_offset = remote - boot_map.start;
884
885 return reinterpret_cast<T*>(&remote_contents[boot_offset]);
886 }
887
888 template <typename T>
889 static T* RemoteContentsPointerToLocal(T* remote_ptr,
890 std::vector<uint8_t>& remote_contents,
891 const ImageHeader& image_header) {
892 if (remote_ptr == nullptr) {
893 return nullptr;
894 }
895
896 uint8_t* remote = reinterpret_cast<uint8_t*>(remote_ptr);
897 ptrdiff_t boot_offset = remote - &remote_contents[0];
898
899 const uint8_t* local_ptr = reinterpret_cast<const uint8_t*>(&image_header) + boot_offset;
900
901 return reinterpret_cast<T*>(const_cast<uint8_t*>(local_ptr));
902 }
903
904 static std::string GetClassDescriptor(mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700905 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin37743352014-11-13 14:38:00 -0800906 CHECK(klass != nullptr);
907
908 std::string descriptor;
909 const char* descriptor_str = klass->GetDescriptor(&descriptor);
910
911 return std::string(descriptor_str);
912 }
913
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700914 template <typename K, typename V, typename D>
915 static std::vector<std::pair<V, K>> SortByValueDesc(
916 const std::map<K, D> map,
917 std::function<V(const D&)> value_mapper = [](const D& d) { return static_cast<V>(d); }) {
Igor Murashkin37743352014-11-13 14:38:00 -0800918 // Store value->key so that we can use the default sort from pair which
919 // sorts by value first and then key
920 std::vector<std::pair<V, K>> value_key_vector;
921
922 for (const auto& kv_pair : map) {
Andreas Gampe7ad71d02016-04-04 13:49:18 -0700923 value_key_vector.push_back(std::make_pair(value_mapper(kv_pair.second), kv_pair.first));
Igor Murashkin37743352014-11-13 14:38:00 -0800924 }
925
926 // Sort in reverse (descending order)
927 std::sort(value_key_vector.rbegin(), value_key_vector.rend());
928 return value_key_vector;
929 }
930
931 static bool GetPageFrameNumber(File* page_map_file,
932 size_t virtual_page_index,
933 uint64_t* page_frame_number,
934 std::string* error_msg) {
935 CHECK(page_map_file != nullptr);
936 CHECK(page_frame_number != nullptr);
937 CHECK(error_msg != nullptr);
938
939 constexpr size_t kPageMapEntrySize = sizeof(uint64_t);
940 constexpr uint64_t kPageFrameNumberMask = (1ULL << 55) - 1; // bits 0-54 [in /proc/$pid/pagemap]
941 constexpr uint64_t kPageSoftDirtyMask = (1ULL << 55); // bit 55 [in /proc/$pid/pagemap]
942
943 uint64_t page_map_entry = 0;
944
945 // Read 64-bit entry from /proc/$pid/pagemap to get the physical page frame number
946 if (!page_map_file->PreadFully(&page_map_entry, kPageMapEntrySize,
947 virtual_page_index * kPageMapEntrySize)) {
948 *error_msg = StringPrintf("Failed to read the virtual page index entry from %s",
949 page_map_file->GetPath().c_str());
950 return false;
951 }
952
953 // TODO: seems useless, remove this.
954 bool soft_dirty = (page_map_entry & kPageSoftDirtyMask) != 0;
955 if ((false)) {
956 LOG(VERBOSE) << soft_dirty; // Suppress unused warning
957 UNREACHABLE();
958 }
959
960 *page_frame_number = page_map_entry & kPageFrameNumberMask;
961
962 return true;
963 }
964
965 static int IsPageDirty(File* page_map_file,
David Sehr45de57f2017-06-21 05:03:22 +0000966 File* clean_page_map_file,
967 File* kpage_flags_file,
968 File* kpage_count_file,
Igor Murashkin37743352014-11-13 14:38:00 -0800969 size_t virtual_page_idx,
970 size_t clean_virtual_page_idx,
971 // Out parameters:
972 uint64_t* page_count, std::string* error_msg) {
973 CHECK(page_map_file != nullptr);
David Sehr45de57f2017-06-21 05:03:22 +0000974 CHECK(clean_page_map_file != nullptr);
975 CHECK_NE(page_map_file, clean_page_map_file);
976 CHECK(kpage_flags_file != nullptr);
977 CHECK(kpage_count_file != nullptr);
Igor Murashkin37743352014-11-13 14:38:00 -0800978 CHECK(page_count != nullptr);
979 CHECK(error_msg != nullptr);
980
981 // Constants are from https://www.kernel.org/doc/Documentation/vm/pagemap.txt
982
983 constexpr size_t kPageFlagsEntrySize = sizeof(uint64_t);
984 constexpr size_t kPageCountEntrySize = sizeof(uint64_t);
985 constexpr uint64_t kPageFlagsDirtyMask = (1ULL << 4); // in /proc/kpageflags
986 constexpr uint64_t kPageFlagsNoPageMask = (1ULL << 20); // in /proc/kpageflags
987 constexpr uint64_t kPageFlagsMmapMask = (1ULL << 11); // in /proc/kpageflags
988
989 uint64_t page_frame_number = 0;
990 if (!GetPageFrameNumber(page_map_file, virtual_page_idx, &page_frame_number, error_msg)) {
991 return -1;
992 }
993
994 uint64_t page_frame_number_clean = 0;
David Sehr45de57f2017-06-21 05:03:22 +0000995 if (!GetPageFrameNumber(clean_page_map_file, clean_virtual_page_idx, &page_frame_number_clean,
Igor Murashkin37743352014-11-13 14:38:00 -0800996 error_msg)) {
997 return -1;
998 }
999
1000 // Read 64-bit entry from /proc/kpageflags to get the dirty bit for a page
1001 uint64_t kpage_flags_entry = 0;
David Sehr45de57f2017-06-21 05:03:22 +00001002 if (!kpage_flags_file->PreadFully(&kpage_flags_entry,
Igor Murashkin37743352014-11-13 14:38:00 -08001003 kPageFlagsEntrySize,
1004 page_frame_number * kPageFlagsEntrySize)) {
1005 *error_msg = StringPrintf("Failed to read the page flags from %s",
David Sehr45de57f2017-06-21 05:03:22 +00001006 kpage_flags_file->GetPath().c_str());
Igor Murashkin37743352014-11-13 14:38:00 -08001007 return -1;
1008 }
1009
1010 // Read 64-bit entyry from /proc/kpagecount to get mapping counts for a page
David Sehr45de57f2017-06-21 05:03:22 +00001011 if (!kpage_count_file->PreadFully(page_count /*out*/,
Igor Murashkin37743352014-11-13 14:38:00 -08001012 kPageCountEntrySize,
1013 page_frame_number * kPageCountEntrySize)) {
1014 *error_msg = StringPrintf("Failed to read the page count from %s",
David Sehr45de57f2017-06-21 05:03:22 +00001015 kpage_count_file->GetPath().c_str());
Igor Murashkin37743352014-11-13 14:38:00 -08001016 return -1;
1017 }
1018
1019 // There must be a page frame at the requested address.
1020 CHECK_EQ(kpage_flags_entry & kPageFlagsNoPageMask, 0u);
1021 // The page frame must be memory mapped
1022 CHECK_NE(kpage_flags_entry & kPageFlagsMmapMask, 0u);
1023
1024 // Page is dirty, i.e. has diverged from file, if the 4th bit is set to 1
1025 bool flags_dirty = (kpage_flags_entry & kPageFlagsDirtyMask) != 0;
1026
1027 // page_frame_number_clean must come from the *same* process
1028 // but a *different* mmap than page_frame_number
1029 if (flags_dirty) {
1030 CHECK_NE(page_frame_number, page_frame_number_clean);
1031 }
1032
1033 return page_frame_number != page_frame_number_clean;
1034 }
1035
David Sehr45de57f2017-06-21 05:03:22 +00001036 private:
Igor Murashkin37743352014-11-13 14:38:00 -08001037 // Return the image location, stripped of any directories, e.g. "boot.art" or "core.art"
1038 std::string GetImageLocationBaseName() const {
1039 return BaseName(std::string(image_location_));
1040 }
1041
1042 std::ostream* os_;
1043 const ImageHeader& image_header_;
Andreas Gampe8994a042015-12-30 19:03:17 +00001044 const std::string image_location_;
Igor Murashkin37743352014-11-13 14:38:00 -08001045 pid_t image_diff_pid_; // Dump image diff against boot.art if pid is non-negative
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001046 pid_t zygote_diff_pid_; // Dump image diff against zygote boot.art if pid is non-negative
David Sehr20e271a2017-06-14 13:02:14 -07001047 bool zygote_pid_only_; // The user only specified a pid for the zygote.
Igor Murashkin37743352014-11-13 14:38:00 -08001048
1049 DISALLOW_COPY_AND_ASSIGN(ImgDiagDumper);
1050};
1051
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001052static int DumpImage(Runtime* runtime,
1053 std::ostream* os,
1054 pid_t image_diff_pid,
1055 pid_t zygote_diff_pid) {
Igor Murashkin37743352014-11-13 14:38:00 -08001056 ScopedObjectAccess soa(Thread::Current());
1057 gc::Heap* heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001058 std::vector<gc::space::ImageSpace*> image_spaces = heap->GetBootImageSpaces();
1059 CHECK(!image_spaces.empty());
1060 for (gc::space::ImageSpace* image_space : image_spaces) {
1061 const ImageHeader& image_header = image_space->GetImageHeader();
1062 if (!image_header.IsValid()) {
1063 fprintf(stderr, "Invalid image header %s\n", image_space->GetImageLocation().c_str());
1064 return EXIT_FAILURE;
1065 }
1066
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001067 ImgDiagDumper img_diag_dumper(os,
1068 image_header,
1069 image_space->GetImageLocation(),
1070 image_diff_pid,
1071 zygote_diff_pid);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001072 if (!img_diag_dumper.Dump()) {
1073 return EXIT_FAILURE;
1074 }
Igor Murashkin37743352014-11-13 14:38:00 -08001075 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001076 return EXIT_SUCCESS;
Igor Murashkin37743352014-11-13 14:38:00 -08001077}
1078
1079struct ImgDiagArgs : public CmdlineArgs {
1080 protected:
1081 using Base = CmdlineArgs;
1082
1083 virtual ParseStatus ParseCustom(const StringPiece& option,
1084 std::string* error_msg) OVERRIDE {
1085 {
1086 ParseStatus base_parse = Base::ParseCustom(option, error_msg);
1087 if (base_parse != kParseUnknownArgument) {
1088 return base_parse;
1089 }
1090 }
1091
1092 if (option.starts_with("--image-diff-pid=")) {
1093 const char* image_diff_pid = option.substr(strlen("--image-diff-pid=")).data();
1094
1095 if (!ParseInt(image_diff_pid, &image_diff_pid_)) {
1096 *error_msg = "Image diff pid out of range";
1097 return kParseError;
1098 }
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001099 } else if (option.starts_with("--zygote-diff-pid=")) {
1100 const char* zygote_diff_pid = option.substr(strlen("--zygote-diff-pid=")).data();
1101
1102 if (!ParseInt(zygote_diff_pid, &zygote_diff_pid_)) {
1103 *error_msg = "Zygote diff pid out of range";
1104 return kParseError;
1105 }
Igor Murashkin37743352014-11-13 14:38:00 -08001106 } else {
1107 return kParseUnknownArgument;
1108 }
1109
1110 return kParseOk;
1111 }
1112
1113 virtual ParseStatus ParseChecks(std::string* error_msg) OVERRIDE {
1114 // Perform the parent checks.
1115 ParseStatus parent_checks = Base::ParseChecks(error_msg);
1116 if (parent_checks != kParseOk) {
1117 return parent_checks;
1118 }
1119
1120 // Perform our own checks.
1121
1122 if (kill(image_diff_pid_,
1123 /*sig*/0) != 0) { // No signal is sent, perform error-checking only.
1124 // Check if the pid exists before proceeding.
1125 if (errno == ESRCH) {
1126 *error_msg = "Process specified does not exist";
1127 } else {
1128 *error_msg = StringPrintf("Failed to check process status: %s", strerror(errno));
1129 }
1130 return kParseError;
1131 } else if (instruction_set_ != kRuntimeISA) {
1132 // Don't allow different ISAs since the images are ISA-specific.
1133 // Right now the code assumes both the runtime ISA and the remote ISA are identical.
1134 *error_msg = "Must use the default runtime ISA; changing ISA is not supported.";
1135 return kParseError;
1136 }
1137
1138 return kParseOk;
1139 }
1140
1141 virtual std::string GetUsage() const {
1142 std::string usage;
1143
1144 usage +=
1145 "Usage: imgdiag [options] ...\n"
1146 " Example: imgdiag --image-diff-pid=$(pidof dex2oat)\n"
1147 " Example: adb shell imgdiag --image-diff-pid=$(pid zygote)\n"
1148 "\n";
1149
1150 usage += Base::GetUsage();
1151
1152 usage += // Optional.
1153 " --image-diff-pid=<pid>: provide the PID of a process whose boot.art you want to diff.\n"
1154 " Example: --image-diff-pid=$(pid zygote)\n"
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001155 " --zygote-diff-pid=<pid>: provide the PID of the zygote whose boot.art you want to diff "
1156 "against.\n"
1157 " Example: --zygote-diff-pid=$(pid zygote)\n"
Igor Murashkin37743352014-11-13 14:38:00 -08001158 "\n";
1159
1160 return usage;
1161 }
1162
1163 public:
1164 pid_t image_diff_pid_ = -1;
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001165 pid_t zygote_diff_pid_ = -1;
Igor Murashkin37743352014-11-13 14:38:00 -08001166};
1167
1168struct ImgDiagMain : public CmdlineMain<ImgDiagArgs> {
1169 virtual bool ExecuteWithRuntime(Runtime* runtime) {
1170 CHECK(args_ != nullptr);
1171
1172 return DumpImage(runtime,
Igor Murashkin37743352014-11-13 14:38:00 -08001173 args_->os_,
Mathieu Chartierc5196cd2016-04-08 14:08:37 -07001174 args_->image_diff_pid_,
1175 args_->zygote_diff_pid_) == EXIT_SUCCESS;
Igor Murashkin37743352014-11-13 14:38:00 -08001176 }
1177};
1178
1179} // namespace art
1180
1181int main(int argc, char** argv) {
1182 art::ImgDiagMain main;
1183 return main.Main(argc, argv);
1184}