1 /*
2 * Copyright (C) 2017 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 <errno.h>
18 #include <inttypes.h>
19 #include <stdint.h>
20 #include <stdlib.h>
21 #include <string.h>
22
23 #include <iostream>
24 #include <memory>
25 #include <string>
26 #include <string_view>
27 #include <vector>
28
29 #include "android-base/stringprintf.h"
30
31 #include "base/logging.h" // For InitLogging.
32 #include "base/string_view_cpp20.h"
33
34 #include "dexlayout.h"
35 #include "dex/dex_file.h"
36 #include "dex_ir.h"
37 #include "dex_ir_builder.h"
38 #ifdef ART_TARGET_ANDROID
39 #include <meminfo/pageacct.h>
40 #include <meminfo/procmeminfo.h>
41 #endif
42 #include "vdex_file.h"
43
44 namespace art {
45
46 using android::base::StringPrintf;
47 #ifdef ART_TARGET_ANDROID
48 using android::meminfo::ProcMemInfo;
49 using android::meminfo::Vma;
50 #endif
51
52 static bool g_verbose = false;
53
54 // The width needed to print a file page offset (32-bit).
55 static constexpr int kPageCountWidth =
56 static_cast<int>(std::numeric_limits<uint32_t>::digits10);
57 // Display the sections.
58 static constexpr char kSectionHeader[] = "Section name";
59
60 struct DexSectionInfo {
61 public:
62 std::string name;
63 char letter;
64 };
65
66 static const std::map<uint16_t, DexSectionInfo> kDexSectionInfoMap = {
67 { DexFile::kDexTypeHeaderItem, { "Header", 'H' } },
68 { DexFile::kDexTypeStringIdItem, { "StringId", 'S' } },
69 { DexFile::kDexTypeTypeIdItem, { "TypeId", 'T' } },
70 { DexFile::kDexTypeProtoIdItem, { "ProtoId", 'P' } },
71 { DexFile::kDexTypeFieldIdItem, { "FieldId", 'F' } },
72 { DexFile::kDexTypeMethodIdItem, { "MethodId", 'M' } },
73 { DexFile::kDexTypeClassDefItem, { "ClassDef", 'C' } },
74 { DexFile::kDexTypeCallSiteIdItem, { "CallSiteId", 'z' } },
75 { DexFile::kDexTypeMethodHandleItem, { "MethodHandle", 'Z' } },
76 { DexFile::kDexTypeMapList, { "TypeMap", 'L' } },
77 { DexFile::kDexTypeTypeList, { "TypeList", 't' } },
78 { DexFile::kDexTypeAnnotationSetRefList, { "AnnotationSetReferenceItem", '1' } },
79 { DexFile::kDexTypeAnnotationSetItem, { "AnnotationSetItem", '2' } },
80 { DexFile::kDexTypeClassDataItem, { "ClassData", 'c' } },
81 { DexFile::kDexTypeCodeItem, { "CodeItem", 'X' } },
82 { DexFile::kDexTypeStringDataItem, { "StringData", 's' } },
83 { DexFile::kDexTypeDebugInfoItem, { "DebugInfo", 'D' } },
84 { DexFile::kDexTypeAnnotationItem, { "AnnotationItem", '3' } },
85 { DexFile::kDexTypeEncodedArrayItem, { "EncodedArrayItem", 'E' } },
86 { DexFile::kDexTypeAnnotationsDirectoryItem, { "AnnotationsDirectoryItem", '4' } }
87 };
88
89 class PageCount {
90 public:
PageCount()91 PageCount() {
92 for (auto it = kDexSectionInfoMap.begin(); it != kDexSectionInfoMap.end(); ++it) {
93 map_[it->first] = 0;
94 }
95 }
Increment(uint16_t type)96 void Increment(uint16_t type) {
97 map_[type]++;
98 }
Get(uint16_t type) const99 size_t Get(uint16_t type) const {
100 auto it = map_.find(type);
101 DCHECK(it != map_.end());
102 return it->second;
103 }
104 private:
105 std::map<uint16_t, size_t> map_;
106 DISALLOW_COPY_AND_ASSIGN(PageCount);
107 };
108
109 class Printer {
110 public:
Printer()111 Printer() : section_header_width_(ComputeHeaderWidth()) {
112 }
113
PrintHeader() const114 void PrintHeader() const {
115 std::cout << StringPrintf("%-*s %*s %*s %% of %% of",
116 section_header_width_,
117 kSectionHeader,
118 kPageCountWidth,
119 "resident",
120 kPageCountWidth,
121 "total"
122 )
123 << std::endl;
124 std::cout << StringPrintf("%-*s %*s %*s sect. total",
125 section_header_width_,
126 "",
127 kPageCountWidth,
128 "pages",
129 kPageCountWidth,
130 "pages")
131 << std::endl;
132 }
133
PrintOne(const char * name,size_t resident,size_t mapped,double percent_of_section,double percent_of_total) const134 void PrintOne(const char* name,
135 size_t resident,
136 size_t mapped,
137 double percent_of_section,
138 double percent_of_total) const {
139 // 6.2 is sufficient to print 0-100% with two decimal places of accuracy.
140 std::cout << StringPrintf("%-*s %*zd %*zd %6.2f %6.2f",
141 section_header_width_,
142 name,
143 kPageCountWidth,
144 resident,
145 kPageCountWidth,
146 mapped,
147 percent_of_section,
148 percent_of_total)
149 << std::endl;
150 }
151
PrintSkipLine() const152 void PrintSkipLine() const { std::cout << std::endl; }
153
154 // Computes the width of the section header column in the table (for fixed formatting).
ComputeHeaderWidth()155 static int ComputeHeaderWidth() {
156 int header_width = 0;
157 for (const auto& pair : kDexSectionInfoMap) {
158 const DexSectionInfo& section_info = pair.second;
159 header_width = std::max(header_width, static_cast<int>(section_info.name.length()));
160 }
161 return header_width;
162 }
163
164 private:
165 const int section_header_width_;
166 };
167
PrintLetterKey()168 static void PrintLetterKey() {
169 std::cout << "L pagetype" << std::endl;
170 for (const auto& pair : kDexSectionInfoMap) {
171 const DexSectionInfo& section_info = pair.second;
172 std::cout << section_info.letter << " " << section_info.name.c_str() << std::endl;
173 }
174 std::cout << "* (Executable page resident)" << std::endl;
175 std::cout << ". (Mapped page not resident)" << std::endl;
176 }
177
178 #ifdef ART_TARGET_ANDROID
PageTypeChar(uint16_t type)179 static char PageTypeChar(uint16_t type) {
180 if (kDexSectionInfoMap.find(type) == kDexSectionInfoMap.end()) {
181 return '-';
182 }
183 return kDexSectionInfoMap.find(type)->second.letter;
184 }
185
FindSectionTypeForPage(size_t page,const std::vector<dex_ir::DexFileSection> & sections)186 static uint16_t FindSectionTypeForPage(size_t page,
187 const std::vector<dex_ir::DexFileSection>& sections) {
188 for (const auto& section : sections) {
189 size_t first_page_of_section = section.offset / kPageSize;
190 // Only consider non-empty sections.
191 if (section.size == 0) {
192 continue;
193 }
194 // Attribute the page to the highest-offset section that starts before the page.
195 if (first_page_of_section <= page) {
196 return section.type;
197 }
198 }
199 // If there's no non-zero sized section with an offset below offset we're looking for, it
200 // must be the header.
201 return DexFile::kDexTypeHeaderItem;
202 }
203
ProcessPageMap(const std::vector<uint64_t> & pagemap,size_t start,size_t end,const std::vector<dex_ir::DexFileSection> & sections,PageCount * page_counts)204 static void ProcessPageMap(const std::vector<uint64_t>& pagemap,
205 size_t start,
206 size_t end,
207 const std::vector<dex_ir::DexFileSection>& sections,
208 PageCount* page_counts) {
209 static constexpr size_t kLineLength = 32;
210 for (size_t page = start; page < end; ++page) {
211 char type_char = '.';
212 if (::android::meminfo::page_present(pagemap[page])) {
213 const size_t dex_page_offset = page - start;
214 uint16_t type = FindSectionTypeForPage(dex_page_offset, sections);
215 page_counts->Increment(type);
216 type_char = PageTypeChar(type);
217 }
218 if (g_verbose) {
219 std::cout << type_char;
220 if ((page - start) % kLineLength == kLineLength - 1) {
221 std::cout << std::endl;
222 }
223 }
224 }
225 if (g_verbose) {
226 if ((end - start) % kLineLength != 0) {
227 std::cout << std::endl;
228 }
229 }
230 }
231
DisplayDexStatistics(size_t start,size_t end,const PageCount & resident_pages,const std::vector<dex_ir::DexFileSection> & sections,Printer * printer)232 static void DisplayDexStatistics(size_t start,
233 size_t end,
234 const PageCount& resident_pages,
235 const std::vector<dex_ir::DexFileSection>& sections,
236 Printer* printer) {
237 // Compute the total possible sizes for sections.
238 PageCount mapped_pages;
239 DCHECK_GE(end, start);
240 size_t total_mapped_pages = end - start;
241 if (total_mapped_pages == 0) {
242 return;
243 }
244 for (size_t page = start; page < end; ++page) {
245 const size_t dex_page_offset = page - start;
246 mapped_pages.Increment(FindSectionTypeForPage(dex_page_offset, sections));
247 }
248 size_t total_resident_pages = 0;
249 printer->PrintHeader();
250 for (size_t i = sections.size(); i > 0; --i) {
251 const dex_ir::DexFileSection& section = sections[i - 1];
252 const uint16_t type = section.type;
253 const DexSectionInfo& section_info = kDexSectionInfoMap.find(type)->second;
254 size_t pages_resident = resident_pages.Get(type);
255 double percent_resident = 0;
256 if (mapped_pages.Get(type) > 0) {
257 percent_resident = 100.0 * pages_resident / mapped_pages.Get(type);
258 }
259 printer->PrintOne(section_info.name.c_str(),
260 pages_resident,
261 mapped_pages.Get(type),
262 percent_resident,
263 100.0 * pages_resident / total_mapped_pages);
264 total_resident_pages += pages_resident;
265 }
266 double percent_of_total = 100.0 * total_resident_pages / total_mapped_pages;
267 printer->PrintOne("GRAND TOTAL",
268 total_resident_pages,
269 total_mapped_pages,
270 percent_of_total,
271 percent_of_total);
272 printer->PrintSkipLine();
273 }
274
ProcessOneDexMapping(const std::vector<uint64_t> & pagemap,uint64_t map_start,const DexFile * dex_file,uint64_t vdex_start,Printer * printer)275 static void ProcessOneDexMapping(const std::vector<uint64_t>& pagemap,
276 uint64_t map_start,
277 const DexFile* dex_file,
278 uint64_t vdex_start,
279 Printer* printer) {
280 uint64_t dex_file_start = reinterpret_cast<uint64_t>(dex_file->Begin());
281 size_t dex_file_size = dex_file->Size();
282 if (dex_file_start < vdex_start) {
283 std::cerr << "Dex file start offset for "
284 << dex_file->GetLocation().c_str()
285 << " is incorrect: map start "
286 << StringPrintf("%" PRIx64 " > dex start %" PRIx64 "\n", map_start, dex_file_start)
287 << std::endl;
288 return;
289 }
290 uint64_t start_page = (dex_file_start - vdex_start) / kPageSize;
291 uint64_t start_address = start_page * kPageSize;
292 uint64_t end_page = RoundUp(start_address + dex_file_size, kPageSize) / kPageSize;
293 std::cout << "DEX "
294 << dex_file->GetLocation().c_str()
295 << StringPrintf(": %" PRIx64 "-%" PRIx64,
296 map_start + start_page * kPageSize,
297 map_start + end_page * kPageSize)
298 << std::endl;
299 // Build a list of the dex file section types, sorted from highest offset to lowest.
300 std::vector<dex_ir::DexFileSection> sections;
301 {
302 Options options;
303 std::unique_ptr<dex_ir::Header> header(dex_ir::DexIrBuilder(*dex_file,
304 /*eagerly_assign_offsets=*/ true,
305 options));
306 sections = dex_ir::GetSortedDexFileSections(header.get(),
307 dex_ir::SortDirection::kSortDescending);
308 }
309 PageCount section_resident_pages;
310 ProcessPageMap(pagemap, start_page, end_page, sections, §ion_resident_pages);
311 DisplayDexStatistics(start_page, end_page, section_resident_pages, sections, printer);
312 }
313
IsVdexFileMapping(const std::string & mapped_name)314 static bool IsVdexFileMapping(const std::string& mapped_name) {
315 // Confirm that the map is from a vdex file.
316 static const char* suffixes[] = { ".vdex" };
317 for (const char* suffix : suffixes) {
318 size_t match_loc = mapped_name.find(suffix);
319 if (match_loc != std::string::npos && mapped_name.length() == match_loc + strlen(suffix)) {
320 return true;
321 }
322 }
323 return false;
324 }
325
DisplayMappingIfFromVdexFile(ProcMemInfo & proc,const Vma & vma,Printer * printer)326 static bool DisplayMappingIfFromVdexFile(ProcMemInfo& proc, const Vma& vma, Printer* printer) {
327 std::string vdex_name = vma.name;
328 // Extract all the dex files from the vdex file.
329 std::string error_msg;
330 std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_name,
331 /*writable=*/ false,
332 /*low_4gb=*/ false,
333 &error_msg /*out*/));
334 if (vdex == nullptr) {
335 std::cerr << "Could not open vdex file "
336 << vdex_name
337 << ": error "
338 << error_msg
339 << std::endl;
340 return false;
341 }
342
343 std::vector<std::unique_ptr<const DexFile>> dex_files;
344 if (!vdex->OpenAllDexFiles(&dex_files, &error_msg)) {
345 std::cerr << "Dex files could not be opened for "
346 << vdex_name
347 << ": error "
348 << error_msg
349 << std::endl;
350 return false;
351 }
352 // Open the page mapping (one uint64_t per page) for the entire vdex mapping.
353 std::vector<uint64_t> pagemap;
354 if (!proc.PageMap(vma, &pagemap)) {
355 std::cerr << "Error creating pagemap." << std::endl;
356 return false;
357 }
358 // Process the dex files.
359 std::cout << "MAPPING "
360 << vma.name
361 << StringPrintf(": %" PRIx64 "-%" PRIx64, vma.start, vma.end)
362 << std::endl;
363 for (const auto& dex_file : dex_files) {
364 ProcessOneDexMapping(pagemap,
365 vma.start,
366 dex_file.get(),
367 reinterpret_cast<uint64_t>(vdex->Begin()),
368 printer);
369 }
370 return true;
371 }
372
ProcessOneOatMapping(const std::vector<uint64_t> & pagemap,Printer * printer)373 static void ProcessOneOatMapping(const std::vector<uint64_t>& pagemap,
374 Printer* printer) {
375 static constexpr size_t kLineLength = 32;
376 size_t resident_page_count = 0;
377 for (size_t page = 0; page < pagemap.size(); ++page) {
378 char type_char = '.';
379 if (::android::meminfo::page_present(pagemap[page])) {
380 ++resident_page_count;
381 type_char = '*';
382 }
383 if (g_verbose) {
384 std::cout << type_char;
385 if (page % kLineLength == kLineLength - 1) {
386 std::cout << std::endl;
387 }
388 }
389 }
390 if (g_verbose) {
391 if (pagemap.size() % kLineLength != 0) {
392 std::cout << std::endl;
393 }
394 }
395 double percent_of_total = 100.0 * resident_page_count / pagemap.size();
396 printer->PrintHeader();
397 printer->PrintOne("EXECUTABLE", resident_page_count, pagemap.size(), percent_of_total, percent_of_total);
398 printer->PrintSkipLine();
399 }
400
IsOatFileMapping(const std::string & mapped_name)401 static bool IsOatFileMapping(const std::string& mapped_name) {
402 // Confirm that the map is from an oat file.
403 static const char* suffixes[] = { ".odex", ".oat" };
404 for (const char* suffix : suffixes) {
405 size_t match_loc = mapped_name.find(suffix);
406 if (match_loc != std::string::npos && mapped_name.length() == match_loc + strlen(suffix)) {
407 return true;
408 }
409 }
410 return false;
411 }
412
DisplayMappingIfFromOatFile(ProcMemInfo & proc,const Vma & vma,Printer * printer)413 static bool DisplayMappingIfFromOatFile(ProcMemInfo& proc, const Vma& vma, Printer* printer) {
414 // Open the page mapping (one uint64_t per page) for the entire vdex mapping.
415 std::vector<uint64_t> pagemap;
416 if (!proc.PageMap(vma, &pagemap) != 0) {
417 std::cerr << "Error creating pagemap." << std::endl;
418 return false;
419 }
420 // Process the dex files.
421 std::cout << "MAPPING "
422 << vma.name
423 << StringPrintf(": %" PRIx64 "-%" PRIx64, vma.start, vma.end)
424 << std::endl;
425 ProcessOneOatMapping(pagemap, printer);
426 return true;
427 }
428
FilterByNameContains(const std::string & mapped_file_name,const std::vector<std::string> & name_filters)429 static bool FilterByNameContains(const std::string& mapped_file_name,
430 const std::vector<std::string>& name_filters) {
431 // If no filters were set, everything matches.
432 if (name_filters.empty()) {
433 return true;
434 }
435 for (const auto& name_contains : name_filters) {
436 if (mapped_file_name.find(name_contains) != std::string::npos) {
437 return true;
438 }
439 }
440 return false;
441 }
442 #endif
443
Usage(const char * cmd)444 static void Usage(const char* cmd) {
445 std::cout << "Usage: " << cmd << " [options] pid" << std::endl
446 << " --contains=<string>: Display sections containing string." << std::endl
447 << " --help: Shows this message." << std::endl
448 << " --verbose: Makes displays verbose." << std::endl;
449 PrintLetterKey();
450 }
451
Abort(const char * msg)452 NO_RETURN static void Abort(const char* msg) {
453 std::cerr << msg;
454 exit(1);
455 }
456
DexDiagMain(int argc,char * argv[])457 static int DexDiagMain(int argc, char* argv[]) {
458 if (argc < 2) {
459 Usage(argv[0]);
460 return EXIT_FAILURE;
461 }
462
463 std::vector<std::string> name_filters;
464 // TODO: add option to track usage by class name, etc.
465 for (int i = 1; i < argc - 1; ++i) {
466 const std::string_view option(argv[i]);
467 if (option == "--help") {
468 Usage(argv[0]);
469 return EXIT_SUCCESS;
470 } else if (option == "--verbose") {
471 g_verbose = true;
472 } else if (StartsWith(option, "--contains=")) {
473 std::string contains(option.substr(strlen("--contains=")));
474 name_filters.push_back(contains);
475 } else {
476 Usage(argv[0]);
477 return EXIT_FAILURE;
478 }
479 }
480
481 // Art specific set up.
482 InitLogging(argv, Abort);
483 MemMap::Init();
484
485 #ifdef ART_TARGET_ANDROID
486 pid_t pid;
487 char* endptr;
488 pid = (pid_t)strtol(argv[argc - 1], &endptr, 10);
489 if (*endptr != '\0' || kill(pid, 0) != 0) {
490 std::cerr << StringPrintf("Invalid PID \"%s\".\n", argv[argc - 1]) << std::endl;
491 return EXIT_FAILURE;
492 }
493
494 // get libmeminfo process information.
495 ProcMemInfo proc(pid);
496 // Get the set of mappings by the specified process.
497 // Do not get the map usage stats, they are never used and it can take
498 // a long time to get this data.
499 const std::vector<Vma>& maps = proc.MapsWithoutUsageStats();
500 if (maps.empty()) {
501 std::cerr << "Error listing maps." << std::endl;
502 return EXIT_FAILURE;
503 }
504
505 bool match_found = false;
506 // Process the mappings that are due to vdex or oat files.
507 Printer printer;
508 for (auto& vma : maps) {
509 std::string mapped_file_name = vma.name;
510 // Filter by name contains options (if any).
511 if (!FilterByNameContains(mapped_file_name, name_filters)) {
512 continue;
513 }
514 if (IsVdexFileMapping(mapped_file_name)) {
515 if (!DisplayMappingIfFromVdexFile(proc, vma, &printer)) {
516 return EXIT_FAILURE;
517 }
518 match_found = true;
519 } else if (IsOatFileMapping(mapped_file_name)) {
520 if (!DisplayMappingIfFromOatFile(proc, vma, &printer)) {
521 return EXIT_FAILURE;
522 }
523 match_found = true;
524 }
525 }
526 if (!match_found) {
527 std::cerr << "No relevant memory maps were found." << std::endl;
528 return EXIT_FAILURE;
529 }
530 #endif
531
532 return EXIT_SUCCESS;
533 }
534
535 } // namespace art
536
main(int argc,char * argv[])537 int main(int argc, char* argv[]) {
538 return art::DexDiagMain(argc, argv);
539 }
540