blob: 0bef205de6c7bea86a218e9f33498b5135c70b3e [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"
Andreas Gampe57943812017-12-06 21:39:13 -080035#include "base/logging.h" // For InitLogging.
Calin Juravle2e2db782016-02-23 12:00:03 +000036#include "base/scoped_flock.h"
37#include "base/stringpiece.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000038#include "base/time_utils.h"
39#include "base/unix_file/fd_file.h"
Mathieu Chartier2f794552017-06-19 10:58:08 -070040#include "boot_image_profile.h"
Calin Juravlee0ac1152017-02-13 19:03:47 -080041#include "bytecode_utils.h"
David Sehr4fcdd6d2016-05-24 14:52:31 -070042#include "dex_file.h"
Mathieu Chartier79c87da2017-10-10 11:54:29 -070043#include "dex_file_loader.h"
Andreas Gampee2abbc62017-09-15 11:59:26 -070044#include "dex_file_types.h"
Calin Juravle33083d62017-01-18 15:29:12 -080045#include "jit/profile_compilation_info.h"
Mathieu Chartierdbddc222017-05-24 12:04:13 -070046#include "profile_assistant.h"
David Sehrf57589f2016-10-17 10:09:33 -070047#include "runtime.h"
Mathieu Chartierdbddc222017-05-24 12:04:13 -070048#include "type_reference.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000049#include "utils.h"
David Sehr546d24f2016-06-02 10:46:19 -070050#include "zip_archive.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000051
52namespace art {
53
54static int original_argc;
55static char** original_argv;
56
57static std::string CommandLine() {
58 std::vector<std::string> command;
59 for (int i = 0; i < original_argc; ++i) {
60 command.push_back(original_argv[i]);
61 }
Andreas Gampe9186ced2016-12-12 14:28:21 -080062 return android::base::Join(command, ' ');
Calin Juravle2e2db782016-02-23 12:00:03 +000063}
64
David Sehr4fcdd6d2016-05-24 14:52:31 -070065static constexpr int kInvalidFd = -1;
66
67static bool FdIsValid(int fd) {
68 return fd != kInvalidFd;
69}
70
Calin Juravle2e2db782016-02-23 12:00:03 +000071static void UsageErrorV(const char* fmt, va_list ap) {
72 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080073 android::base::StringAppendV(&error, fmt, ap);
Calin Juravle2e2db782016-02-23 12:00:03 +000074 LOG(ERROR) << error;
75}
76
77static void UsageError(const char* fmt, ...) {
78 va_list ap;
79 va_start(ap, fmt);
80 UsageErrorV(fmt, ap);
81 va_end(ap);
82}
83
84NO_RETURN static void Usage(const char *fmt, ...) {
85 va_list ap;
86 va_start(ap, fmt);
87 UsageErrorV(fmt, ap);
88 va_end(ap);
89
90 UsageError("Command: %s", CommandLine().c_str());
91 UsageError("Usage: profman [options]...");
92 UsageError("");
David Sehr4fcdd6d2016-05-24 14:52:31 -070093 UsageError(" --dump-only: dumps the content of the specified profile files");
94 UsageError(" to standard output (default) in a human readable form.");
95 UsageError("");
David Sehr7c80f2d2017-02-07 16:47:58 -080096 UsageError(" --dump-output-to-fd=<number>: redirects --dump-only output to a file descriptor.");
97 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -070098 UsageError(" --dump-classes-and-methods: dumps a sorted list of classes and methods that are");
99 UsageError(" in the specified profile file to standard output (default) in a human");
100 UsageError(" readable form. The output is valid input for --create-profile-from");
Calin Juravle876f3502016-03-24 16:16:34 +0000101 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000102 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
103 UsageError(" Can be specified multiple time, in which case the data from the different");
104 UsageError(" profiles will be aggregated.");
105 UsageError("");
106 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
107 UsageError(" Cannot be used together with --profile-file.");
108 UsageError("");
109 UsageError(" --reference-profile-file=<filename>: specify a reference profile.");
110 UsageError(" The data in this file will be compared with the data obtained by merging");
111 UsageError(" all the files specified with --profile-file or --profile-file-fd.");
112 UsageError(" If the exit code is EXIT_COMPILE then all --profile-file will be merged into");
113 UsageError(" --reference-profile-file. ");
114 UsageError("");
115 UsageError(" --reference-profile-file-fd=<number>: same as --reference-profile-file but");
116 UsageError(" accepts a file descriptor. Cannot be used together with");
117 UsageError(" --reference-profile-file.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800118 UsageError("");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100119 UsageError(" --generate-test-profile=<filename>: generates a random profile file for testing.");
120 UsageError(" --generate-test-profile-num-dex=<number>: number of dex files that should be");
121 UsageError(" included in the generated profile. Defaults to 20.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700122 UsageError(" --generate-test-profile-method-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100123 UsageError(" number of methods that should be generated. Defaults to 5.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700124 UsageError(" --generate-test-profile-class-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100125 UsageError(" number of classes that should be generated. Defaults to 5.");
Jeff Haof0a31f82017-03-27 15:50:37 -0700126 UsageError(" --generate-test-profile-seed=<number>: seed for random number generator used when");
127 UsageError(" generating random test profiles. Defaults to using NanoTime.");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100128 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -0700129 UsageError(" --create-profile-from=<filename>: creates a profile from a list of classes and");
130 UsageError(" methods.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800131 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700132 UsageError(" --dex-location=<string>: location string to use with corresponding");
133 UsageError(" apk-fd to find dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700134 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700135 UsageError(" --apk-fd=<number>: file descriptor containing an open APK to");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700136 UsageError(" search for dex files");
David Sehr7c80f2d2017-02-07 16:47:58 -0800137 UsageError(" --apk-=<filename>: an APK to search for dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700138 UsageError("");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700139 UsageError(" --generate-boot-image-profile: Generate a boot image profile based on input");
140 UsageError(" profiles. Requires passing in dex files to inspect properties of classes.");
141 UsageError(" --boot-image-class-threshold=<value>: specify minimum number of class occurrences");
142 UsageError(" to include a class in the boot image profile. Default is 10.");
143 UsageError(" --boot-image-clean-class-threshold=<value>: specify minimum number of clean class");
144 UsageError(" occurrences to include a class in the boot image profile. A clean class is a");
145 UsageError(" class that doesn't have any static fields or native methods and is likely to");
146 UsageError(" remain clean in the image. Default is 3.");
Mathieu Chartier8eecddf2017-07-12 16:05:54 -0700147 UsageError(" --boot-image-sampled-method-threshold=<value>: minimum number of profiles a");
148 UsageError(" non-hot method needs to be in order to be hot in the output profile. The");
149 UsageError(" default is max int.");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700150 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000151
152 exit(EXIT_FAILURE);
153}
154
Calin Juravle7bcdb532016-06-07 16:14:47 +0100155// Note: make sure you update the Usage if you change these values.
156static constexpr uint16_t kDefaultTestProfileNumDex = 20;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700157static constexpr uint16_t kDefaultTestProfileMethodPercentage = 5;
158static constexpr uint16_t kDefaultTestProfileClassPercentage = 5;
Calin Juravle7bcdb532016-06-07 16:14:47 +0100159
Calin Juravlee0ac1152017-02-13 19:03:47 -0800160// Separators used when parsing human friendly representation of profiles.
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800161static const std::string kMethodSep = "->"; // NOLINT [runtime/string] [4]
162static const std::string kMissingTypesMarker = "missing_types"; // NOLINT [runtime/string] [4]
163static const std::string kInvalidClassDescriptor = "invalid_class"; // NOLINT [runtime/string] [4]
164static const std::string kInvalidMethod = "invalid_method"; // NOLINT [runtime/string] [4]
165static const std::string kClassAllMethods = "*"; // NOLINT [runtime/string] [4]
Calin Juravlee0ac1152017-02-13 19:03:47 -0800166static constexpr char kProfileParsingInlineChacheSep = '+';
167static constexpr char kProfileParsingTypeSep = ',';
168static constexpr char kProfileParsingFirstCharInSignature = '(';
Mathieu Chartierea650f32017-05-24 12:04:13 -0700169static constexpr char kMethodFlagStringHot = 'H';
170static constexpr char kMethodFlagStringStartup = 'S';
171static constexpr char kMethodFlagStringPostStartup = 'P';
Calin Juravlee0ac1152017-02-13 19:03:47 -0800172
173// TODO(calin): This class has grown too much from its initial design. Split the functionality
174// into smaller, more contained pieces.
Calin Juravle2e2db782016-02-23 12:00:03 +0000175class ProfMan FINAL {
176 public:
177 ProfMan() :
David Sehr4fcdd6d2016-05-24 14:52:31 -0700178 reference_profile_file_fd_(kInvalidFd),
179 dump_only_(false),
Mathieu Chartier34067262017-04-06 13:55:46 -0700180 dump_classes_and_methods_(false),
Mathieu Chartier2f794552017-06-19 10:58:08 -0700181 generate_boot_image_profile_(false),
David Sehr4fcdd6d2016-05-24 14:52:31 -0700182 dump_output_to_fd_(kInvalidFd),
Calin Juravle7bcdb532016-06-07 16:14:47 +0100183 test_profile_num_dex_(kDefaultTestProfileNumDex),
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700184 test_profile_method_percerntage_(kDefaultTestProfileMethodPercentage),
185 test_profile_class_percentage_(kDefaultTestProfileClassPercentage),
Jeff Haof0a31f82017-03-27 15:50:37 -0700186 test_profile_seed_(NanoTime()),
Calin Juravle2e2db782016-02-23 12:00:03 +0000187 start_ns_(NanoTime()) {}
188
189 ~ProfMan() {
190 LogCompletionTime();
191 }
192
193 void ParseArgs(int argc, char **argv) {
194 original_argc = argc;
195 original_argv = argv;
196
Andreas Gampe51d80cc2017-06-21 21:05:13 -0700197 InitLogging(argv, Runtime::Abort);
Calin Juravle2e2db782016-02-23 12:00:03 +0000198
199 // Skip over the command name.
200 argv++;
201 argc--;
202
203 if (argc == 0) {
204 Usage("No arguments specified");
205 }
206
207 for (int i = 0; i < argc; ++i) {
208 const StringPiece option(argv[i]);
209 const bool log_options = false;
210 if (log_options) {
Calin Juravle876f3502016-03-24 16:16:34 +0000211 LOG(INFO) << "profman: option[" << i << "]=" << argv[i];
Calin Juravle2e2db782016-02-23 12:00:03 +0000212 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700213 if (option == "--dump-only") {
214 dump_only_ = true;
Mathieu Chartier34067262017-04-06 13:55:46 -0700215 } else if (option == "--dump-classes-and-methods") {
216 dump_classes_and_methods_ = true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800217 } else if (option.starts_with("--create-profile-from=")) {
218 create_profile_from_file_ = option.substr(strlen("--create-profile-from=")).ToString();
David Sehr4fcdd6d2016-05-24 14:52:31 -0700219 } else if (option.starts_with("--dump-output-to-fd=")) {
220 ParseUintOption(option, "--dump-output-to-fd", &dump_output_to_fd_, Usage);
Mathieu Chartier2f794552017-06-19 10:58:08 -0700221 } else if (option == "--generate-boot-image-profile") {
222 generate_boot_image_profile_ = true;
223 } else if (option.starts_with("--boot-image-class-threshold=")) {
224 ParseUintOption(option,
225 "--boot-image-class-threshold",
226 &boot_image_options_.image_class_theshold,
227 Usage);
228 } else if (option.starts_with("--boot-image-clean-class-threshold=")) {
229 ParseUintOption(option,
230 "--boot-image-clean-class-threshold",
231 &boot_image_options_.image_class_clean_theshold,
232 Usage);
Mathieu Chartier8eecddf2017-07-12 16:05:54 -0700233 } else if (option.starts_with("--boot-image-sampled-method-threshold=")) {
234 ParseUintOption(option,
235 "--boot-image-sampled-method-threshold",
236 &boot_image_options_.compiled_method_threshold,
237 Usage);
Calin Juravle876f3502016-03-24 16:16:34 +0000238 } else if (option.starts_with("--profile-file=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000239 profile_files_.push_back(option.substr(strlen("--profile-file=")).ToString());
240 } else if (option.starts_with("--profile-file-fd=")) {
241 ParseFdForCollection(option, "--profile-file-fd", &profile_files_fd_);
242 } else if (option.starts_with("--reference-profile-file=")) {
243 reference_profile_file_ = option.substr(strlen("--reference-profile-file=")).ToString();
244 } else if (option.starts_with("--reference-profile-file-fd=")) {
245 ParseUintOption(option, "--reference-profile-file-fd", &reference_profile_file_fd_, Usage);
David Sehr546d24f2016-06-02 10:46:19 -0700246 } else if (option.starts_with("--dex-location=")) {
247 dex_locations_.push_back(option.substr(strlen("--dex-location=")).ToString());
248 } else if (option.starts_with("--apk-fd=")) {
249 ParseFdForCollection(option, "--apk-fd", &apks_fd_);
David Sehr7c80f2d2017-02-07 16:47:58 -0800250 } else if (option.starts_with("--apk=")) {
251 apk_files_.push_back(option.substr(strlen("--apk=")).ToString());
Calin Juravle7bcdb532016-06-07 16:14:47 +0100252 } else if (option.starts_with("--generate-test-profile=")) {
253 test_profile_ = option.substr(strlen("--generate-test-profile=")).ToString();
254 } else if (option.starts_with("--generate-test-profile-num-dex=")) {
255 ParseUintOption(option,
256 "--generate-test-profile-num-dex",
257 &test_profile_num_dex_,
258 Usage);
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700259 } else if (option.starts_with("--generate-test-profile-method-percentage")) {
Calin Juravle7bcdb532016-06-07 16:14:47 +0100260 ParseUintOption(option,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700261 "--generate-test-profile-method-percentage",
262 &test_profile_method_percerntage_,
Calin Juravle7bcdb532016-06-07 16:14:47 +0100263 Usage);
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700264 } else if (option.starts_with("--generate-test-profile-class-percentage")) {
Calin Juravle7bcdb532016-06-07 16:14:47 +0100265 ParseUintOption(option,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700266 "--generate-test-profile-class-percentage",
267 &test_profile_class_percentage_,
Calin Juravle7bcdb532016-06-07 16:14:47 +0100268 Usage);
Jeff Haof0a31f82017-03-27 15:50:37 -0700269 } else if (option.starts_with("--generate-test-profile-seed=")) {
270 ParseUintOption(option, "--generate-test-profile-seed", &test_profile_seed_, Usage);
Calin Juravle2e2db782016-02-23 12:00:03 +0000271 } else {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700272 Usage("Unknown argument '%s'", option.data());
Calin Juravle2e2db782016-02-23 12:00:03 +0000273 }
274 }
275
David Sehr153da0e2017-02-15 08:54:51 -0800276 // Validate global consistency between file/fd options.
Calin Juravle2e2db782016-02-23 12:00:03 +0000277 if (!profile_files_.empty() && !profile_files_fd_.empty()) {
278 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
279 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700280 if (!reference_profile_file_.empty() && FdIsValid(reference_profile_file_fd_)) {
281 Usage("Reference profile should not be specified with both "
282 "--reference-profile-file-fd and --reference-profile-file");
283 }
David Sehr153da0e2017-02-15 08:54:51 -0800284 if (!apk_files_.empty() && !apks_fd_.empty()) {
285 Usage("APK files should not be specified with both --apk-fd and --apk");
Calin Juravle2e2db782016-02-23 12:00:03 +0000286 }
287 }
288
289 ProfileAssistant::ProcessingResult ProcessProfiles() {
David Sehr153da0e2017-02-15 08:54:51 -0800290 // Validate that at least one profile file was passed, as well as a reference profile.
291 if (profile_files_.empty() && profile_files_fd_.empty()) {
292 Usage("No profile files specified.");
293 }
294 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
295 Usage("No reference profile file specified.");
296 }
297 if ((!profile_files_.empty() && FdIsValid(reference_profile_file_fd_)) ||
298 (!profile_files_fd_.empty() && !FdIsValid(reference_profile_file_fd_))) {
299 Usage("Options --profile-file-fd and --reference-profile-file-fd "
300 "should only be used together");
301 }
Calin Juravle2e2db782016-02-23 12:00:03 +0000302 ProfileAssistant::ProcessingResult result;
303 if (profile_files_.empty()) {
304 // The file doesn't need to be flushed here (ProcessProfiles will do it)
305 // so don't check the usage.
306 File file(reference_profile_file_fd_, false);
307 result = ProfileAssistant::ProcessProfiles(profile_files_fd_, reference_profile_file_fd_);
308 CloseAllFds(profile_files_fd_, "profile_files_fd_");
309 } else {
310 result = ProfileAssistant::ProcessProfiles(profile_files_, reference_profile_file_);
311 }
312 return result;
313 }
314
David Sehr7c80f2d2017-02-07 16:47:58 -0800315 void OpenApkFilesFromLocations(std::vector<std::unique_ptr<const DexFile>>* dex_files) {
316 bool use_apk_fd_list = !apks_fd_.empty();
317 if (use_apk_fd_list) {
David Sehr153da0e2017-02-15 08:54:51 -0800318 // Get the APKs from the collection of FDs.
David Sehr7c80f2d2017-02-07 16:47:58 -0800319 CHECK_EQ(dex_locations_.size(), apks_fd_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800320 } else if (!apk_files_.empty()) {
321 // Get the APKs from the collection of filenames.
David Sehr7c80f2d2017-02-07 16:47:58 -0800322 CHECK_EQ(dex_locations_.size(), apk_files_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800323 } else {
324 // No APKs were specified.
325 CHECK(dex_locations_.empty());
326 return;
David Sehr7c80f2d2017-02-07 16:47:58 -0800327 }
328 static constexpr bool kVerifyChecksum = true;
329 for (size_t i = 0; i < dex_locations_.size(); ++i) {
330 std::string error_msg;
331 std::vector<std::unique_ptr<const DexFile>> dex_files_for_location;
332 if (use_apk_fd_list) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700333 if (DexFileLoader::OpenZip(apks_fd_[i],
334 dex_locations_[i],
Nicolas Geoffray095c6c92017-10-19 13:59:55 +0100335 /* verify */ true,
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700336 kVerifyChecksum,
337 &error_msg,
338 &dex_files_for_location)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800339 } else {
340 LOG(WARNING) << "OpenZip failed for '" << dex_locations_[i] << "' " << error_msg;
341 continue;
342 }
343 } else {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700344 if (DexFileLoader::Open(apk_files_[i].c_str(),
345 dex_locations_[i],
Nicolas Geoffray095c6c92017-10-19 13:59:55 +0100346 /* verify */ true,
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700347 kVerifyChecksum,
348 &error_msg,
349 &dex_files_for_location)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800350 } else {
351 LOG(WARNING) << "Open failed for '" << dex_locations_[i] << "' " << error_msg;
352 continue;
353 }
354 }
355 for (std::unique_ptr<const DexFile>& dex_file : dex_files_for_location) {
356 dex_files->emplace_back(std::move(dex_file));
357 }
358 }
359 }
360
Mathieu Chartier2f794552017-06-19 10:58:08 -0700361 std::unique_ptr<const ProfileCompilationInfo> LoadProfile(const std::string& filename, int fd) {
362 if (!filename.empty()) {
363 fd = open(filename.c_str(), O_RDWR);
364 if (fd < 0) {
365 LOG(ERROR) << "Cannot open " << filename << strerror(errno);
366 return nullptr;
367 }
368 }
369 std::unique_ptr<ProfileCompilationInfo> info(new ProfileCompilationInfo);
370 if (!info->Load(fd)) {
371 LOG(ERROR) << "Cannot load profile info from fd=" << fd << "\n";
372 return nullptr;
373 }
374 return info;
375 }
376
David Sehrb18991b2017-02-08 20:58:10 -0800377 int DumpOneProfile(const std::string& banner,
378 const std::string& filename,
379 int fd,
380 const std::vector<std::unique_ptr<const DexFile>>* dex_files,
381 std::string* dump) {
Mathieu Chartier2f794552017-06-19 10:58:08 -0700382 std::unique_ptr<const ProfileCompilationInfo> info(LoadProfile(filename, fd));
383 if (info == nullptr) {
384 LOG(ERROR) << "Cannot load profile info from filename=" << filename << " fd=" << fd;
Calin Juravle876f3502016-03-24 16:16:34 +0000385 return -1;
386 }
Mathieu Chartier2f794552017-06-19 10:58:08 -0700387 *dump += banner + "\n" + info->DumpInfo(dex_files) + "\n";
David Sehr4fcdd6d2016-05-24 14:52:31 -0700388 return 0;
389 }
390
391 int DumpProfileInfo() {
David Sehr153da0e2017-02-15 08:54:51 -0800392 // Validate that at least one profile file or reference was specified.
393 if (profile_files_.empty() && profile_files_fd_.empty() &&
394 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
395 Usage("No profile files or reference profile specified.");
396 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700397 static const char* kEmptyString = "";
David Sehr546d24f2016-06-02 10:46:19 -0700398 static const char* kOrdinaryProfile = "=== profile ===";
399 static const char* kReferenceProfile = "=== reference profile ===";
400
401 // Open apk/zip files and and read dex files.
402 MemMap::Init(); // for ZipArchive::OpenFromFd
David Sehrb18991b2017-02-08 20:58:10 -0800403 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7c80f2d2017-02-07 16:47:58 -0800404 OpenApkFilesFromLocations(&dex_files);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700405 std::string dump;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700406 // Dump individual profile files.
407 if (!profile_files_fd_.empty()) {
408 for (int profile_file_fd : profile_files_fd_) {
David Sehr546d24f2016-06-02 10:46:19 -0700409 int ret = DumpOneProfile(kOrdinaryProfile,
410 kEmptyString,
411 profile_file_fd,
412 &dex_files,
413 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700414 if (ret != 0) {
415 return ret;
416 }
417 }
418 }
419 if (!profile_files_.empty()) {
420 for (const std::string& profile_file : profile_files_) {
David Sehr546d24f2016-06-02 10:46:19 -0700421 int ret = DumpOneProfile(kOrdinaryProfile, profile_file, kInvalidFd, &dex_files, &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700422 if (ret != 0) {
423 return ret;
424 }
425 }
426 }
427 // Dump reference profile file.
428 if (FdIsValid(reference_profile_file_fd_)) {
David Sehr546d24f2016-06-02 10:46:19 -0700429 int ret = DumpOneProfile(kReferenceProfile,
430 kEmptyString,
431 reference_profile_file_fd_,
432 &dex_files,
433 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700434 if (ret != 0) {
435 return ret;
436 }
437 }
438 if (!reference_profile_file_.empty()) {
David Sehr546d24f2016-06-02 10:46:19 -0700439 int ret = DumpOneProfile(kReferenceProfile,
440 reference_profile_file_,
441 kInvalidFd,
442 &dex_files,
David Sehr4fcdd6d2016-05-24 14:52:31 -0700443 &dump);
444 if (ret != 0) {
445 return ret;
446 }
447 }
448 if (!FdIsValid(dump_output_to_fd_)) {
449 std::cout << dump;
450 } else {
451 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
452 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
453 return -1;
454 }
455 }
Calin Juravle876f3502016-03-24 16:16:34 +0000456 return 0;
457 }
458
459 bool ShouldOnlyDumpProfile() {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700460 return dump_only_;
Calin Juravle876f3502016-03-24 16:16:34 +0000461 }
462
Mathieu Chartier34067262017-04-06 13:55:46 -0700463 bool GetClassNamesAndMethods(int fd,
464 std::vector<std::unique_ptr<const DexFile>>* dex_files,
465 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800466 ProfileCompilationInfo profile_info;
467 if (!profile_info.Load(fd)) {
468 LOG(ERROR) << "Cannot load profile info";
469 return false;
470 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700471 for (const std::unique_ptr<const DexFile>& dex_file : *dex_files) {
472 std::set<dex::TypeIndex> class_types;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700473 std::set<uint16_t> hot_methods;
474 std::set<uint16_t> startup_methods;
475 std::set<uint16_t> post_startup_methods;
476 std::set<uint16_t> combined_methods;
477 if (profile_info.GetClassesAndMethods(*dex_file.get(),
478 &class_types,
479 &hot_methods,
480 &startup_methods,
481 &post_startup_methods)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700482 for (const dex::TypeIndex& type_index : class_types) {
483 const DexFile::TypeId& type_id = dex_file->GetTypeId(type_index);
484 out_lines->insert(std::string(dex_file->GetTypeDescriptor(type_id)));
485 }
Mathieu Chartierea650f32017-05-24 12:04:13 -0700486 combined_methods = hot_methods;
487 combined_methods.insert(startup_methods.begin(), startup_methods.end());
488 combined_methods.insert(post_startup_methods.begin(), post_startup_methods.end());
489 for (uint16_t dex_method_idx : combined_methods) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700490 const DexFile::MethodId& id = dex_file->GetMethodId(dex_method_idx);
491 std::string signature_string(dex_file->GetMethodSignature(id).ToString());
492 std::string type_string(dex_file->GetTypeDescriptor(dex_file->GetTypeId(id.class_idx_)));
493 std::string method_name(dex_file->GetMethodName(id));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700494 std::string flags_string;
495 if (hot_methods.find(dex_method_idx) != hot_methods.end()) {
496 flags_string += kMethodFlagStringHot;
497 }
498 if (startup_methods.find(dex_method_idx) != startup_methods.end()) {
499 flags_string += kMethodFlagStringStartup;
500 }
501 if (post_startup_methods.find(dex_method_idx) != post_startup_methods.end()) {
502 flags_string += kMethodFlagStringPostStartup;
503 }
504 out_lines->insert(flags_string +
505 type_string +
506 kMethodSep +
507 method_name +
508 signature_string);
Mathieu Chartier34067262017-04-06 13:55:46 -0700509 }
510 }
511 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800512 return true;
513 }
514
Mathieu Chartier34067262017-04-06 13:55:46 -0700515 bool GetClassNamesAndMethods(const std::string& profile_file,
516 std::vector<std::unique_ptr<const DexFile>>* dex_files,
517 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800518 int fd = open(profile_file.c_str(), O_RDONLY);
519 if (!FdIsValid(fd)) {
520 LOG(ERROR) << "Cannot open " << profile_file << strerror(errno);
521 return false;
522 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700523 if (!GetClassNamesAndMethods(fd, dex_files, out_lines)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800524 return false;
525 }
526 if (close(fd) < 0) {
527 PLOG(WARNING) << "Failed to close descriptor";
528 }
529 return true;
530 }
531
Mathieu Chartierea650f32017-05-24 12:04:13 -0700532 int DumpClassesAndMethods() {
David Sehr153da0e2017-02-15 08:54:51 -0800533 // Validate that at least one profile file or reference was specified.
534 if (profile_files_.empty() && profile_files_fd_.empty() &&
535 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
536 Usage("No profile files or reference profile specified.");
537 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800538 // Open apk/zip files and and read dex files.
539 MemMap::Init(); // for ZipArchive::OpenFromFd
540 // Open the dex files to get the names for classes.
541 std::vector<std::unique_ptr<const DexFile>> dex_files;
542 OpenApkFilesFromLocations(&dex_files);
543 // Build a vector of class names from individual profile files.
544 std::set<std::string> class_names;
545 if (!profile_files_fd_.empty()) {
546 for (int profile_file_fd : profile_files_fd_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700547 if (!GetClassNamesAndMethods(profile_file_fd, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800548 return -1;
549 }
550 }
551 }
552 if (!profile_files_.empty()) {
553 for (const std::string& profile_file : profile_files_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700554 if (!GetClassNamesAndMethods(profile_file, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800555 return -1;
556 }
557 }
558 }
559 // Concatenate class names from reference profile file.
560 if (FdIsValid(reference_profile_file_fd_)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700561 if (!GetClassNamesAndMethods(reference_profile_file_fd_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800562 return -1;
563 }
564 }
565 if (!reference_profile_file_.empty()) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700566 if (!GetClassNamesAndMethods(reference_profile_file_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800567 return -1;
568 }
569 }
570 // Dump the class names.
571 std::string dump;
572 for (const std::string& class_name : class_names) {
573 dump += class_name + std::string("\n");
574 }
575 if (!FdIsValid(dump_output_to_fd_)) {
576 std::cout << dump;
577 } else {
578 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
579 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
580 return -1;
581 }
582 }
583 return 0;
584 }
585
Mathieu Chartier34067262017-04-06 13:55:46 -0700586 bool ShouldOnlyDumpClassesAndMethods() {
587 return dump_classes_and_methods_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800588 }
589
590 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
591 // the given function.
592 template <typename T>
593 static T* ReadCommentedInputFromFile(
594 const char* input_filename, std::function<std::string(const char*)>* process) {
595 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
596 if (input_file.get() == nullptr) {
597 LOG(ERROR) << "Failed to open input file " << input_filename;
598 return nullptr;
599 }
600 std::unique_ptr<T> result(
601 ReadCommentedInputStream<T>(*input_file, process));
602 input_file->close();
603 return result.release();
604 }
605
606 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
607 // with the given function.
608 template <typename T>
609 static T* ReadCommentedInputStream(
610 std::istream& in_stream,
611 std::function<std::string(const char*)>* process) {
612 std::unique_ptr<T> output(new T());
613 while (in_stream.good()) {
614 std::string dot;
615 std::getline(in_stream, dot);
616 if (android::base::StartsWith(dot, "#") || dot.empty()) {
617 continue;
618 }
619 if (process != nullptr) {
620 std::string descriptor((*process)(dot.c_str()));
621 output->insert(output->end(), descriptor);
622 } else {
623 output->insert(output->end(), dot);
624 }
625 }
626 return output.release();
627 }
628
Calin Juravlee0ac1152017-02-13 19:03:47 -0800629 // Find class klass_descriptor in the given dex_files and store its reference
630 // in the out parameter class_ref.
631 // Return true if the definition of the class was found in any of the dex_files.
632 bool FindClass(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
633 const std::string& klass_descriptor,
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700634 /*out*/TypeReference* class_ref) {
Calin Juravle08556882017-05-26 16:40:45 -0700635 constexpr uint16_t kInvalidTypeIndex = std::numeric_limits<uint16_t>::max() - 1;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800636 for (const std::unique_ptr<const DexFile>& dex_file_ptr : dex_files) {
637 const DexFile* dex_file = dex_file_ptr.get();
Calin Juravle08556882017-05-26 16:40:45 -0700638 if (klass_descriptor == kInvalidClassDescriptor) {
639 if (kInvalidTypeIndex >= dex_file->NumTypeIds()) {
640 // The dex file does not contain all possible type ids which leaves us room
641 // to add an "invalid" type id.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700642 *class_ref = TypeReference(dex_file, dex::TypeIndex(kInvalidTypeIndex));
Calin Juravle08556882017-05-26 16:40:45 -0700643 return true;
644 } else {
645 // The dex file contains all possible type ids. We don't have any free type id
646 // that we can use as invalid.
647 continue;
648 }
649 }
650
Calin Juravlee0ac1152017-02-13 19:03:47 -0800651 const DexFile::TypeId* type_id = dex_file->FindTypeId(klass_descriptor.c_str());
652 if (type_id == nullptr) {
653 continue;
654 }
655 dex::TypeIndex type_index = dex_file->GetIndexForTypeId(*type_id);
656 if (dex_file->FindClassDef(type_index) == nullptr) {
657 // Class is only referenced in the current dex file but not defined in it.
658 continue;
659 }
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700660 *class_ref = TypeReference(dex_file, type_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800661 return true;
662 }
663 return false;
664 }
665
Mathieu Chartier34067262017-04-06 13:55:46 -0700666 // Find the method specified by method_spec in the class class_ref.
Calin Juravle08556882017-05-26 16:40:45 -0700667 uint32_t FindMethodIndex(const TypeReference& class_ref,
668 const std::string& method_spec) {
669 const DexFile* dex_file = class_ref.dex_file;
670 if (method_spec == kInvalidMethod) {
671 constexpr uint16_t kInvalidMethodIndex = std::numeric_limits<uint16_t>::max() - 1;
672 return kInvalidMethodIndex >= dex_file->NumMethodIds()
673 ? kInvalidMethodIndex
Andreas Gampee2abbc62017-09-15 11:59:26 -0700674 : dex::kDexNoIndex;
Calin Juravle08556882017-05-26 16:40:45 -0700675 }
676
Calin Juravlee0ac1152017-02-13 19:03:47 -0800677 std::vector<std::string> name_and_signature;
678 Split(method_spec, kProfileParsingFirstCharInSignature, &name_and_signature);
679 if (name_and_signature.size() != 2) {
680 LOG(ERROR) << "Invalid method name and signature " << method_spec;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700681 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800682 }
Calin Juravle08556882017-05-26 16:40:45 -0700683
Calin Juravlee0ac1152017-02-13 19:03:47 -0800684 const std::string& name = name_and_signature[0];
685 const std::string& signature = kProfileParsingFirstCharInSignature + name_and_signature[1];
Calin Juravlee0ac1152017-02-13 19:03:47 -0800686
687 const DexFile::StringId* name_id = dex_file->FindStringId(name.c_str());
688 if (name_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700689 LOG(WARNING) << "Could not find name: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700690 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800691 }
692 dex::TypeIndex return_type_idx;
693 std::vector<dex::TypeIndex> param_type_idxs;
694 if (!dex_file->CreateTypeList(signature, &return_type_idx, &param_type_idxs)) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700695 LOG(WARNING) << "Could not create type list" << signature;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700696 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800697 }
698 const DexFile::ProtoId* proto_id = dex_file->FindProtoId(return_type_idx, param_type_idxs);
699 if (proto_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700700 LOG(WARNING) << "Could not find proto_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700701 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800702 }
703 const DexFile::MethodId* method_id = dex_file->FindMethodId(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700704 dex_file->GetTypeId(class_ref.TypeIndex()), *name_id, *proto_id);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800705 if (method_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700706 LOG(WARNING) << "Could not find method_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700707 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800708 }
709
Mathieu Chartier34067262017-04-06 13:55:46 -0700710 return dex_file->GetIndexForMethodId(*method_id);
711 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800712
Mathieu Chartier34067262017-04-06 13:55:46 -0700713 // Given a method, return true if the method has a single INVOKE_VIRTUAL in its byte code.
714 // Upon success it returns true and stores the method index and the invoke dex pc
715 // in the output parameters.
716 // The format of the method spec is "inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
717 //
718 // TODO(calin): support INVOKE_INTERFACE and the range variants.
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700719 bool HasSingleInvoke(const TypeReference& class_ref,
Mathieu Chartier34067262017-04-06 13:55:46 -0700720 uint16_t method_index,
721 /*out*/uint32_t* dex_pc) {
722 const DexFile* dex_file = class_ref.dex_file;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800723 uint32_t offset = dex_file->FindCodeItemOffset(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700724 *dex_file->FindClassDef(class_ref.TypeIndex()),
Mathieu Chartier34067262017-04-06 13:55:46 -0700725 method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800726 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(offset);
727
728 bool found_invoke = false;
Mathieu Chartier0021feb2017-11-07 00:08:52 -0800729 for (const DexInstructionPcPair& inst : code_item->Instructions()) {
730 if (inst->Opcode() == Instruction::INVOKE_VIRTUAL) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800731 if (found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700732 LOG(ERROR) << "Multiple invoke INVOKE_VIRTUAL found: "
733 << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800734 return false;
735 }
736 found_invoke = true;
Mathieu Chartier0021feb2017-11-07 00:08:52 -0800737 *dex_pc = inst.DexPc();
Calin Juravlee0ac1152017-02-13 19:03:47 -0800738 }
739 }
740 if (!found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700741 LOG(ERROR) << "Could not find any INVOKE_VIRTUAL: " << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800742 }
743 return found_invoke;
744 }
745
746 // Process a line defining a class or a method and its inline caches.
747 // Upon success return true and add the class or the method info to profile.
Calin Juravle589e71e2017-03-03 16:05:05 -0800748 // The possible line formats are:
749 // "LJustTheCass;".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800750 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
Calin Juravle08556882017-05-26 16:40:45 -0700751 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,invalid_class".
Calin Juravle589e71e2017-03-03 16:05:05 -0800752 // "LTestInline;->inlineMissingTypes(LSuper;)I+missing_types".
753 // "LTestInline;->inlineNoInlineCaches(LSuper;)I".
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700754 // "LTestInline;->*".
Calin Juravle08556882017-05-26 16:40:45 -0700755 // "invalid_class".
756 // "LTestInline;->invalid_method".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800757 // The method and classes are searched only in the given dex files.
758 bool ProcessLine(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
759 const std::string& line,
760 /*out*/ProfileCompilationInfo* profile) {
761 std::string klass;
762 std::string method_str;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700763 bool is_hot = false;
764 bool is_startup = false;
765 bool is_post_startup = false;
766 const size_t method_sep_index = line.find(kMethodSep, 0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800767 if (method_sep_index == std::string::npos) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700768 klass = line.substr(0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800769 } else {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700770 // The method prefix flags are only valid for method strings.
771 size_t start_index = 0;
772 while (start_index < line.size() && line[start_index] != 'L') {
773 const char c = line[start_index];
774 if (c == kMethodFlagStringHot) {
775 is_hot = true;
776 } else if (c == kMethodFlagStringStartup) {
777 is_startup = true;
778 } else if (c == kMethodFlagStringPostStartup) {
779 is_post_startup = true;
780 } else {
781 LOG(WARNING) << "Invalid flag " << c;
782 return false;
783 }
784 ++start_index;
785 }
786 klass = line.substr(start_index, method_sep_index - start_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800787 method_str = line.substr(method_sep_index + kMethodSep.size());
788 }
789
Vladimir Markof3c52b42017-11-17 17:32:12 +0000790 TypeReference class_ref(/* dex_file */ nullptr, dex::TypeIndex());
Calin Juravlee0ac1152017-02-13 19:03:47 -0800791 if (!FindClass(dex_files, klass, &class_ref)) {
Mathieu Chartier3f121342017-03-06 11:16:20 -0800792 LOG(WARNING) << "Could not find class: " << klass;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800793 return false;
794 }
795
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700796 if (method_str.empty() || method_str == kClassAllMethods) {
797 // Start by adding the class.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800798 std::set<DexCacheResolvedClasses> resolved_class_set;
799 const DexFile* dex_file = class_ref.dex_file;
800 const auto& dex_resolved_classes = resolved_class_set.emplace(
801 dex_file->GetLocation(),
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700802 DexFileLoader::GetBaseLocation(dex_file->GetLocation()),
Mathieu Chartierea650f32017-05-24 12:04:13 -0700803 dex_file->GetLocationChecksum(),
804 dex_file->NumMethodIds());
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700805 dex_resolved_classes.first->AddClass(class_ref.TypeIndex());
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700806 std::vector<ProfileMethodInfo> methods;
807 if (method_str == kClassAllMethods) {
808 // Add all of the methods.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700809 const DexFile::ClassDef* class_def = dex_file->FindClassDef(class_ref.TypeIndex());
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700810 const uint8_t* class_data = dex_file->GetClassData(*class_def);
811 if (class_data != nullptr) {
812 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700813 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800814 while (it.HasNextMethod()) {
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700815 if (it.GetMethodCodeItemOffset() != 0) {
816 // Add all of the methods that have code to the profile.
817 const uint32_t method_idx = it.GetMemberIndex();
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700818 methods.push_back(ProfileMethodInfo(MethodReference(dex_file, method_idx)));
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700819 }
820 it.Next();
821 }
822 }
823 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700824 // TODO: Check return values?
825 profile->AddMethods(methods);
826 profile->AddClasses(resolved_class_set);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800827 return true;
828 }
829
830 // Process the method.
831 std::string method_spec;
832 std::vector<std::string> inline_cache_elems;
833
Mathieu Chartierea650f32017-05-24 12:04:13 -0700834 // If none of the flags are set, default to hot.
835 is_hot = is_hot || (!is_hot && !is_startup && !is_post_startup);
836
Calin Juravlee0ac1152017-02-13 19:03:47 -0800837 std::vector<std::string> method_elems;
Calin Juravle589e71e2017-03-03 16:05:05 -0800838 bool is_missing_types = false;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800839 Split(method_str, kProfileParsingInlineChacheSep, &method_elems);
840 if (method_elems.size() == 2) {
841 method_spec = method_elems[0];
Calin Juravle589e71e2017-03-03 16:05:05 -0800842 is_missing_types = method_elems[1] == kMissingTypesMarker;
843 if (!is_missing_types) {
844 Split(method_elems[1], kProfileParsingTypeSep, &inline_cache_elems);
845 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800846 } else if (method_elems.size() == 1) {
847 method_spec = method_elems[0];
848 } else {
849 LOG(ERROR) << "Invalid method line: " << line;
850 return false;
851 }
852
Mathieu Chartier34067262017-04-06 13:55:46 -0700853 const uint32_t method_index = FindMethodIndex(class_ref, method_spec);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700854 if (method_index == dex::kDexNoIndex) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800855 return false;
856 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700857
Mathieu Chartier34067262017-04-06 13:55:46 -0700858 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
859 if (is_missing_types || !inline_cache_elems.empty()) {
860 uint32_t dex_pc;
861 if (!HasSingleInvoke(class_ref, method_index, &dex_pc)) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800862 return false;
863 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000864 std::vector<TypeReference> classes(inline_cache_elems.size(),
865 TypeReference(/* dex_file */ nullptr, dex::TypeIndex()));
Mathieu Chartier34067262017-04-06 13:55:46 -0700866 size_t class_it = 0;
867 for (const std::string& ic_class : inline_cache_elems) {
868 if (!FindClass(dex_files, ic_class, &(classes[class_it++]))) {
869 LOG(ERROR) << "Could not find class: " << ic_class;
870 return false;
871 }
872 }
873 inline_caches.emplace_back(dex_pc, is_missing_types, classes);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800874 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700875 MethodReference ref(class_ref.dex_file, method_index);
Mathieu Chartierea650f32017-05-24 12:04:13 -0700876 if (is_hot) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700877 profile->AddMethod(ProfileMethodInfo(ref, inline_caches));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700878 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700879 uint32_t flags = 0;
880 using Hotness = ProfileCompilationInfo::MethodHotness;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700881 if (is_startup) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700882 flags |= Hotness::kFlagStartup;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700883 }
884 if (is_post_startup) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700885 flags |= Hotness::kFlagPostStartup;
886 }
887 if (flags != 0) {
888 if (!profile->AddMethodIndex(static_cast<Hotness::Flag>(flags), ref)) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700889 return false;
890 }
Mathieu Chartiere46f3a82017-06-19 19:54:12 -0700891 DCHECK(profile->GetMethodHotness(ref).IsInProfile());
Mathieu Chartierea650f32017-05-24 12:04:13 -0700892 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800893 return true;
894 }
895
Mathieu Chartier2f794552017-06-19 10:58:08 -0700896 int OpenReferenceProfile() const {
897 int fd = reference_profile_file_fd_;
898 if (!FdIsValid(fd)) {
899 CHECK(!reference_profile_file_.empty());
900 fd = open(reference_profile_file_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
901 if (fd < 0) {
902 LOG(ERROR) << "Cannot open " << reference_profile_file_ << strerror(errno);
903 return kInvalidFd;
904 }
905 }
906 return fd;
907 }
908
Calin Juravlee0ac1152017-02-13 19:03:47 -0800909 // Creates a profile from a human friendly textual representation.
910 // The expected input format is:
911 // # Classes
912 // Ljava/lang/Comparable;
913 // Ljava/lang/Math;
914 // # Methods with inline caches
915 // LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;
916 // LTestInline;->noInlineCache(LSuper;)I
David Sehr7c80f2d2017-02-07 16:47:58 -0800917 int CreateProfile() {
David Sehr153da0e2017-02-15 08:54:51 -0800918 // Validate parameters for this command.
919 if (apk_files_.empty() && apks_fd_.empty()) {
920 Usage("APK files must be specified");
921 }
922 if (dex_locations_.empty()) {
923 Usage("DEX locations must be specified");
924 }
925 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
926 Usage("Reference profile must be specified with --reference-profile-file or "
927 "--reference-profile-file-fd");
928 }
929 if (!profile_files_.empty() || !profile_files_fd_.empty()) {
930 Usage("Profile must be specified with --reference-profile-file or "
931 "--reference-profile-file-fd");
932 }
933 // for ZipArchive::OpenFromFd
934 MemMap::Init();
David Sehr7c80f2d2017-02-07 16:47:58 -0800935 // Open the profile output file if needed.
Mathieu Chartier2f794552017-06-19 10:58:08 -0700936 int fd = OpenReferenceProfile();
David Sehr7c80f2d2017-02-07 16:47:58 -0800937 if (!FdIsValid(fd)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800938 return -1;
David Sehr7c80f2d2017-02-07 16:47:58 -0800939 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800940 // Read the user-specified list of classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800941 std::unique_ptr<std::unordered_set<std::string>>
Calin Juravlee0ac1152017-02-13 19:03:47 -0800942 user_lines(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
David Sehr7c80f2d2017-02-07 16:47:58 -0800943 create_profile_from_file_.c_str(), nullptr)); // No post-processing.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800944
945 // Open the dex files to look up classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800946 std::vector<std::unique_ptr<const DexFile>> dex_files;
947 OpenApkFilesFromLocations(&dex_files);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800948
949 // Process the lines one by one and add the successful ones to the profile.
David Sehr7c80f2d2017-02-07 16:47:58 -0800950 ProfileCompilationInfo info;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800951
952 for (const auto& line : *user_lines) {
953 ProcessLine(dex_files, line, &info);
954 }
955
David Sehr7c80f2d2017-02-07 16:47:58 -0800956 // Write the profile file.
957 CHECK(info.Save(fd));
958 if (close(fd) < 0) {
959 PLOG(WARNING) << "Failed to close descriptor";
960 }
961 return 0;
962 }
963
Mathieu Chartier2f794552017-06-19 10:58:08 -0700964 bool ShouldCreateBootProfile() const {
965 return generate_boot_image_profile_;
966 }
967
968 int CreateBootProfile() {
969 // Initialize memmap since it's required to open dex files.
970 MemMap::Init();
971 // Open the profile output file.
972 const int reference_fd = OpenReferenceProfile();
973 if (!FdIsValid(reference_fd)) {
974 PLOG(ERROR) << "Error opening reference profile";
975 return -1;
976 }
977 // Open the dex files.
978 std::vector<std::unique_ptr<const DexFile>> dex_files;
979 OpenApkFilesFromLocations(&dex_files);
980 if (dex_files.empty()) {
981 PLOG(ERROR) << "Expected dex files for creating boot profile";
982 return -2;
983 }
984 // Open the input profiles.
985 std::vector<std::unique_ptr<const ProfileCompilationInfo>> profiles;
986 if (!profile_files_fd_.empty()) {
987 for (int profile_file_fd : profile_files_fd_) {
988 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile("", profile_file_fd));
989 if (profile == nullptr) {
990 return -3;
991 }
992 profiles.emplace_back(std::move(profile));
993 }
994 }
995 if (!profile_files_.empty()) {
996 for (const std::string& profile_file : profile_files_) {
997 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile(profile_file, kInvalidFd));
998 if (profile == nullptr) {
999 return -4;
1000 }
1001 profiles.emplace_back(std::move(profile));
1002 }
1003 }
1004 ProfileCompilationInfo out_profile;
1005 GenerateBootImageProfile(dex_files,
1006 profiles,
1007 boot_image_options_,
1008 VLOG_IS_ON(profiler),
1009 &out_profile);
1010 out_profile.Save(reference_fd);
1011 close(reference_fd);
1012 return 0;
1013 }
1014
David Sehr7c80f2d2017-02-07 16:47:58 -08001015 bool ShouldCreateProfile() {
1016 return !create_profile_from_file_.empty();
1017 }
1018
Calin Juravle7bcdb532016-06-07 16:14:47 +01001019 int GenerateTestProfile() {
David Sehr153da0e2017-02-15 08:54:51 -08001020 // Validate parameters for this command.
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001021 if (test_profile_method_percerntage_ > 100) {
1022 Usage("Invalid percentage for --generate-test-profile-method-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001023 }
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001024 if (test_profile_class_percentage_ > 100) {
1025 Usage("Invalid percentage for --generate-test-profile-class-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001026 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001027 // If given APK files or DEX locations, check that they're ok.
1028 if (!apk_files_.empty() || !apks_fd_.empty() || !dex_locations_.empty()) {
1029 if (apk_files_.empty() && apks_fd_.empty()) {
1030 Usage("APK files must be specified when passing DEX locations to --generate-test-profile");
1031 }
1032 if (dex_locations_.empty()) {
1033 Usage("DEX locations must be specified when passing APK files to --generate-test-profile");
1034 }
1035 }
David Sehr153da0e2017-02-15 08:54:51 -08001036 // ShouldGenerateTestProfile confirms !test_profile_.empty().
George Burgess IV71f77262016-10-25 13:08:17 -07001037 int profile_test_fd = open(test_profile_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001038 if (profile_test_fd < 0) {
David Sehr7c80f2d2017-02-07 16:47:58 -08001039 LOG(ERROR) << "Cannot open " << test_profile_ << strerror(errno);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001040 return -1;
1041 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001042 bool result;
1043 if (apk_files_.empty() && apks_fd_.empty() && dex_locations_.empty()) {
1044 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1045 test_profile_num_dex_,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001046 test_profile_method_percerntage_,
1047 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001048 test_profile_seed_);
1049 } else {
1050 // Initialize MemMap for ZipArchive::OpenFromFd.
1051 MemMap::Init();
1052 // Open the dex files to look up classes and methods.
1053 std::vector<std::unique_ptr<const DexFile>> dex_files;
1054 OpenApkFilesFromLocations(&dex_files);
1055 // Create a random profile file based on the set of dex files.
1056 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1057 dex_files,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001058 test_profile_method_percerntage_,
1059 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001060 test_profile_seed_);
1061 }
Calin Juravle7bcdb532016-06-07 16:14:47 +01001062 close(profile_test_fd); // ignore close result.
1063 return result ? 0 : -1;
1064 }
1065
1066 bool ShouldGenerateTestProfile() {
1067 return !test_profile_.empty();
1068 }
1069
Calin Juravle2e2db782016-02-23 12:00:03 +00001070 private:
1071 static void ParseFdForCollection(const StringPiece& option,
1072 const char* arg_name,
1073 std::vector<int>* fds) {
1074 int fd;
1075 ParseUintOption(option, arg_name, &fd, Usage);
1076 fds->push_back(fd);
1077 }
1078
1079 static void CloseAllFds(const std::vector<int>& fds, const char* descriptor) {
1080 for (size_t i = 0; i < fds.size(); i++) {
1081 if (close(fds[i]) < 0) {
1082 PLOG(WARNING) << "Failed to close descriptor for " << descriptor << " at index " << i;
1083 }
1084 }
1085 }
1086
1087 void LogCompletionTime() {
David Sehr52683cf2016-05-05 09:02:38 -07001088 static constexpr uint64_t kLogThresholdTime = MsToNs(100); // 100ms
1089 uint64_t time_taken = NanoTime() - start_ns_;
David Sehred793012016-05-05 13:39:43 -07001090 if (time_taken > kLogThresholdTime) {
David Sehrd8557182016-05-06 12:29:35 -07001091 LOG(WARNING) << "profman took " << PrettyDuration(time_taken);
David Sehred793012016-05-05 13:39:43 -07001092 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001093 }
1094
1095 std::vector<std::string> profile_files_;
1096 std::vector<int> profile_files_fd_;
David Sehr546d24f2016-06-02 10:46:19 -07001097 std::vector<std::string> dex_locations_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001098 std::vector<std::string> apk_files_;
David Sehr546d24f2016-06-02 10:46:19 -07001099 std::vector<int> apks_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001100 std::string reference_profile_file_;
1101 int reference_profile_file_fd_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001102 bool dump_only_;
Mathieu Chartier34067262017-04-06 13:55:46 -07001103 bool dump_classes_and_methods_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001104 bool generate_boot_image_profile_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001105 int dump_output_to_fd_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001106 BootImageOptions boot_image_options_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001107 std::string test_profile_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001108 std::string create_profile_from_file_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001109 uint16_t test_profile_num_dex_;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001110 uint16_t test_profile_method_percerntage_;
1111 uint16_t test_profile_class_percentage_;
Jeff Haof0a31f82017-03-27 15:50:37 -07001112 uint32_t test_profile_seed_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001113 uint64_t start_ns_;
1114};
1115
1116// See ProfileAssistant::ProcessingResult for return codes.
1117static int profman(int argc, char** argv) {
1118 ProfMan profman;
1119
1120 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1121 profman.ParseArgs(argc, argv);
1122
Calin Juravle7bcdb532016-06-07 16:14:47 +01001123 if (profman.ShouldGenerateTestProfile()) {
1124 return profman.GenerateTestProfile();
1125 }
Calin Juravle876f3502016-03-24 16:16:34 +00001126 if (profman.ShouldOnlyDumpProfile()) {
1127 return profman.DumpProfileInfo();
1128 }
Mathieu Chartier34067262017-04-06 13:55:46 -07001129 if (profman.ShouldOnlyDumpClassesAndMethods()) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001130 return profman.DumpClassesAndMethods();
David Sehr7c80f2d2017-02-07 16:47:58 -08001131 }
1132 if (profman.ShouldCreateProfile()) {
1133 return profman.CreateProfile();
1134 }
Mathieu Chartier2f794552017-06-19 10:58:08 -07001135
1136 if (profman.ShouldCreateBootProfile()) {
1137 return profman.CreateBootProfile();
1138 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001139 // Process profile information and assess if we need to do a profile guided compilation.
1140 // This operation involves I/O.
1141 return profman.ProcessProfiles();
1142}
1143
1144} // namespace art
1145
1146int main(int argc, char **argv) {
1147 return art::profman(argc, argv);
1148}
1149