blob: a5a55463232ca617de49655322107d60f6aca49d [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"
Mathieu Chartier79c87da2017-10-10 11:54:29 -070042#include "dex_file_loader.h"
Andreas Gampee2abbc62017-09-15 11:59:26 -070043#include "dex_file_types.h"
Calin Juravle33083d62017-01-18 15:29:12 -080044#include "jit/profile_compilation_info.h"
Mathieu Chartierdbddc222017-05-24 12:04:13 -070045#include "profile_assistant.h"
David Sehrf57589f2016-10-17 10:09:33 -070046#include "runtime.h"
Mathieu Chartierdbddc222017-05-24 12:04:13 -070047#include "type_reference.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000048#include "utils.h"
David Sehr546d24f2016-06-02 10:46:19 -070049#include "zip_archive.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000050
51namespace art {
52
53static int original_argc;
54static char** original_argv;
55
56static std::string CommandLine() {
57 std::vector<std::string> command;
58 for (int i = 0; i < original_argc; ++i) {
59 command.push_back(original_argv[i]);
60 }
Andreas Gampe9186ced2016-12-12 14:28:21 -080061 return android::base::Join(command, ' ');
Calin Juravle2e2db782016-02-23 12:00:03 +000062}
63
David Sehr4fcdd6d2016-05-24 14:52:31 -070064static constexpr int kInvalidFd = -1;
65
66static bool FdIsValid(int fd) {
67 return fd != kInvalidFd;
68}
69
Calin Juravle2e2db782016-02-23 12:00:03 +000070static void UsageErrorV(const char* fmt, va_list ap) {
71 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080072 android::base::StringAppendV(&error, fmt, ap);
Calin Juravle2e2db782016-02-23 12:00:03 +000073 LOG(ERROR) << error;
74}
75
76static void UsageError(const char* fmt, ...) {
77 va_list ap;
78 va_start(ap, fmt);
79 UsageErrorV(fmt, ap);
80 va_end(ap);
81}
82
83NO_RETURN static void Usage(const char *fmt, ...) {
84 va_list ap;
85 va_start(ap, fmt);
86 UsageErrorV(fmt, ap);
87 va_end(ap);
88
89 UsageError("Command: %s", CommandLine().c_str());
90 UsageError("Usage: profman [options]...");
91 UsageError("");
David Sehr4fcdd6d2016-05-24 14:52:31 -070092 UsageError(" --dump-only: dumps the content of the specified profile files");
93 UsageError(" to standard output (default) in a human readable form.");
94 UsageError("");
David Sehr7c80f2d2017-02-07 16:47:58 -080095 UsageError(" --dump-output-to-fd=<number>: redirects --dump-only output to a file descriptor.");
96 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -070097 UsageError(" --dump-classes-and-methods: dumps a sorted list of classes and methods that are");
98 UsageError(" in the specified profile file to standard output (default) in a human");
99 UsageError(" readable form. The output is valid input for --create-profile-from");
Calin Juravle876f3502016-03-24 16:16:34 +0000100 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000101 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
102 UsageError(" Can be specified multiple time, in which case the data from the different");
103 UsageError(" profiles will be aggregated.");
104 UsageError("");
105 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
106 UsageError(" Cannot be used together with --profile-file.");
107 UsageError("");
108 UsageError(" --reference-profile-file=<filename>: specify a reference profile.");
109 UsageError(" The data in this file will be compared with the data obtained by merging");
110 UsageError(" all the files specified with --profile-file or --profile-file-fd.");
111 UsageError(" If the exit code is EXIT_COMPILE then all --profile-file will be merged into");
112 UsageError(" --reference-profile-file. ");
113 UsageError("");
114 UsageError(" --reference-profile-file-fd=<number>: same as --reference-profile-file but");
115 UsageError(" accepts a file descriptor. Cannot be used together with");
116 UsageError(" --reference-profile-file.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800117 UsageError("");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100118 UsageError(" --generate-test-profile=<filename>: generates a random profile file for testing.");
119 UsageError(" --generate-test-profile-num-dex=<number>: number of dex files that should be");
120 UsageError(" included in the generated profile. Defaults to 20.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700121 UsageError(" --generate-test-profile-method-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100122 UsageError(" number of methods that should be generated. Defaults to 5.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700123 UsageError(" --generate-test-profile-class-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100124 UsageError(" number of classes that should be generated. Defaults to 5.");
Jeff Haof0a31f82017-03-27 15:50:37 -0700125 UsageError(" --generate-test-profile-seed=<number>: seed for random number generator used when");
126 UsageError(" generating random test profiles. Defaults to using NanoTime.");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100127 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -0700128 UsageError(" --create-profile-from=<filename>: creates a profile from a list of classes and");
129 UsageError(" methods.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800130 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700131 UsageError(" --dex-location=<string>: location string to use with corresponding");
132 UsageError(" apk-fd to find dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700133 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700134 UsageError(" --apk-fd=<number>: file descriptor containing an open APK to");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700135 UsageError(" search for dex files");
David Sehr7c80f2d2017-02-07 16:47:58 -0800136 UsageError(" --apk-=<filename>: an APK to search for dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700137 UsageError("");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700138 UsageError(" --generate-boot-image-profile: Generate a boot image profile based on input");
139 UsageError(" profiles. Requires passing in dex files to inspect properties of classes.");
140 UsageError(" --boot-image-class-threshold=<value>: specify minimum number of class occurrences");
141 UsageError(" to include a class in the boot image profile. Default is 10.");
142 UsageError(" --boot-image-clean-class-threshold=<value>: specify minimum number of clean class");
143 UsageError(" occurrences to include a class in the boot image profile. A clean class is a");
144 UsageError(" class that doesn't have any static fields or native methods and is likely to");
145 UsageError(" remain clean in the image. Default is 3.");
Mathieu Chartier8eecddf2017-07-12 16:05:54 -0700146 UsageError(" --boot-image-sampled-method-threshold=<value>: minimum number of profiles a");
147 UsageError(" non-hot method needs to be in order to be hot in the output profile. The");
148 UsageError(" default is max int.");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700149 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000150
151 exit(EXIT_FAILURE);
152}
153
Calin Juravle7bcdb532016-06-07 16:14:47 +0100154// Note: make sure you update the Usage if you change these values.
155static constexpr uint16_t kDefaultTestProfileNumDex = 20;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700156static constexpr uint16_t kDefaultTestProfileMethodPercentage = 5;
157static constexpr uint16_t kDefaultTestProfileClassPercentage = 5;
Calin Juravle7bcdb532016-06-07 16:14:47 +0100158
Calin Juravlee0ac1152017-02-13 19:03:47 -0800159// Separators used when parsing human friendly representation of profiles.
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800160static const std::string kMethodSep = "->"; // NOLINT [runtime/string] [4]
161static const std::string kMissingTypesMarker = "missing_types"; // NOLINT [runtime/string] [4]
162static const std::string kInvalidClassDescriptor = "invalid_class"; // NOLINT [runtime/string] [4]
163static const std::string kInvalidMethod = "invalid_method"; // NOLINT [runtime/string] [4]
164static const std::string kClassAllMethods = "*"; // NOLINT [runtime/string] [4]
Calin Juravlee0ac1152017-02-13 19:03:47 -0800165static constexpr char kProfileParsingInlineChacheSep = '+';
166static constexpr char kProfileParsingTypeSep = ',';
167static constexpr char kProfileParsingFirstCharInSignature = '(';
Mathieu Chartierea650f32017-05-24 12:04:13 -0700168static constexpr char kMethodFlagStringHot = 'H';
169static constexpr char kMethodFlagStringStartup = 'S';
170static constexpr char kMethodFlagStringPostStartup = 'P';
Calin Juravlee0ac1152017-02-13 19:03:47 -0800171
172// TODO(calin): This class has grown too much from its initial design. Split the functionality
173// into smaller, more contained pieces.
Calin Juravle2e2db782016-02-23 12:00:03 +0000174class ProfMan FINAL {
175 public:
176 ProfMan() :
David Sehr4fcdd6d2016-05-24 14:52:31 -0700177 reference_profile_file_fd_(kInvalidFd),
178 dump_only_(false),
Mathieu Chartier34067262017-04-06 13:55:46 -0700179 dump_classes_and_methods_(false),
Mathieu Chartier2f794552017-06-19 10:58:08 -0700180 generate_boot_image_profile_(false),
David Sehr4fcdd6d2016-05-24 14:52:31 -0700181 dump_output_to_fd_(kInvalidFd),
Calin Juravle7bcdb532016-06-07 16:14:47 +0100182 test_profile_num_dex_(kDefaultTestProfileNumDex),
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700183 test_profile_method_percerntage_(kDefaultTestProfileMethodPercentage),
184 test_profile_class_percentage_(kDefaultTestProfileClassPercentage),
Jeff Haof0a31f82017-03-27 15:50:37 -0700185 test_profile_seed_(NanoTime()),
Calin Juravle2e2db782016-02-23 12:00:03 +0000186 start_ns_(NanoTime()) {}
187
188 ~ProfMan() {
189 LogCompletionTime();
190 }
191
192 void ParseArgs(int argc, char **argv) {
193 original_argc = argc;
194 original_argv = argv;
195
Andreas Gampe51d80cc2017-06-21 21:05:13 -0700196 InitLogging(argv, Runtime::Abort);
Calin Juravle2e2db782016-02-23 12:00:03 +0000197
198 // Skip over the command name.
199 argv++;
200 argc--;
201
202 if (argc == 0) {
203 Usage("No arguments specified");
204 }
205
206 for (int i = 0; i < argc; ++i) {
207 const StringPiece option(argv[i]);
208 const bool log_options = false;
209 if (log_options) {
Calin Juravle876f3502016-03-24 16:16:34 +0000210 LOG(INFO) << "profman: option[" << i << "]=" << argv[i];
Calin Juravle2e2db782016-02-23 12:00:03 +0000211 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700212 if (option == "--dump-only") {
213 dump_only_ = true;
Mathieu Chartier34067262017-04-06 13:55:46 -0700214 } else if (option == "--dump-classes-and-methods") {
215 dump_classes_and_methods_ = true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800216 } else if (option.starts_with("--create-profile-from=")) {
217 create_profile_from_file_ = option.substr(strlen("--create-profile-from=")).ToString();
David Sehr4fcdd6d2016-05-24 14:52:31 -0700218 } else if (option.starts_with("--dump-output-to-fd=")) {
219 ParseUintOption(option, "--dump-output-to-fd", &dump_output_to_fd_, Usage);
Mathieu Chartier2f794552017-06-19 10:58:08 -0700220 } else if (option == "--generate-boot-image-profile") {
221 generate_boot_image_profile_ = true;
222 } else if (option.starts_with("--boot-image-class-threshold=")) {
223 ParseUintOption(option,
224 "--boot-image-class-threshold",
225 &boot_image_options_.image_class_theshold,
226 Usage);
227 } else if (option.starts_with("--boot-image-clean-class-threshold=")) {
228 ParseUintOption(option,
229 "--boot-image-clean-class-threshold",
230 &boot_image_options_.image_class_clean_theshold,
231 Usage);
Mathieu Chartier8eecddf2017-07-12 16:05:54 -0700232 } else if (option.starts_with("--boot-image-sampled-method-threshold=")) {
233 ParseUintOption(option,
234 "--boot-image-sampled-method-threshold",
235 &boot_image_options_.compiled_method_threshold,
236 Usage);
Calin Juravle876f3502016-03-24 16:16:34 +0000237 } else if (option.starts_with("--profile-file=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000238 profile_files_.push_back(option.substr(strlen("--profile-file=")).ToString());
239 } else if (option.starts_with("--profile-file-fd=")) {
240 ParseFdForCollection(option, "--profile-file-fd", &profile_files_fd_);
241 } else if (option.starts_with("--reference-profile-file=")) {
242 reference_profile_file_ = option.substr(strlen("--reference-profile-file=")).ToString();
243 } else if (option.starts_with("--reference-profile-file-fd=")) {
244 ParseUintOption(option, "--reference-profile-file-fd", &reference_profile_file_fd_, Usage);
David Sehr546d24f2016-06-02 10:46:19 -0700245 } else if (option.starts_with("--dex-location=")) {
246 dex_locations_.push_back(option.substr(strlen("--dex-location=")).ToString());
247 } else if (option.starts_with("--apk-fd=")) {
248 ParseFdForCollection(option, "--apk-fd", &apks_fd_);
David Sehr7c80f2d2017-02-07 16:47:58 -0800249 } else if (option.starts_with("--apk=")) {
250 apk_files_.push_back(option.substr(strlen("--apk=")).ToString());
Calin Juravle7bcdb532016-06-07 16:14:47 +0100251 } else if (option.starts_with("--generate-test-profile=")) {
252 test_profile_ = option.substr(strlen("--generate-test-profile=")).ToString();
253 } else if (option.starts_with("--generate-test-profile-num-dex=")) {
254 ParseUintOption(option,
255 "--generate-test-profile-num-dex",
256 &test_profile_num_dex_,
257 Usage);
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700258 } else if (option.starts_with("--generate-test-profile-method-percentage")) {
Calin Juravle7bcdb532016-06-07 16:14:47 +0100259 ParseUintOption(option,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700260 "--generate-test-profile-method-percentage",
261 &test_profile_method_percerntage_,
Calin Juravle7bcdb532016-06-07 16:14:47 +0100262 Usage);
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700263 } else if (option.starts_with("--generate-test-profile-class-percentage")) {
Calin Juravle7bcdb532016-06-07 16:14:47 +0100264 ParseUintOption(option,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700265 "--generate-test-profile-class-percentage",
266 &test_profile_class_percentage_,
Calin Juravle7bcdb532016-06-07 16:14:47 +0100267 Usage);
Jeff Haof0a31f82017-03-27 15:50:37 -0700268 } else if (option.starts_with("--generate-test-profile-seed=")) {
269 ParseUintOption(option, "--generate-test-profile-seed", &test_profile_seed_, Usage);
Calin Juravle2e2db782016-02-23 12:00:03 +0000270 } else {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700271 Usage("Unknown argument '%s'", option.data());
Calin Juravle2e2db782016-02-23 12:00:03 +0000272 }
273 }
274
David Sehr153da0e2017-02-15 08:54:51 -0800275 // Validate global consistency between file/fd options.
Calin Juravle2e2db782016-02-23 12:00:03 +0000276 if (!profile_files_.empty() && !profile_files_fd_.empty()) {
277 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
278 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700279 if (!reference_profile_file_.empty() && FdIsValid(reference_profile_file_fd_)) {
280 Usage("Reference profile should not be specified with both "
281 "--reference-profile-file-fd and --reference-profile-file");
282 }
David Sehr153da0e2017-02-15 08:54:51 -0800283 if (!apk_files_.empty() && !apks_fd_.empty()) {
284 Usage("APK files should not be specified with both --apk-fd and --apk");
Calin Juravle2e2db782016-02-23 12:00:03 +0000285 }
286 }
287
288 ProfileAssistant::ProcessingResult ProcessProfiles() {
David Sehr153da0e2017-02-15 08:54:51 -0800289 // Validate that at least one profile file was passed, as well as a reference profile.
290 if (profile_files_.empty() && profile_files_fd_.empty()) {
291 Usage("No profile files specified.");
292 }
293 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
294 Usage("No reference profile file specified.");
295 }
296 if ((!profile_files_.empty() && FdIsValid(reference_profile_file_fd_)) ||
297 (!profile_files_fd_.empty() && !FdIsValid(reference_profile_file_fd_))) {
298 Usage("Options --profile-file-fd and --reference-profile-file-fd "
299 "should only be used together");
300 }
Calin Juravle2e2db782016-02-23 12:00:03 +0000301 ProfileAssistant::ProcessingResult result;
302 if (profile_files_.empty()) {
303 // The file doesn't need to be flushed here (ProcessProfiles will do it)
304 // so don't check the usage.
305 File file(reference_profile_file_fd_, false);
306 result = ProfileAssistant::ProcessProfiles(profile_files_fd_, reference_profile_file_fd_);
307 CloseAllFds(profile_files_fd_, "profile_files_fd_");
308 } else {
309 result = ProfileAssistant::ProcessProfiles(profile_files_, reference_profile_file_);
310 }
311 return result;
312 }
313
David Sehr7c80f2d2017-02-07 16:47:58 -0800314 void OpenApkFilesFromLocations(std::vector<std::unique_ptr<const DexFile>>* dex_files) {
315 bool use_apk_fd_list = !apks_fd_.empty();
316 if (use_apk_fd_list) {
David Sehr153da0e2017-02-15 08:54:51 -0800317 // Get the APKs from the collection of FDs.
David Sehr7c80f2d2017-02-07 16:47:58 -0800318 CHECK_EQ(dex_locations_.size(), apks_fd_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800319 } else if (!apk_files_.empty()) {
320 // Get the APKs from the collection of filenames.
David Sehr7c80f2d2017-02-07 16:47:58 -0800321 CHECK_EQ(dex_locations_.size(), apk_files_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800322 } else {
323 // No APKs were specified.
324 CHECK(dex_locations_.empty());
325 return;
David Sehr7c80f2d2017-02-07 16:47:58 -0800326 }
327 static constexpr bool kVerifyChecksum = true;
328 for (size_t i = 0; i < dex_locations_.size(); ++i) {
329 std::string error_msg;
330 std::vector<std::unique_ptr<const DexFile>> dex_files_for_location;
331 if (use_apk_fd_list) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700332 if (DexFileLoader::OpenZip(apks_fd_[i],
333 dex_locations_[i],
Nicolas Geoffray095c6c92017-10-19 13:59:55 +0100334 /* verify */ true,
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700335 kVerifyChecksum,
336 &error_msg,
337 &dex_files_for_location)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800338 } else {
339 LOG(WARNING) << "OpenZip failed for '" << dex_locations_[i] << "' " << error_msg;
340 continue;
341 }
342 } else {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700343 if (DexFileLoader::Open(apk_files_[i].c_str(),
344 dex_locations_[i],
Nicolas Geoffray095c6c92017-10-19 13:59:55 +0100345 /* verify */ true,
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700346 kVerifyChecksum,
347 &error_msg,
348 &dex_files_for_location)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800349 } else {
350 LOG(WARNING) << "Open failed for '" << dex_locations_[i] << "' " << error_msg;
351 continue;
352 }
353 }
354 for (std::unique_ptr<const DexFile>& dex_file : dex_files_for_location) {
355 dex_files->emplace_back(std::move(dex_file));
356 }
357 }
358 }
359
Mathieu Chartier2f794552017-06-19 10:58:08 -0700360 std::unique_ptr<const ProfileCompilationInfo> LoadProfile(const std::string& filename, int fd) {
361 if (!filename.empty()) {
362 fd = open(filename.c_str(), O_RDWR);
363 if (fd < 0) {
364 LOG(ERROR) << "Cannot open " << filename << strerror(errno);
365 return nullptr;
366 }
367 }
368 std::unique_ptr<ProfileCompilationInfo> info(new ProfileCompilationInfo);
369 if (!info->Load(fd)) {
370 LOG(ERROR) << "Cannot load profile info from fd=" << fd << "\n";
371 return nullptr;
372 }
373 return info;
374 }
375
David Sehrb18991b2017-02-08 20:58:10 -0800376 int DumpOneProfile(const std::string& banner,
377 const std::string& filename,
378 int fd,
379 const std::vector<std::unique_ptr<const DexFile>>* dex_files,
380 std::string* dump) {
Mathieu Chartier2f794552017-06-19 10:58:08 -0700381 std::unique_ptr<const ProfileCompilationInfo> info(LoadProfile(filename, fd));
382 if (info == nullptr) {
383 LOG(ERROR) << "Cannot load profile info from filename=" << filename << " fd=" << fd;
Calin Juravle876f3502016-03-24 16:16:34 +0000384 return -1;
385 }
Mathieu Chartier2f794552017-06-19 10:58:08 -0700386 *dump += banner + "\n" + info->DumpInfo(dex_files) + "\n";
David Sehr4fcdd6d2016-05-24 14:52:31 -0700387 return 0;
388 }
389
390 int DumpProfileInfo() {
David Sehr153da0e2017-02-15 08:54:51 -0800391 // Validate that at least one profile file or reference was specified.
392 if (profile_files_.empty() && profile_files_fd_.empty() &&
393 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
394 Usage("No profile files or reference profile specified.");
395 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700396 static const char* kEmptyString = "";
David Sehr546d24f2016-06-02 10:46:19 -0700397 static const char* kOrdinaryProfile = "=== profile ===";
398 static const char* kReferenceProfile = "=== reference profile ===";
399
400 // Open apk/zip files and and read dex files.
401 MemMap::Init(); // for ZipArchive::OpenFromFd
David Sehrb18991b2017-02-08 20:58:10 -0800402 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7c80f2d2017-02-07 16:47:58 -0800403 OpenApkFilesFromLocations(&dex_files);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700404 std::string dump;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700405 // Dump individual profile files.
406 if (!profile_files_fd_.empty()) {
407 for (int profile_file_fd : profile_files_fd_) {
David Sehr546d24f2016-06-02 10:46:19 -0700408 int ret = DumpOneProfile(kOrdinaryProfile,
409 kEmptyString,
410 profile_file_fd,
411 &dex_files,
412 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700413 if (ret != 0) {
414 return ret;
415 }
416 }
417 }
418 if (!profile_files_.empty()) {
419 for (const std::string& profile_file : profile_files_) {
David Sehr546d24f2016-06-02 10:46:19 -0700420 int ret = DumpOneProfile(kOrdinaryProfile, profile_file, kInvalidFd, &dex_files, &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700421 if (ret != 0) {
422 return ret;
423 }
424 }
425 }
426 // Dump reference profile file.
427 if (FdIsValid(reference_profile_file_fd_)) {
David Sehr546d24f2016-06-02 10:46:19 -0700428 int ret = DumpOneProfile(kReferenceProfile,
429 kEmptyString,
430 reference_profile_file_fd_,
431 &dex_files,
432 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700433 if (ret != 0) {
434 return ret;
435 }
436 }
437 if (!reference_profile_file_.empty()) {
David Sehr546d24f2016-06-02 10:46:19 -0700438 int ret = DumpOneProfile(kReferenceProfile,
439 reference_profile_file_,
440 kInvalidFd,
441 &dex_files,
David Sehr4fcdd6d2016-05-24 14:52:31 -0700442 &dump);
443 if (ret != 0) {
444 return ret;
445 }
446 }
447 if (!FdIsValid(dump_output_to_fd_)) {
448 std::cout << dump;
449 } else {
450 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
451 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
452 return -1;
453 }
454 }
Calin Juravle876f3502016-03-24 16:16:34 +0000455 return 0;
456 }
457
458 bool ShouldOnlyDumpProfile() {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700459 return dump_only_;
Calin Juravle876f3502016-03-24 16:16:34 +0000460 }
461
Mathieu Chartier34067262017-04-06 13:55:46 -0700462 bool GetClassNamesAndMethods(int fd,
463 std::vector<std::unique_ptr<const DexFile>>* dex_files,
464 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800465 ProfileCompilationInfo profile_info;
466 if (!profile_info.Load(fd)) {
467 LOG(ERROR) << "Cannot load profile info";
468 return false;
469 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700470 for (const std::unique_ptr<const DexFile>& dex_file : *dex_files) {
471 std::set<dex::TypeIndex> class_types;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700472 std::set<uint16_t> hot_methods;
473 std::set<uint16_t> startup_methods;
474 std::set<uint16_t> post_startup_methods;
475 std::set<uint16_t> combined_methods;
476 if (profile_info.GetClassesAndMethods(*dex_file.get(),
477 &class_types,
478 &hot_methods,
479 &startup_methods,
480 &post_startup_methods)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700481 for (const dex::TypeIndex& type_index : class_types) {
482 const DexFile::TypeId& type_id = dex_file->GetTypeId(type_index);
483 out_lines->insert(std::string(dex_file->GetTypeDescriptor(type_id)));
484 }
Mathieu Chartierea650f32017-05-24 12:04:13 -0700485 combined_methods = hot_methods;
486 combined_methods.insert(startup_methods.begin(), startup_methods.end());
487 combined_methods.insert(post_startup_methods.begin(), post_startup_methods.end());
488 for (uint16_t dex_method_idx : combined_methods) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700489 const DexFile::MethodId& id = dex_file->GetMethodId(dex_method_idx);
490 std::string signature_string(dex_file->GetMethodSignature(id).ToString());
491 std::string type_string(dex_file->GetTypeDescriptor(dex_file->GetTypeId(id.class_idx_)));
492 std::string method_name(dex_file->GetMethodName(id));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700493 std::string flags_string;
494 if (hot_methods.find(dex_method_idx) != hot_methods.end()) {
495 flags_string += kMethodFlagStringHot;
496 }
497 if (startup_methods.find(dex_method_idx) != startup_methods.end()) {
498 flags_string += kMethodFlagStringStartup;
499 }
500 if (post_startup_methods.find(dex_method_idx) != post_startup_methods.end()) {
501 flags_string += kMethodFlagStringPostStartup;
502 }
503 out_lines->insert(flags_string +
504 type_string +
505 kMethodSep +
506 method_name +
507 signature_string);
Mathieu Chartier34067262017-04-06 13:55:46 -0700508 }
509 }
510 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800511 return true;
512 }
513
Mathieu Chartier34067262017-04-06 13:55:46 -0700514 bool GetClassNamesAndMethods(const std::string& profile_file,
515 std::vector<std::unique_ptr<const DexFile>>* dex_files,
516 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800517 int fd = open(profile_file.c_str(), O_RDONLY);
518 if (!FdIsValid(fd)) {
519 LOG(ERROR) << "Cannot open " << profile_file << strerror(errno);
520 return false;
521 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700522 if (!GetClassNamesAndMethods(fd, dex_files, out_lines)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800523 return false;
524 }
525 if (close(fd) < 0) {
526 PLOG(WARNING) << "Failed to close descriptor";
527 }
528 return true;
529 }
530
Mathieu Chartierea650f32017-05-24 12:04:13 -0700531 int DumpClassesAndMethods() {
David Sehr153da0e2017-02-15 08:54:51 -0800532 // Validate that at least one profile file or reference was specified.
533 if (profile_files_.empty() && profile_files_fd_.empty() &&
534 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
535 Usage("No profile files or reference profile specified.");
536 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800537 // Open apk/zip files and and read dex files.
538 MemMap::Init(); // for ZipArchive::OpenFromFd
539 // Open the dex files to get the names for classes.
540 std::vector<std::unique_ptr<const DexFile>> dex_files;
541 OpenApkFilesFromLocations(&dex_files);
542 // Build a vector of class names from individual profile files.
543 std::set<std::string> class_names;
544 if (!profile_files_fd_.empty()) {
545 for (int profile_file_fd : profile_files_fd_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700546 if (!GetClassNamesAndMethods(profile_file_fd, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800547 return -1;
548 }
549 }
550 }
551 if (!profile_files_.empty()) {
552 for (const std::string& profile_file : profile_files_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700553 if (!GetClassNamesAndMethods(profile_file, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800554 return -1;
555 }
556 }
557 }
558 // Concatenate class names from reference profile file.
559 if (FdIsValid(reference_profile_file_fd_)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700560 if (!GetClassNamesAndMethods(reference_profile_file_fd_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800561 return -1;
562 }
563 }
564 if (!reference_profile_file_.empty()) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700565 if (!GetClassNamesAndMethods(reference_profile_file_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800566 return -1;
567 }
568 }
569 // Dump the class names.
570 std::string dump;
571 for (const std::string& class_name : class_names) {
572 dump += class_name + std::string("\n");
573 }
574 if (!FdIsValid(dump_output_to_fd_)) {
575 std::cout << dump;
576 } else {
577 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
578 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
579 return -1;
580 }
581 }
582 return 0;
583 }
584
Mathieu Chartier34067262017-04-06 13:55:46 -0700585 bool ShouldOnlyDumpClassesAndMethods() {
586 return dump_classes_and_methods_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800587 }
588
589 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
590 // the given function.
591 template <typename T>
592 static T* ReadCommentedInputFromFile(
593 const char* input_filename, std::function<std::string(const char*)>* process) {
594 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
595 if (input_file.get() == nullptr) {
596 LOG(ERROR) << "Failed to open input file " << input_filename;
597 return nullptr;
598 }
599 std::unique_ptr<T> result(
600 ReadCommentedInputStream<T>(*input_file, process));
601 input_file->close();
602 return result.release();
603 }
604
605 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
606 // with the given function.
607 template <typename T>
608 static T* ReadCommentedInputStream(
609 std::istream& in_stream,
610 std::function<std::string(const char*)>* process) {
611 std::unique_ptr<T> output(new T());
612 while (in_stream.good()) {
613 std::string dot;
614 std::getline(in_stream, dot);
615 if (android::base::StartsWith(dot, "#") || dot.empty()) {
616 continue;
617 }
618 if (process != nullptr) {
619 std::string descriptor((*process)(dot.c_str()));
620 output->insert(output->end(), descriptor);
621 } else {
622 output->insert(output->end(), dot);
623 }
624 }
625 return output.release();
626 }
627
Calin Juravlee0ac1152017-02-13 19:03:47 -0800628 // Find class klass_descriptor in the given dex_files and store its reference
629 // in the out parameter class_ref.
630 // Return true if the definition of the class was found in any of the dex_files.
631 bool FindClass(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
632 const std::string& klass_descriptor,
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700633 /*out*/TypeReference* class_ref) {
Calin Juravle08556882017-05-26 16:40:45 -0700634 constexpr uint16_t kInvalidTypeIndex = std::numeric_limits<uint16_t>::max() - 1;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800635 for (const std::unique_ptr<const DexFile>& dex_file_ptr : dex_files) {
636 const DexFile* dex_file = dex_file_ptr.get();
Calin Juravle08556882017-05-26 16:40:45 -0700637 if (klass_descriptor == kInvalidClassDescriptor) {
638 if (kInvalidTypeIndex >= dex_file->NumTypeIds()) {
639 // The dex file does not contain all possible type ids which leaves us room
640 // to add an "invalid" type id.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700641 *class_ref = TypeReference(dex_file, dex::TypeIndex(kInvalidTypeIndex));
Calin Juravle08556882017-05-26 16:40:45 -0700642 return true;
643 } else {
644 // The dex file contains all possible type ids. We don't have any free type id
645 // that we can use as invalid.
646 continue;
647 }
648 }
649
Calin Juravlee0ac1152017-02-13 19:03:47 -0800650 const DexFile::TypeId* type_id = dex_file->FindTypeId(klass_descriptor.c_str());
651 if (type_id == nullptr) {
652 continue;
653 }
654 dex::TypeIndex type_index = dex_file->GetIndexForTypeId(*type_id);
655 if (dex_file->FindClassDef(type_index) == nullptr) {
656 // Class is only referenced in the current dex file but not defined in it.
657 continue;
658 }
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700659 *class_ref = TypeReference(dex_file, type_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800660 return true;
661 }
662 return false;
663 }
664
Mathieu Chartier34067262017-04-06 13:55:46 -0700665 // Find the method specified by method_spec in the class class_ref.
Calin Juravle08556882017-05-26 16:40:45 -0700666 uint32_t FindMethodIndex(const TypeReference& class_ref,
667 const std::string& method_spec) {
668 const DexFile* dex_file = class_ref.dex_file;
669 if (method_spec == kInvalidMethod) {
670 constexpr uint16_t kInvalidMethodIndex = std::numeric_limits<uint16_t>::max() - 1;
671 return kInvalidMethodIndex >= dex_file->NumMethodIds()
672 ? kInvalidMethodIndex
Andreas Gampee2abbc62017-09-15 11:59:26 -0700673 : dex::kDexNoIndex;
Calin Juravle08556882017-05-26 16:40:45 -0700674 }
675
Calin Juravlee0ac1152017-02-13 19:03:47 -0800676 std::vector<std::string> name_and_signature;
677 Split(method_spec, kProfileParsingFirstCharInSignature, &name_and_signature);
678 if (name_and_signature.size() != 2) {
679 LOG(ERROR) << "Invalid method name and signature " << method_spec;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700680 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800681 }
Calin Juravle08556882017-05-26 16:40:45 -0700682
Calin Juravlee0ac1152017-02-13 19:03:47 -0800683 const std::string& name = name_and_signature[0];
684 const std::string& signature = kProfileParsingFirstCharInSignature + name_and_signature[1];
Calin Juravlee0ac1152017-02-13 19:03:47 -0800685
686 const DexFile::StringId* name_id = dex_file->FindStringId(name.c_str());
687 if (name_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700688 LOG(WARNING) << "Could not find name: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700689 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800690 }
691 dex::TypeIndex return_type_idx;
692 std::vector<dex::TypeIndex> param_type_idxs;
693 if (!dex_file->CreateTypeList(signature, &return_type_idx, &param_type_idxs)) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700694 LOG(WARNING) << "Could not create type list" << signature;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700695 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800696 }
697 const DexFile::ProtoId* proto_id = dex_file->FindProtoId(return_type_idx, param_type_idxs);
698 if (proto_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700699 LOG(WARNING) << "Could not find proto_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700700 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800701 }
702 const DexFile::MethodId* method_id = dex_file->FindMethodId(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700703 dex_file->GetTypeId(class_ref.TypeIndex()), *name_id, *proto_id);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800704 if (method_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700705 LOG(WARNING) << "Could not find method_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700706 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800707 }
708
Mathieu Chartier34067262017-04-06 13:55:46 -0700709 return dex_file->GetIndexForMethodId(*method_id);
710 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800711
Mathieu Chartier34067262017-04-06 13:55:46 -0700712 // Given a method, return true if the method has a single INVOKE_VIRTUAL in its byte code.
713 // Upon success it returns true and stores the method index and the invoke dex pc
714 // in the output parameters.
715 // The format of the method spec is "inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
716 //
717 // TODO(calin): support INVOKE_INTERFACE and the range variants.
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700718 bool HasSingleInvoke(const TypeReference& class_ref,
Mathieu Chartier34067262017-04-06 13:55:46 -0700719 uint16_t method_index,
720 /*out*/uint32_t* dex_pc) {
721 const DexFile* dex_file = class_ref.dex_file;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800722 uint32_t offset = dex_file->FindCodeItemOffset(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700723 *dex_file->FindClassDef(class_ref.TypeIndex()),
Mathieu Chartier34067262017-04-06 13:55:46 -0700724 method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800725 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(offset);
726
727 bool found_invoke = false;
Mathieu Chartier0021feb2017-11-07 00:08:52 -0800728 for (const DexInstructionPcPair& inst : code_item->Instructions()) {
729 if (inst->Opcode() == Instruction::INVOKE_VIRTUAL) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800730 if (found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700731 LOG(ERROR) << "Multiple invoke INVOKE_VIRTUAL found: "
732 << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800733 return false;
734 }
735 found_invoke = true;
Mathieu Chartier0021feb2017-11-07 00:08:52 -0800736 *dex_pc = inst.DexPc();
Calin Juravlee0ac1152017-02-13 19:03:47 -0800737 }
738 }
739 if (!found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700740 LOG(ERROR) << "Could not find any INVOKE_VIRTUAL: " << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800741 }
742 return found_invoke;
743 }
744
745 // Process a line defining a class or a method and its inline caches.
746 // Upon success return true and add the class or the method info to profile.
Calin Juravle589e71e2017-03-03 16:05:05 -0800747 // The possible line formats are:
748 // "LJustTheCass;".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800749 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
Calin Juravle08556882017-05-26 16:40:45 -0700750 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,invalid_class".
Calin Juravle589e71e2017-03-03 16:05:05 -0800751 // "LTestInline;->inlineMissingTypes(LSuper;)I+missing_types".
752 // "LTestInline;->inlineNoInlineCaches(LSuper;)I".
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700753 // "LTestInline;->*".
Calin Juravle08556882017-05-26 16:40:45 -0700754 // "invalid_class".
755 // "LTestInline;->invalid_method".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800756 // The method and classes are searched only in the given dex files.
757 bool ProcessLine(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
758 const std::string& line,
759 /*out*/ProfileCompilationInfo* profile) {
760 std::string klass;
761 std::string method_str;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700762 bool is_hot = false;
763 bool is_startup = false;
764 bool is_post_startup = false;
765 const size_t method_sep_index = line.find(kMethodSep, 0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800766 if (method_sep_index == std::string::npos) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700767 klass = line.substr(0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800768 } else {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700769 // The method prefix flags are only valid for method strings.
770 size_t start_index = 0;
771 while (start_index < line.size() && line[start_index] != 'L') {
772 const char c = line[start_index];
773 if (c == kMethodFlagStringHot) {
774 is_hot = true;
775 } else if (c == kMethodFlagStringStartup) {
776 is_startup = true;
777 } else if (c == kMethodFlagStringPostStartup) {
778 is_post_startup = true;
779 } else {
780 LOG(WARNING) << "Invalid flag " << c;
781 return false;
782 }
783 ++start_index;
784 }
785 klass = line.substr(start_index, method_sep_index - start_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800786 method_str = line.substr(method_sep_index + kMethodSep.size());
787 }
788
Vladimir Markof3c52b42017-11-17 17:32:12 +0000789 TypeReference class_ref(/* dex_file */ nullptr, dex::TypeIndex());
Calin Juravlee0ac1152017-02-13 19:03:47 -0800790 if (!FindClass(dex_files, klass, &class_ref)) {
Mathieu Chartier3f121342017-03-06 11:16:20 -0800791 LOG(WARNING) << "Could not find class: " << klass;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800792 return false;
793 }
794
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700795 if (method_str.empty() || method_str == kClassAllMethods) {
796 // Start by adding the class.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800797 std::set<DexCacheResolvedClasses> resolved_class_set;
798 const DexFile* dex_file = class_ref.dex_file;
799 const auto& dex_resolved_classes = resolved_class_set.emplace(
800 dex_file->GetLocation(),
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700801 DexFileLoader::GetBaseLocation(dex_file->GetLocation()),
Mathieu Chartierea650f32017-05-24 12:04:13 -0700802 dex_file->GetLocationChecksum(),
803 dex_file->NumMethodIds());
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700804 dex_resolved_classes.first->AddClass(class_ref.TypeIndex());
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700805 std::vector<ProfileMethodInfo> methods;
806 if (method_str == kClassAllMethods) {
807 // Add all of the methods.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700808 const DexFile::ClassDef* class_def = dex_file->FindClassDef(class_ref.TypeIndex());
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700809 const uint8_t* class_data = dex_file->GetClassData(*class_def);
810 if (class_data != nullptr) {
811 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700812 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800813 while (it.HasNextMethod()) {
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700814 if (it.GetMethodCodeItemOffset() != 0) {
815 // Add all of the methods that have code to the profile.
816 const uint32_t method_idx = it.GetMemberIndex();
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700817 methods.push_back(ProfileMethodInfo(MethodReference(dex_file, method_idx)));
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700818 }
819 it.Next();
820 }
821 }
822 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700823 // TODO: Check return values?
824 profile->AddMethods(methods);
825 profile->AddClasses(resolved_class_set);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800826 return true;
827 }
828
829 // Process the method.
830 std::string method_spec;
831 std::vector<std::string> inline_cache_elems;
832
Mathieu Chartierea650f32017-05-24 12:04:13 -0700833 // If none of the flags are set, default to hot.
834 is_hot = is_hot || (!is_hot && !is_startup && !is_post_startup);
835
Calin Juravlee0ac1152017-02-13 19:03:47 -0800836 std::vector<std::string> method_elems;
Calin Juravle589e71e2017-03-03 16:05:05 -0800837 bool is_missing_types = false;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800838 Split(method_str, kProfileParsingInlineChacheSep, &method_elems);
839 if (method_elems.size() == 2) {
840 method_spec = method_elems[0];
Calin Juravle589e71e2017-03-03 16:05:05 -0800841 is_missing_types = method_elems[1] == kMissingTypesMarker;
842 if (!is_missing_types) {
843 Split(method_elems[1], kProfileParsingTypeSep, &inline_cache_elems);
844 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800845 } else if (method_elems.size() == 1) {
846 method_spec = method_elems[0];
847 } else {
848 LOG(ERROR) << "Invalid method line: " << line;
849 return false;
850 }
851
Mathieu Chartier34067262017-04-06 13:55:46 -0700852 const uint32_t method_index = FindMethodIndex(class_ref, method_spec);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700853 if (method_index == dex::kDexNoIndex) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800854 return false;
855 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700856
Mathieu Chartier34067262017-04-06 13:55:46 -0700857 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
858 if (is_missing_types || !inline_cache_elems.empty()) {
859 uint32_t dex_pc;
860 if (!HasSingleInvoke(class_ref, method_index, &dex_pc)) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800861 return false;
862 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000863 std::vector<TypeReference> classes(inline_cache_elems.size(),
864 TypeReference(/* dex_file */ nullptr, dex::TypeIndex()));
Mathieu Chartier34067262017-04-06 13:55:46 -0700865 size_t class_it = 0;
866 for (const std::string& ic_class : inline_cache_elems) {
867 if (!FindClass(dex_files, ic_class, &(classes[class_it++]))) {
868 LOG(ERROR) << "Could not find class: " << ic_class;
869 return false;
870 }
871 }
872 inline_caches.emplace_back(dex_pc, is_missing_types, classes);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800873 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700874 MethodReference ref(class_ref.dex_file, method_index);
Mathieu Chartierea650f32017-05-24 12:04:13 -0700875 if (is_hot) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700876 profile->AddMethod(ProfileMethodInfo(ref, inline_caches));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700877 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700878 uint32_t flags = 0;
879 using Hotness = ProfileCompilationInfo::MethodHotness;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700880 if (is_startup) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700881 flags |= Hotness::kFlagStartup;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700882 }
883 if (is_post_startup) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700884 flags |= Hotness::kFlagPostStartup;
885 }
886 if (flags != 0) {
887 if (!profile->AddMethodIndex(static_cast<Hotness::Flag>(flags), ref)) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700888 return false;
889 }
Mathieu Chartiere46f3a82017-06-19 19:54:12 -0700890 DCHECK(profile->GetMethodHotness(ref).IsInProfile());
Mathieu Chartierea650f32017-05-24 12:04:13 -0700891 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800892 return true;
893 }
894
Mathieu Chartier2f794552017-06-19 10:58:08 -0700895 int OpenReferenceProfile() const {
896 int fd = reference_profile_file_fd_;
897 if (!FdIsValid(fd)) {
898 CHECK(!reference_profile_file_.empty());
899 fd = open(reference_profile_file_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
900 if (fd < 0) {
901 LOG(ERROR) << "Cannot open " << reference_profile_file_ << strerror(errno);
902 return kInvalidFd;
903 }
904 }
905 return fd;
906 }
907
Calin Juravlee0ac1152017-02-13 19:03:47 -0800908 // Creates a profile from a human friendly textual representation.
909 // The expected input format is:
910 // # Classes
911 // Ljava/lang/Comparable;
912 // Ljava/lang/Math;
913 // # Methods with inline caches
914 // LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;
915 // LTestInline;->noInlineCache(LSuper;)I
David Sehr7c80f2d2017-02-07 16:47:58 -0800916 int CreateProfile() {
David Sehr153da0e2017-02-15 08:54:51 -0800917 // Validate parameters for this command.
918 if (apk_files_.empty() && apks_fd_.empty()) {
919 Usage("APK files must be specified");
920 }
921 if (dex_locations_.empty()) {
922 Usage("DEX locations must be specified");
923 }
924 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
925 Usage("Reference profile must be specified with --reference-profile-file or "
926 "--reference-profile-file-fd");
927 }
928 if (!profile_files_.empty() || !profile_files_fd_.empty()) {
929 Usage("Profile must be specified with --reference-profile-file or "
930 "--reference-profile-file-fd");
931 }
932 // for ZipArchive::OpenFromFd
933 MemMap::Init();
David Sehr7c80f2d2017-02-07 16:47:58 -0800934 // Open the profile output file if needed.
Mathieu Chartier2f794552017-06-19 10:58:08 -0700935 int fd = OpenReferenceProfile();
David Sehr7c80f2d2017-02-07 16:47:58 -0800936 if (!FdIsValid(fd)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800937 return -1;
David Sehr7c80f2d2017-02-07 16:47:58 -0800938 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800939 // Read the user-specified list of classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800940 std::unique_ptr<std::unordered_set<std::string>>
Calin Juravlee0ac1152017-02-13 19:03:47 -0800941 user_lines(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
David Sehr7c80f2d2017-02-07 16:47:58 -0800942 create_profile_from_file_.c_str(), nullptr)); // No post-processing.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800943
944 // Open the dex files to look up classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800945 std::vector<std::unique_ptr<const DexFile>> dex_files;
946 OpenApkFilesFromLocations(&dex_files);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800947
948 // Process the lines one by one and add the successful ones to the profile.
David Sehr7c80f2d2017-02-07 16:47:58 -0800949 ProfileCompilationInfo info;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800950
951 for (const auto& line : *user_lines) {
952 ProcessLine(dex_files, line, &info);
953 }
954
David Sehr7c80f2d2017-02-07 16:47:58 -0800955 // Write the profile file.
956 CHECK(info.Save(fd));
957 if (close(fd) < 0) {
958 PLOG(WARNING) << "Failed to close descriptor";
959 }
960 return 0;
961 }
962
Mathieu Chartier2f794552017-06-19 10:58:08 -0700963 bool ShouldCreateBootProfile() const {
964 return generate_boot_image_profile_;
965 }
966
967 int CreateBootProfile() {
968 // Initialize memmap since it's required to open dex files.
969 MemMap::Init();
970 // Open the profile output file.
971 const int reference_fd = OpenReferenceProfile();
972 if (!FdIsValid(reference_fd)) {
973 PLOG(ERROR) << "Error opening reference profile";
974 return -1;
975 }
976 // Open the dex files.
977 std::vector<std::unique_ptr<const DexFile>> dex_files;
978 OpenApkFilesFromLocations(&dex_files);
979 if (dex_files.empty()) {
980 PLOG(ERROR) << "Expected dex files for creating boot profile";
981 return -2;
982 }
983 // Open the input profiles.
984 std::vector<std::unique_ptr<const ProfileCompilationInfo>> profiles;
985 if (!profile_files_fd_.empty()) {
986 for (int profile_file_fd : profile_files_fd_) {
987 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile("", profile_file_fd));
988 if (profile == nullptr) {
989 return -3;
990 }
991 profiles.emplace_back(std::move(profile));
992 }
993 }
994 if (!profile_files_.empty()) {
995 for (const std::string& profile_file : profile_files_) {
996 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile(profile_file, kInvalidFd));
997 if (profile == nullptr) {
998 return -4;
999 }
1000 profiles.emplace_back(std::move(profile));
1001 }
1002 }
1003 ProfileCompilationInfo out_profile;
1004 GenerateBootImageProfile(dex_files,
1005 profiles,
1006 boot_image_options_,
1007 VLOG_IS_ON(profiler),
1008 &out_profile);
1009 out_profile.Save(reference_fd);
1010 close(reference_fd);
1011 return 0;
1012 }
1013
David Sehr7c80f2d2017-02-07 16:47:58 -08001014 bool ShouldCreateProfile() {
1015 return !create_profile_from_file_.empty();
1016 }
1017
Calin Juravle7bcdb532016-06-07 16:14:47 +01001018 int GenerateTestProfile() {
David Sehr153da0e2017-02-15 08:54:51 -08001019 // Validate parameters for this command.
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001020 if (test_profile_method_percerntage_ > 100) {
1021 Usage("Invalid percentage for --generate-test-profile-method-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001022 }
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001023 if (test_profile_class_percentage_ > 100) {
1024 Usage("Invalid percentage for --generate-test-profile-class-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001025 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001026 // If given APK files or DEX locations, check that they're ok.
1027 if (!apk_files_.empty() || !apks_fd_.empty() || !dex_locations_.empty()) {
1028 if (apk_files_.empty() && apks_fd_.empty()) {
1029 Usage("APK files must be specified when passing DEX locations to --generate-test-profile");
1030 }
1031 if (dex_locations_.empty()) {
1032 Usage("DEX locations must be specified when passing APK files to --generate-test-profile");
1033 }
1034 }
David Sehr153da0e2017-02-15 08:54:51 -08001035 // ShouldGenerateTestProfile confirms !test_profile_.empty().
George Burgess IV71f77262016-10-25 13:08:17 -07001036 int profile_test_fd = open(test_profile_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001037 if (profile_test_fd < 0) {
David Sehr7c80f2d2017-02-07 16:47:58 -08001038 LOG(ERROR) << "Cannot open " << test_profile_ << strerror(errno);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001039 return -1;
1040 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001041 bool result;
1042 if (apk_files_.empty() && apks_fd_.empty() && dex_locations_.empty()) {
1043 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1044 test_profile_num_dex_,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001045 test_profile_method_percerntage_,
1046 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001047 test_profile_seed_);
1048 } else {
1049 // Initialize MemMap for ZipArchive::OpenFromFd.
1050 MemMap::Init();
1051 // Open the dex files to look up classes and methods.
1052 std::vector<std::unique_ptr<const DexFile>> dex_files;
1053 OpenApkFilesFromLocations(&dex_files);
1054 // Create a random profile file based on the set of dex files.
1055 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1056 dex_files,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001057 test_profile_method_percerntage_,
1058 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001059 test_profile_seed_);
1060 }
Calin Juravle7bcdb532016-06-07 16:14:47 +01001061 close(profile_test_fd); // ignore close result.
1062 return result ? 0 : -1;
1063 }
1064
1065 bool ShouldGenerateTestProfile() {
1066 return !test_profile_.empty();
1067 }
1068
Calin Juravle2e2db782016-02-23 12:00:03 +00001069 private:
1070 static void ParseFdForCollection(const StringPiece& option,
1071 const char* arg_name,
1072 std::vector<int>* fds) {
1073 int fd;
1074 ParseUintOption(option, arg_name, &fd, Usage);
1075 fds->push_back(fd);
1076 }
1077
1078 static void CloseAllFds(const std::vector<int>& fds, const char* descriptor) {
1079 for (size_t i = 0; i < fds.size(); i++) {
1080 if (close(fds[i]) < 0) {
1081 PLOG(WARNING) << "Failed to close descriptor for " << descriptor << " at index " << i;
1082 }
1083 }
1084 }
1085
1086 void LogCompletionTime() {
David Sehr52683cf2016-05-05 09:02:38 -07001087 static constexpr uint64_t kLogThresholdTime = MsToNs(100); // 100ms
1088 uint64_t time_taken = NanoTime() - start_ns_;
David Sehred793012016-05-05 13:39:43 -07001089 if (time_taken > kLogThresholdTime) {
David Sehrd8557182016-05-06 12:29:35 -07001090 LOG(WARNING) << "profman took " << PrettyDuration(time_taken);
David Sehred793012016-05-05 13:39:43 -07001091 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001092 }
1093
1094 std::vector<std::string> profile_files_;
1095 std::vector<int> profile_files_fd_;
David Sehr546d24f2016-06-02 10:46:19 -07001096 std::vector<std::string> dex_locations_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001097 std::vector<std::string> apk_files_;
David Sehr546d24f2016-06-02 10:46:19 -07001098 std::vector<int> apks_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001099 std::string reference_profile_file_;
1100 int reference_profile_file_fd_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001101 bool dump_only_;
Mathieu Chartier34067262017-04-06 13:55:46 -07001102 bool dump_classes_and_methods_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001103 bool generate_boot_image_profile_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001104 int dump_output_to_fd_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001105 BootImageOptions boot_image_options_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001106 std::string test_profile_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001107 std::string create_profile_from_file_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001108 uint16_t test_profile_num_dex_;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001109 uint16_t test_profile_method_percerntage_;
1110 uint16_t test_profile_class_percentage_;
Jeff Haof0a31f82017-03-27 15:50:37 -07001111 uint32_t test_profile_seed_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001112 uint64_t start_ns_;
1113};
1114
1115// See ProfileAssistant::ProcessingResult for return codes.
1116static int profman(int argc, char** argv) {
1117 ProfMan profman;
1118
1119 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1120 profman.ParseArgs(argc, argv);
1121
Calin Juravle7bcdb532016-06-07 16:14:47 +01001122 if (profman.ShouldGenerateTestProfile()) {
1123 return profman.GenerateTestProfile();
1124 }
Calin Juravle876f3502016-03-24 16:16:34 +00001125 if (profman.ShouldOnlyDumpProfile()) {
1126 return profman.DumpProfileInfo();
1127 }
Mathieu Chartier34067262017-04-06 13:55:46 -07001128 if (profman.ShouldOnlyDumpClassesAndMethods()) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001129 return profman.DumpClassesAndMethods();
David Sehr7c80f2d2017-02-07 16:47:58 -08001130 }
1131 if (profman.ShouldCreateProfile()) {
1132 return profman.CreateProfile();
1133 }
Mathieu Chartier2f794552017-06-19 10:58:08 -07001134
1135 if (profman.ShouldCreateBootProfile()) {
1136 return profman.CreateBootProfile();
1137 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001138 // Process profile information and assess if we need to do a profile guided compilation.
1139 // This operation involves I/O.
1140 return profman.ProcessProfiles();
1141}
1142
1143} // namespace art
1144
1145int main(int argc, char **argv) {
1146 return art::profman(argc, argv);
1147}
1148