blob: b9f020934624fec1c97c474ecfbe49877a34dccf [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>
Calin Juravlee10c1e22018-01-26 20:10:15 -080021#include <sys/param.h>
Calin Juravle2e2db782016-02-23 12:00:03 +000022#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.
David Sehrc431b9d2018-03-02 12:01:51 -080036#include "base/mutex.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000037#include "base/scoped_flock.h"
38#include "base/stringpiece.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000039#include "base/time_utils.h"
40#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080041#include "base/utils.h"
David Sehr79e26072018-04-06 17:58:50 -070042#include "base/zip_archive.h"
Mathieu Chartier2f794552017-06-19 10:58:08 -070043#include "boot_image_profile.h"
David Sehr013fd802018-01-11 22:55:24 -080044#include "dex/art_dex_file_loader.h"
David Sehr312f3b22018-03-19 08:39:26 -070045#include "dex/bytecode_utils.h"
David Sehr9e734c72018-01-04 17:56:19 -080046#include "dex/code_item_accessors-inl.h"
47#include "dex/dex_file.h"
48#include "dex/dex_file_loader.h"
49#include "dex/dex_file_types.h"
David Sehr312f3b22018-03-19 08:39:26 -070050#include "dex/type_reference.h"
Calin Juravle33083d62017-01-18 15:29:12 -080051#include "jit/profile_compilation_info.h"
Mathieu Chartierdbddc222017-05-24 12:04:13 -070052#include "profile_assistant.h"
David Sehrf57589f2016-10-17 10:09:33 -070053#include "runtime.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000054
55namespace art {
56
57static int original_argc;
58static char** original_argv;
59
60static std::string CommandLine() {
61 std::vector<std::string> command;
62 for (int i = 0; i < original_argc; ++i) {
63 command.push_back(original_argv[i]);
64 }
Andreas Gampe9186ced2016-12-12 14:28:21 -080065 return android::base::Join(command, ' ');
Calin Juravle2e2db782016-02-23 12:00:03 +000066}
67
David Sehr4fcdd6d2016-05-24 14:52:31 -070068static constexpr int kInvalidFd = -1;
69
70static bool FdIsValid(int fd) {
71 return fd != kInvalidFd;
72}
73
Calin Juravle2e2db782016-02-23 12:00:03 +000074static void UsageErrorV(const char* fmt, va_list ap) {
75 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080076 android::base::StringAppendV(&error, fmt, ap);
Calin Juravle2e2db782016-02-23 12:00:03 +000077 LOG(ERROR) << error;
78}
79
80static void UsageError(const char* fmt, ...) {
81 va_list ap;
82 va_start(ap, fmt);
83 UsageErrorV(fmt, ap);
84 va_end(ap);
85}
86
87NO_RETURN static void Usage(const char *fmt, ...) {
88 va_list ap;
89 va_start(ap, fmt);
90 UsageErrorV(fmt, ap);
91 va_end(ap);
92
93 UsageError("Command: %s", CommandLine().c_str());
94 UsageError("Usage: profman [options]...");
95 UsageError("");
David Sehr4fcdd6d2016-05-24 14:52:31 -070096 UsageError(" --dump-only: dumps the content of the specified profile files");
97 UsageError(" to standard output (default) in a human readable form.");
98 UsageError("");
David Sehr7c80f2d2017-02-07 16:47:58 -080099 UsageError(" --dump-output-to-fd=<number>: redirects --dump-only output to a file descriptor.");
100 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -0700101 UsageError(" --dump-classes-and-methods: dumps a sorted list of classes and methods that are");
102 UsageError(" in the specified profile file to standard output (default) in a human");
103 UsageError(" readable form. The output is valid input for --create-profile-from");
Calin Juravle876f3502016-03-24 16:16:34 +0000104 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000105 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
106 UsageError(" Can be specified multiple time, in which case the data from the different");
107 UsageError(" profiles will be aggregated.");
108 UsageError("");
109 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
110 UsageError(" Cannot be used together with --profile-file.");
111 UsageError("");
112 UsageError(" --reference-profile-file=<filename>: specify a reference profile.");
113 UsageError(" The data in this file will be compared with the data obtained by merging");
114 UsageError(" all the files specified with --profile-file or --profile-file-fd.");
115 UsageError(" If the exit code is EXIT_COMPILE then all --profile-file will be merged into");
116 UsageError(" --reference-profile-file. ");
117 UsageError("");
118 UsageError(" --reference-profile-file-fd=<number>: same as --reference-profile-file but");
119 UsageError(" accepts a file descriptor. Cannot be used together with");
120 UsageError(" --reference-profile-file.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800121 UsageError("");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100122 UsageError(" --generate-test-profile=<filename>: generates a random profile file for testing.");
123 UsageError(" --generate-test-profile-num-dex=<number>: number of dex files that should be");
124 UsageError(" included in the generated profile. Defaults to 20.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700125 UsageError(" --generate-test-profile-method-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100126 UsageError(" number of methods that should be generated. Defaults to 5.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700127 UsageError(" --generate-test-profile-class-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100128 UsageError(" number of classes that should be generated. Defaults to 5.");
Jeff Haof0a31f82017-03-27 15:50:37 -0700129 UsageError(" --generate-test-profile-seed=<number>: seed for random number generator used when");
130 UsageError(" generating random test profiles. Defaults to using NanoTime.");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100131 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -0700132 UsageError(" --create-profile-from=<filename>: creates a profile from a list of classes and");
133 UsageError(" methods.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800134 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700135 UsageError(" --dex-location=<string>: location string to use with corresponding");
136 UsageError(" apk-fd to find dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700137 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700138 UsageError(" --apk-fd=<number>: file descriptor containing an open APK to");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700139 UsageError(" search for dex files");
David Sehr7c80f2d2017-02-07 16:47:58 -0800140 UsageError(" --apk-=<filename>: an APK to search for dex files");
David Brazdilf13ac7c2018-01-30 10:09:08 +0000141 UsageError(" --skip-apk-verification: do not attempt to verify APKs");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700142 UsageError("");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700143 UsageError(" --generate-boot-image-profile: Generate a boot image profile based on input");
144 UsageError(" profiles. Requires passing in dex files to inspect properties of classes.");
145 UsageError(" --boot-image-class-threshold=<value>: specify minimum number of class occurrences");
146 UsageError(" to include a class in the boot image profile. Default is 10.");
147 UsageError(" --boot-image-clean-class-threshold=<value>: specify minimum number of clean class");
148 UsageError(" occurrences to include a class in the boot image profile. A clean class is a");
149 UsageError(" class that doesn't have any static fields or native methods and is likely to");
150 UsageError(" remain clean in the image. Default is 3.");
Mathieu Chartier8eecddf2017-07-12 16:05:54 -0700151 UsageError(" --boot-image-sampled-method-threshold=<value>: minimum number of profiles a");
152 UsageError(" non-hot method needs to be in order to be hot in the output profile. The");
153 UsageError(" default is max int.");
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800154 UsageError(" --copy-and-update-profile-key: if present, profman will copy the profile from");
155 UsageError(" the file passed with --profile-fd(file) to the profile passed with");
156 UsageError(" --reference-profile-fd(file) and update at the same time the profile-key");
157 UsageError(" of entries corresponding to the apks passed with --apk(-fd).");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700158 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000159
160 exit(EXIT_FAILURE);
161}
162
Calin Juravle7bcdb532016-06-07 16:14:47 +0100163// Note: make sure you update the Usage if you change these values.
164static constexpr uint16_t kDefaultTestProfileNumDex = 20;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700165static constexpr uint16_t kDefaultTestProfileMethodPercentage = 5;
166static constexpr uint16_t kDefaultTestProfileClassPercentage = 5;
Calin Juravle7bcdb532016-06-07 16:14:47 +0100167
Calin Juravlee0ac1152017-02-13 19:03:47 -0800168// Separators used when parsing human friendly representation of profiles.
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800169static const std::string kMethodSep = "->"; // NOLINT [runtime/string] [4]
170static const std::string kMissingTypesMarker = "missing_types"; // NOLINT [runtime/string] [4]
171static const std::string kInvalidClassDescriptor = "invalid_class"; // NOLINT [runtime/string] [4]
172static const std::string kInvalidMethod = "invalid_method"; // NOLINT [runtime/string] [4]
173static const std::string kClassAllMethods = "*"; // NOLINT [runtime/string] [4]
Calin Juravlee0ac1152017-02-13 19:03:47 -0800174static constexpr char kProfileParsingInlineChacheSep = '+';
175static constexpr char kProfileParsingTypeSep = ',';
176static constexpr char kProfileParsingFirstCharInSignature = '(';
Mathieu Chartierea650f32017-05-24 12:04:13 -0700177static constexpr char kMethodFlagStringHot = 'H';
178static constexpr char kMethodFlagStringStartup = 'S';
179static constexpr char kMethodFlagStringPostStartup = 'P';
Calin Juravlee0ac1152017-02-13 19:03:47 -0800180
181// TODO(calin): This class has grown too much from its initial design. Split the functionality
182// into smaller, more contained pieces.
Calin Juravle2e2db782016-02-23 12:00:03 +0000183class ProfMan FINAL {
184 public:
185 ProfMan() :
David Sehr4fcdd6d2016-05-24 14:52:31 -0700186 reference_profile_file_fd_(kInvalidFd),
187 dump_only_(false),
Mathieu Chartier34067262017-04-06 13:55:46 -0700188 dump_classes_and_methods_(false),
Mathieu Chartier2f794552017-06-19 10:58:08 -0700189 generate_boot_image_profile_(false),
David Sehr4fcdd6d2016-05-24 14:52:31 -0700190 dump_output_to_fd_(kInvalidFd),
Calin Juravle7bcdb532016-06-07 16:14:47 +0100191 test_profile_num_dex_(kDefaultTestProfileNumDex),
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700192 test_profile_method_percerntage_(kDefaultTestProfileMethodPercentage),
193 test_profile_class_percentage_(kDefaultTestProfileClassPercentage),
Jeff Haof0a31f82017-03-27 15:50:37 -0700194 test_profile_seed_(NanoTime()),
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800195 start_ns_(NanoTime()),
196 copy_and_update_profile_key_(false) {}
Calin Juravle2e2db782016-02-23 12:00:03 +0000197
198 ~ProfMan() {
199 LogCompletionTime();
200 }
201
202 void ParseArgs(int argc, char **argv) {
203 original_argc = argc;
204 original_argv = argv;
205
David Sehrc431b9d2018-03-02 12:01:51 -0800206 Locks::Init();
Andreas Gampe51d80cc2017-06-21 21:05:13 -0700207 InitLogging(argv, Runtime::Abort);
Calin Juravle2e2db782016-02-23 12:00:03 +0000208
209 // Skip over the command name.
210 argv++;
211 argc--;
212
213 if (argc == 0) {
214 Usage("No arguments specified");
215 }
216
217 for (int i = 0; i < argc; ++i) {
218 const StringPiece option(argv[i]);
219 const bool log_options = false;
220 if (log_options) {
Calin Juravle876f3502016-03-24 16:16:34 +0000221 LOG(INFO) << "profman: option[" << i << "]=" << argv[i];
Calin Juravle2e2db782016-02-23 12:00:03 +0000222 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700223 if (option == "--dump-only") {
224 dump_only_ = true;
Mathieu Chartier34067262017-04-06 13:55:46 -0700225 } else if (option == "--dump-classes-and-methods") {
226 dump_classes_and_methods_ = true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800227 } else if (option.starts_with("--create-profile-from=")) {
228 create_profile_from_file_ = option.substr(strlen("--create-profile-from=")).ToString();
David Sehr4fcdd6d2016-05-24 14:52:31 -0700229 } else if (option.starts_with("--dump-output-to-fd=")) {
230 ParseUintOption(option, "--dump-output-to-fd", &dump_output_to_fd_, Usage);
Mathieu Chartier2f794552017-06-19 10:58:08 -0700231 } else if (option == "--generate-boot-image-profile") {
232 generate_boot_image_profile_ = true;
233 } else if (option.starts_with("--boot-image-class-threshold=")) {
234 ParseUintOption(option,
235 "--boot-image-class-threshold",
236 &boot_image_options_.image_class_theshold,
237 Usage);
238 } else if (option.starts_with("--boot-image-clean-class-threshold=")) {
239 ParseUintOption(option,
240 "--boot-image-clean-class-threshold",
241 &boot_image_options_.image_class_clean_theshold,
242 Usage);
Mathieu Chartier8eecddf2017-07-12 16:05:54 -0700243 } else if (option.starts_with("--boot-image-sampled-method-threshold=")) {
244 ParseUintOption(option,
245 "--boot-image-sampled-method-threshold",
246 &boot_image_options_.compiled_method_threshold,
247 Usage);
Calin Juravle876f3502016-03-24 16:16:34 +0000248 } else if (option.starts_with("--profile-file=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000249 profile_files_.push_back(option.substr(strlen("--profile-file=")).ToString());
250 } else if (option.starts_with("--profile-file-fd=")) {
251 ParseFdForCollection(option, "--profile-file-fd", &profile_files_fd_);
252 } else if (option.starts_with("--reference-profile-file=")) {
253 reference_profile_file_ = option.substr(strlen("--reference-profile-file=")).ToString();
254 } else if (option.starts_with("--reference-profile-file-fd=")) {
255 ParseUintOption(option, "--reference-profile-file-fd", &reference_profile_file_fd_, Usage);
David Sehr546d24f2016-06-02 10:46:19 -0700256 } else if (option.starts_with("--dex-location=")) {
257 dex_locations_.push_back(option.substr(strlen("--dex-location=")).ToString());
258 } else if (option.starts_with("--apk-fd=")) {
259 ParseFdForCollection(option, "--apk-fd", &apks_fd_);
David Sehr7c80f2d2017-02-07 16:47:58 -0800260 } else if (option.starts_with("--apk=")) {
261 apk_files_.push_back(option.substr(strlen("--apk=")).ToString());
Calin Juravle7bcdb532016-06-07 16:14:47 +0100262 } else if (option.starts_with("--generate-test-profile=")) {
263 test_profile_ = option.substr(strlen("--generate-test-profile=")).ToString();
264 } else if (option.starts_with("--generate-test-profile-num-dex=")) {
265 ParseUintOption(option,
266 "--generate-test-profile-num-dex",
267 &test_profile_num_dex_,
268 Usage);
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700269 } else if (option.starts_with("--generate-test-profile-method-percentage")) {
Calin Juravle7bcdb532016-06-07 16:14:47 +0100270 ParseUintOption(option,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700271 "--generate-test-profile-method-percentage",
272 &test_profile_method_percerntage_,
Calin Juravle7bcdb532016-06-07 16:14:47 +0100273 Usage);
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700274 } else if (option.starts_with("--generate-test-profile-class-percentage")) {
Calin Juravle7bcdb532016-06-07 16:14:47 +0100275 ParseUintOption(option,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700276 "--generate-test-profile-class-percentage",
277 &test_profile_class_percentage_,
Calin Juravle7bcdb532016-06-07 16:14:47 +0100278 Usage);
Jeff Haof0a31f82017-03-27 15:50:37 -0700279 } else if (option.starts_with("--generate-test-profile-seed=")) {
280 ParseUintOption(option, "--generate-test-profile-seed", &test_profile_seed_, Usage);
Calin Juravle02c08792018-02-15 19:40:48 -0800281 } else if (option.starts_with("--copy-and-update-profile-key")) {
282 copy_and_update_profile_key_ = true;
Calin Juravle2e2db782016-02-23 12:00:03 +0000283 } else {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700284 Usage("Unknown argument '%s'", option.data());
Calin Juravle2e2db782016-02-23 12:00:03 +0000285 }
286 }
287
David Sehr153da0e2017-02-15 08:54:51 -0800288 // Validate global consistency between file/fd options.
Calin Juravle2e2db782016-02-23 12:00:03 +0000289 if (!profile_files_.empty() && !profile_files_fd_.empty()) {
290 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
291 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700292 if (!reference_profile_file_.empty() && FdIsValid(reference_profile_file_fd_)) {
293 Usage("Reference profile should not be specified with both "
294 "--reference-profile-file-fd and --reference-profile-file");
295 }
David Sehr153da0e2017-02-15 08:54:51 -0800296 if (!apk_files_.empty() && !apks_fd_.empty()) {
297 Usage("APK files should not be specified with both --apk-fd and --apk");
Calin Juravle2e2db782016-02-23 12:00:03 +0000298 }
299 }
300
Calin Juravlee10c1e22018-01-26 20:10:15 -0800301 struct ProfileFilterKey {
302 ProfileFilterKey(const std::string& dex_location, uint32_t checksum)
303 : dex_location_(dex_location), checksum_(checksum) {}
304 const std::string dex_location_;
305 uint32_t checksum_;
306
307 bool operator==(const ProfileFilterKey& other) const {
308 return checksum_ == other.checksum_ && dex_location_ == other.dex_location_;
309 }
310 bool operator<(const ProfileFilterKey& other) const {
311 return checksum_ == other.checksum_
312 ? dex_location_ < other.dex_location_
313 : checksum_ < other.checksum_;
314 }
315 };
316
Calin Juravle2e2db782016-02-23 12:00:03 +0000317 ProfileAssistant::ProcessingResult ProcessProfiles() {
David Sehr153da0e2017-02-15 08:54:51 -0800318 // Validate that at least one profile file was passed, as well as a reference profile.
319 if (profile_files_.empty() && profile_files_fd_.empty()) {
320 Usage("No profile files specified.");
321 }
322 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
323 Usage("No reference profile file specified.");
324 }
325 if ((!profile_files_.empty() && FdIsValid(reference_profile_file_fd_)) ||
326 (!profile_files_fd_.empty() && !FdIsValid(reference_profile_file_fd_))) {
327 Usage("Options --profile-file-fd and --reference-profile-file-fd "
328 "should only be used together");
329 }
Calin Juravlee10c1e22018-01-26 20:10:15 -0800330
331 // Check if we have any apks which we should use to filter the profile data.
332 std::set<ProfileFilterKey> profile_filter_keys;
333 if (!GetProfileFilterKeyFromApks(&profile_filter_keys)) {
334 return ProfileAssistant::kErrorIO;
335 }
336
337 // Build the profile filter function. If the set of keys is empty it means we
338 // don't have any apks; as such we do not filter anything.
339 const ProfileCompilationInfo::ProfileLoadFilterFn& filter_fn =
340 [profile_filter_keys](const std::string& dex_location, uint32_t checksum) {
341 if (profile_filter_keys.empty()) {
342 // No --apk was specified. Accept all dex files.
343 return true;
344 } else {
345 bool res = profile_filter_keys.find(
346 ProfileFilterKey(dex_location, checksum)) != profile_filter_keys.end();
347 return res;
348 }
349 };
350
Calin Juravle2e2db782016-02-23 12:00:03 +0000351 ProfileAssistant::ProcessingResult result;
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800352
Calin Juravle2e2db782016-02-23 12:00:03 +0000353 if (profile_files_.empty()) {
354 // The file doesn't need to be flushed here (ProcessProfiles will do it)
355 // so don't check the usage.
356 File file(reference_profile_file_fd_, false);
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800357 result = ProfileAssistant::ProcessProfiles(profile_files_fd_,
Calin Juravlee10c1e22018-01-26 20:10:15 -0800358 reference_profile_file_fd_,
359 filter_fn);
Calin Juravle2e2db782016-02-23 12:00:03 +0000360 CloseAllFds(profile_files_fd_, "profile_files_fd_");
361 } else {
Calin Juravlee10c1e22018-01-26 20:10:15 -0800362 result = ProfileAssistant::ProcessProfiles(profile_files_,
363 reference_profile_file_,
364 filter_fn);
Calin Juravle2e2db782016-02-23 12:00:03 +0000365 }
366 return result;
367 }
368
Calin Juravlee10c1e22018-01-26 20:10:15 -0800369 bool GetProfileFilterKeyFromApks(std::set<ProfileFilterKey>* profile_filter_keys) {
370 auto process_fn = [profile_filter_keys](std::unique_ptr<const DexFile>&& dex_file) {
371 // Store the profile key of the location instead of the location itself.
372 // This will make the matching in the profile filter method much easier.
373 profile_filter_keys->emplace(ProfileCompilationInfo::GetProfileDexFileKey(
374 dex_file->GetLocation()), dex_file->GetLocationChecksum());
375 };
376 return OpenApkFilesFromLocations(process_fn);
377 }
378
379 bool OpenApkFilesFromLocations(std::vector<std::unique_ptr<const DexFile>>* dex_files) {
380 auto process_fn = [dex_files](std::unique_ptr<const DexFile>&& dex_file) {
381 dex_files->emplace_back(std::move(dex_file));
382 };
383 return OpenApkFilesFromLocations(process_fn);
384 }
385
386 bool OpenApkFilesFromLocations(
387 std::function<void(std::unique_ptr<const DexFile>&&)> process_fn) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800388 bool use_apk_fd_list = !apks_fd_.empty();
389 if (use_apk_fd_list) {
David Sehr153da0e2017-02-15 08:54:51 -0800390 // Get the APKs from the collection of FDs.
Calin Juravlee10c1e22018-01-26 20:10:15 -0800391 if (dex_locations_.empty()) {
392 // Try to compute the dex locations from the file paths of the descriptions.
393 // This will make it easier to invoke profman with --apk-fd and without
394 // being force to pass --dex-location when the location would be the apk path.
395 if (!ComputeDexLocationsFromApkFds()) {
396 return false;
397 }
398 } else {
399 if (dex_locations_.size() != apks_fd_.size()) {
400 Usage("The number of apk-fds must match the number of dex-locations.");
401 }
402 }
David Sehr153da0e2017-02-15 08:54:51 -0800403 } else if (!apk_files_.empty()) {
Calin Juravle02c08792018-02-15 19:40:48 -0800404 if (dex_locations_.empty()) {
405 // If no dex locations are specified use the apk names as locations.
406 dex_locations_ = apk_files_;
407 } else if (dex_locations_.size() != apk_files_.size()) {
408 Usage("The number of apk-fds must match the number of dex-locations.");
409 }
David Sehr153da0e2017-02-15 08:54:51 -0800410 } else {
411 // No APKs were specified.
412 CHECK(dex_locations_.empty());
Calin Juravlee10c1e22018-01-26 20:10:15 -0800413 return true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800414 }
415 static constexpr bool kVerifyChecksum = true;
416 for (size_t i = 0; i < dex_locations_.size(); ++i) {
417 std::string error_msg;
David Sehr013fd802018-01-11 22:55:24 -0800418 const ArtDexFileLoader dex_file_loader;
David Sehr7c80f2d2017-02-07 16:47:58 -0800419 std::vector<std::unique_ptr<const DexFile>> dex_files_for_location;
Calin Juravle1bfe4bd2018-04-26 16:00:11 -0700420 // We do not need to verify the apk for processing profiles.
David Sehr7c80f2d2017-02-07 16:47:58 -0800421 if (use_apk_fd_list) {
David Sehr013fd802018-01-11 22:55:24 -0800422 if (dex_file_loader.OpenZip(apks_fd_[i],
423 dex_locations_[i],
Calin Juravle1bfe4bd2018-04-26 16:00:11 -0700424 /* verify */ false,
David Sehr013fd802018-01-11 22:55:24 -0800425 kVerifyChecksum,
426 &error_msg,
427 &dex_files_for_location)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800428 } else {
Calin Juravlee10c1e22018-01-26 20:10:15 -0800429 LOG(ERROR) << "OpenZip failed for '" << dex_locations_[i] << "' " << error_msg;
430 return false;
David Sehr7c80f2d2017-02-07 16:47:58 -0800431 }
432 } else {
David Sehr013fd802018-01-11 22:55:24 -0800433 if (dex_file_loader.Open(apk_files_[i].c_str(),
434 dex_locations_[i],
Calin Juravle1bfe4bd2018-04-26 16:00:11 -0700435 /* verify */ false,
David Sehr013fd802018-01-11 22:55:24 -0800436 kVerifyChecksum,
437 &error_msg,
438 &dex_files_for_location)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800439 } else {
Calin Juravlee10c1e22018-01-26 20:10:15 -0800440 LOG(ERROR) << "Open failed for '" << dex_locations_[i] << "' " << error_msg;
441 return false;
David Sehr7c80f2d2017-02-07 16:47:58 -0800442 }
443 }
444 for (std::unique_ptr<const DexFile>& dex_file : dex_files_for_location) {
Calin Juravlee10c1e22018-01-26 20:10:15 -0800445 process_fn(std::move(dex_file));
David Sehr7c80f2d2017-02-07 16:47:58 -0800446 }
447 }
Calin Juravlee10c1e22018-01-26 20:10:15 -0800448 return true;
449 }
450
451 // Get the dex locations from the apk fds.
452 // The methods reads the links from /proc/self/fd/ to find the original apk paths
453 // and puts them in the dex_locations_ vector.
454 bool ComputeDexLocationsFromApkFds() {
455 // We can't use a char array of PATH_MAX size without exceeding the frame size.
456 // So we use a vector as the buffer for the path.
457 std::vector<char> buffer(PATH_MAX, 0);
458 for (size_t i = 0; i < apks_fd_.size(); ++i) {
459 std::string fd_path = "/proc/self/fd/" + std::to_string(apks_fd_[i]);
460 ssize_t len = readlink(fd_path.c_str(), buffer.data(), buffer.size() - 1);
461 if (len == -1) {
462 PLOG(ERROR) << "Could not open path from fd";
463 return false;
464 }
465
466 buffer[len] = '\0';
467 dex_locations_.push_back(buffer.data());
468 }
469 return true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800470 }
471
Mathieu Chartier2f794552017-06-19 10:58:08 -0700472 std::unique_ptr<const ProfileCompilationInfo> LoadProfile(const std::string& filename, int fd) {
473 if (!filename.empty()) {
474 fd = open(filename.c_str(), O_RDWR);
475 if (fd < 0) {
476 LOG(ERROR) << "Cannot open " << filename << strerror(errno);
477 return nullptr;
478 }
479 }
480 std::unique_ptr<ProfileCompilationInfo> info(new ProfileCompilationInfo);
481 if (!info->Load(fd)) {
482 LOG(ERROR) << "Cannot load profile info from fd=" << fd << "\n";
483 return nullptr;
484 }
485 return info;
486 }
487
David Sehrb18991b2017-02-08 20:58:10 -0800488 int DumpOneProfile(const std::string& banner,
489 const std::string& filename,
490 int fd,
491 const std::vector<std::unique_ptr<const DexFile>>* dex_files,
492 std::string* dump) {
Mathieu Chartier2f794552017-06-19 10:58:08 -0700493 std::unique_ptr<const ProfileCompilationInfo> info(LoadProfile(filename, fd));
494 if (info == nullptr) {
495 LOG(ERROR) << "Cannot load profile info from filename=" << filename << " fd=" << fd;
Calin Juravle876f3502016-03-24 16:16:34 +0000496 return -1;
497 }
Mathieu Chartier2f794552017-06-19 10:58:08 -0700498 *dump += banner + "\n" + info->DumpInfo(dex_files) + "\n";
David Sehr4fcdd6d2016-05-24 14:52:31 -0700499 return 0;
500 }
501
502 int DumpProfileInfo() {
David Sehr153da0e2017-02-15 08:54:51 -0800503 // Validate that at least one profile file or reference was specified.
504 if (profile_files_.empty() && profile_files_fd_.empty() &&
505 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
506 Usage("No profile files or reference profile specified.");
507 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700508 static const char* kEmptyString = "";
David Sehr546d24f2016-06-02 10:46:19 -0700509 static const char* kOrdinaryProfile = "=== profile ===";
510 static const char* kReferenceProfile = "=== reference profile ===";
511
David Sehrb18991b2017-02-08 20:58:10 -0800512 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7c80f2d2017-02-07 16:47:58 -0800513 OpenApkFilesFromLocations(&dex_files);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700514 std::string dump;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700515 // Dump individual profile files.
516 if (!profile_files_fd_.empty()) {
517 for (int profile_file_fd : profile_files_fd_) {
David Sehr546d24f2016-06-02 10:46:19 -0700518 int ret = DumpOneProfile(kOrdinaryProfile,
519 kEmptyString,
520 profile_file_fd,
521 &dex_files,
522 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700523 if (ret != 0) {
524 return ret;
525 }
526 }
527 }
528 if (!profile_files_.empty()) {
529 for (const std::string& profile_file : profile_files_) {
David Sehr546d24f2016-06-02 10:46:19 -0700530 int ret = DumpOneProfile(kOrdinaryProfile, profile_file, kInvalidFd, &dex_files, &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700531 if (ret != 0) {
532 return ret;
533 }
534 }
535 }
536 // Dump reference profile file.
537 if (FdIsValid(reference_profile_file_fd_)) {
David Sehr546d24f2016-06-02 10:46:19 -0700538 int ret = DumpOneProfile(kReferenceProfile,
539 kEmptyString,
540 reference_profile_file_fd_,
541 &dex_files,
542 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700543 if (ret != 0) {
544 return ret;
545 }
546 }
547 if (!reference_profile_file_.empty()) {
David Sehr546d24f2016-06-02 10:46:19 -0700548 int ret = DumpOneProfile(kReferenceProfile,
549 reference_profile_file_,
550 kInvalidFd,
551 &dex_files,
David Sehr4fcdd6d2016-05-24 14:52:31 -0700552 &dump);
553 if (ret != 0) {
554 return ret;
555 }
556 }
557 if (!FdIsValid(dump_output_to_fd_)) {
558 std::cout << dump;
559 } else {
560 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
561 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
562 return -1;
563 }
564 }
Calin Juravle876f3502016-03-24 16:16:34 +0000565 return 0;
566 }
567
568 bool ShouldOnlyDumpProfile() {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700569 return dump_only_;
Calin Juravle876f3502016-03-24 16:16:34 +0000570 }
571
Mathieu Chartier34067262017-04-06 13:55:46 -0700572 bool GetClassNamesAndMethods(int fd,
573 std::vector<std::unique_ptr<const DexFile>>* dex_files,
574 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800575 ProfileCompilationInfo profile_info;
576 if (!profile_info.Load(fd)) {
577 LOG(ERROR) << "Cannot load profile info";
578 return false;
579 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700580 for (const std::unique_ptr<const DexFile>& dex_file : *dex_files) {
581 std::set<dex::TypeIndex> class_types;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700582 std::set<uint16_t> hot_methods;
583 std::set<uint16_t> startup_methods;
584 std::set<uint16_t> post_startup_methods;
585 std::set<uint16_t> combined_methods;
586 if (profile_info.GetClassesAndMethods(*dex_file.get(),
587 &class_types,
588 &hot_methods,
589 &startup_methods,
590 &post_startup_methods)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700591 for (const dex::TypeIndex& type_index : class_types) {
592 const DexFile::TypeId& type_id = dex_file->GetTypeId(type_index);
593 out_lines->insert(std::string(dex_file->GetTypeDescriptor(type_id)));
594 }
Mathieu Chartierea650f32017-05-24 12:04:13 -0700595 combined_methods = hot_methods;
596 combined_methods.insert(startup_methods.begin(), startup_methods.end());
597 combined_methods.insert(post_startup_methods.begin(), post_startup_methods.end());
598 for (uint16_t dex_method_idx : combined_methods) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700599 const DexFile::MethodId& id = dex_file->GetMethodId(dex_method_idx);
600 std::string signature_string(dex_file->GetMethodSignature(id).ToString());
601 std::string type_string(dex_file->GetTypeDescriptor(dex_file->GetTypeId(id.class_idx_)));
602 std::string method_name(dex_file->GetMethodName(id));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700603 std::string flags_string;
604 if (hot_methods.find(dex_method_idx) != hot_methods.end()) {
605 flags_string += kMethodFlagStringHot;
606 }
607 if (startup_methods.find(dex_method_idx) != startup_methods.end()) {
608 flags_string += kMethodFlagStringStartup;
609 }
610 if (post_startup_methods.find(dex_method_idx) != post_startup_methods.end()) {
611 flags_string += kMethodFlagStringPostStartup;
612 }
613 out_lines->insert(flags_string +
614 type_string +
615 kMethodSep +
616 method_name +
617 signature_string);
Mathieu Chartier34067262017-04-06 13:55:46 -0700618 }
619 }
620 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800621 return true;
622 }
623
Mathieu Chartier34067262017-04-06 13:55:46 -0700624 bool GetClassNamesAndMethods(const std::string& profile_file,
625 std::vector<std::unique_ptr<const DexFile>>* dex_files,
626 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800627 int fd = open(profile_file.c_str(), O_RDONLY);
628 if (!FdIsValid(fd)) {
629 LOG(ERROR) << "Cannot open " << profile_file << strerror(errno);
630 return false;
631 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700632 if (!GetClassNamesAndMethods(fd, dex_files, out_lines)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800633 return false;
634 }
635 if (close(fd) < 0) {
636 PLOG(WARNING) << "Failed to close descriptor";
637 }
638 return true;
639 }
640
Mathieu Chartierea650f32017-05-24 12:04:13 -0700641 int DumpClassesAndMethods() {
David Sehr153da0e2017-02-15 08:54:51 -0800642 // Validate that at least one profile file or reference was specified.
643 if (profile_files_.empty() && profile_files_fd_.empty() &&
644 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
645 Usage("No profile files or reference profile specified.");
646 }
Calin Juravlee10c1e22018-01-26 20:10:15 -0800647
David Sehr7c80f2d2017-02-07 16:47:58 -0800648 // Open the dex files to get the names for classes.
649 std::vector<std::unique_ptr<const DexFile>> dex_files;
650 OpenApkFilesFromLocations(&dex_files);
651 // Build a vector of class names from individual profile files.
652 std::set<std::string> class_names;
653 if (!profile_files_fd_.empty()) {
654 for (int profile_file_fd : profile_files_fd_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700655 if (!GetClassNamesAndMethods(profile_file_fd, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800656 return -1;
657 }
658 }
659 }
660 if (!profile_files_.empty()) {
661 for (const std::string& profile_file : profile_files_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700662 if (!GetClassNamesAndMethods(profile_file, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800663 return -1;
664 }
665 }
666 }
667 // Concatenate class names from reference profile file.
668 if (FdIsValid(reference_profile_file_fd_)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700669 if (!GetClassNamesAndMethods(reference_profile_file_fd_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800670 return -1;
671 }
672 }
673 if (!reference_profile_file_.empty()) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700674 if (!GetClassNamesAndMethods(reference_profile_file_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800675 return -1;
676 }
677 }
678 // Dump the class names.
679 std::string dump;
680 for (const std::string& class_name : class_names) {
681 dump += class_name + std::string("\n");
682 }
683 if (!FdIsValid(dump_output_to_fd_)) {
684 std::cout << dump;
685 } else {
686 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
687 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
688 return -1;
689 }
690 }
691 return 0;
692 }
693
Mathieu Chartier34067262017-04-06 13:55:46 -0700694 bool ShouldOnlyDumpClassesAndMethods() {
695 return dump_classes_and_methods_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800696 }
697
698 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
699 // the given function.
700 template <typename T>
701 static T* ReadCommentedInputFromFile(
702 const char* input_filename, std::function<std::string(const char*)>* process) {
703 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
704 if (input_file.get() == nullptr) {
705 LOG(ERROR) << "Failed to open input file " << input_filename;
706 return nullptr;
707 }
708 std::unique_ptr<T> result(
709 ReadCommentedInputStream<T>(*input_file, process));
710 input_file->close();
711 return result.release();
712 }
713
714 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
715 // with the given function.
716 template <typename T>
717 static T* ReadCommentedInputStream(
718 std::istream& in_stream,
719 std::function<std::string(const char*)>* process) {
720 std::unique_ptr<T> output(new T());
721 while (in_stream.good()) {
722 std::string dot;
723 std::getline(in_stream, dot);
724 if (android::base::StartsWith(dot, "#") || dot.empty()) {
725 continue;
726 }
727 if (process != nullptr) {
728 std::string descriptor((*process)(dot.c_str()));
729 output->insert(output->end(), descriptor);
730 } else {
731 output->insert(output->end(), dot);
732 }
733 }
734 return output.release();
735 }
736
Calin Juravlee0ac1152017-02-13 19:03:47 -0800737 // Find class klass_descriptor in the given dex_files and store its reference
738 // in the out parameter class_ref.
739 // Return true if the definition of the class was found in any of the dex_files.
740 bool FindClass(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
741 const std::string& klass_descriptor,
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700742 /*out*/TypeReference* class_ref) {
Calin Juravle08556882017-05-26 16:40:45 -0700743 constexpr uint16_t kInvalidTypeIndex = std::numeric_limits<uint16_t>::max() - 1;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800744 for (const std::unique_ptr<const DexFile>& dex_file_ptr : dex_files) {
745 const DexFile* dex_file = dex_file_ptr.get();
Calin Juravle08556882017-05-26 16:40:45 -0700746 if (klass_descriptor == kInvalidClassDescriptor) {
747 if (kInvalidTypeIndex >= dex_file->NumTypeIds()) {
748 // The dex file does not contain all possible type ids which leaves us room
749 // to add an "invalid" type id.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700750 *class_ref = TypeReference(dex_file, dex::TypeIndex(kInvalidTypeIndex));
Calin Juravle08556882017-05-26 16:40:45 -0700751 return true;
752 } else {
753 // The dex file contains all possible type ids. We don't have any free type id
754 // that we can use as invalid.
755 continue;
756 }
757 }
758
Calin Juravlee0ac1152017-02-13 19:03:47 -0800759 const DexFile::TypeId* type_id = dex_file->FindTypeId(klass_descriptor.c_str());
760 if (type_id == nullptr) {
761 continue;
762 }
763 dex::TypeIndex type_index = dex_file->GetIndexForTypeId(*type_id);
764 if (dex_file->FindClassDef(type_index) == nullptr) {
765 // Class is only referenced in the current dex file but not defined in it.
766 continue;
767 }
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700768 *class_ref = TypeReference(dex_file, type_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800769 return true;
770 }
771 return false;
772 }
773
Mathieu Chartier34067262017-04-06 13:55:46 -0700774 // Find the method specified by method_spec in the class class_ref.
Calin Juravle08556882017-05-26 16:40:45 -0700775 uint32_t FindMethodIndex(const TypeReference& class_ref,
776 const std::string& method_spec) {
777 const DexFile* dex_file = class_ref.dex_file;
778 if (method_spec == kInvalidMethod) {
779 constexpr uint16_t kInvalidMethodIndex = std::numeric_limits<uint16_t>::max() - 1;
780 return kInvalidMethodIndex >= dex_file->NumMethodIds()
781 ? kInvalidMethodIndex
Andreas Gampee2abbc62017-09-15 11:59:26 -0700782 : dex::kDexNoIndex;
Calin Juravle08556882017-05-26 16:40:45 -0700783 }
784
Calin Juravlee0ac1152017-02-13 19:03:47 -0800785 std::vector<std::string> name_and_signature;
786 Split(method_spec, kProfileParsingFirstCharInSignature, &name_and_signature);
787 if (name_and_signature.size() != 2) {
788 LOG(ERROR) << "Invalid method name and signature " << method_spec;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700789 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800790 }
Calin Juravle08556882017-05-26 16:40:45 -0700791
Calin Juravlee0ac1152017-02-13 19:03:47 -0800792 const std::string& name = name_and_signature[0];
793 const std::string& signature = kProfileParsingFirstCharInSignature + name_and_signature[1];
Calin Juravlee0ac1152017-02-13 19:03:47 -0800794
795 const DexFile::StringId* name_id = dex_file->FindStringId(name.c_str());
796 if (name_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700797 LOG(WARNING) << "Could not find name: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700798 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800799 }
800 dex::TypeIndex return_type_idx;
801 std::vector<dex::TypeIndex> param_type_idxs;
802 if (!dex_file->CreateTypeList(signature, &return_type_idx, &param_type_idxs)) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700803 LOG(WARNING) << "Could not create type list" << signature;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700804 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800805 }
806 const DexFile::ProtoId* proto_id = dex_file->FindProtoId(return_type_idx, param_type_idxs);
807 if (proto_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700808 LOG(WARNING) << "Could not find proto_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700809 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800810 }
811 const DexFile::MethodId* method_id = dex_file->FindMethodId(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700812 dex_file->GetTypeId(class_ref.TypeIndex()), *name_id, *proto_id);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800813 if (method_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700814 LOG(WARNING) << "Could not find method_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700815 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800816 }
817
Mathieu Chartier34067262017-04-06 13:55:46 -0700818 return dex_file->GetIndexForMethodId(*method_id);
819 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800820
Mathieu Chartier34067262017-04-06 13:55:46 -0700821 // Given a method, return true if the method has a single INVOKE_VIRTUAL in its byte code.
822 // Upon success it returns true and stores the method index and the invoke dex pc
823 // in the output parameters.
824 // The format of the method spec is "inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
825 //
826 // TODO(calin): support INVOKE_INTERFACE and the range variants.
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700827 bool HasSingleInvoke(const TypeReference& class_ref,
Mathieu Chartier34067262017-04-06 13:55:46 -0700828 uint16_t method_index,
829 /*out*/uint32_t* dex_pc) {
830 const DexFile* dex_file = class_ref.dex_file;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800831 uint32_t offset = dex_file->FindCodeItemOffset(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700832 *dex_file->FindClassDef(class_ref.TypeIndex()),
Mathieu Chartier34067262017-04-06 13:55:46 -0700833 method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800834 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(offset);
835
836 bool found_invoke = false;
Mathieu Chartier698ebbc2018-01-05 11:00:42 -0800837 for (const DexInstructionPcPair& inst : CodeItemInstructionAccessor(*dex_file, code_item)) {
Mathieu Chartier0021feb2017-11-07 00:08:52 -0800838 if (inst->Opcode() == Instruction::INVOKE_VIRTUAL) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800839 if (found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700840 LOG(ERROR) << "Multiple invoke INVOKE_VIRTUAL found: "
841 << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800842 return false;
843 }
844 found_invoke = true;
Mathieu Chartier0021feb2017-11-07 00:08:52 -0800845 *dex_pc = inst.DexPc();
Calin Juravlee0ac1152017-02-13 19:03:47 -0800846 }
847 }
848 if (!found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700849 LOG(ERROR) << "Could not find any INVOKE_VIRTUAL: " << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800850 }
851 return found_invoke;
852 }
853
854 // Process a line defining a class or a method and its inline caches.
855 // Upon success return true and add the class or the method info to profile.
Calin Juravle589e71e2017-03-03 16:05:05 -0800856 // The possible line formats are:
857 // "LJustTheCass;".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800858 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
Calin Juravle08556882017-05-26 16:40:45 -0700859 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,invalid_class".
Calin Juravle589e71e2017-03-03 16:05:05 -0800860 // "LTestInline;->inlineMissingTypes(LSuper;)I+missing_types".
861 // "LTestInline;->inlineNoInlineCaches(LSuper;)I".
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700862 // "LTestInline;->*".
Calin Juravle08556882017-05-26 16:40:45 -0700863 // "invalid_class".
864 // "LTestInline;->invalid_method".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800865 // The method and classes are searched only in the given dex files.
866 bool ProcessLine(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
867 const std::string& line,
868 /*out*/ProfileCompilationInfo* profile) {
869 std::string klass;
870 std::string method_str;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700871 bool is_hot = false;
872 bool is_startup = false;
873 bool is_post_startup = false;
874 const size_t method_sep_index = line.find(kMethodSep, 0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800875 if (method_sep_index == std::string::npos) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700876 klass = line.substr(0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800877 } else {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700878 // The method prefix flags are only valid for method strings.
879 size_t start_index = 0;
880 while (start_index < line.size() && line[start_index] != 'L') {
881 const char c = line[start_index];
882 if (c == kMethodFlagStringHot) {
883 is_hot = true;
884 } else if (c == kMethodFlagStringStartup) {
885 is_startup = true;
886 } else if (c == kMethodFlagStringPostStartup) {
887 is_post_startup = true;
888 } else {
889 LOG(WARNING) << "Invalid flag " << c;
890 return false;
891 }
892 ++start_index;
893 }
894 klass = line.substr(start_index, method_sep_index - start_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800895 method_str = line.substr(method_sep_index + kMethodSep.size());
896 }
897
Calin Juravleee9cb412018-02-13 20:32:35 -0800898 uint32_t flags = 0;
899 if (is_hot) {
900 flags |= ProfileCompilationInfo::MethodHotness::kFlagHot;
901 }
902 if (is_startup) {
903 flags |= ProfileCompilationInfo::MethodHotness::kFlagStartup;
904 }
905 if (is_post_startup) {
906 flags |= ProfileCompilationInfo::MethodHotness::kFlagPostStartup;
907 }
908
Vladimir Markof3c52b42017-11-17 17:32:12 +0000909 TypeReference class_ref(/* dex_file */ nullptr, dex::TypeIndex());
Calin Juravlee0ac1152017-02-13 19:03:47 -0800910 if (!FindClass(dex_files, klass, &class_ref)) {
Mathieu Chartier3f121342017-03-06 11:16:20 -0800911 LOG(WARNING) << "Could not find class: " << klass;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800912 return false;
913 }
914
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700915 if (method_str.empty() || method_str == kClassAllMethods) {
916 // Start by adding the class.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800917 std::set<DexCacheResolvedClasses> resolved_class_set;
918 const DexFile* dex_file = class_ref.dex_file;
919 const auto& dex_resolved_classes = resolved_class_set.emplace(
920 dex_file->GetLocation(),
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700921 DexFileLoader::GetBaseLocation(dex_file->GetLocation()),
Mathieu Chartierea650f32017-05-24 12:04:13 -0700922 dex_file->GetLocationChecksum(),
923 dex_file->NumMethodIds());
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700924 dex_resolved_classes.first->AddClass(class_ref.TypeIndex());
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700925 std::vector<ProfileMethodInfo> methods;
926 if (method_str == kClassAllMethods) {
927 // Add all of the methods.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700928 const DexFile::ClassDef* class_def = dex_file->FindClassDef(class_ref.TypeIndex());
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700929 const uint8_t* class_data = dex_file->GetClassData(*class_def);
930 if (class_data != nullptr) {
931 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700932 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800933 while (it.HasNextMethod()) {
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700934 if (it.GetMethodCodeItemOffset() != 0) {
935 // Add all of the methods that have code to the profile.
936 const uint32_t method_idx = it.GetMemberIndex();
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700937 methods.push_back(ProfileMethodInfo(MethodReference(dex_file, method_idx)));
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700938 }
939 it.Next();
940 }
941 }
942 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700943 // TODO: Check return values?
Calin Juravleee9cb412018-02-13 20:32:35 -0800944 profile->AddMethods(methods, static_cast<ProfileCompilationInfo::MethodHotness::Flag>(flags));
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700945 profile->AddClasses(resolved_class_set);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800946 return true;
947 }
948
949 // Process the method.
950 std::string method_spec;
951 std::vector<std::string> inline_cache_elems;
952
Mathieu Chartierea650f32017-05-24 12:04:13 -0700953 // If none of the flags are set, default to hot.
954 is_hot = is_hot || (!is_hot && !is_startup && !is_post_startup);
955
Calin Juravlee0ac1152017-02-13 19:03:47 -0800956 std::vector<std::string> method_elems;
Calin Juravle589e71e2017-03-03 16:05:05 -0800957 bool is_missing_types = false;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800958 Split(method_str, kProfileParsingInlineChacheSep, &method_elems);
959 if (method_elems.size() == 2) {
960 method_spec = method_elems[0];
Calin Juravle589e71e2017-03-03 16:05:05 -0800961 is_missing_types = method_elems[1] == kMissingTypesMarker;
962 if (!is_missing_types) {
963 Split(method_elems[1], kProfileParsingTypeSep, &inline_cache_elems);
964 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800965 } else if (method_elems.size() == 1) {
966 method_spec = method_elems[0];
967 } else {
968 LOG(ERROR) << "Invalid method line: " << line;
969 return false;
970 }
971
Mathieu Chartier34067262017-04-06 13:55:46 -0700972 const uint32_t method_index = FindMethodIndex(class_ref, method_spec);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700973 if (method_index == dex::kDexNoIndex) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800974 return false;
975 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700976
Mathieu Chartier34067262017-04-06 13:55:46 -0700977 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
978 if (is_missing_types || !inline_cache_elems.empty()) {
979 uint32_t dex_pc;
980 if (!HasSingleInvoke(class_ref, method_index, &dex_pc)) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800981 return false;
982 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000983 std::vector<TypeReference> classes(inline_cache_elems.size(),
984 TypeReference(/* dex_file */ nullptr, dex::TypeIndex()));
Mathieu Chartier34067262017-04-06 13:55:46 -0700985 size_t class_it = 0;
986 for (const std::string& ic_class : inline_cache_elems) {
987 if (!FindClass(dex_files, ic_class, &(classes[class_it++]))) {
988 LOG(ERROR) << "Could not find class: " << ic_class;
989 return false;
990 }
991 }
992 inline_caches.emplace_back(dex_pc, is_missing_types, classes);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800993 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700994 MethodReference ref(class_ref.dex_file, method_index);
Mathieu Chartierea650f32017-05-24 12:04:13 -0700995 if (is_hot) {
Calin Juravleee9cb412018-02-13 20:32:35 -0800996 profile->AddMethod(ProfileMethodInfo(ref, inline_caches),
997 static_cast<ProfileCompilationInfo::MethodHotness::Flag>(flags));
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700998 }
999 if (flags != 0) {
Calin Juravleee9cb412018-02-13 20:32:35 -08001000 if (!profile->AddMethodIndex(
1001 static_cast<ProfileCompilationInfo::MethodHotness::Flag>(flags), ref)) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001002 return false;
1003 }
Mathieu Chartiere46f3a82017-06-19 19:54:12 -07001004 DCHECK(profile->GetMethodHotness(ref).IsInProfile());
Mathieu Chartierea650f32017-05-24 12:04:13 -07001005 }
Calin Juravlee0ac1152017-02-13 19:03:47 -08001006 return true;
1007 }
1008
Mathieu Chartier2f794552017-06-19 10:58:08 -07001009 int OpenReferenceProfile() const {
1010 int fd = reference_profile_file_fd_;
1011 if (!FdIsValid(fd)) {
1012 CHECK(!reference_profile_file_.empty());
1013 fd = open(reference_profile_file_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
1014 if (fd < 0) {
1015 LOG(ERROR) << "Cannot open " << reference_profile_file_ << strerror(errno);
1016 return kInvalidFd;
1017 }
1018 }
1019 return fd;
1020 }
1021
Calin Juravlee0ac1152017-02-13 19:03:47 -08001022 // Creates a profile from a human friendly textual representation.
1023 // The expected input format is:
1024 // # Classes
1025 // Ljava/lang/Comparable;
1026 // Ljava/lang/Math;
1027 // # Methods with inline caches
1028 // LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;
1029 // LTestInline;->noInlineCache(LSuper;)I
David Sehr7c80f2d2017-02-07 16:47:58 -08001030 int CreateProfile() {
David Sehr153da0e2017-02-15 08:54:51 -08001031 // Validate parameters for this command.
1032 if (apk_files_.empty() && apks_fd_.empty()) {
1033 Usage("APK files must be specified");
1034 }
1035 if (dex_locations_.empty()) {
1036 Usage("DEX locations must be specified");
1037 }
1038 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
1039 Usage("Reference profile must be specified with --reference-profile-file or "
1040 "--reference-profile-file-fd");
1041 }
1042 if (!profile_files_.empty() || !profile_files_fd_.empty()) {
1043 Usage("Profile must be specified with --reference-profile-file or "
1044 "--reference-profile-file-fd");
1045 }
David Sehr7c80f2d2017-02-07 16:47:58 -08001046 // Open the profile output file if needed.
Mathieu Chartier2f794552017-06-19 10:58:08 -07001047 int fd = OpenReferenceProfile();
David Sehr7c80f2d2017-02-07 16:47:58 -08001048 if (!FdIsValid(fd)) {
David Sehr7c80f2d2017-02-07 16:47:58 -08001049 return -1;
David Sehr7c80f2d2017-02-07 16:47:58 -08001050 }
Calin Juravlee0ac1152017-02-13 19:03:47 -08001051 // Read the user-specified list of classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -08001052 std::unique_ptr<std::unordered_set<std::string>>
Calin Juravlee0ac1152017-02-13 19:03:47 -08001053 user_lines(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
David Sehr7c80f2d2017-02-07 16:47:58 -08001054 create_profile_from_file_.c_str(), nullptr)); // No post-processing.
Calin Juravlee0ac1152017-02-13 19:03:47 -08001055
1056 // Open the dex files to look up classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -08001057 std::vector<std::unique_ptr<const DexFile>> dex_files;
1058 OpenApkFilesFromLocations(&dex_files);
Calin Juravlee0ac1152017-02-13 19:03:47 -08001059
1060 // Process the lines one by one and add the successful ones to the profile.
David Sehr7c80f2d2017-02-07 16:47:58 -08001061 ProfileCompilationInfo info;
Calin Juravlee0ac1152017-02-13 19:03:47 -08001062
1063 for (const auto& line : *user_lines) {
1064 ProcessLine(dex_files, line, &info);
1065 }
1066
David Sehr7c80f2d2017-02-07 16:47:58 -08001067 // Write the profile file.
1068 CHECK(info.Save(fd));
1069 if (close(fd) < 0) {
1070 PLOG(WARNING) << "Failed to close descriptor";
1071 }
1072 return 0;
1073 }
1074
Mathieu Chartier2f794552017-06-19 10:58:08 -07001075 bool ShouldCreateBootProfile() const {
1076 return generate_boot_image_profile_;
1077 }
1078
1079 int CreateBootProfile() {
Mathieu Chartier2f794552017-06-19 10:58:08 -07001080 // Open the profile output file.
1081 const int reference_fd = OpenReferenceProfile();
1082 if (!FdIsValid(reference_fd)) {
1083 PLOG(ERROR) << "Error opening reference profile";
1084 return -1;
1085 }
1086 // Open the dex files.
1087 std::vector<std::unique_ptr<const DexFile>> dex_files;
1088 OpenApkFilesFromLocations(&dex_files);
1089 if (dex_files.empty()) {
1090 PLOG(ERROR) << "Expected dex files for creating boot profile";
1091 return -2;
1092 }
1093 // Open the input profiles.
1094 std::vector<std::unique_ptr<const ProfileCompilationInfo>> profiles;
1095 if (!profile_files_fd_.empty()) {
1096 for (int profile_file_fd : profile_files_fd_) {
1097 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile("", profile_file_fd));
1098 if (profile == nullptr) {
1099 return -3;
1100 }
1101 profiles.emplace_back(std::move(profile));
1102 }
1103 }
1104 if (!profile_files_.empty()) {
1105 for (const std::string& profile_file : profile_files_) {
1106 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile(profile_file, kInvalidFd));
1107 if (profile == nullptr) {
1108 return -4;
1109 }
1110 profiles.emplace_back(std::move(profile));
1111 }
1112 }
1113 ProfileCompilationInfo out_profile;
1114 GenerateBootImageProfile(dex_files,
1115 profiles,
1116 boot_image_options_,
1117 VLOG_IS_ON(profiler),
1118 &out_profile);
1119 out_profile.Save(reference_fd);
1120 close(reference_fd);
1121 return 0;
1122 }
1123
David Sehr7c80f2d2017-02-07 16:47:58 -08001124 bool ShouldCreateProfile() {
1125 return !create_profile_from_file_.empty();
1126 }
1127
Calin Juravle7bcdb532016-06-07 16:14:47 +01001128 int GenerateTestProfile() {
David Sehr153da0e2017-02-15 08:54:51 -08001129 // Validate parameters for this command.
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001130 if (test_profile_method_percerntage_ > 100) {
1131 Usage("Invalid percentage for --generate-test-profile-method-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001132 }
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001133 if (test_profile_class_percentage_ > 100) {
1134 Usage("Invalid percentage for --generate-test-profile-class-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001135 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001136 // If given APK files or DEX locations, check that they're ok.
1137 if (!apk_files_.empty() || !apks_fd_.empty() || !dex_locations_.empty()) {
1138 if (apk_files_.empty() && apks_fd_.empty()) {
1139 Usage("APK files must be specified when passing DEX locations to --generate-test-profile");
1140 }
1141 if (dex_locations_.empty()) {
1142 Usage("DEX locations must be specified when passing APK files to --generate-test-profile");
1143 }
1144 }
David Sehr153da0e2017-02-15 08:54:51 -08001145 // ShouldGenerateTestProfile confirms !test_profile_.empty().
George Burgess IV71f77262016-10-25 13:08:17 -07001146 int profile_test_fd = open(test_profile_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001147 if (profile_test_fd < 0) {
David Sehr7c80f2d2017-02-07 16:47:58 -08001148 LOG(ERROR) << "Cannot open " << test_profile_ << strerror(errno);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001149 return -1;
1150 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001151 bool result;
1152 if (apk_files_.empty() && apks_fd_.empty() && dex_locations_.empty()) {
1153 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1154 test_profile_num_dex_,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001155 test_profile_method_percerntage_,
1156 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001157 test_profile_seed_);
1158 } else {
Jeff Haof0a31f82017-03-27 15:50:37 -07001159 // Open the dex files to look up classes and methods.
1160 std::vector<std::unique_ptr<const DexFile>> dex_files;
1161 OpenApkFilesFromLocations(&dex_files);
1162 // Create a random profile file based on the set of dex files.
1163 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1164 dex_files,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001165 test_profile_method_percerntage_,
1166 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001167 test_profile_seed_);
1168 }
Calin Juravle7bcdb532016-06-07 16:14:47 +01001169 close(profile_test_fd); // ignore close result.
1170 return result ? 0 : -1;
1171 }
1172
1173 bool ShouldGenerateTestProfile() {
1174 return !test_profile_.empty();
1175 }
1176
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001177 bool ShouldCopyAndUpdateProfileKey() const {
1178 return copy_and_update_profile_key_;
1179 }
1180
Calin Juravle02c08792018-02-15 19:40:48 -08001181 int32_t CopyAndUpdateProfileKey() {
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001182 // Validate that at least one profile file was passed, as well as a reference profile.
1183 if (!(profile_files_.size() == 1 ^ profile_files_fd_.size() == 1)) {
1184 Usage("Only one profile file should be specified.");
1185 }
1186 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
1187 Usage("No reference profile file specified.");
1188 }
1189
1190 if (apk_files_.empty() && apks_fd_.empty()) {
1191 Usage("No apk files specified");
1192 }
1193
Calin Juravle02c08792018-02-15 19:40:48 -08001194 static constexpr int32_t kErrorFailedToUpdateProfile = -1;
1195 static constexpr int32_t kErrorFailedToSaveProfile = -2;
1196 static constexpr int32_t kErrorFailedToLoadProfile = -3;
1197
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001198 bool use_fds = profile_files_fd_.size() == 1;
1199
1200 ProfileCompilationInfo profile;
1201 // Do not clear if invalid. The input might be an archive.
Calin Juravle02c08792018-02-15 19:40:48 -08001202 bool load_ok = use_fds
1203 ? profile.Load(profile_files_fd_[0])
1204 : profile.Load(profile_files_[0], /*clear_if_invalid*/ false);
1205 if (load_ok) {
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001206 // Open the dex files to look up classes and methods.
1207 std::vector<std::unique_ptr<const DexFile>> dex_files;
1208 OpenApkFilesFromLocations(&dex_files);
1209 if (!profile.UpdateProfileKeys(dex_files)) {
Calin Juravle02c08792018-02-15 19:40:48 -08001210 return kErrorFailedToUpdateProfile;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001211 }
Calin Juravle02c08792018-02-15 19:40:48 -08001212 bool result = use_fds
1213 ? profile.Save(reference_profile_file_fd_)
1214 : profile.Save(reference_profile_file_, /*bytes_written*/ nullptr);
1215 return result ? 0 : kErrorFailedToSaveProfile;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001216 } else {
Calin Juravle02c08792018-02-15 19:40:48 -08001217 return kErrorFailedToLoadProfile;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001218 }
1219 }
1220
Calin Juravle2e2db782016-02-23 12:00:03 +00001221 private:
1222 static void ParseFdForCollection(const StringPiece& option,
1223 const char* arg_name,
1224 std::vector<int>* fds) {
1225 int fd;
1226 ParseUintOption(option, arg_name, &fd, Usage);
1227 fds->push_back(fd);
1228 }
1229
1230 static void CloseAllFds(const std::vector<int>& fds, const char* descriptor) {
1231 for (size_t i = 0; i < fds.size(); i++) {
1232 if (close(fds[i]) < 0) {
Calin Juravlee10c1e22018-01-26 20:10:15 -08001233 PLOG(WARNING) << "Failed to close descriptor for "
1234 << descriptor << " at index " << i << ": " << fds[i];
Calin Juravle2e2db782016-02-23 12:00:03 +00001235 }
1236 }
1237 }
1238
1239 void LogCompletionTime() {
David Sehr52683cf2016-05-05 09:02:38 -07001240 static constexpr uint64_t kLogThresholdTime = MsToNs(100); // 100ms
1241 uint64_t time_taken = NanoTime() - start_ns_;
David Sehred793012016-05-05 13:39:43 -07001242 if (time_taken > kLogThresholdTime) {
David Sehrd8557182016-05-06 12:29:35 -07001243 LOG(WARNING) << "profman took " << PrettyDuration(time_taken);
David Sehred793012016-05-05 13:39:43 -07001244 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001245 }
1246
1247 std::vector<std::string> profile_files_;
1248 std::vector<int> profile_files_fd_;
David Sehr546d24f2016-06-02 10:46:19 -07001249 std::vector<std::string> dex_locations_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001250 std::vector<std::string> apk_files_;
David Sehr546d24f2016-06-02 10:46:19 -07001251 std::vector<int> apks_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001252 std::string reference_profile_file_;
1253 int reference_profile_file_fd_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001254 bool dump_only_;
Mathieu Chartier34067262017-04-06 13:55:46 -07001255 bool dump_classes_and_methods_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001256 bool generate_boot_image_profile_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001257 int dump_output_to_fd_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001258 BootImageOptions boot_image_options_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001259 std::string test_profile_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001260 std::string create_profile_from_file_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001261 uint16_t test_profile_num_dex_;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001262 uint16_t test_profile_method_percerntage_;
1263 uint16_t test_profile_class_percentage_;
Jeff Haof0a31f82017-03-27 15:50:37 -07001264 uint32_t test_profile_seed_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001265 uint64_t start_ns_;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001266 bool copy_and_update_profile_key_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001267};
1268
1269// See ProfileAssistant::ProcessingResult for return codes.
1270static int profman(int argc, char** argv) {
1271 ProfMan profman;
1272
1273 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1274 profman.ParseArgs(argc, argv);
1275
Calin Juravlee10c1e22018-01-26 20:10:15 -08001276 // Initialize MemMap for ZipArchive::OpenFromFd.
1277 MemMap::Init();
1278
Calin Juravle7bcdb532016-06-07 16:14:47 +01001279 if (profman.ShouldGenerateTestProfile()) {
1280 return profman.GenerateTestProfile();
1281 }
Calin Juravle876f3502016-03-24 16:16:34 +00001282 if (profman.ShouldOnlyDumpProfile()) {
1283 return profman.DumpProfileInfo();
1284 }
Mathieu Chartier34067262017-04-06 13:55:46 -07001285 if (profman.ShouldOnlyDumpClassesAndMethods()) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001286 return profman.DumpClassesAndMethods();
David Sehr7c80f2d2017-02-07 16:47:58 -08001287 }
1288 if (profman.ShouldCreateProfile()) {
1289 return profman.CreateProfile();
1290 }
Mathieu Chartier2f794552017-06-19 10:58:08 -07001291
1292 if (profman.ShouldCreateBootProfile()) {
1293 return profman.CreateBootProfile();
1294 }
Calin Juravle02c08792018-02-15 19:40:48 -08001295
1296 if (profman.ShouldCopyAndUpdateProfileKey()) {
1297 return profman.CopyAndUpdateProfileKey();
1298 }
1299
Calin Juravle2e2db782016-02-23 12:00:03 +00001300 // Process profile information and assess if we need to do a profile guided compilation.
1301 // This operation involves I/O.
1302 return profman.ProcessProfiles();
1303}
1304
1305} // namespace art
1306
1307int main(int argc, char **argv) {
1308 return art::profman(argc, argv);
1309}
1310