blob: 5e840e699c768eae9377ea10be7c6575fe65b8f3 [file] [log] [blame]
Calin Juravle2e2db782016-02-23 12:00:03 +00001/*
2 * Copyright (C) 2016 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
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070017#include <errno.h>
Calin Juravle2e2db782016-02-23 12:00:03 +000018#include <stdio.h>
19#include <stdlib.h>
20#include <sys/file.h>
21#include <sys/stat.h>
22#include <unistd.h>
23
David Sehr7c80f2d2017-02-07 16:47:58 -080024#include <fstream>
Calin Juravle876f3502016-03-24 16:16:34 +000025#include <iostream>
David Sehr7c80f2d2017-02-07 16:47:58 -080026#include <set>
Calin Juravle2e2db782016-02-23 12:00:03 +000027#include <string>
David Sehr7c80f2d2017-02-07 16:47:58 -080028#include <unordered_set>
Calin Juravle2e2db782016-02-23 12:00:03 +000029#include <vector>
30
Andreas Gampe46ee31b2016-12-14 10:11:49 -080031#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080032#include "android-base/strings.h"
33
Calin Juravle2e2db782016-02-23 12:00:03 +000034#include "base/dumpable.h"
35#include "base/scoped_flock.h"
36#include "base/stringpiece.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000037#include "base/time_utils.h"
38#include "base/unix_file/fd_file.h"
Mathieu Chartier2f794552017-06-19 10:58:08 -070039#include "boot_image_profile.h"
Calin Juravlee0ac1152017-02-13 19:03:47 -080040#include "bytecode_utils.h"
David Sehr4fcdd6d2016-05-24 14:52:31 -070041#include "dex_file.h"
Calin Juravle33083d62017-01-18 15:29:12 -080042#include "jit/profile_compilation_info.h"
Mathieu Chartierdbddc222017-05-24 12:04:13 -070043#include "profile_assistant.h"
David Sehrf57589f2016-10-17 10:09:33 -070044#include "runtime.h"
Mathieu Chartierdbddc222017-05-24 12:04:13 -070045#include "type_reference.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000046#include "utils.h"
David Sehr546d24f2016-06-02 10:46:19 -070047#include "zip_archive.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000048
49namespace art {
50
51static int original_argc;
52static char** original_argv;
53
54static std::string CommandLine() {
55 std::vector<std::string> command;
56 for (int i = 0; i < original_argc; ++i) {
57 command.push_back(original_argv[i]);
58 }
Andreas Gampe9186ced2016-12-12 14:28:21 -080059 return android::base::Join(command, ' ');
Calin Juravle2e2db782016-02-23 12:00:03 +000060}
61
David Sehr4fcdd6d2016-05-24 14:52:31 -070062static constexpr int kInvalidFd = -1;
63
64static bool FdIsValid(int fd) {
65 return fd != kInvalidFd;
66}
67
Calin Juravle2e2db782016-02-23 12:00:03 +000068static void UsageErrorV(const char* fmt, va_list ap) {
69 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080070 android::base::StringAppendV(&error, fmt, ap);
Calin Juravle2e2db782016-02-23 12:00:03 +000071 LOG(ERROR) << error;
72}
73
74static void UsageError(const char* fmt, ...) {
75 va_list ap;
76 va_start(ap, fmt);
77 UsageErrorV(fmt, ap);
78 va_end(ap);
79}
80
81NO_RETURN static void Usage(const char *fmt, ...) {
82 va_list ap;
83 va_start(ap, fmt);
84 UsageErrorV(fmt, ap);
85 va_end(ap);
86
87 UsageError("Command: %s", CommandLine().c_str());
88 UsageError("Usage: profman [options]...");
89 UsageError("");
David Sehr4fcdd6d2016-05-24 14:52:31 -070090 UsageError(" --dump-only: dumps the content of the specified profile files");
91 UsageError(" to standard output (default) in a human readable form.");
92 UsageError("");
David Sehr7c80f2d2017-02-07 16:47:58 -080093 UsageError(" --dump-output-to-fd=<number>: redirects --dump-only output to a file descriptor.");
94 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -070095 UsageError(" --dump-classes-and-methods: dumps a sorted list of classes and methods that are");
96 UsageError(" in the specified profile file to standard output (default) in a human");
97 UsageError(" readable form. The output is valid input for --create-profile-from");
Calin Juravle876f3502016-03-24 16:16:34 +000098 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +000099 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
100 UsageError(" Can be specified multiple time, in which case the data from the different");
101 UsageError(" profiles will be aggregated.");
102 UsageError("");
103 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
104 UsageError(" Cannot be used together with --profile-file.");
105 UsageError("");
106 UsageError(" --reference-profile-file=<filename>: specify a reference profile.");
107 UsageError(" The data in this file will be compared with the data obtained by merging");
108 UsageError(" all the files specified with --profile-file or --profile-file-fd.");
109 UsageError(" If the exit code is EXIT_COMPILE then all --profile-file will be merged into");
110 UsageError(" --reference-profile-file. ");
111 UsageError("");
112 UsageError(" --reference-profile-file-fd=<number>: same as --reference-profile-file but");
113 UsageError(" accepts a file descriptor. Cannot be used together with");
114 UsageError(" --reference-profile-file.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800115 UsageError("");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100116 UsageError(" --generate-test-profile=<filename>: generates a random profile file for testing.");
117 UsageError(" --generate-test-profile-num-dex=<number>: number of dex files that should be");
118 UsageError(" included in the generated profile. Defaults to 20.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700119 UsageError(" --generate-test-profile-method-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100120 UsageError(" number of methods that should be generated. Defaults to 5.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700121 UsageError(" --generate-test-profile-class-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100122 UsageError(" number of classes that should be generated. Defaults to 5.");
Jeff Haof0a31f82017-03-27 15:50:37 -0700123 UsageError(" --generate-test-profile-seed=<number>: seed for random number generator used when");
124 UsageError(" generating random test profiles. Defaults to using NanoTime.");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100125 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -0700126 UsageError(" --create-profile-from=<filename>: creates a profile from a list of classes and");
127 UsageError(" methods.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800128 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700129 UsageError(" --dex-location=<string>: location string to use with corresponding");
130 UsageError(" apk-fd to find dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700131 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700132 UsageError(" --apk-fd=<number>: file descriptor containing an open APK to");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700133 UsageError(" search for dex files");
David Sehr7c80f2d2017-02-07 16:47:58 -0800134 UsageError(" --apk-=<filename>: an APK to search for dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700135 UsageError("");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700136 UsageError(" --generate-boot-image-profile: Generate a boot image profile based on input");
137 UsageError(" profiles. Requires passing in dex files to inspect properties of classes.");
138 UsageError(" --boot-image-class-threshold=<value>: specify minimum number of class occurrences");
139 UsageError(" to include a class in the boot image profile. Default is 10.");
140 UsageError(" --boot-image-clean-class-threshold=<value>: specify minimum number of clean class");
141 UsageError(" occurrences to include a class in the boot image profile. A clean class is a");
142 UsageError(" class that doesn't have any static fields or native methods and is likely to");
143 UsageError(" remain clean in the image. Default is 3.");
Mathieu Chartier8eecddf2017-07-12 16:05:54 -0700144 UsageError(" --boot-image-sampled-method-threshold=<value>: minimum number of profiles a");
145 UsageError(" non-hot method needs to be in order to be hot in the output profile. The");
146 UsageError(" default is max int.");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700147 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000148
149 exit(EXIT_FAILURE);
150}
151
Calin Juravle7bcdb532016-06-07 16:14:47 +0100152// Note: make sure you update the Usage if you change these values.
153static constexpr uint16_t kDefaultTestProfileNumDex = 20;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700154static constexpr uint16_t kDefaultTestProfileMethodPercentage = 5;
155static constexpr uint16_t kDefaultTestProfileClassPercentage = 5;
Calin Juravle7bcdb532016-06-07 16:14:47 +0100156
Calin Juravlee0ac1152017-02-13 19:03:47 -0800157// Separators used when parsing human friendly representation of profiles.
158static const std::string kMethodSep = "->";
Calin Juravle589e71e2017-03-03 16:05:05 -0800159static const std::string kMissingTypesMarker = "missing_types";
Calin Juravle08556882017-05-26 16:40:45 -0700160static const std::string kInvalidClassDescriptor = "invalid_class";
161static const std::string kInvalidMethod = "invalid_method";
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700162static const std::string kClassAllMethods = "*";
Calin Juravlee0ac1152017-02-13 19:03:47 -0800163static constexpr char kProfileParsingInlineChacheSep = '+';
164static constexpr char kProfileParsingTypeSep = ',';
165static constexpr char kProfileParsingFirstCharInSignature = '(';
Mathieu Chartierea650f32017-05-24 12:04:13 -0700166static constexpr char kMethodFlagStringHot = 'H';
167static constexpr char kMethodFlagStringStartup = 'S';
168static constexpr char kMethodFlagStringPostStartup = 'P';
Calin Juravlee0ac1152017-02-13 19:03:47 -0800169
170// TODO(calin): This class has grown too much from its initial design. Split the functionality
171// into smaller, more contained pieces.
Calin Juravle2e2db782016-02-23 12:00:03 +0000172class ProfMan FINAL {
173 public:
174 ProfMan() :
David Sehr4fcdd6d2016-05-24 14:52:31 -0700175 reference_profile_file_fd_(kInvalidFd),
176 dump_only_(false),
Mathieu Chartier34067262017-04-06 13:55:46 -0700177 dump_classes_and_methods_(false),
Mathieu Chartier2f794552017-06-19 10:58:08 -0700178 generate_boot_image_profile_(false),
David Sehr4fcdd6d2016-05-24 14:52:31 -0700179 dump_output_to_fd_(kInvalidFd),
Calin Juravle7bcdb532016-06-07 16:14:47 +0100180 test_profile_num_dex_(kDefaultTestProfileNumDex),
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700181 test_profile_method_percerntage_(kDefaultTestProfileMethodPercentage),
182 test_profile_class_percentage_(kDefaultTestProfileClassPercentage),
Jeff Haof0a31f82017-03-27 15:50:37 -0700183 test_profile_seed_(NanoTime()),
Calin Juravle2e2db782016-02-23 12:00:03 +0000184 start_ns_(NanoTime()) {}
185
186 ~ProfMan() {
187 LogCompletionTime();
188 }
189
190 void ParseArgs(int argc, char **argv) {
191 original_argc = argc;
192 original_argv = argv;
193
Andreas Gampe51d80cc2017-06-21 21:05:13 -0700194 InitLogging(argv, Runtime::Abort);
Calin Juravle2e2db782016-02-23 12:00:03 +0000195
196 // Skip over the command name.
197 argv++;
198 argc--;
199
200 if (argc == 0) {
201 Usage("No arguments specified");
202 }
203
204 for (int i = 0; i < argc; ++i) {
205 const StringPiece option(argv[i]);
206 const bool log_options = false;
207 if (log_options) {
Calin Juravle876f3502016-03-24 16:16:34 +0000208 LOG(INFO) << "profman: option[" << i << "]=" << argv[i];
Calin Juravle2e2db782016-02-23 12:00:03 +0000209 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700210 if (option == "--dump-only") {
211 dump_only_ = true;
Mathieu Chartier34067262017-04-06 13:55:46 -0700212 } else if (option == "--dump-classes-and-methods") {
213 dump_classes_and_methods_ = true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800214 } else if (option.starts_with("--create-profile-from=")) {
215 create_profile_from_file_ = option.substr(strlen("--create-profile-from=")).ToString();
David Sehr4fcdd6d2016-05-24 14:52:31 -0700216 } else if (option.starts_with("--dump-output-to-fd=")) {
217 ParseUintOption(option, "--dump-output-to-fd", &dump_output_to_fd_, Usage);
Mathieu Chartier2f794552017-06-19 10:58:08 -0700218 } else if (option == "--generate-boot-image-profile") {
219 generate_boot_image_profile_ = true;
220 } else if (option.starts_with("--boot-image-class-threshold=")) {
221 ParseUintOption(option,
222 "--boot-image-class-threshold",
223 &boot_image_options_.image_class_theshold,
224 Usage);
225 } else if (option.starts_with("--boot-image-clean-class-threshold=")) {
226 ParseUintOption(option,
227 "--boot-image-clean-class-threshold",
228 &boot_image_options_.image_class_clean_theshold,
229 Usage);
Mathieu Chartier8eecddf2017-07-12 16:05:54 -0700230 } else if (option.starts_with("--boot-image-sampled-method-threshold=")) {
231 ParseUintOption(option,
232 "--boot-image-sampled-method-threshold",
233 &boot_image_options_.compiled_method_threshold,
234 Usage);
Calin Juravle876f3502016-03-24 16:16:34 +0000235 } else if (option.starts_with("--profile-file=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000236 profile_files_.push_back(option.substr(strlen("--profile-file=")).ToString());
237 } else if (option.starts_with("--profile-file-fd=")) {
238 ParseFdForCollection(option, "--profile-file-fd", &profile_files_fd_);
239 } else if (option.starts_with("--reference-profile-file=")) {
240 reference_profile_file_ = option.substr(strlen("--reference-profile-file=")).ToString();
241 } else if (option.starts_with("--reference-profile-file-fd=")) {
242 ParseUintOption(option, "--reference-profile-file-fd", &reference_profile_file_fd_, Usage);
David Sehr546d24f2016-06-02 10:46:19 -0700243 } else if (option.starts_with("--dex-location=")) {
244 dex_locations_.push_back(option.substr(strlen("--dex-location=")).ToString());
245 } else if (option.starts_with("--apk-fd=")) {
246 ParseFdForCollection(option, "--apk-fd", &apks_fd_);
David Sehr7c80f2d2017-02-07 16:47:58 -0800247 } else if (option.starts_with("--apk=")) {
248 apk_files_.push_back(option.substr(strlen("--apk=")).ToString());
Calin Juravle7bcdb532016-06-07 16:14:47 +0100249 } else if (option.starts_with("--generate-test-profile=")) {
250 test_profile_ = option.substr(strlen("--generate-test-profile=")).ToString();
251 } else if (option.starts_with("--generate-test-profile-num-dex=")) {
252 ParseUintOption(option,
253 "--generate-test-profile-num-dex",
254 &test_profile_num_dex_,
255 Usage);
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700256 } else if (option.starts_with("--generate-test-profile-method-percentage")) {
Calin Juravle7bcdb532016-06-07 16:14:47 +0100257 ParseUintOption(option,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700258 "--generate-test-profile-method-percentage",
259 &test_profile_method_percerntage_,
Calin Juravle7bcdb532016-06-07 16:14:47 +0100260 Usage);
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700261 } else if (option.starts_with("--generate-test-profile-class-percentage")) {
Calin Juravle7bcdb532016-06-07 16:14:47 +0100262 ParseUintOption(option,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700263 "--generate-test-profile-class-percentage",
264 &test_profile_class_percentage_,
Calin Juravle7bcdb532016-06-07 16:14:47 +0100265 Usage);
Jeff Haof0a31f82017-03-27 15:50:37 -0700266 } else if (option.starts_with("--generate-test-profile-seed=")) {
267 ParseUintOption(option, "--generate-test-profile-seed", &test_profile_seed_, Usage);
Calin Juravle2e2db782016-02-23 12:00:03 +0000268 } else {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700269 Usage("Unknown argument '%s'", option.data());
Calin Juravle2e2db782016-02-23 12:00:03 +0000270 }
271 }
272
David Sehr153da0e2017-02-15 08:54:51 -0800273 // Validate global consistency between file/fd options.
Calin Juravle2e2db782016-02-23 12:00:03 +0000274 if (!profile_files_.empty() && !profile_files_fd_.empty()) {
275 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
276 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700277 if (!reference_profile_file_.empty() && FdIsValid(reference_profile_file_fd_)) {
278 Usage("Reference profile should not be specified with both "
279 "--reference-profile-file-fd and --reference-profile-file");
280 }
David Sehr153da0e2017-02-15 08:54:51 -0800281 if (!apk_files_.empty() && !apks_fd_.empty()) {
282 Usage("APK files should not be specified with both --apk-fd and --apk");
Calin Juravle2e2db782016-02-23 12:00:03 +0000283 }
284 }
285
286 ProfileAssistant::ProcessingResult ProcessProfiles() {
David Sehr153da0e2017-02-15 08:54:51 -0800287 // Validate that at least one profile file was passed, as well as a reference profile.
288 if (profile_files_.empty() && profile_files_fd_.empty()) {
289 Usage("No profile files specified.");
290 }
291 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
292 Usage("No reference profile file specified.");
293 }
294 if ((!profile_files_.empty() && FdIsValid(reference_profile_file_fd_)) ||
295 (!profile_files_fd_.empty() && !FdIsValid(reference_profile_file_fd_))) {
296 Usage("Options --profile-file-fd and --reference-profile-file-fd "
297 "should only be used together");
298 }
Calin Juravle2e2db782016-02-23 12:00:03 +0000299 ProfileAssistant::ProcessingResult result;
300 if (profile_files_.empty()) {
301 // The file doesn't need to be flushed here (ProcessProfiles will do it)
302 // so don't check the usage.
303 File file(reference_profile_file_fd_, false);
304 result = ProfileAssistant::ProcessProfiles(profile_files_fd_, reference_profile_file_fd_);
305 CloseAllFds(profile_files_fd_, "profile_files_fd_");
306 } else {
307 result = ProfileAssistant::ProcessProfiles(profile_files_, reference_profile_file_);
308 }
309 return result;
310 }
311
David Sehr7c80f2d2017-02-07 16:47:58 -0800312 void OpenApkFilesFromLocations(std::vector<std::unique_ptr<const DexFile>>* dex_files) {
313 bool use_apk_fd_list = !apks_fd_.empty();
314 if (use_apk_fd_list) {
David Sehr153da0e2017-02-15 08:54:51 -0800315 // Get the APKs from the collection of FDs.
David Sehr7c80f2d2017-02-07 16:47:58 -0800316 CHECK_EQ(dex_locations_.size(), apks_fd_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800317 } else if (!apk_files_.empty()) {
318 // Get the APKs from the collection of filenames.
David Sehr7c80f2d2017-02-07 16:47:58 -0800319 CHECK_EQ(dex_locations_.size(), apk_files_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800320 } else {
321 // No APKs were specified.
322 CHECK(dex_locations_.empty());
323 return;
David Sehr7c80f2d2017-02-07 16:47:58 -0800324 }
325 static constexpr bool kVerifyChecksum = true;
326 for (size_t i = 0; i < dex_locations_.size(); ++i) {
327 std::string error_msg;
328 std::vector<std::unique_ptr<const DexFile>> dex_files_for_location;
329 if (use_apk_fd_list) {
330 if (DexFile::OpenZip(apks_fd_[i],
331 dex_locations_[i],
332 kVerifyChecksum,
333 &error_msg,
334 &dex_files_for_location)) {
335 } else {
336 LOG(WARNING) << "OpenZip failed for '" << dex_locations_[i] << "' " << error_msg;
337 continue;
338 }
339 } else {
340 if (DexFile::Open(apk_files_[i].c_str(),
341 dex_locations_[i],
342 kVerifyChecksum,
343 &error_msg,
344 &dex_files_for_location)) {
345 } else {
346 LOG(WARNING) << "Open failed for '" << dex_locations_[i] << "' " << error_msg;
347 continue;
348 }
349 }
350 for (std::unique_ptr<const DexFile>& dex_file : dex_files_for_location) {
351 dex_files->emplace_back(std::move(dex_file));
352 }
353 }
354 }
355
Mathieu Chartier2f794552017-06-19 10:58:08 -0700356 std::unique_ptr<const ProfileCompilationInfo> LoadProfile(const std::string& filename, int fd) {
357 if (!filename.empty()) {
358 fd = open(filename.c_str(), O_RDWR);
359 if (fd < 0) {
360 LOG(ERROR) << "Cannot open " << filename << strerror(errno);
361 return nullptr;
362 }
363 }
364 std::unique_ptr<ProfileCompilationInfo> info(new ProfileCompilationInfo);
365 if (!info->Load(fd)) {
366 LOG(ERROR) << "Cannot load profile info from fd=" << fd << "\n";
367 return nullptr;
368 }
369 return info;
370 }
371
David Sehrb18991b2017-02-08 20:58:10 -0800372 int DumpOneProfile(const std::string& banner,
373 const std::string& filename,
374 int fd,
375 const std::vector<std::unique_ptr<const DexFile>>* dex_files,
376 std::string* dump) {
Mathieu Chartier2f794552017-06-19 10:58:08 -0700377 std::unique_ptr<const ProfileCompilationInfo> info(LoadProfile(filename, fd));
378 if (info == nullptr) {
379 LOG(ERROR) << "Cannot load profile info from filename=" << filename << " fd=" << fd;
Calin Juravle876f3502016-03-24 16:16:34 +0000380 return -1;
381 }
Mathieu Chartier2f794552017-06-19 10:58:08 -0700382 *dump += banner + "\n" + info->DumpInfo(dex_files) + "\n";
David Sehr4fcdd6d2016-05-24 14:52:31 -0700383 return 0;
384 }
385
386 int DumpProfileInfo() {
David Sehr153da0e2017-02-15 08:54:51 -0800387 // Validate that at least one profile file or reference was specified.
388 if (profile_files_.empty() && profile_files_fd_.empty() &&
389 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
390 Usage("No profile files or reference profile specified.");
391 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700392 static const char* kEmptyString = "";
David Sehr546d24f2016-06-02 10:46:19 -0700393 static const char* kOrdinaryProfile = "=== profile ===";
394 static const char* kReferenceProfile = "=== reference profile ===";
395
396 // Open apk/zip files and and read dex files.
397 MemMap::Init(); // for ZipArchive::OpenFromFd
David Sehrb18991b2017-02-08 20:58:10 -0800398 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7c80f2d2017-02-07 16:47:58 -0800399 OpenApkFilesFromLocations(&dex_files);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700400 std::string dump;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700401 // Dump individual profile files.
402 if (!profile_files_fd_.empty()) {
403 for (int profile_file_fd : profile_files_fd_) {
David Sehr546d24f2016-06-02 10:46:19 -0700404 int ret = DumpOneProfile(kOrdinaryProfile,
405 kEmptyString,
406 profile_file_fd,
407 &dex_files,
408 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700409 if (ret != 0) {
410 return ret;
411 }
412 }
413 }
414 if (!profile_files_.empty()) {
415 for (const std::string& profile_file : profile_files_) {
David Sehr546d24f2016-06-02 10:46:19 -0700416 int ret = DumpOneProfile(kOrdinaryProfile, profile_file, kInvalidFd, &dex_files, &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700417 if (ret != 0) {
418 return ret;
419 }
420 }
421 }
422 // Dump reference profile file.
423 if (FdIsValid(reference_profile_file_fd_)) {
David Sehr546d24f2016-06-02 10:46:19 -0700424 int ret = DumpOneProfile(kReferenceProfile,
425 kEmptyString,
426 reference_profile_file_fd_,
427 &dex_files,
428 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700429 if (ret != 0) {
430 return ret;
431 }
432 }
433 if (!reference_profile_file_.empty()) {
David Sehr546d24f2016-06-02 10:46:19 -0700434 int ret = DumpOneProfile(kReferenceProfile,
435 reference_profile_file_,
436 kInvalidFd,
437 &dex_files,
David Sehr4fcdd6d2016-05-24 14:52:31 -0700438 &dump);
439 if (ret != 0) {
440 return ret;
441 }
442 }
443 if (!FdIsValid(dump_output_to_fd_)) {
444 std::cout << dump;
445 } else {
446 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
447 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
448 return -1;
449 }
450 }
Calin Juravle876f3502016-03-24 16:16:34 +0000451 return 0;
452 }
453
454 bool ShouldOnlyDumpProfile() {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700455 return dump_only_;
Calin Juravle876f3502016-03-24 16:16:34 +0000456 }
457
Mathieu Chartier34067262017-04-06 13:55:46 -0700458 bool GetClassNamesAndMethods(int fd,
459 std::vector<std::unique_ptr<const DexFile>>* dex_files,
460 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800461 ProfileCompilationInfo profile_info;
462 if (!profile_info.Load(fd)) {
463 LOG(ERROR) << "Cannot load profile info";
464 return false;
465 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700466 for (const std::unique_ptr<const DexFile>& dex_file : *dex_files) {
467 std::set<dex::TypeIndex> class_types;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700468 std::set<uint16_t> hot_methods;
469 std::set<uint16_t> startup_methods;
470 std::set<uint16_t> post_startup_methods;
471 std::set<uint16_t> combined_methods;
472 if (profile_info.GetClassesAndMethods(*dex_file.get(),
473 &class_types,
474 &hot_methods,
475 &startup_methods,
476 &post_startup_methods)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700477 for (const dex::TypeIndex& type_index : class_types) {
478 const DexFile::TypeId& type_id = dex_file->GetTypeId(type_index);
479 out_lines->insert(std::string(dex_file->GetTypeDescriptor(type_id)));
480 }
Mathieu Chartierea650f32017-05-24 12:04:13 -0700481 combined_methods = hot_methods;
482 combined_methods.insert(startup_methods.begin(), startup_methods.end());
483 combined_methods.insert(post_startup_methods.begin(), post_startup_methods.end());
484 for (uint16_t dex_method_idx : combined_methods) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700485 const DexFile::MethodId& id = dex_file->GetMethodId(dex_method_idx);
486 std::string signature_string(dex_file->GetMethodSignature(id).ToString());
487 std::string type_string(dex_file->GetTypeDescriptor(dex_file->GetTypeId(id.class_idx_)));
488 std::string method_name(dex_file->GetMethodName(id));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700489 std::string flags_string;
490 if (hot_methods.find(dex_method_idx) != hot_methods.end()) {
491 flags_string += kMethodFlagStringHot;
492 }
493 if (startup_methods.find(dex_method_idx) != startup_methods.end()) {
494 flags_string += kMethodFlagStringStartup;
495 }
496 if (post_startup_methods.find(dex_method_idx) != post_startup_methods.end()) {
497 flags_string += kMethodFlagStringPostStartup;
498 }
499 out_lines->insert(flags_string +
500 type_string +
501 kMethodSep +
502 method_name +
503 signature_string);
Mathieu Chartier34067262017-04-06 13:55:46 -0700504 }
505 }
506 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800507 return true;
508 }
509
Mathieu Chartier34067262017-04-06 13:55:46 -0700510 bool GetClassNamesAndMethods(const std::string& profile_file,
511 std::vector<std::unique_ptr<const DexFile>>* dex_files,
512 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800513 int fd = open(profile_file.c_str(), O_RDONLY);
514 if (!FdIsValid(fd)) {
515 LOG(ERROR) << "Cannot open " << profile_file << strerror(errno);
516 return false;
517 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700518 if (!GetClassNamesAndMethods(fd, dex_files, out_lines)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800519 return false;
520 }
521 if (close(fd) < 0) {
522 PLOG(WARNING) << "Failed to close descriptor";
523 }
524 return true;
525 }
526
Mathieu Chartierea650f32017-05-24 12:04:13 -0700527 int DumpClassesAndMethods() {
David Sehr153da0e2017-02-15 08:54:51 -0800528 // Validate that at least one profile file or reference was specified.
529 if (profile_files_.empty() && profile_files_fd_.empty() &&
530 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
531 Usage("No profile files or reference profile specified.");
532 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800533 // Open apk/zip files and and read dex files.
534 MemMap::Init(); // for ZipArchive::OpenFromFd
535 // Open the dex files to get the names for classes.
536 std::vector<std::unique_ptr<const DexFile>> dex_files;
537 OpenApkFilesFromLocations(&dex_files);
538 // Build a vector of class names from individual profile files.
539 std::set<std::string> class_names;
540 if (!profile_files_fd_.empty()) {
541 for (int profile_file_fd : profile_files_fd_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700542 if (!GetClassNamesAndMethods(profile_file_fd, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800543 return -1;
544 }
545 }
546 }
547 if (!profile_files_.empty()) {
548 for (const std::string& profile_file : profile_files_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700549 if (!GetClassNamesAndMethods(profile_file, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800550 return -1;
551 }
552 }
553 }
554 // Concatenate class names from reference profile file.
555 if (FdIsValid(reference_profile_file_fd_)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700556 if (!GetClassNamesAndMethods(reference_profile_file_fd_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800557 return -1;
558 }
559 }
560 if (!reference_profile_file_.empty()) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700561 if (!GetClassNamesAndMethods(reference_profile_file_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800562 return -1;
563 }
564 }
565 // Dump the class names.
566 std::string dump;
567 for (const std::string& class_name : class_names) {
568 dump += class_name + std::string("\n");
569 }
570 if (!FdIsValid(dump_output_to_fd_)) {
571 std::cout << dump;
572 } else {
573 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
574 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
575 return -1;
576 }
577 }
578 return 0;
579 }
580
Mathieu Chartier34067262017-04-06 13:55:46 -0700581 bool ShouldOnlyDumpClassesAndMethods() {
582 return dump_classes_and_methods_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800583 }
584
585 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
586 // the given function.
587 template <typename T>
588 static T* ReadCommentedInputFromFile(
589 const char* input_filename, std::function<std::string(const char*)>* process) {
590 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
591 if (input_file.get() == nullptr) {
592 LOG(ERROR) << "Failed to open input file " << input_filename;
593 return nullptr;
594 }
595 std::unique_ptr<T> result(
596 ReadCommentedInputStream<T>(*input_file, process));
597 input_file->close();
598 return result.release();
599 }
600
601 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
602 // with the given function.
603 template <typename T>
604 static T* ReadCommentedInputStream(
605 std::istream& in_stream,
606 std::function<std::string(const char*)>* process) {
607 std::unique_ptr<T> output(new T());
608 while (in_stream.good()) {
609 std::string dot;
610 std::getline(in_stream, dot);
611 if (android::base::StartsWith(dot, "#") || dot.empty()) {
612 continue;
613 }
614 if (process != nullptr) {
615 std::string descriptor((*process)(dot.c_str()));
616 output->insert(output->end(), descriptor);
617 } else {
618 output->insert(output->end(), dot);
619 }
620 }
621 return output.release();
622 }
623
Calin Juravlee0ac1152017-02-13 19:03:47 -0800624 // Find class klass_descriptor in the given dex_files and store its reference
625 // in the out parameter class_ref.
626 // Return true if the definition of the class was found in any of the dex_files.
627 bool FindClass(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
628 const std::string& klass_descriptor,
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700629 /*out*/TypeReference* class_ref) {
Calin Juravle08556882017-05-26 16:40:45 -0700630 constexpr uint16_t kInvalidTypeIndex = std::numeric_limits<uint16_t>::max() - 1;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800631 for (const std::unique_ptr<const DexFile>& dex_file_ptr : dex_files) {
632 const DexFile* dex_file = dex_file_ptr.get();
Calin Juravle08556882017-05-26 16:40:45 -0700633 if (klass_descriptor == kInvalidClassDescriptor) {
634 if (kInvalidTypeIndex >= dex_file->NumTypeIds()) {
635 // The dex file does not contain all possible type ids which leaves us room
636 // to add an "invalid" type id.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700637 *class_ref = TypeReference(dex_file, dex::TypeIndex(kInvalidTypeIndex));
Calin Juravle08556882017-05-26 16:40:45 -0700638 return true;
639 } else {
640 // The dex file contains all possible type ids. We don't have any free type id
641 // that we can use as invalid.
642 continue;
643 }
644 }
645
Calin Juravlee0ac1152017-02-13 19:03:47 -0800646 const DexFile::TypeId* type_id = dex_file->FindTypeId(klass_descriptor.c_str());
647 if (type_id == nullptr) {
648 continue;
649 }
650 dex::TypeIndex type_index = dex_file->GetIndexForTypeId(*type_id);
651 if (dex_file->FindClassDef(type_index) == nullptr) {
652 // Class is only referenced in the current dex file but not defined in it.
653 continue;
654 }
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700655 *class_ref = TypeReference(dex_file, type_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800656 return true;
657 }
658 return false;
659 }
660
Mathieu Chartier34067262017-04-06 13:55:46 -0700661 // Find the method specified by method_spec in the class class_ref.
Calin Juravle08556882017-05-26 16:40:45 -0700662 uint32_t FindMethodIndex(const TypeReference& class_ref,
663 const std::string& method_spec) {
664 const DexFile* dex_file = class_ref.dex_file;
665 if (method_spec == kInvalidMethod) {
666 constexpr uint16_t kInvalidMethodIndex = std::numeric_limits<uint16_t>::max() - 1;
667 return kInvalidMethodIndex >= dex_file->NumMethodIds()
668 ? kInvalidMethodIndex
669 : DexFile::kDexNoIndex;
670 }
671
Calin Juravlee0ac1152017-02-13 19:03:47 -0800672 std::vector<std::string> name_and_signature;
673 Split(method_spec, kProfileParsingFirstCharInSignature, &name_and_signature);
674 if (name_and_signature.size() != 2) {
675 LOG(ERROR) << "Invalid method name and signature " << method_spec;
Calin Juravle08556882017-05-26 16:40:45 -0700676 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800677 }
Calin Juravle08556882017-05-26 16:40:45 -0700678
Calin Juravlee0ac1152017-02-13 19:03:47 -0800679 const std::string& name = name_and_signature[0];
680 const std::string& signature = kProfileParsingFirstCharInSignature + name_and_signature[1];
Calin Juravlee0ac1152017-02-13 19:03:47 -0800681
682 const DexFile::StringId* name_id = dex_file->FindStringId(name.c_str());
683 if (name_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700684 LOG(WARNING) << "Could not find name: " << name;
Mathieu Chartier34067262017-04-06 13:55:46 -0700685 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800686 }
687 dex::TypeIndex return_type_idx;
688 std::vector<dex::TypeIndex> param_type_idxs;
689 if (!dex_file->CreateTypeList(signature, &return_type_idx, &param_type_idxs)) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700690 LOG(WARNING) << "Could not create type list" << signature;
Mathieu Chartier34067262017-04-06 13:55:46 -0700691 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800692 }
693 const DexFile::ProtoId* proto_id = dex_file->FindProtoId(return_type_idx, param_type_idxs);
694 if (proto_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700695 LOG(WARNING) << "Could not find proto_id: " << name;
Mathieu Chartier34067262017-04-06 13:55:46 -0700696 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800697 }
698 const DexFile::MethodId* method_id = dex_file->FindMethodId(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700699 dex_file->GetTypeId(class_ref.TypeIndex()), *name_id, *proto_id);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800700 if (method_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700701 LOG(WARNING) << "Could not find method_id: " << name;
Mathieu Chartier34067262017-04-06 13:55:46 -0700702 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800703 }
704
Mathieu Chartier34067262017-04-06 13:55:46 -0700705 return dex_file->GetIndexForMethodId(*method_id);
706 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800707
Mathieu Chartier34067262017-04-06 13:55:46 -0700708 // Given a method, return true if the method has a single INVOKE_VIRTUAL in its byte code.
709 // Upon success it returns true and stores the method index and the invoke dex pc
710 // in the output parameters.
711 // The format of the method spec is "inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
712 //
713 // TODO(calin): support INVOKE_INTERFACE and the range variants.
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700714 bool HasSingleInvoke(const TypeReference& class_ref,
Mathieu Chartier34067262017-04-06 13:55:46 -0700715 uint16_t method_index,
716 /*out*/uint32_t* dex_pc) {
717 const DexFile* dex_file = class_ref.dex_file;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800718 uint32_t offset = dex_file->FindCodeItemOffset(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700719 *dex_file->FindClassDef(class_ref.TypeIndex()),
Mathieu Chartier34067262017-04-06 13:55:46 -0700720 method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800721 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(offset);
722
723 bool found_invoke = false;
724 for (CodeItemIterator it(*code_item); !it.Done(); it.Advance()) {
725 if (it.CurrentInstruction().Opcode() == Instruction::INVOKE_VIRTUAL) {
726 if (found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700727 LOG(ERROR) << "Multiple invoke INVOKE_VIRTUAL found: "
728 << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800729 return false;
730 }
731 found_invoke = true;
732 *dex_pc = it.CurrentDexPc();
733 }
734 }
735 if (!found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700736 LOG(ERROR) << "Could not find any INVOKE_VIRTUAL: " << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800737 }
738 return found_invoke;
739 }
740
741 // Process a line defining a class or a method and its inline caches.
742 // Upon success return true and add the class or the method info to profile.
Calin Juravle589e71e2017-03-03 16:05:05 -0800743 // The possible line formats are:
744 // "LJustTheCass;".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800745 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
Calin Juravle08556882017-05-26 16:40:45 -0700746 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,invalid_class".
Calin Juravle589e71e2017-03-03 16:05:05 -0800747 // "LTestInline;->inlineMissingTypes(LSuper;)I+missing_types".
748 // "LTestInline;->inlineNoInlineCaches(LSuper;)I".
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700749 // "LTestInline;->*".
Calin Juravle08556882017-05-26 16:40:45 -0700750 // "invalid_class".
751 // "LTestInline;->invalid_method".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800752 // The method and classes are searched only in the given dex files.
753 bool ProcessLine(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
754 const std::string& line,
755 /*out*/ProfileCompilationInfo* profile) {
756 std::string klass;
757 std::string method_str;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700758 bool is_hot = false;
759 bool is_startup = false;
760 bool is_post_startup = false;
761 const size_t method_sep_index = line.find(kMethodSep, 0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800762 if (method_sep_index == std::string::npos) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700763 klass = line.substr(0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800764 } else {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700765 // The method prefix flags are only valid for method strings.
766 size_t start_index = 0;
767 while (start_index < line.size() && line[start_index] != 'L') {
768 const char c = line[start_index];
769 if (c == kMethodFlagStringHot) {
770 is_hot = true;
771 } else if (c == kMethodFlagStringStartup) {
772 is_startup = true;
773 } else if (c == kMethodFlagStringPostStartup) {
774 is_post_startup = true;
775 } else {
776 LOG(WARNING) << "Invalid flag " << c;
777 return false;
778 }
779 ++start_index;
780 }
781 klass = line.substr(start_index, method_sep_index - start_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800782 method_str = line.substr(method_sep_index + kMethodSep.size());
783 }
784
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700785 TypeReference class_ref;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800786 if (!FindClass(dex_files, klass, &class_ref)) {
Mathieu Chartier3f121342017-03-06 11:16:20 -0800787 LOG(WARNING) << "Could not find class: " << klass;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800788 return false;
789 }
790
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700791 if (method_str.empty() || method_str == kClassAllMethods) {
792 // Start by adding the class.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800793 std::set<DexCacheResolvedClasses> resolved_class_set;
794 const DexFile* dex_file = class_ref.dex_file;
795 const auto& dex_resolved_classes = resolved_class_set.emplace(
796 dex_file->GetLocation(),
797 dex_file->GetBaseLocation(),
Mathieu Chartierea650f32017-05-24 12:04:13 -0700798 dex_file->GetLocationChecksum(),
799 dex_file->NumMethodIds());
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700800 dex_resolved_classes.first->AddClass(class_ref.TypeIndex());
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700801 std::vector<ProfileMethodInfo> methods;
802 if (method_str == kClassAllMethods) {
803 // Add all of the methods.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700804 const DexFile::ClassDef* class_def = dex_file->FindClassDef(class_ref.TypeIndex());
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700805 const uint8_t* class_data = dex_file->GetClassData(*class_def);
806 if (class_data != nullptr) {
807 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700808 it.SkipAllFields();
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700809 while (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
810 if (it.GetMethodCodeItemOffset() != 0) {
811 // Add all of the methods that have code to the profile.
812 const uint32_t method_idx = it.GetMemberIndex();
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700813 methods.push_back(ProfileMethodInfo(MethodReference(dex_file, method_idx)));
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700814 }
815 it.Next();
816 }
817 }
818 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700819 // TODO: Check return values?
820 profile->AddMethods(methods);
821 profile->AddClasses(resolved_class_set);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800822 return true;
823 }
824
825 // Process the method.
826 std::string method_spec;
827 std::vector<std::string> inline_cache_elems;
828
Mathieu Chartierea650f32017-05-24 12:04:13 -0700829 // If none of the flags are set, default to hot.
830 is_hot = is_hot || (!is_hot && !is_startup && !is_post_startup);
831
Calin Juravlee0ac1152017-02-13 19:03:47 -0800832 std::vector<std::string> method_elems;
Calin Juravle589e71e2017-03-03 16:05:05 -0800833 bool is_missing_types = false;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800834 Split(method_str, kProfileParsingInlineChacheSep, &method_elems);
835 if (method_elems.size() == 2) {
836 method_spec = method_elems[0];
Calin Juravle589e71e2017-03-03 16:05:05 -0800837 is_missing_types = method_elems[1] == kMissingTypesMarker;
838 if (!is_missing_types) {
839 Split(method_elems[1], kProfileParsingTypeSep, &inline_cache_elems);
840 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800841 } else if (method_elems.size() == 1) {
842 method_spec = method_elems[0];
843 } else {
844 LOG(ERROR) << "Invalid method line: " << line;
845 return false;
846 }
847
Mathieu Chartier34067262017-04-06 13:55:46 -0700848 const uint32_t method_index = FindMethodIndex(class_ref, method_spec);
849 if (method_index == DexFile::kDexNoIndex) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800850 return false;
851 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700852
Mathieu Chartier34067262017-04-06 13:55:46 -0700853 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
854 if (is_missing_types || !inline_cache_elems.empty()) {
855 uint32_t dex_pc;
856 if (!HasSingleInvoke(class_ref, method_index, &dex_pc)) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800857 return false;
858 }
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700859 std::vector<TypeReference> classes(inline_cache_elems.size());
Mathieu Chartier34067262017-04-06 13:55:46 -0700860 size_t class_it = 0;
861 for (const std::string& ic_class : inline_cache_elems) {
862 if (!FindClass(dex_files, ic_class, &(classes[class_it++]))) {
863 LOG(ERROR) << "Could not find class: " << ic_class;
864 return false;
865 }
866 }
867 inline_caches.emplace_back(dex_pc, is_missing_types, classes);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800868 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700869 MethodReference ref(class_ref.dex_file, method_index);
Mathieu Chartierea650f32017-05-24 12:04:13 -0700870 if (is_hot) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700871 profile->AddMethod(ProfileMethodInfo(ref, inline_caches));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700872 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700873 uint32_t flags = 0;
874 using Hotness = ProfileCompilationInfo::MethodHotness;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700875 if (is_startup) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700876 flags |= Hotness::kFlagStartup;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700877 }
878 if (is_post_startup) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700879 flags |= Hotness::kFlagPostStartup;
880 }
881 if (flags != 0) {
882 if (!profile->AddMethodIndex(static_cast<Hotness::Flag>(flags), ref)) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700883 return false;
884 }
Mathieu Chartiere46f3a82017-06-19 19:54:12 -0700885 DCHECK(profile->GetMethodHotness(ref).IsInProfile());
Mathieu Chartierea650f32017-05-24 12:04:13 -0700886 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800887 return true;
888 }
889
Mathieu Chartier2f794552017-06-19 10:58:08 -0700890 int OpenReferenceProfile() const {
891 int fd = reference_profile_file_fd_;
892 if (!FdIsValid(fd)) {
893 CHECK(!reference_profile_file_.empty());
894 fd = open(reference_profile_file_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
895 if (fd < 0) {
896 LOG(ERROR) << "Cannot open " << reference_profile_file_ << strerror(errno);
897 return kInvalidFd;
898 }
899 }
900 return fd;
901 }
902
Calin Juravlee0ac1152017-02-13 19:03:47 -0800903 // Creates a profile from a human friendly textual representation.
904 // The expected input format is:
905 // # Classes
906 // Ljava/lang/Comparable;
907 // Ljava/lang/Math;
908 // # Methods with inline caches
909 // LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;
910 // LTestInline;->noInlineCache(LSuper;)I
David Sehr7c80f2d2017-02-07 16:47:58 -0800911 int CreateProfile() {
David Sehr153da0e2017-02-15 08:54:51 -0800912 // Validate parameters for this command.
913 if (apk_files_.empty() && apks_fd_.empty()) {
914 Usage("APK files must be specified");
915 }
916 if (dex_locations_.empty()) {
917 Usage("DEX locations must be specified");
918 }
919 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
920 Usage("Reference profile must be specified with --reference-profile-file or "
921 "--reference-profile-file-fd");
922 }
923 if (!profile_files_.empty() || !profile_files_fd_.empty()) {
924 Usage("Profile must be specified with --reference-profile-file or "
925 "--reference-profile-file-fd");
926 }
927 // for ZipArchive::OpenFromFd
928 MemMap::Init();
David Sehr7c80f2d2017-02-07 16:47:58 -0800929 // Open the profile output file if needed.
Mathieu Chartier2f794552017-06-19 10:58:08 -0700930 int fd = OpenReferenceProfile();
David Sehr7c80f2d2017-02-07 16:47:58 -0800931 if (!FdIsValid(fd)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800932 return -1;
David Sehr7c80f2d2017-02-07 16:47:58 -0800933 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800934 // Read the user-specified list of classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800935 std::unique_ptr<std::unordered_set<std::string>>
Calin Juravlee0ac1152017-02-13 19:03:47 -0800936 user_lines(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
David Sehr7c80f2d2017-02-07 16:47:58 -0800937 create_profile_from_file_.c_str(), nullptr)); // No post-processing.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800938
939 // Open the dex files to look up classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800940 std::vector<std::unique_ptr<const DexFile>> dex_files;
941 OpenApkFilesFromLocations(&dex_files);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800942
943 // Process the lines one by one and add the successful ones to the profile.
David Sehr7c80f2d2017-02-07 16:47:58 -0800944 ProfileCompilationInfo info;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800945
946 for (const auto& line : *user_lines) {
947 ProcessLine(dex_files, line, &info);
948 }
949
David Sehr7c80f2d2017-02-07 16:47:58 -0800950 // Write the profile file.
951 CHECK(info.Save(fd));
952 if (close(fd) < 0) {
953 PLOG(WARNING) << "Failed to close descriptor";
954 }
955 return 0;
956 }
957
Mathieu Chartier2f794552017-06-19 10:58:08 -0700958 bool ShouldCreateBootProfile() const {
959 return generate_boot_image_profile_;
960 }
961
962 int CreateBootProfile() {
963 // Initialize memmap since it's required to open dex files.
964 MemMap::Init();
965 // Open the profile output file.
966 const int reference_fd = OpenReferenceProfile();
967 if (!FdIsValid(reference_fd)) {
968 PLOG(ERROR) << "Error opening reference profile";
969 return -1;
970 }
971 // Open the dex files.
972 std::vector<std::unique_ptr<const DexFile>> dex_files;
973 OpenApkFilesFromLocations(&dex_files);
974 if (dex_files.empty()) {
975 PLOG(ERROR) << "Expected dex files for creating boot profile";
976 return -2;
977 }
978 // Open the input profiles.
979 std::vector<std::unique_ptr<const ProfileCompilationInfo>> profiles;
980 if (!profile_files_fd_.empty()) {
981 for (int profile_file_fd : profile_files_fd_) {
982 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile("", profile_file_fd));
983 if (profile == nullptr) {
984 return -3;
985 }
986 profiles.emplace_back(std::move(profile));
987 }
988 }
989 if (!profile_files_.empty()) {
990 for (const std::string& profile_file : profile_files_) {
991 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile(profile_file, kInvalidFd));
992 if (profile == nullptr) {
993 return -4;
994 }
995 profiles.emplace_back(std::move(profile));
996 }
997 }
998 ProfileCompilationInfo out_profile;
999 GenerateBootImageProfile(dex_files,
1000 profiles,
1001 boot_image_options_,
1002 VLOG_IS_ON(profiler),
1003 &out_profile);
1004 out_profile.Save(reference_fd);
1005 close(reference_fd);
1006 return 0;
1007 }
1008
David Sehr7c80f2d2017-02-07 16:47:58 -08001009 bool ShouldCreateProfile() {
1010 return !create_profile_from_file_.empty();
1011 }
1012
Calin Juravle7bcdb532016-06-07 16:14:47 +01001013 int GenerateTestProfile() {
David Sehr153da0e2017-02-15 08:54:51 -08001014 // Validate parameters for this command.
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001015 if (test_profile_method_percerntage_ > 100) {
1016 Usage("Invalid percentage for --generate-test-profile-method-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001017 }
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001018 if (test_profile_class_percentage_ > 100) {
1019 Usage("Invalid percentage for --generate-test-profile-class-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001020 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001021 // If given APK files or DEX locations, check that they're ok.
1022 if (!apk_files_.empty() || !apks_fd_.empty() || !dex_locations_.empty()) {
1023 if (apk_files_.empty() && apks_fd_.empty()) {
1024 Usage("APK files must be specified when passing DEX locations to --generate-test-profile");
1025 }
1026 if (dex_locations_.empty()) {
1027 Usage("DEX locations must be specified when passing APK files to --generate-test-profile");
1028 }
1029 }
David Sehr153da0e2017-02-15 08:54:51 -08001030 // ShouldGenerateTestProfile confirms !test_profile_.empty().
George Burgess IV71f77262016-10-25 13:08:17 -07001031 int profile_test_fd = open(test_profile_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001032 if (profile_test_fd < 0) {
David Sehr7c80f2d2017-02-07 16:47:58 -08001033 LOG(ERROR) << "Cannot open " << test_profile_ << strerror(errno);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001034 return -1;
1035 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001036 bool result;
1037 if (apk_files_.empty() && apks_fd_.empty() && dex_locations_.empty()) {
1038 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1039 test_profile_num_dex_,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001040 test_profile_method_percerntage_,
1041 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001042 test_profile_seed_);
1043 } else {
1044 // Initialize MemMap for ZipArchive::OpenFromFd.
1045 MemMap::Init();
1046 // Open the dex files to look up classes and methods.
1047 std::vector<std::unique_ptr<const DexFile>> dex_files;
1048 OpenApkFilesFromLocations(&dex_files);
1049 // Create a random profile file based on the set of dex files.
1050 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1051 dex_files,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001052 test_profile_method_percerntage_,
1053 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001054 test_profile_seed_);
1055 }
Calin Juravle7bcdb532016-06-07 16:14:47 +01001056 close(profile_test_fd); // ignore close result.
1057 return result ? 0 : -1;
1058 }
1059
1060 bool ShouldGenerateTestProfile() {
1061 return !test_profile_.empty();
1062 }
1063
Calin Juravle2e2db782016-02-23 12:00:03 +00001064 private:
1065 static void ParseFdForCollection(const StringPiece& option,
1066 const char* arg_name,
1067 std::vector<int>* fds) {
1068 int fd;
1069 ParseUintOption(option, arg_name, &fd, Usage);
1070 fds->push_back(fd);
1071 }
1072
1073 static void CloseAllFds(const std::vector<int>& fds, const char* descriptor) {
1074 for (size_t i = 0; i < fds.size(); i++) {
1075 if (close(fds[i]) < 0) {
1076 PLOG(WARNING) << "Failed to close descriptor for " << descriptor << " at index " << i;
1077 }
1078 }
1079 }
1080
1081 void LogCompletionTime() {
David Sehr52683cf2016-05-05 09:02:38 -07001082 static constexpr uint64_t kLogThresholdTime = MsToNs(100); // 100ms
1083 uint64_t time_taken = NanoTime() - start_ns_;
David Sehred793012016-05-05 13:39:43 -07001084 if (time_taken > kLogThresholdTime) {
David Sehrd8557182016-05-06 12:29:35 -07001085 LOG(WARNING) << "profman took " << PrettyDuration(time_taken);
David Sehred793012016-05-05 13:39:43 -07001086 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001087 }
1088
1089 std::vector<std::string> profile_files_;
1090 std::vector<int> profile_files_fd_;
David Sehr546d24f2016-06-02 10:46:19 -07001091 std::vector<std::string> dex_locations_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001092 std::vector<std::string> apk_files_;
David Sehr546d24f2016-06-02 10:46:19 -07001093 std::vector<int> apks_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001094 std::string reference_profile_file_;
1095 int reference_profile_file_fd_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001096 bool dump_only_;
Mathieu Chartier34067262017-04-06 13:55:46 -07001097 bool dump_classes_and_methods_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001098 bool generate_boot_image_profile_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001099 int dump_output_to_fd_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001100 BootImageOptions boot_image_options_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001101 std::string test_profile_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001102 std::string create_profile_from_file_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001103 uint16_t test_profile_num_dex_;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001104 uint16_t test_profile_method_percerntage_;
1105 uint16_t test_profile_class_percentage_;
Jeff Haof0a31f82017-03-27 15:50:37 -07001106 uint32_t test_profile_seed_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001107 uint64_t start_ns_;
1108};
1109
1110// See ProfileAssistant::ProcessingResult for return codes.
1111static int profman(int argc, char** argv) {
1112 ProfMan profman;
1113
1114 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1115 profman.ParseArgs(argc, argv);
1116
Calin Juravle7bcdb532016-06-07 16:14:47 +01001117 if (profman.ShouldGenerateTestProfile()) {
1118 return profman.GenerateTestProfile();
1119 }
Calin Juravle876f3502016-03-24 16:16:34 +00001120 if (profman.ShouldOnlyDumpProfile()) {
1121 return profman.DumpProfileInfo();
1122 }
Mathieu Chartier34067262017-04-06 13:55:46 -07001123 if (profman.ShouldOnlyDumpClassesAndMethods()) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001124 return profman.DumpClassesAndMethods();
David Sehr7c80f2d2017-02-07 16:47:58 -08001125 }
1126 if (profman.ShouldCreateProfile()) {
1127 return profman.CreateProfile();
1128 }
Mathieu Chartier2f794552017-06-19 10:58:08 -07001129
1130 if (profman.ShouldCreateBootProfile()) {
1131 return profman.CreateBootProfile();
1132 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001133 // Process profile information and assess if we need to do a profile guided compilation.
1134 // This operation involves I/O.
1135 return profman.ProcessProfiles();
1136}
1137
1138} // namespace art
1139
1140int main(int argc, char **argv) {
1141 return art::profman(argc, argv);
1142}
1143