blob: 8ccf7b4c1dbaddc23a276f6f422d1cbf105aa62a [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.
160static const std::string kMethodSep = "->";
Calin Juravle589e71e2017-03-03 16:05:05 -0800161static const std::string kMissingTypesMarker = "missing_types";
Calin Juravle08556882017-05-26 16:40:45 -0700162static const std::string kInvalidClassDescriptor = "invalid_class";
163static const std::string kInvalidMethod = "invalid_method";
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700164static const std::string kClassAllMethods = "*";
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],
334 kVerifyChecksum,
335 &error_msg,
336 &dex_files_for_location)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800337 } else {
338 LOG(WARNING) << "OpenZip failed for '" << dex_locations_[i] << "' " << error_msg;
339 continue;
340 }
341 } else {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700342 if (DexFileLoader::Open(apk_files_[i].c_str(),
343 dex_locations_[i],
344 kVerifyChecksum,
345 &error_msg,
346 &dex_files_for_location)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800347 } else {
348 LOG(WARNING) << "Open failed for '" << dex_locations_[i] << "' " << error_msg;
349 continue;
350 }
351 }
352 for (std::unique_ptr<const DexFile>& dex_file : dex_files_for_location) {
353 dex_files->emplace_back(std::move(dex_file));
354 }
355 }
356 }
357
Mathieu Chartier2f794552017-06-19 10:58:08 -0700358 std::unique_ptr<const ProfileCompilationInfo> LoadProfile(const std::string& filename, int fd) {
359 if (!filename.empty()) {
360 fd = open(filename.c_str(), O_RDWR);
361 if (fd < 0) {
362 LOG(ERROR) << "Cannot open " << filename << strerror(errno);
363 return nullptr;
364 }
365 }
366 std::unique_ptr<ProfileCompilationInfo> info(new ProfileCompilationInfo);
367 if (!info->Load(fd)) {
368 LOG(ERROR) << "Cannot load profile info from fd=" << fd << "\n";
369 return nullptr;
370 }
371 return info;
372 }
373
David Sehrb18991b2017-02-08 20:58:10 -0800374 int DumpOneProfile(const std::string& banner,
375 const std::string& filename,
376 int fd,
377 const std::vector<std::unique_ptr<const DexFile>>* dex_files,
378 std::string* dump) {
Mathieu Chartier2f794552017-06-19 10:58:08 -0700379 std::unique_ptr<const ProfileCompilationInfo> info(LoadProfile(filename, fd));
380 if (info == nullptr) {
381 LOG(ERROR) << "Cannot load profile info from filename=" << filename << " fd=" << fd;
Calin Juravle876f3502016-03-24 16:16:34 +0000382 return -1;
383 }
Mathieu Chartier2f794552017-06-19 10:58:08 -0700384 *dump += banner + "\n" + info->DumpInfo(dex_files) + "\n";
David Sehr4fcdd6d2016-05-24 14:52:31 -0700385 return 0;
386 }
387
388 int DumpProfileInfo() {
David Sehr153da0e2017-02-15 08:54:51 -0800389 // Validate that at least one profile file or reference was specified.
390 if (profile_files_.empty() && profile_files_fd_.empty() &&
391 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
392 Usage("No profile files or reference profile specified.");
393 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700394 static const char* kEmptyString = "";
David Sehr546d24f2016-06-02 10:46:19 -0700395 static const char* kOrdinaryProfile = "=== profile ===";
396 static const char* kReferenceProfile = "=== reference profile ===";
397
398 // Open apk/zip files and and read dex files.
399 MemMap::Init(); // for ZipArchive::OpenFromFd
David Sehrb18991b2017-02-08 20:58:10 -0800400 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7c80f2d2017-02-07 16:47:58 -0800401 OpenApkFilesFromLocations(&dex_files);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700402 std::string dump;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700403 // Dump individual profile files.
404 if (!profile_files_fd_.empty()) {
405 for (int profile_file_fd : profile_files_fd_) {
David Sehr546d24f2016-06-02 10:46:19 -0700406 int ret = DumpOneProfile(kOrdinaryProfile,
407 kEmptyString,
408 profile_file_fd,
409 &dex_files,
410 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700411 if (ret != 0) {
412 return ret;
413 }
414 }
415 }
416 if (!profile_files_.empty()) {
417 for (const std::string& profile_file : profile_files_) {
David Sehr546d24f2016-06-02 10:46:19 -0700418 int ret = DumpOneProfile(kOrdinaryProfile, profile_file, kInvalidFd, &dex_files, &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700419 if (ret != 0) {
420 return ret;
421 }
422 }
423 }
424 // Dump reference profile file.
425 if (FdIsValid(reference_profile_file_fd_)) {
David Sehr546d24f2016-06-02 10:46:19 -0700426 int ret = DumpOneProfile(kReferenceProfile,
427 kEmptyString,
428 reference_profile_file_fd_,
429 &dex_files,
430 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700431 if (ret != 0) {
432 return ret;
433 }
434 }
435 if (!reference_profile_file_.empty()) {
David Sehr546d24f2016-06-02 10:46:19 -0700436 int ret = DumpOneProfile(kReferenceProfile,
437 reference_profile_file_,
438 kInvalidFd,
439 &dex_files,
David Sehr4fcdd6d2016-05-24 14:52:31 -0700440 &dump);
441 if (ret != 0) {
442 return ret;
443 }
444 }
445 if (!FdIsValid(dump_output_to_fd_)) {
446 std::cout << dump;
447 } else {
448 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
449 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
450 return -1;
451 }
452 }
Calin Juravle876f3502016-03-24 16:16:34 +0000453 return 0;
454 }
455
456 bool ShouldOnlyDumpProfile() {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700457 return dump_only_;
Calin Juravle876f3502016-03-24 16:16:34 +0000458 }
459
Mathieu Chartier34067262017-04-06 13:55:46 -0700460 bool GetClassNamesAndMethods(int fd,
461 std::vector<std::unique_ptr<const DexFile>>* dex_files,
462 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800463 ProfileCompilationInfo profile_info;
464 if (!profile_info.Load(fd)) {
465 LOG(ERROR) << "Cannot load profile info";
466 return false;
467 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700468 for (const std::unique_ptr<const DexFile>& dex_file : *dex_files) {
469 std::set<dex::TypeIndex> class_types;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700470 std::set<uint16_t> hot_methods;
471 std::set<uint16_t> startup_methods;
472 std::set<uint16_t> post_startup_methods;
473 std::set<uint16_t> combined_methods;
474 if (profile_info.GetClassesAndMethods(*dex_file.get(),
475 &class_types,
476 &hot_methods,
477 &startup_methods,
478 &post_startup_methods)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700479 for (const dex::TypeIndex& type_index : class_types) {
480 const DexFile::TypeId& type_id = dex_file->GetTypeId(type_index);
481 out_lines->insert(std::string(dex_file->GetTypeDescriptor(type_id)));
482 }
Mathieu Chartierea650f32017-05-24 12:04:13 -0700483 combined_methods = hot_methods;
484 combined_methods.insert(startup_methods.begin(), startup_methods.end());
485 combined_methods.insert(post_startup_methods.begin(), post_startup_methods.end());
486 for (uint16_t dex_method_idx : combined_methods) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700487 const DexFile::MethodId& id = dex_file->GetMethodId(dex_method_idx);
488 std::string signature_string(dex_file->GetMethodSignature(id).ToString());
489 std::string type_string(dex_file->GetTypeDescriptor(dex_file->GetTypeId(id.class_idx_)));
490 std::string method_name(dex_file->GetMethodName(id));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700491 std::string flags_string;
492 if (hot_methods.find(dex_method_idx) != hot_methods.end()) {
493 flags_string += kMethodFlagStringHot;
494 }
495 if (startup_methods.find(dex_method_idx) != startup_methods.end()) {
496 flags_string += kMethodFlagStringStartup;
497 }
498 if (post_startup_methods.find(dex_method_idx) != post_startup_methods.end()) {
499 flags_string += kMethodFlagStringPostStartup;
500 }
501 out_lines->insert(flags_string +
502 type_string +
503 kMethodSep +
504 method_name +
505 signature_string);
Mathieu Chartier34067262017-04-06 13:55:46 -0700506 }
507 }
508 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800509 return true;
510 }
511
Mathieu Chartier34067262017-04-06 13:55:46 -0700512 bool GetClassNamesAndMethods(const std::string& profile_file,
513 std::vector<std::unique_ptr<const DexFile>>* dex_files,
514 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800515 int fd = open(profile_file.c_str(), O_RDONLY);
516 if (!FdIsValid(fd)) {
517 LOG(ERROR) << "Cannot open " << profile_file << strerror(errno);
518 return false;
519 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700520 if (!GetClassNamesAndMethods(fd, dex_files, out_lines)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800521 return false;
522 }
523 if (close(fd) < 0) {
524 PLOG(WARNING) << "Failed to close descriptor";
525 }
526 return true;
527 }
528
Mathieu Chartierea650f32017-05-24 12:04:13 -0700529 int DumpClassesAndMethods() {
David Sehr153da0e2017-02-15 08:54:51 -0800530 // Validate that at least one profile file or reference was specified.
531 if (profile_files_.empty() && profile_files_fd_.empty() &&
532 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
533 Usage("No profile files or reference profile specified.");
534 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800535 // Open apk/zip files and and read dex files.
536 MemMap::Init(); // for ZipArchive::OpenFromFd
537 // Open the dex files to get the names for classes.
538 std::vector<std::unique_ptr<const DexFile>> dex_files;
539 OpenApkFilesFromLocations(&dex_files);
540 // Build a vector of class names from individual profile files.
541 std::set<std::string> class_names;
542 if (!profile_files_fd_.empty()) {
543 for (int profile_file_fd : profile_files_fd_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700544 if (!GetClassNamesAndMethods(profile_file_fd, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800545 return -1;
546 }
547 }
548 }
549 if (!profile_files_.empty()) {
550 for (const std::string& profile_file : profile_files_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700551 if (!GetClassNamesAndMethods(profile_file, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800552 return -1;
553 }
554 }
555 }
556 // Concatenate class names from reference profile file.
557 if (FdIsValid(reference_profile_file_fd_)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700558 if (!GetClassNamesAndMethods(reference_profile_file_fd_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800559 return -1;
560 }
561 }
562 if (!reference_profile_file_.empty()) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700563 if (!GetClassNamesAndMethods(reference_profile_file_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800564 return -1;
565 }
566 }
567 // Dump the class names.
568 std::string dump;
569 for (const std::string& class_name : class_names) {
570 dump += class_name + std::string("\n");
571 }
572 if (!FdIsValid(dump_output_to_fd_)) {
573 std::cout << dump;
574 } else {
575 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
576 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
577 return -1;
578 }
579 }
580 return 0;
581 }
582
Mathieu Chartier34067262017-04-06 13:55:46 -0700583 bool ShouldOnlyDumpClassesAndMethods() {
584 return dump_classes_and_methods_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800585 }
586
587 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
588 // the given function.
589 template <typename T>
590 static T* ReadCommentedInputFromFile(
591 const char* input_filename, std::function<std::string(const char*)>* process) {
592 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
593 if (input_file.get() == nullptr) {
594 LOG(ERROR) << "Failed to open input file " << input_filename;
595 return nullptr;
596 }
597 std::unique_ptr<T> result(
598 ReadCommentedInputStream<T>(*input_file, process));
599 input_file->close();
600 return result.release();
601 }
602
603 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
604 // with the given function.
605 template <typename T>
606 static T* ReadCommentedInputStream(
607 std::istream& in_stream,
608 std::function<std::string(const char*)>* process) {
609 std::unique_ptr<T> output(new T());
610 while (in_stream.good()) {
611 std::string dot;
612 std::getline(in_stream, dot);
613 if (android::base::StartsWith(dot, "#") || dot.empty()) {
614 continue;
615 }
616 if (process != nullptr) {
617 std::string descriptor((*process)(dot.c_str()));
618 output->insert(output->end(), descriptor);
619 } else {
620 output->insert(output->end(), dot);
621 }
622 }
623 return output.release();
624 }
625
Calin Juravlee0ac1152017-02-13 19:03:47 -0800626 // Find class klass_descriptor in the given dex_files and store its reference
627 // in the out parameter class_ref.
628 // Return true if the definition of the class was found in any of the dex_files.
629 bool FindClass(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
630 const std::string& klass_descriptor,
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700631 /*out*/TypeReference* class_ref) {
Calin Juravle08556882017-05-26 16:40:45 -0700632 constexpr uint16_t kInvalidTypeIndex = std::numeric_limits<uint16_t>::max() - 1;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800633 for (const std::unique_ptr<const DexFile>& dex_file_ptr : dex_files) {
634 const DexFile* dex_file = dex_file_ptr.get();
Calin Juravle08556882017-05-26 16:40:45 -0700635 if (klass_descriptor == kInvalidClassDescriptor) {
636 if (kInvalidTypeIndex >= dex_file->NumTypeIds()) {
637 // The dex file does not contain all possible type ids which leaves us room
638 // to add an "invalid" type id.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700639 *class_ref = TypeReference(dex_file, dex::TypeIndex(kInvalidTypeIndex));
Calin Juravle08556882017-05-26 16:40:45 -0700640 return true;
641 } else {
642 // The dex file contains all possible type ids. We don't have any free type id
643 // that we can use as invalid.
644 continue;
645 }
646 }
647
Calin Juravlee0ac1152017-02-13 19:03:47 -0800648 const DexFile::TypeId* type_id = dex_file->FindTypeId(klass_descriptor.c_str());
649 if (type_id == nullptr) {
650 continue;
651 }
652 dex::TypeIndex type_index = dex_file->GetIndexForTypeId(*type_id);
653 if (dex_file->FindClassDef(type_index) == nullptr) {
654 // Class is only referenced in the current dex file but not defined in it.
655 continue;
656 }
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700657 *class_ref = TypeReference(dex_file, type_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800658 return true;
659 }
660 return false;
661 }
662
Mathieu Chartier34067262017-04-06 13:55:46 -0700663 // Find the method specified by method_spec in the class class_ref.
Calin Juravle08556882017-05-26 16:40:45 -0700664 uint32_t FindMethodIndex(const TypeReference& class_ref,
665 const std::string& method_spec) {
666 const DexFile* dex_file = class_ref.dex_file;
667 if (method_spec == kInvalidMethod) {
668 constexpr uint16_t kInvalidMethodIndex = std::numeric_limits<uint16_t>::max() - 1;
669 return kInvalidMethodIndex >= dex_file->NumMethodIds()
670 ? kInvalidMethodIndex
Andreas Gampee2abbc62017-09-15 11:59:26 -0700671 : dex::kDexNoIndex;
Calin Juravle08556882017-05-26 16:40:45 -0700672 }
673
Calin Juravlee0ac1152017-02-13 19:03:47 -0800674 std::vector<std::string> name_and_signature;
675 Split(method_spec, kProfileParsingFirstCharInSignature, &name_and_signature);
676 if (name_and_signature.size() != 2) {
677 LOG(ERROR) << "Invalid method name and signature " << method_spec;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700678 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800679 }
Calin Juravle08556882017-05-26 16:40:45 -0700680
Calin Juravlee0ac1152017-02-13 19:03:47 -0800681 const std::string& name = name_and_signature[0];
682 const std::string& signature = kProfileParsingFirstCharInSignature + name_and_signature[1];
Calin Juravlee0ac1152017-02-13 19:03:47 -0800683
684 const DexFile::StringId* name_id = dex_file->FindStringId(name.c_str());
685 if (name_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700686 LOG(WARNING) << "Could not find name: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700687 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800688 }
689 dex::TypeIndex return_type_idx;
690 std::vector<dex::TypeIndex> param_type_idxs;
691 if (!dex_file->CreateTypeList(signature, &return_type_idx, &param_type_idxs)) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700692 LOG(WARNING) << "Could not create type list" << signature;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700693 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800694 }
695 const DexFile::ProtoId* proto_id = dex_file->FindProtoId(return_type_idx, param_type_idxs);
696 if (proto_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700697 LOG(WARNING) << "Could not find proto_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700698 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800699 }
700 const DexFile::MethodId* method_id = dex_file->FindMethodId(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700701 dex_file->GetTypeId(class_ref.TypeIndex()), *name_id, *proto_id);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800702 if (method_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700703 LOG(WARNING) << "Could not find method_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700704 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800705 }
706
Mathieu Chartier34067262017-04-06 13:55:46 -0700707 return dex_file->GetIndexForMethodId(*method_id);
708 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800709
Mathieu Chartier34067262017-04-06 13:55:46 -0700710 // Given a method, return true if the method has a single INVOKE_VIRTUAL in its byte code.
711 // Upon success it returns true and stores the method index and the invoke dex pc
712 // in the output parameters.
713 // The format of the method spec is "inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
714 //
715 // TODO(calin): support INVOKE_INTERFACE and the range variants.
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700716 bool HasSingleInvoke(const TypeReference& class_ref,
Mathieu Chartier34067262017-04-06 13:55:46 -0700717 uint16_t method_index,
718 /*out*/uint32_t* dex_pc) {
719 const DexFile* dex_file = class_ref.dex_file;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800720 uint32_t offset = dex_file->FindCodeItemOffset(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700721 *dex_file->FindClassDef(class_ref.TypeIndex()),
Mathieu Chartier34067262017-04-06 13:55:46 -0700722 method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800723 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(offset);
724
725 bool found_invoke = false;
726 for (CodeItemIterator it(*code_item); !it.Done(); it.Advance()) {
727 if (it.CurrentInstruction().Opcode() == Instruction::INVOKE_VIRTUAL) {
728 if (found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700729 LOG(ERROR) << "Multiple invoke INVOKE_VIRTUAL found: "
730 << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800731 return false;
732 }
733 found_invoke = true;
734 *dex_pc = it.CurrentDexPc();
735 }
736 }
737 if (!found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700738 LOG(ERROR) << "Could not find any INVOKE_VIRTUAL: " << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800739 }
740 return found_invoke;
741 }
742
743 // Process a line defining a class or a method and its inline caches.
744 // Upon success return true and add the class or the method info to profile.
Calin Juravle589e71e2017-03-03 16:05:05 -0800745 // The possible line formats are:
746 // "LJustTheCass;".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800747 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
Calin Juravle08556882017-05-26 16:40:45 -0700748 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,invalid_class".
Calin Juravle589e71e2017-03-03 16:05:05 -0800749 // "LTestInline;->inlineMissingTypes(LSuper;)I+missing_types".
750 // "LTestInline;->inlineNoInlineCaches(LSuper;)I".
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700751 // "LTestInline;->*".
Calin Juravle08556882017-05-26 16:40:45 -0700752 // "invalid_class".
753 // "LTestInline;->invalid_method".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800754 // The method and classes are searched only in the given dex files.
755 bool ProcessLine(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
756 const std::string& line,
757 /*out*/ProfileCompilationInfo* profile) {
758 std::string klass;
759 std::string method_str;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700760 bool is_hot = false;
761 bool is_startup = false;
762 bool is_post_startup = false;
763 const size_t method_sep_index = line.find(kMethodSep, 0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800764 if (method_sep_index == std::string::npos) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700765 klass = line.substr(0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800766 } else {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700767 // The method prefix flags are only valid for method strings.
768 size_t start_index = 0;
769 while (start_index < line.size() && line[start_index] != 'L') {
770 const char c = line[start_index];
771 if (c == kMethodFlagStringHot) {
772 is_hot = true;
773 } else if (c == kMethodFlagStringStartup) {
774 is_startup = true;
775 } else if (c == kMethodFlagStringPostStartup) {
776 is_post_startup = true;
777 } else {
778 LOG(WARNING) << "Invalid flag " << c;
779 return false;
780 }
781 ++start_index;
782 }
783 klass = line.substr(start_index, method_sep_index - start_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800784 method_str = line.substr(method_sep_index + kMethodSep.size());
785 }
786
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700787 TypeReference class_ref;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800788 if (!FindClass(dex_files, klass, &class_ref)) {
Mathieu Chartier3f121342017-03-06 11:16:20 -0800789 LOG(WARNING) << "Could not find class: " << klass;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800790 return false;
791 }
792
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700793 if (method_str.empty() || method_str == kClassAllMethods) {
794 // Start by adding the class.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800795 std::set<DexCacheResolvedClasses> resolved_class_set;
796 const DexFile* dex_file = class_ref.dex_file;
797 const auto& dex_resolved_classes = resolved_class_set.emplace(
798 dex_file->GetLocation(),
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700799 DexFileLoader::GetBaseLocation(dex_file->GetLocation()),
Mathieu Chartierea650f32017-05-24 12:04:13 -0700800 dex_file->GetLocationChecksum(),
801 dex_file->NumMethodIds());
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700802 dex_resolved_classes.first->AddClass(class_ref.TypeIndex());
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700803 std::vector<ProfileMethodInfo> methods;
804 if (method_str == kClassAllMethods) {
805 // Add all of the methods.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700806 const DexFile::ClassDef* class_def = dex_file->FindClassDef(class_ref.TypeIndex());
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700807 const uint8_t* class_data = dex_file->GetClassData(*class_def);
808 if (class_data != nullptr) {
809 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700810 it.SkipAllFields();
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700811 while (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
812 if (it.GetMethodCodeItemOffset() != 0) {
813 // Add all of the methods that have code to the profile.
814 const uint32_t method_idx = it.GetMemberIndex();
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700815 methods.push_back(ProfileMethodInfo(MethodReference(dex_file, method_idx)));
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700816 }
817 it.Next();
818 }
819 }
820 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700821 // TODO: Check return values?
822 profile->AddMethods(methods);
823 profile->AddClasses(resolved_class_set);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800824 return true;
825 }
826
827 // Process the method.
828 std::string method_spec;
829 std::vector<std::string> inline_cache_elems;
830
Mathieu Chartierea650f32017-05-24 12:04:13 -0700831 // If none of the flags are set, default to hot.
832 is_hot = is_hot || (!is_hot && !is_startup && !is_post_startup);
833
Calin Juravlee0ac1152017-02-13 19:03:47 -0800834 std::vector<std::string> method_elems;
Calin Juravle589e71e2017-03-03 16:05:05 -0800835 bool is_missing_types = false;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800836 Split(method_str, kProfileParsingInlineChacheSep, &method_elems);
837 if (method_elems.size() == 2) {
838 method_spec = method_elems[0];
Calin Juravle589e71e2017-03-03 16:05:05 -0800839 is_missing_types = method_elems[1] == kMissingTypesMarker;
840 if (!is_missing_types) {
841 Split(method_elems[1], kProfileParsingTypeSep, &inline_cache_elems);
842 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800843 } else if (method_elems.size() == 1) {
844 method_spec = method_elems[0];
845 } else {
846 LOG(ERROR) << "Invalid method line: " << line;
847 return false;
848 }
849
Mathieu Chartier34067262017-04-06 13:55:46 -0700850 const uint32_t method_index = FindMethodIndex(class_ref, method_spec);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700851 if (method_index == dex::kDexNoIndex) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800852 return false;
853 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700854
Mathieu Chartier34067262017-04-06 13:55:46 -0700855 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
856 if (is_missing_types || !inline_cache_elems.empty()) {
857 uint32_t dex_pc;
858 if (!HasSingleInvoke(class_ref, method_index, &dex_pc)) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800859 return false;
860 }
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700861 std::vector<TypeReference> classes(inline_cache_elems.size());
Mathieu Chartier34067262017-04-06 13:55:46 -0700862 size_t class_it = 0;
863 for (const std::string& ic_class : inline_cache_elems) {
864 if (!FindClass(dex_files, ic_class, &(classes[class_it++]))) {
865 LOG(ERROR) << "Could not find class: " << ic_class;
866 return false;
867 }
868 }
869 inline_caches.emplace_back(dex_pc, is_missing_types, classes);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800870 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700871 MethodReference ref(class_ref.dex_file, method_index);
Mathieu Chartierea650f32017-05-24 12:04:13 -0700872 if (is_hot) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700873 profile->AddMethod(ProfileMethodInfo(ref, inline_caches));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700874 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700875 uint32_t flags = 0;
876 using Hotness = ProfileCompilationInfo::MethodHotness;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700877 if (is_startup) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700878 flags |= Hotness::kFlagStartup;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700879 }
880 if (is_post_startup) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700881 flags |= Hotness::kFlagPostStartup;
882 }
883 if (flags != 0) {
884 if (!profile->AddMethodIndex(static_cast<Hotness::Flag>(flags), ref)) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700885 return false;
886 }
Mathieu Chartiere46f3a82017-06-19 19:54:12 -0700887 DCHECK(profile->GetMethodHotness(ref).IsInProfile());
Mathieu Chartierea650f32017-05-24 12:04:13 -0700888 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800889 return true;
890 }
891
Mathieu Chartier2f794552017-06-19 10:58:08 -0700892 int OpenReferenceProfile() const {
893 int fd = reference_profile_file_fd_;
894 if (!FdIsValid(fd)) {
895 CHECK(!reference_profile_file_.empty());
896 fd = open(reference_profile_file_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
897 if (fd < 0) {
898 LOG(ERROR) << "Cannot open " << reference_profile_file_ << strerror(errno);
899 return kInvalidFd;
900 }
901 }
902 return fd;
903 }
904
Calin Juravlee0ac1152017-02-13 19:03:47 -0800905 // Creates a profile from a human friendly textual representation.
906 // The expected input format is:
907 // # Classes
908 // Ljava/lang/Comparable;
909 // Ljava/lang/Math;
910 // # Methods with inline caches
911 // LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;
912 // LTestInline;->noInlineCache(LSuper;)I
David Sehr7c80f2d2017-02-07 16:47:58 -0800913 int CreateProfile() {
David Sehr153da0e2017-02-15 08:54:51 -0800914 // Validate parameters for this command.
915 if (apk_files_.empty() && apks_fd_.empty()) {
916 Usage("APK files must be specified");
917 }
918 if (dex_locations_.empty()) {
919 Usage("DEX locations must be specified");
920 }
921 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
922 Usage("Reference profile must be specified with --reference-profile-file or "
923 "--reference-profile-file-fd");
924 }
925 if (!profile_files_.empty() || !profile_files_fd_.empty()) {
926 Usage("Profile must be specified with --reference-profile-file or "
927 "--reference-profile-file-fd");
928 }
929 // for ZipArchive::OpenFromFd
930 MemMap::Init();
David Sehr7c80f2d2017-02-07 16:47:58 -0800931 // Open the profile output file if needed.
Mathieu Chartier2f794552017-06-19 10:58:08 -0700932 int fd = OpenReferenceProfile();
David Sehr7c80f2d2017-02-07 16:47:58 -0800933 if (!FdIsValid(fd)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800934 return -1;
David Sehr7c80f2d2017-02-07 16:47:58 -0800935 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800936 // Read the user-specified list of classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800937 std::unique_ptr<std::unordered_set<std::string>>
Calin Juravlee0ac1152017-02-13 19:03:47 -0800938 user_lines(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
David Sehr7c80f2d2017-02-07 16:47:58 -0800939 create_profile_from_file_.c_str(), nullptr)); // No post-processing.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800940
941 // Open the dex files to look up classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800942 std::vector<std::unique_ptr<const DexFile>> dex_files;
943 OpenApkFilesFromLocations(&dex_files);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800944
945 // Process the lines one by one and add the successful ones to the profile.
David Sehr7c80f2d2017-02-07 16:47:58 -0800946 ProfileCompilationInfo info;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800947
948 for (const auto& line : *user_lines) {
949 ProcessLine(dex_files, line, &info);
950 }
951
David Sehr7c80f2d2017-02-07 16:47:58 -0800952 // Write the profile file.
953 CHECK(info.Save(fd));
954 if (close(fd) < 0) {
955 PLOG(WARNING) << "Failed to close descriptor";
956 }
957 return 0;
958 }
959
Mathieu Chartier2f794552017-06-19 10:58:08 -0700960 bool ShouldCreateBootProfile() const {
961 return generate_boot_image_profile_;
962 }
963
964 int CreateBootProfile() {
965 // Initialize memmap since it's required to open dex files.
966 MemMap::Init();
967 // Open the profile output file.
968 const int reference_fd = OpenReferenceProfile();
969 if (!FdIsValid(reference_fd)) {
970 PLOG(ERROR) << "Error opening reference profile";
971 return -1;
972 }
973 // Open the dex files.
974 std::vector<std::unique_ptr<const DexFile>> dex_files;
975 OpenApkFilesFromLocations(&dex_files);
976 if (dex_files.empty()) {
977 PLOG(ERROR) << "Expected dex files for creating boot profile";
978 return -2;
979 }
980 // Open the input profiles.
981 std::vector<std::unique_ptr<const ProfileCompilationInfo>> profiles;
982 if (!profile_files_fd_.empty()) {
983 for (int profile_file_fd : profile_files_fd_) {
984 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile("", profile_file_fd));
985 if (profile == nullptr) {
986 return -3;
987 }
988 profiles.emplace_back(std::move(profile));
989 }
990 }
991 if (!profile_files_.empty()) {
992 for (const std::string& profile_file : profile_files_) {
993 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile(profile_file, kInvalidFd));
994 if (profile == nullptr) {
995 return -4;
996 }
997 profiles.emplace_back(std::move(profile));
998 }
999 }
1000 ProfileCompilationInfo out_profile;
1001 GenerateBootImageProfile(dex_files,
1002 profiles,
1003 boot_image_options_,
1004 VLOG_IS_ON(profiler),
1005 &out_profile);
1006 out_profile.Save(reference_fd);
1007 close(reference_fd);
1008 return 0;
1009 }
1010
David Sehr7c80f2d2017-02-07 16:47:58 -08001011 bool ShouldCreateProfile() {
1012 return !create_profile_from_file_.empty();
1013 }
1014
Calin Juravle7bcdb532016-06-07 16:14:47 +01001015 int GenerateTestProfile() {
David Sehr153da0e2017-02-15 08:54:51 -08001016 // Validate parameters for this command.
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001017 if (test_profile_method_percerntage_ > 100) {
1018 Usage("Invalid percentage for --generate-test-profile-method-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001019 }
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001020 if (test_profile_class_percentage_ > 100) {
1021 Usage("Invalid percentage for --generate-test-profile-class-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001022 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001023 // If given APK files or DEX locations, check that they're ok.
1024 if (!apk_files_.empty() || !apks_fd_.empty() || !dex_locations_.empty()) {
1025 if (apk_files_.empty() && apks_fd_.empty()) {
1026 Usage("APK files must be specified when passing DEX locations to --generate-test-profile");
1027 }
1028 if (dex_locations_.empty()) {
1029 Usage("DEX locations must be specified when passing APK files to --generate-test-profile");
1030 }
1031 }
David Sehr153da0e2017-02-15 08:54:51 -08001032 // ShouldGenerateTestProfile confirms !test_profile_.empty().
George Burgess IV71f77262016-10-25 13:08:17 -07001033 int profile_test_fd = open(test_profile_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001034 if (profile_test_fd < 0) {
David Sehr7c80f2d2017-02-07 16:47:58 -08001035 LOG(ERROR) << "Cannot open " << test_profile_ << strerror(errno);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001036 return -1;
1037 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001038 bool result;
1039 if (apk_files_.empty() && apks_fd_.empty() && dex_locations_.empty()) {
1040 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1041 test_profile_num_dex_,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001042 test_profile_method_percerntage_,
1043 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001044 test_profile_seed_);
1045 } else {
1046 // Initialize MemMap for ZipArchive::OpenFromFd.
1047 MemMap::Init();
1048 // Open the dex files to look up classes and methods.
1049 std::vector<std::unique_ptr<const DexFile>> dex_files;
1050 OpenApkFilesFromLocations(&dex_files);
1051 // Create a random profile file based on the set of dex files.
1052 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1053 dex_files,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001054 test_profile_method_percerntage_,
1055 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001056 test_profile_seed_);
1057 }
Calin Juravle7bcdb532016-06-07 16:14:47 +01001058 close(profile_test_fd); // ignore close result.
1059 return result ? 0 : -1;
1060 }
1061
1062 bool ShouldGenerateTestProfile() {
1063 return !test_profile_.empty();
1064 }
1065
Calin Juravle2e2db782016-02-23 12:00:03 +00001066 private:
1067 static void ParseFdForCollection(const StringPiece& option,
1068 const char* arg_name,
1069 std::vector<int>* fds) {
1070 int fd;
1071 ParseUintOption(option, arg_name, &fd, Usage);
1072 fds->push_back(fd);
1073 }
1074
1075 static void CloseAllFds(const std::vector<int>& fds, const char* descriptor) {
1076 for (size_t i = 0; i < fds.size(); i++) {
1077 if (close(fds[i]) < 0) {
1078 PLOG(WARNING) << "Failed to close descriptor for " << descriptor << " at index " << i;
1079 }
1080 }
1081 }
1082
1083 void LogCompletionTime() {
David Sehr52683cf2016-05-05 09:02:38 -07001084 static constexpr uint64_t kLogThresholdTime = MsToNs(100); // 100ms
1085 uint64_t time_taken = NanoTime() - start_ns_;
David Sehred793012016-05-05 13:39:43 -07001086 if (time_taken > kLogThresholdTime) {
David Sehrd8557182016-05-06 12:29:35 -07001087 LOG(WARNING) << "profman took " << PrettyDuration(time_taken);
David Sehred793012016-05-05 13:39:43 -07001088 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001089 }
1090
1091 std::vector<std::string> profile_files_;
1092 std::vector<int> profile_files_fd_;
David Sehr546d24f2016-06-02 10:46:19 -07001093 std::vector<std::string> dex_locations_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001094 std::vector<std::string> apk_files_;
David Sehr546d24f2016-06-02 10:46:19 -07001095 std::vector<int> apks_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001096 std::string reference_profile_file_;
1097 int reference_profile_file_fd_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001098 bool dump_only_;
Mathieu Chartier34067262017-04-06 13:55:46 -07001099 bool dump_classes_and_methods_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001100 bool generate_boot_image_profile_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001101 int dump_output_to_fd_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001102 BootImageOptions boot_image_options_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001103 std::string test_profile_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001104 std::string create_profile_from_file_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001105 uint16_t test_profile_num_dex_;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001106 uint16_t test_profile_method_percerntage_;
1107 uint16_t test_profile_class_percentage_;
Jeff Haof0a31f82017-03-27 15:50:37 -07001108 uint32_t test_profile_seed_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001109 uint64_t start_ns_;
1110};
1111
1112// See ProfileAssistant::ProcessingResult for return codes.
1113static int profman(int argc, char** argv) {
1114 ProfMan profman;
1115
1116 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1117 profman.ParseArgs(argc, argv);
1118
Calin Juravle7bcdb532016-06-07 16:14:47 +01001119 if (profman.ShouldGenerateTestProfile()) {
1120 return profman.GenerateTestProfile();
1121 }
Calin Juravle876f3502016-03-24 16:16:34 +00001122 if (profman.ShouldOnlyDumpProfile()) {
1123 return profman.DumpProfileInfo();
1124 }
Mathieu Chartier34067262017-04-06 13:55:46 -07001125 if (profman.ShouldOnlyDumpClassesAndMethods()) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001126 return profman.DumpClassesAndMethods();
David Sehr7c80f2d2017-02-07 16:47:58 -08001127 }
1128 if (profman.ShouldCreateProfile()) {
1129 return profman.CreateProfile();
1130 }
Mathieu Chartier2f794552017-06-19 10:58:08 -07001131
1132 if (profman.ShouldCreateBootProfile()) {
1133 return profman.CreateBootProfile();
1134 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001135 // Process profile information and assess if we need to do a profile guided compilation.
1136 // This operation involves I/O.
1137 return profman.ProcessProfiles();
1138}
1139
1140} // namespace art
1141
1142int main(int argc, char **argv) {
1143 return art::profman(argc, argv);
1144}
1145