blob: 90e342d16aac8a79bef75d347e4701b7045f6b4b [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 <sys/stat.h>
23#include <unistd.h>
24
David Sehr7c80f2d2017-02-07 16:47:58 -080025#include <fstream>
Calin Juravle876f3502016-03-24 16:16:34 +000026#include <iostream>
David Sehr7c80f2d2017-02-07 16:47:58 -080027#include <set>
Calin Juravle2e2db782016-02-23 12:00:03 +000028#include <string>
David Sehr7c80f2d2017-02-07 16:47:58 -080029#include <unordered_set>
Calin Juravle2e2db782016-02-23 12:00:03 +000030#include <vector>
31
Andreas Gampe46ee31b2016-12-14 10:11:49 -080032#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080033#include "android-base/strings.h"
34
Calin Juravle2e2db782016-02-23 12:00:03 +000035#include "base/dumpable.h"
Andreas Gampe57943812017-12-06 21:39:13 -080036#include "base/logging.h" // For InitLogging.
David Sehrc431b9d2018-03-02 12:01:51 -080037#include "base/mutex.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000038#include "base/scoped_flock.h"
39#include "base/stringpiece.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000040#include "base/time_utils.h"
41#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080042#include "base/utils.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"
David Sehr546d24f2016-06-02 10:46:19 -070054#include "zip_archive.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000055
56namespace art {
57
58static int original_argc;
59static char** original_argv;
60
61static std::string CommandLine() {
62 std::vector<std::string> command;
63 for (int i = 0; i < original_argc; ++i) {
64 command.push_back(original_argv[i]);
65 }
Andreas Gampe9186ced2016-12-12 14:28:21 -080066 return android::base::Join(command, ' ');
Calin Juravle2e2db782016-02-23 12:00:03 +000067}
68
David Sehr4fcdd6d2016-05-24 14:52:31 -070069static constexpr int kInvalidFd = -1;
70
71static bool FdIsValid(int fd) {
72 return fd != kInvalidFd;
73}
74
Calin Juravle2e2db782016-02-23 12:00:03 +000075static void UsageErrorV(const char* fmt, va_list ap) {
76 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080077 android::base::StringAppendV(&error, fmt, ap);
Calin Juravle2e2db782016-02-23 12:00:03 +000078 LOG(ERROR) << error;
79}
80
81static void UsageError(const char* fmt, ...) {
82 va_list ap;
83 va_start(ap, fmt);
84 UsageErrorV(fmt, ap);
85 va_end(ap);
86}
87
88NO_RETURN static void Usage(const char *fmt, ...) {
89 va_list ap;
90 va_start(ap, fmt);
91 UsageErrorV(fmt, ap);
92 va_end(ap);
93
94 UsageError("Command: %s", CommandLine().c_str());
95 UsageError("Usage: profman [options]...");
96 UsageError("");
David Sehr4fcdd6d2016-05-24 14:52:31 -070097 UsageError(" --dump-only: dumps the content of the specified profile files");
98 UsageError(" to standard output (default) in a human readable form.");
99 UsageError("");
David Sehr7c80f2d2017-02-07 16:47:58 -0800100 UsageError(" --dump-output-to-fd=<number>: redirects --dump-only output to a file descriptor.");
101 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -0700102 UsageError(" --dump-classes-and-methods: dumps a sorted list of classes and methods that are");
103 UsageError(" in the specified profile file to standard output (default) in a human");
104 UsageError(" readable form. The output is valid input for --create-profile-from");
Calin Juravle876f3502016-03-24 16:16:34 +0000105 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000106 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
107 UsageError(" Can be specified multiple time, in which case the data from the different");
108 UsageError(" profiles will be aggregated.");
109 UsageError("");
110 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
111 UsageError(" Cannot be used together with --profile-file.");
112 UsageError("");
113 UsageError(" --reference-profile-file=<filename>: specify a reference profile.");
114 UsageError(" The data in this file will be compared with the data obtained by merging");
115 UsageError(" all the files specified with --profile-file or --profile-file-fd.");
116 UsageError(" If the exit code is EXIT_COMPILE then all --profile-file will be merged into");
117 UsageError(" --reference-profile-file. ");
118 UsageError("");
119 UsageError(" --reference-profile-file-fd=<number>: same as --reference-profile-file but");
120 UsageError(" accepts a file descriptor. Cannot be used together with");
121 UsageError(" --reference-profile-file.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800122 UsageError("");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100123 UsageError(" --generate-test-profile=<filename>: generates a random profile file for testing.");
124 UsageError(" --generate-test-profile-num-dex=<number>: number of dex files that should be");
125 UsageError(" included in the generated profile. Defaults to 20.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700126 UsageError(" --generate-test-profile-method-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100127 UsageError(" number of methods that should be generated. Defaults to 5.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700128 UsageError(" --generate-test-profile-class-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100129 UsageError(" number of classes that should be generated. Defaults to 5.");
Jeff Haof0a31f82017-03-27 15:50:37 -0700130 UsageError(" --generate-test-profile-seed=<number>: seed for random number generator used when");
131 UsageError(" generating random test profiles. Defaults to using NanoTime.");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100132 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -0700133 UsageError(" --create-profile-from=<filename>: creates a profile from a list of classes and");
134 UsageError(" methods.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800135 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700136 UsageError(" --dex-location=<string>: location string to use with corresponding");
137 UsageError(" apk-fd to find dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700138 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700139 UsageError(" --apk-fd=<number>: file descriptor containing an open APK to");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700140 UsageError(" search for dex files");
David Sehr7c80f2d2017-02-07 16:47:58 -0800141 UsageError(" --apk-=<filename>: an APK to search for dex files");
David Brazdilf13ac7c2018-01-30 10:09:08 +0000142 UsageError(" --skip-apk-verification: do not attempt to verify APKs");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700143 UsageError("");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700144 UsageError(" --generate-boot-image-profile: Generate a boot image profile based on input");
145 UsageError(" profiles. Requires passing in dex files to inspect properties of classes.");
146 UsageError(" --boot-image-class-threshold=<value>: specify minimum number of class occurrences");
147 UsageError(" to include a class in the boot image profile. Default is 10.");
148 UsageError(" --boot-image-clean-class-threshold=<value>: specify minimum number of clean class");
149 UsageError(" occurrences to include a class in the boot image profile. A clean class is a");
150 UsageError(" class that doesn't have any static fields or native methods and is likely to");
151 UsageError(" remain clean in the image. Default is 3.");
Mathieu Chartier8eecddf2017-07-12 16:05:54 -0700152 UsageError(" --boot-image-sampled-method-threshold=<value>: minimum number of profiles a");
153 UsageError(" non-hot method needs to be in order to be hot in the output profile. The");
154 UsageError(" default is max int.");
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800155 UsageError(" --copy-and-update-profile-key: if present, profman will copy the profile from");
156 UsageError(" the file passed with --profile-fd(file) to the profile passed with");
157 UsageError(" --reference-profile-fd(file) and update at the same time the profile-key");
158 UsageError(" of entries corresponding to the apks passed with --apk(-fd).");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700159 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000160
161 exit(EXIT_FAILURE);
162}
163
Calin Juravle7bcdb532016-06-07 16:14:47 +0100164// Note: make sure you update the Usage if you change these values.
165static constexpr uint16_t kDefaultTestProfileNumDex = 20;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700166static constexpr uint16_t kDefaultTestProfileMethodPercentage = 5;
167static constexpr uint16_t kDefaultTestProfileClassPercentage = 5;
Calin Juravle7bcdb532016-06-07 16:14:47 +0100168
Calin Juravlee0ac1152017-02-13 19:03:47 -0800169// Separators used when parsing human friendly representation of profiles.
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800170static const std::string kMethodSep = "->"; // NOLINT [runtime/string] [4]
171static const std::string kMissingTypesMarker = "missing_types"; // NOLINT [runtime/string] [4]
172static const std::string kInvalidClassDescriptor = "invalid_class"; // NOLINT [runtime/string] [4]
173static const std::string kInvalidMethod = "invalid_method"; // NOLINT [runtime/string] [4]
174static const std::string kClassAllMethods = "*"; // NOLINT [runtime/string] [4]
Calin Juravlee0ac1152017-02-13 19:03:47 -0800175static constexpr char kProfileParsingInlineChacheSep = '+';
176static constexpr char kProfileParsingTypeSep = ',';
177static constexpr char kProfileParsingFirstCharInSignature = '(';
Mathieu Chartierea650f32017-05-24 12:04:13 -0700178static constexpr char kMethodFlagStringHot = 'H';
179static constexpr char kMethodFlagStringStartup = 'S';
180static constexpr char kMethodFlagStringPostStartup = 'P';
Calin Juravlee0ac1152017-02-13 19:03:47 -0800181
182// TODO(calin): This class has grown too much from its initial design. Split the functionality
183// into smaller, more contained pieces.
Calin Juravle2e2db782016-02-23 12:00:03 +0000184class ProfMan FINAL {
185 public:
186 ProfMan() :
David Sehr4fcdd6d2016-05-24 14:52:31 -0700187 reference_profile_file_fd_(kInvalidFd),
188 dump_only_(false),
Mathieu Chartier34067262017-04-06 13:55:46 -0700189 dump_classes_and_methods_(false),
Mathieu Chartier2f794552017-06-19 10:58:08 -0700190 generate_boot_image_profile_(false),
David Brazdilf13ac7c2018-01-30 10:09:08 +0000191 skip_apk_verification_(false),
David Sehr4fcdd6d2016-05-24 14:52:31 -0700192 dump_output_to_fd_(kInvalidFd),
Calin Juravle7bcdb532016-06-07 16:14:47 +0100193 test_profile_num_dex_(kDefaultTestProfileNumDex),
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700194 test_profile_method_percerntage_(kDefaultTestProfileMethodPercentage),
195 test_profile_class_percentage_(kDefaultTestProfileClassPercentage),
Jeff Haof0a31f82017-03-27 15:50:37 -0700196 test_profile_seed_(NanoTime()),
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800197 start_ns_(NanoTime()),
198 copy_and_update_profile_key_(false) {}
Calin Juravle2e2db782016-02-23 12:00:03 +0000199
200 ~ProfMan() {
201 LogCompletionTime();
202 }
203
204 void ParseArgs(int argc, char **argv) {
205 original_argc = argc;
206 original_argv = argv;
207
David Sehrc431b9d2018-03-02 12:01:51 -0800208 Locks::Init();
Andreas Gampe51d80cc2017-06-21 21:05:13 -0700209 InitLogging(argv, Runtime::Abort);
Calin Juravle2e2db782016-02-23 12:00:03 +0000210
211 // Skip over the command name.
212 argv++;
213 argc--;
214
215 if (argc == 0) {
216 Usage("No arguments specified");
217 }
218
219 for (int i = 0; i < argc; ++i) {
220 const StringPiece option(argv[i]);
221 const bool log_options = false;
222 if (log_options) {
Calin Juravle876f3502016-03-24 16:16:34 +0000223 LOG(INFO) << "profman: option[" << i << "]=" << argv[i];
Calin Juravle2e2db782016-02-23 12:00:03 +0000224 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700225 if (option == "--dump-only") {
226 dump_only_ = true;
Mathieu Chartier34067262017-04-06 13:55:46 -0700227 } else if (option == "--dump-classes-and-methods") {
228 dump_classes_and_methods_ = true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800229 } else if (option.starts_with("--create-profile-from=")) {
230 create_profile_from_file_ = option.substr(strlen("--create-profile-from=")).ToString();
David Sehr4fcdd6d2016-05-24 14:52:31 -0700231 } else if (option.starts_with("--dump-output-to-fd=")) {
232 ParseUintOption(option, "--dump-output-to-fd", &dump_output_to_fd_, Usage);
Mathieu Chartier2f794552017-06-19 10:58:08 -0700233 } else if (option == "--generate-boot-image-profile") {
234 generate_boot_image_profile_ = true;
David Brazdilf13ac7c2018-01-30 10:09:08 +0000235 } else if (option == "--skip-apk-verification") {
236 skip_apk_verification_ = true;
Mathieu Chartier2f794552017-06-19 10:58:08 -0700237 } else if (option.starts_with("--boot-image-class-threshold=")) {
238 ParseUintOption(option,
239 "--boot-image-class-threshold",
240 &boot_image_options_.image_class_theshold,
241 Usage);
242 } else if (option.starts_with("--boot-image-clean-class-threshold=")) {
243 ParseUintOption(option,
244 "--boot-image-clean-class-threshold",
245 &boot_image_options_.image_class_clean_theshold,
246 Usage);
Mathieu Chartier8eecddf2017-07-12 16:05:54 -0700247 } else if (option.starts_with("--boot-image-sampled-method-threshold=")) {
248 ParseUintOption(option,
249 "--boot-image-sampled-method-threshold",
250 &boot_image_options_.compiled_method_threshold,
251 Usage);
Calin Juravle876f3502016-03-24 16:16:34 +0000252 } else if (option.starts_with("--profile-file=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000253 profile_files_.push_back(option.substr(strlen("--profile-file=")).ToString());
254 } else if (option.starts_with("--profile-file-fd=")) {
255 ParseFdForCollection(option, "--profile-file-fd", &profile_files_fd_);
256 } else if (option.starts_with("--reference-profile-file=")) {
257 reference_profile_file_ = option.substr(strlen("--reference-profile-file=")).ToString();
258 } else if (option.starts_with("--reference-profile-file-fd=")) {
259 ParseUintOption(option, "--reference-profile-file-fd", &reference_profile_file_fd_, Usage);
David Sehr546d24f2016-06-02 10:46:19 -0700260 } else if (option.starts_with("--dex-location=")) {
261 dex_locations_.push_back(option.substr(strlen("--dex-location=")).ToString());
262 } else if (option.starts_with("--apk-fd=")) {
263 ParseFdForCollection(option, "--apk-fd", &apks_fd_);
David Sehr7c80f2d2017-02-07 16:47:58 -0800264 } else if (option.starts_with("--apk=")) {
265 apk_files_.push_back(option.substr(strlen("--apk=")).ToString());
Calin Juravle7bcdb532016-06-07 16:14:47 +0100266 } else if (option.starts_with("--generate-test-profile=")) {
267 test_profile_ = option.substr(strlen("--generate-test-profile=")).ToString();
268 } else if (option.starts_with("--generate-test-profile-num-dex=")) {
269 ParseUintOption(option,
270 "--generate-test-profile-num-dex",
271 &test_profile_num_dex_,
272 Usage);
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700273 } else if (option.starts_with("--generate-test-profile-method-percentage")) {
Calin Juravle7bcdb532016-06-07 16:14:47 +0100274 ParseUintOption(option,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700275 "--generate-test-profile-method-percentage",
276 &test_profile_method_percerntage_,
Calin Juravle7bcdb532016-06-07 16:14:47 +0100277 Usage);
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700278 } else if (option.starts_with("--generate-test-profile-class-percentage")) {
Calin Juravle7bcdb532016-06-07 16:14:47 +0100279 ParseUintOption(option,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700280 "--generate-test-profile-class-percentage",
281 &test_profile_class_percentage_,
Calin Juravle7bcdb532016-06-07 16:14:47 +0100282 Usage);
Jeff Haof0a31f82017-03-27 15:50:37 -0700283 } else if (option.starts_with("--generate-test-profile-seed=")) {
284 ParseUintOption(option, "--generate-test-profile-seed", &test_profile_seed_, Usage);
Calin Juravle02c08792018-02-15 19:40:48 -0800285 } else if (option.starts_with("--copy-and-update-profile-key")) {
286 copy_and_update_profile_key_ = true;
Calin Juravle2e2db782016-02-23 12:00:03 +0000287 } else {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700288 Usage("Unknown argument '%s'", option.data());
Calin Juravle2e2db782016-02-23 12:00:03 +0000289 }
290 }
291
David Sehr153da0e2017-02-15 08:54:51 -0800292 // Validate global consistency between file/fd options.
Calin Juravle2e2db782016-02-23 12:00:03 +0000293 if (!profile_files_.empty() && !profile_files_fd_.empty()) {
294 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
295 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700296 if (!reference_profile_file_.empty() && FdIsValid(reference_profile_file_fd_)) {
297 Usage("Reference profile should not be specified with both "
298 "--reference-profile-file-fd and --reference-profile-file");
299 }
David Sehr153da0e2017-02-15 08:54:51 -0800300 if (!apk_files_.empty() && !apks_fd_.empty()) {
301 Usage("APK files should not be specified with both --apk-fd and --apk");
Calin Juravle2e2db782016-02-23 12:00:03 +0000302 }
303 }
304
Calin Juravlee10c1e22018-01-26 20:10:15 -0800305 struct ProfileFilterKey {
306 ProfileFilterKey(const std::string& dex_location, uint32_t checksum)
307 : dex_location_(dex_location), checksum_(checksum) {}
308 const std::string dex_location_;
309 uint32_t checksum_;
310
311 bool operator==(const ProfileFilterKey& other) const {
312 return checksum_ == other.checksum_ && dex_location_ == other.dex_location_;
313 }
314 bool operator<(const ProfileFilterKey& other) const {
315 return checksum_ == other.checksum_
316 ? dex_location_ < other.dex_location_
317 : checksum_ < other.checksum_;
318 }
319 };
320
Calin Juravle2e2db782016-02-23 12:00:03 +0000321 ProfileAssistant::ProcessingResult ProcessProfiles() {
David Sehr153da0e2017-02-15 08:54:51 -0800322 // Validate that at least one profile file was passed, as well as a reference profile.
323 if (profile_files_.empty() && profile_files_fd_.empty()) {
324 Usage("No profile files specified.");
325 }
326 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
327 Usage("No reference profile file specified.");
328 }
329 if ((!profile_files_.empty() && FdIsValid(reference_profile_file_fd_)) ||
330 (!profile_files_fd_.empty() && !FdIsValid(reference_profile_file_fd_))) {
331 Usage("Options --profile-file-fd and --reference-profile-file-fd "
332 "should only be used together");
333 }
Calin Juravlee10c1e22018-01-26 20:10:15 -0800334
335 // Check if we have any apks which we should use to filter the profile data.
336 std::set<ProfileFilterKey> profile_filter_keys;
337 if (!GetProfileFilterKeyFromApks(&profile_filter_keys)) {
338 return ProfileAssistant::kErrorIO;
339 }
340
341 // Build the profile filter function. If the set of keys is empty it means we
342 // don't have any apks; as such we do not filter anything.
343 const ProfileCompilationInfo::ProfileLoadFilterFn& filter_fn =
344 [profile_filter_keys](const std::string& dex_location, uint32_t checksum) {
345 if (profile_filter_keys.empty()) {
346 // No --apk was specified. Accept all dex files.
347 return true;
348 } else {
349 bool res = profile_filter_keys.find(
350 ProfileFilterKey(dex_location, checksum)) != profile_filter_keys.end();
351 return res;
352 }
353 };
354
Calin Juravle2e2db782016-02-23 12:00:03 +0000355 ProfileAssistant::ProcessingResult result;
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800356
Calin Juravle2e2db782016-02-23 12:00:03 +0000357 if (profile_files_.empty()) {
358 // The file doesn't need to be flushed here (ProcessProfiles will do it)
359 // so don't check the usage.
360 File file(reference_profile_file_fd_, false);
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800361 result = ProfileAssistant::ProcessProfiles(profile_files_fd_,
Calin Juravlee10c1e22018-01-26 20:10:15 -0800362 reference_profile_file_fd_,
363 filter_fn);
Calin Juravle2e2db782016-02-23 12:00:03 +0000364 CloseAllFds(profile_files_fd_, "profile_files_fd_");
365 } else {
Calin Juravlee10c1e22018-01-26 20:10:15 -0800366 result = ProfileAssistant::ProcessProfiles(profile_files_,
367 reference_profile_file_,
368 filter_fn);
Calin Juravle2e2db782016-02-23 12:00:03 +0000369 }
370 return result;
371 }
372
David Brazdilf13ac7c2018-01-30 10:09:08 +0000373 bool ShouldSkipApkVerification() const {
374 return skip_apk_verification_;
375 }
376
Calin Juravlee10c1e22018-01-26 20:10:15 -0800377 bool GetProfileFilterKeyFromApks(std::set<ProfileFilterKey>* profile_filter_keys) {
378 auto process_fn = [profile_filter_keys](std::unique_ptr<const DexFile>&& dex_file) {
379 // Store the profile key of the location instead of the location itself.
380 // This will make the matching in the profile filter method much easier.
381 profile_filter_keys->emplace(ProfileCompilationInfo::GetProfileDexFileKey(
382 dex_file->GetLocation()), dex_file->GetLocationChecksum());
383 };
384 return OpenApkFilesFromLocations(process_fn);
385 }
386
387 bool OpenApkFilesFromLocations(std::vector<std::unique_ptr<const DexFile>>* dex_files) {
388 auto process_fn = [dex_files](std::unique_ptr<const DexFile>&& dex_file) {
389 dex_files->emplace_back(std::move(dex_file));
390 };
391 return OpenApkFilesFromLocations(process_fn);
392 }
393
394 bool OpenApkFilesFromLocations(
395 std::function<void(std::unique_ptr<const DexFile>&&)> process_fn) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800396 bool use_apk_fd_list = !apks_fd_.empty();
397 if (use_apk_fd_list) {
David Sehr153da0e2017-02-15 08:54:51 -0800398 // Get the APKs from the collection of FDs.
Calin Juravlee10c1e22018-01-26 20:10:15 -0800399 if (dex_locations_.empty()) {
400 // Try to compute the dex locations from the file paths of the descriptions.
401 // This will make it easier to invoke profman with --apk-fd and without
402 // being force to pass --dex-location when the location would be the apk path.
403 if (!ComputeDexLocationsFromApkFds()) {
404 return false;
405 }
406 } else {
407 if (dex_locations_.size() != apks_fd_.size()) {
408 Usage("The number of apk-fds must match the number of dex-locations.");
409 }
410 }
David Sehr153da0e2017-02-15 08:54:51 -0800411 } else if (!apk_files_.empty()) {
Calin Juravle02c08792018-02-15 19:40:48 -0800412 if (dex_locations_.empty()) {
413 // If no dex locations are specified use the apk names as locations.
414 dex_locations_ = apk_files_;
415 } else if (dex_locations_.size() != apk_files_.size()) {
416 Usage("The number of apk-fds must match the number of dex-locations.");
417 }
David Sehr153da0e2017-02-15 08:54:51 -0800418 } else {
419 // No APKs were specified.
420 CHECK(dex_locations_.empty());
Calin Juravlee10c1e22018-01-26 20:10:15 -0800421 return true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800422 }
423 static constexpr bool kVerifyChecksum = true;
424 for (size_t i = 0; i < dex_locations_.size(); ++i) {
425 std::string error_msg;
David Sehr013fd802018-01-11 22:55:24 -0800426 const ArtDexFileLoader dex_file_loader;
David Sehr7c80f2d2017-02-07 16:47:58 -0800427 std::vector<std::unique_ptr<const DexFile>> dex_files_for_location;
428 if (use_apk_fd_list) {
David Sehr013fd802018-01-11 22:55:24 -0800429 if (dex_file_loader.OpenZip(apks_fd_[i],
430 dex_locations_[i],
David Brazdilf13ac7c2018-01-30 10:09:08 +0000431 /* verify */ !ShouldSkipApkVerification(),
David Sehr013fd802018-01-11 22:55:24 -0800432 kVerifyChecksum,
433 &error_msg,
434 &dex_files_for_location)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800435 } else {
Calin Juravlee10c1e22018-01-26 20:10:15 -0800436 LOG(ERROR) << "OpenZip failed for '" << dex_locations_[i] << "' " << error_msg;
437 return false;
David Sehr7c80f2d2017-02-07 16:47:58 -0800438 }
439 } else {
David Sehr013fd802018-01-11 22:55:24 -0800440 if (dex_file_loader.Open(apk_files_[i].c_str(),
441 dex_locations_[i],
David Brazdilf13ac7c2018-01-30 10:09:08 +0000442 /* verify */ !ShouldSkipApkVerification(),
David Sehr013fd802018-01-11 22:55:24 -0800443 kVerifyChecksum,
444 &error_msg,
445 &dex_files_for_location)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800446 } else {
Calin Juravlee10c1e22018-01-26 20:10:15 -0800447 LOG(ERROR) << "Open failed for '" << dex_locations_[i] << "' " << error_msg;
448 return false;
David Sehr7c80f2d2017-02-07 16:47:58 -0800449 }
450 }
451 for (std::unique_ptr<const DexFile>& dex_file : dex_files_for_location) {
Calin Juravlee10c1e22018-01-26 20:10:15 -0800452 process_fn(std::move(dex_file));
David Sehr7c80f2d2017-02-07 16:47:58 -0800453 }
454 }
Calin Juravlee10c1e22018-01-26 20:10:15 -0800455 return true;
456 }
457
458 // Get the dex locations from the apk fds.
459 // The methods reads the links from /proc/self/fd/ to find the original apk paths
460 // and puts them in the dex_locations_ vector.
461 bool ComputeDexLocationsFromApkFds() {
462 // We can't use a char array of PATH_MAX size without exceeding the frame size.
463 // So we use a vector as the buffer for the path.
464 std::vector<char> buffer(PATH_MAX, 0);
465 for (size_t i = 0; i < apks_fd_.size(); ++i) {
466 std::string fd_path = "/proc/self/fd/" + std::to_string(apks_fd_[i]);
467 ssize_t len = readlink(fd_path.c_str(), buffer.data(), buffer.size() - 1);
468 if (len == -1) {
469 PLOG(ERROR) << "Could not open path from fd";
470 return false;
471 }
472
473 buffer[len] = '\0';
474 dex_locations_.push_back(buffer.data());
475 }
476 return true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800477 }
478
Mathieu Chartier2f794552017-06-19 10:58:08 -0700479 std::unique_ptr<const ProfileCompilationInfo> LoadProfile(const std::string& filename, int fd) {
480 if (!filename.empty()) {
481 fd = open(filename.c_str(), O_RDWR);
482 if (fd < 0) {
483 LOG(ERROR) << "Cannot open " << filename << strerror(errno);
484 return nullptr;
485 }
486 }
487 std::unique_ptr<ProfileCompilationInfo> info(new ProfileCompilationInfo);
488 if (!info->Load(fd)) {
489 LOG(ERROR) << "Cannot load profile info from fd=" << fd << "\n";
490 return nullptr;
491 }
492 return info;
493 }
494
David Sehrb18991b2017-02-08 20:58:10 -0800495 int DumpOneProfile(const std::string& banner,
496 const std::string& filename,
497 int fd,
498 const std::vector<std::unique_ptr<const DexFile>>* dex_files,
499 std::string* dump) {
Mathieu Chartier2f794552017-06-19 10:58:08 -0700500 std::unique_ptr<const ProfileCompilationInfo> info(LoadProfile(filename, fd));
501 if (info == nullptr) {
502 LOG(ERROR) << "Cannot load profile info from filename=" << filename << " fd=" << fd;
Calin Juravle876f3502016-03-24 16:16:34 +0000503 return -1;
504 }
Mathieu Chartier2f794552017-06-19 10:58:08 -0700505 *dump += banner + "\n" + info->DumpInfo(dex_files) + "\n";
David Sehr4fcdd6d2016-05-24 14:52:31 -0700506 return 0;
507 }
508
509 int DumpProfileInfo() {
David Sehr153da0e2017-02-15 08:54:51 -0800510 // Validate that at least one profile file or reference was specified.
511 if (profile_files_.empty() && profile_files_fd_.empty() &&
512 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
513 Usage("No profile files or reference profile specified.");
514 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700515 static const char* kEmptyString = "";
David Sehr546d24f2016-06-02 10:46:19 -0700516 static const char* kOrdinaryProfile = "=== profile ===";
517 static const char* kReferenceProfile = "=== reference profile ===";
518
David Sehrb18991b2017-02-08 20:58:10 -0800519 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7c80f2d2017-02-07 16:47:58 -0800520 OpenApkFilesFromLocations(&dex_files);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700521 std::string dump;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700522 // Dump individual profile files.
523 if (!profile_files_fd_.empty()) {
524 for (int profile_file_fd : profile_files_fd_) {
David Sehr546d24f2016-06-02 10:46:19 -0700525 int ret = DumpOneProfile(kOrdinaryProfile,
526 kEmptyString,
527 profile_file_fd,
528 &dex_files,
529 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700530 if (ret != 0) {
531 return ret;
532 }
533 }
534 }
535 if (!profile_files_.empty()) {
536 for (const std::string& profile_file : profile_files_) {
David Sehr546d24f2016-06-02 10:46:19 -0700537 int ret = DumpOneProfile(kOrdinaryProfile, profile_file, kInvalidFd, &dex_files, &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700538 if (ret != 0) {
539 return ret;
540 }
541 }
542 }
543 // Dump reference profile file.
544 if (FdIsValid(reference_profile_file_fd_)) {
David Sehr546d24f2016-06-02 10:46:19 -0700545 int ret = DumpOneProfile(kReferenceProfile,
546 kEmptyString,
547 reference_profile_file_fd_,
548 &dex_files,
549 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700550 if (ret != 0) {
551 return ret;
552 }
553 }
554 if (!reference_profile_file_.empty()) {
David Sehr546d24f2016-06-02 10:46:19 -0700555 int ret = DumpOneProfile(kReferenceProfile,
556 reference_profile_file_,
557 kInvalidFd,
558 &dex_files,
David Sehr4fcdd6d2016-05-24 14:52:31 -0700559 &dump);
560 if (ret != 0) {
561 return ret;
562 }
563 }
564 if (!FdIsValid(dump_output_to_fd_)) {
565 std::cout << dump;
566 } else {
567 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
568 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
569 return -1;
570 }
571 }
Calin Juravle876f3502016-03-24 16:16:34 +0000572 return 0;
573 }
574
575 bool ShouldOnlyDumpProfile() {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700576 return dump_only_;
Calin Juravle876f3502016-03-24 16:16:34 +0000577 }
578
Mathieu Chartier34067262017-04-06 13:55:46 -0700579 bool GetClassNamesAndMethods(int fd,
580 std::vector<std::unique_ptr<const DexFile>>* dex_files,
581 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800582 ProfileCompilationInfo profile_info;
583 if (!profile_info.Load(fd)) {
584 LOG(ERROR) << "Cannot load profile info";
585 return false;
586 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700587 for (const std::unique_ptr<const DexFile>& dex_file : *dex_files) {
588 std::set<dex::TypeIndex> class_types;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700589 std::set<uint16_t> hot_methods;
590 std::set<uint16_t> startup_methods;
591 std::set<uint16_t> post_startup_methods;
592 std::set<uint16_t> combined_methods;
593 if (profile_info.GetClassesAndMethods(*dex_file.get(),
594 &class_types,
595 &hot_methods,
596 &startup_methods,
597 &post_startup_methods)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700598 for (const dex::TypeIndex& type_index : class_types) {
599 const DexFile::TypeId& type_id = dex_file->GetTypeId(type_index);
600 out_lines->insert(std::string(dex_file->GetTypeDescriptor(type_id)));
601 }
Mathieu Chartierea650f32017-05-24 12:04:13 -0700602 combined_methods = hot_methods;
603 combined_methods.insert(startup_methods.begin(), startup_methods.end());
604 combined_methods.insert(post_startup_methods.begin(), post_startup_methods.end());
605 for (uint16_t dex_method_idx : combined_methods) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700606 const DexFile::MethodId& id = dex_file->GetMethodId(dex_method_idx);
607 std::string signature_string(dex_file->GetMethodSignature(id).ToString());
608 std::string type_string(dex_file->GetTypeDescriptor(dex_file->GetTypeId(id.class_idx_)));
609 std::string method_name(dex_file->GetMethodName(id));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700610 std::string flags_string;
611 if (hot_methods.find(dex_method_idx) != hot_methods.end()) {
612 flags_string += kMethodFlagStringHot;
613 }
614 if (startup_methods.find(dex_method_idx) != startup_methods.end()) {
615 flags_string += kMethodFlagStringStartup;
616 }
617 if (post_startup_methods.find(dex_method_idx) != post_startup_methods.end()) {
618 flags_string += kMethodFlagStringPostStartup;
619 }
620 out_lines->insert(flags_string +
621 type_string +
622 kMethodSep +
623 method_name +
624 signature_string);
Mathieu Chartier34067262017-04-06 13:55:46 -0700625 }
626 }
627 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800628 return true;
629 }
630
Mathieu Chartier34067262017-04-06 13:55:46 -0700631 bool GetClassNamesAndMethods(const std::string& profile_file,
632 std::vector<std::unique_ptr<const DexFile>>* dex_files,
633 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800634 int fd = open(profile_file.c_str(), O_RDONLY);
635 if (!FdIsValid(fd)) {
636 LOG(ERROR) << "Cannot open " << profile_file << strerror(errno);
637 return false;
638 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700639 if (!GetClassNamesAndMethods(fd, dex_files, out_lines)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800640 return false;
641 }
642 if (close(fd) < 0) {
643 PLOG(WARNING) << "Failed to close descriptor";
644 }
645 return true;
646 }
647
Mathieu Chartierea650f32017-05-24 12:04:13 -0700648 int DumpClassesAndMethods() {
David Sehr153da0e2017-02-15 08:54:51 -0800649 // Validate that at least one profile file or reference was specified.
650 if (profile_files_.empty() && profile_files_fd_.empty() &&
651 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
652 Usage("No profile files or reference profile specified.");
653 }
Calin Juravlee10c1e22018-01-26 20:10:15 -0800654
David Sehr7c80f2d2017-02-07 16:47:58 -0800655 // Open the dex files to get the names for classes.
656 std::vector<std::unique_ptr<const DexFile>> dex_files;
657 OpenApkFilesFromLocations(&dex_files);
658 // Build a vector of class names from individual profile files.
659 std::set<std::string> class_names;
660 if (!profile_files_fd_.empty()) {
661 for (int profile_file_fd : profile_files_fd_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700662 if (!GetClassNamesAndMethods(profile_file_fd, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800663 return -1;
664 }
665 }
666 }
667 if (!profile_files_.empty()) {
668 for (const std::string& profile_file : profile_files_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700669 if (!GetClassNamesAndMethods(profile_file, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800670 return -1;
671 }
672 }
673 }
674 // Concatenate class names from reference profile file.
675 if (FdIsValid(reference_profile_file_fd_)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700676 if (!GetClassNamesAndMethods(reference_profile_file_fd_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800677 return -1;
678 }
679 }
680 if (!reference_profile_file_.empty()) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700681 if (!GetClassNamesAndMethods(reference_profile_file_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800682 return -1;
683 }
684 }
685 // Dump the class names.
686 std::string dump;
687 for (const std::string& class_name : class_names) {
688 dump += class_name + std::string("\n");
689 }
690 if (!FdIsValid(dump_output_to_fd_)) {
691 std::cout << dump;
692 } else {
693 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
694 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
695 return -1;
696 }
697 }
698 return 0;
699 }
700
Mathieu Chartier34067262017-04-06 13:55:46 -0700701 bool ShouldOnlyDumpClassesAndMethods() {
702 return dump_classes_and_methods_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800703 }
704
705 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
706 // the given function.
707 template <typename T>
708 static T* ReadCommentedInputFromFile(
709 const char* input_filename, std::function<std::string(const char*)>* process) {
710 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
711 if (input_file.get() == nullptr) {
712 LOG(ERROR) << "Failed to open input file " << input_filename;
713 return nullptr;
714 }
715 std::unique_ptr<T> result(
716 ReadCommentedInputStream<T>(*input_file, process));
717 input_file->close();
718 return result.release();
719 }
720
721 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
722 // with the given function.
723 template <typename T>
724 static T* ReadCommentedInputStream(
725 std::istream& in_stream,
726 std::function<std::string(const char*)>* process) {
727 std::unique_ptr<T> output(new T());
728 while (in_stream.good()) {
729 std::string dot;
730 std::getline(in_stream, dot);
731 if (android::base::StartsWith(dot, "#") || dot.empty()) {
732 continue;
733 }
734 if (process != nullptr) {
735 std::string descriptor((*process)(dot.c_str()));
736 output->insert(output->end(), descriptor);
737 } else {
738 output->insert(output->end(), dot);
739 }
740 }
741 return output.release();
742 }
743
Calin Juravlee0ac1152017-02-13 19:03:47 -0800744 // Find class klass_descriptor in the given dex_files and store its reference
745 // in the out parameter class_ref.
746 // Return true if the definition of the class was found in any of the dex_files.
747 bool FindClass(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
748 const std::string& klass_descriptor,
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700749 /*out*/TypeReference* class_ref) {
Calin Juravle08556882017-05-26 16:40:45 -0700750 constexpr uint16_t kInvalidTypeIndex = std::numeric_limits<uint16_t>::max() - 1;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800751 for (const std::unique_ptr<const DexFile>& dex_file_ptr : dex_files) {
752 const DexFile* dex_file = dex_file_ptr.get();
Calin Juravle08556882017-05-26 16:40:45 -0700753 if (klass_descriptor == kInvalidClassDescriptor) {
754 if (kInvalidTypeIndex >= dex_file->NumTypeIds()) {
755 // The dex file does not contain all possible type ids which leaves us room
756 // to add an "invalid" type id.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700757 *class_ref = TypeReference(dex_file, dex::TypeIndex(kInvalidTypeIndex));
Calin Juravle08556882017-05-26 16:40:45 -0700758 return true;
759 } else {
760 // The dex file contains all possible type ids. We don't have any free type id
761 // that we can use as invalid.
762 continue;
763 }
764 }
765
Calin Juravlee0ac1152017-02-13 19:03:47 -0800766 const DexFile::TypeId* type_id = dex_file->FindTypeId(klass_descriptor.c_str());
767 if (type_id == nullptr) {
768 continue;
769 }
770 dex::TypeIndex type_index = dex_file->GetIndexForTypeId(*type_id);
771 if (dex_file->FindClassDef(type_index) == nullptr) {
772 // Class is only referenced in the current dex file but not defined in it.
773 continue;
774 }
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700775 *class_ref = TypeReference(dex_file, type_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800776 return true;
777 }
778 return false;
779 }
780
Mathieu Chartier34067262017-04-06 13:55:46 -0700781 // Find the method specified by method_spec in the class class_ref.
Calin Juravle08556882017-05-26 16:40:45 -0700782 uint32_t FindMethodIndex(const TypeReference& class_ref,
783 const std::string& method_spec) {
784 const DexFile* dex_file = class_ref.dex_file;
785 if (method_spec == kInvalidMethod) {
786 constexpr uint16_t kInvalidMethodIndex = std::numeric_limits<uint16_t>::max() - 1;
787 return kInvalidMethodIndex >= dex_file->NumMethodIds()
788 ? kInvalidMethodIndex
Andreas Gampee2abbc62017-09-15 11:59:26 -0700789 : dex::kDexNoIndex;
Calin Juravle08556882017-05-26 16:40:45 -0700790 }
791
Calin Juravlee0ac1152017-02-13 19:03:47 -0800792 std::vector<std::string> name_and_signature;
793 Split(method_spec, kProfileParsingFirstCharInSignature, &name_and_signature);
794 if (name_and_signature.size() != 2) {
795 LOG(ERROR) << "Invalid method name and signature " << method_spec;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700796 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800797 }
Calin Juravle08556882017-05-26 16:40:45 -0700798
Calin Juravlee0ac1152017-02-13 19:03:47 -0800799 const std::string& name = name_and_signature[0];
800 const std::string& signature = kProfileParsingFirstCharInSignature + name_and_signature[1];
Calin Juravlee0ac1152017-02-13 19:03:47 -0800801
802 const DexFile::StringId* name_id = dex_file->FindStringId(name.c_str());
803 if (name_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700804 LOG(WARNING) << "Could not find name: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700805 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800806 }
807 dex::TypeIndex return_type_idx;
808 std::vector<dex::TypeIndex> param_type_idxs;
809 if (!dex_file->CreateTypeList(signature, &return_type_idx, &param_type_idxs)) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700810 LOG(WARNING) << "Could not create type list" << signature;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700811 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800812 }
813 const DexFile::ProtoId* proto_id = dex_file->FindProtoId(return_type_idx, param_type_idxs);
814 if (proto_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700815 LOG(WARNING) << "Could not find proto_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700816 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800817 }
818 const DexFile::MethodId* method_id = dex_file->FindMethodId(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700819 dex_file->GetTypeId(class_ref.TypeIndex()), *name_id, *proto_id);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800820 if (method_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700821 LOG(WARNING) << "Could not find method_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700822 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800823 }
824
Mathieu Chartier34067262017-04-06 13:55:46 -0700825 return dex_file->GetIndexForMethodId(*method_id);
826 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800827
Mathieu Chartier34067262017-04-06 13:55:46 -0700828 // Given a method, return true if the method has a single INVOKE_VIRTUAL in its byte code.
829 // Upon success it returns true and stores the method index and the invoke dex pc
830 // in the output parameters.
831 // The format of the method spec is "inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
832 //
833 // TODO(calin): support INVOKE_INTERFACE and the range variants.
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700834 bool HasSingleInvoke(const TypeReference& class_ref,
Mathieu Chartier34067262017-04-06 13:55:46 -0700835 uint16_t method_index,
836 /*out*/uint32_t* dex_pc) {
837 const DexFile* dex_file = class_ref.dex_file;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800838 uint32_t offset = dex_file->FindCodeItemOffset(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700839 *dex_file->FindClassDef(class_ref.TypeIndex()),
Mathieu Chartier34067262017-04-06 13:55:46 -0700840 method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800841 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(offset);
842
843 bool found_invoke = false;
Mathieu Chartier698ebbc2018-01-05 11:00:42 -0800844 for (const DexInstructionPcPair& inst : CodeItemInstructionAccessor(*dex_file, code_item)) {
Mathieu Chartier0021feb2017-11-07 00:08:52 -0800845 if (inst->Opcode() == Instruction::INVOKE_VIRTUAL) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800846 if (found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700847 LOG(ERROR) << "Multiple invoke INVOKE_VIRTUAL found: "
848 << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800849 return false;
850 }
851 found_invoke = true;
Mathieu Chartier0021feb2017-11-07 00:08:52 -0800852 *dex_pc = inst.DexPc();
Calin Juravlee0ac1152017-02-13 19:03:47 -0800853 }
854 }
855 if (!found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700856 LOG(ERROR) << "Could not find any INVOKE_VIRTUAL: " << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800857 }
858 return found_invoke;
859 }
860
861 // Process a line defining a class or a method and its inline caches.
862 // Upon success return true and add the class or the method info to profile.
Calin Juravle589e71e2017-03-03 16:05:05 -0800863 // The possible line formats are:
864 // "LJustTheCass;".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800865 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
Calin Juravle08556882017-05-26 16:40:45 -0700866 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,invalid_class".
Calin Juravle589e71e2017-03-03 16:05:05 -0800867 // "LTestInline;->inlineMissingTypes(LSuper;)I+missing_types".
868 // "LTestInline;->inlineNoInlineCaches(LSuper;)I".
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700869 // "LTestInline;->*".
Calin Juravle08556882017-05-26 16:40:45 -0700870 // "invalid_class".
871 // "LTestInline;->invalid_method".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800872 // The method and classes are searched only in the given dex files.
873 bool ProcessLine(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
874 const std::string& line,
875 /*out*/ProfileCompilationInfo* profile) {
876 std::string klass;
877 std::string method_str;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700878 bool is_hot = false;
879 bool is_startup = false;
880 bool is_post_startup = false;
881 const size_t method_sep_index = line.find(kMethodSep, 0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800882 if (method_sep_index == std::string::npos) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700883 klass = line.substr(0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800884 } else {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700885 // The method prefix flags are only valid for method strings.
886 size_t start_index = 0;
887 while (start_index < line.size() && line[start_index] != 'L') {
888 const char c = line[start_index];
889 if (c == kMethodFlagStringHot) {
890 is_hot = true;
891 } else if (c == kMethodFlagStringStartup) {
892 is_startup = true;
893 } else if (c == kMethodFlagStringPostStartup) {
894 is_post_startup = true;
895 } else {
896 LOG(WARNING) << "Invalid flag " << c;
897 return false;
898 }
899 ++start_index;
900 }
901 klass = line.substr(start_index, method_sep_index - start_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800902 method_str = line.substr(method_sep_index + kMethodSep.size());
903 }
904
Calin Juravleee9cb412018-02-13 20:32:35 -0800905 uint32_t flags = 0;
906 if (is_hot) {
907 flags |= ProfileCompilationInfo::MethodHotness::kFlagHot;
908 }
909 if (is_startup) {
910 flags |= ProfileCompilationInfo::MethodHotness::kFlagStartup;
911 }
912 if (is_post_startup) {
913 flags |= ProfileCompilationInfo::MethodHotness::kFlagPostStartup;
914 }
915
Vladimir Markof3c52b42017-11-17 17:32:12 +0000916 TypeReference class_ref(/* dex_file */ nullptr, dex::TypeIndex());
Calin Juravlee0ac1152017-02-13 19:03:47 -0800917 if (!FindClass(dex_files, klass, &class_ref)) {
Mathieu Chartier3f121342017-03-06 11:16:20 -0800918 LOG(WARNING) << "Could not find class: " << klass;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800919 return false;
920 }
921
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700922 if (method_str.empty() || method_str == kClassAllMethods) {
923 // Start by adding the class.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800924 std::set<DexCacheResolvedClasses> resolved_class_set;
925 const DexFile* dex_file = class_ref.dex_file;
926 const auto& dex_resolved_classes = resolved_class_set.emplace(
927 dex_file->GetLocation(),
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700928 DexFileLoader::GetBaseLocation(dex_file->GetLocation()),
Mathieu Chartierea650f32017-05-24 12:04:13 -0700929 dex_file->GetLocationChecksum(),
930 dex_file->NumMethodIds());
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700931 dex_resolved_classes.first->AddClass(class_ref.TypeIndex());
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700932 std::vector<ProfileMethodInfo> methods;
933 if (method_str == kClassAllMethods) {
934 // Add all of the methods.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700935 const DexFile::ClassDef* class_def = dex_file->FindClassDef(class_ref.TypeIndex());
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700936 const uint8_t* class_data = dex_file->GetClassData(*class_def);
937 if (class_data != nullptr) {
938 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700939 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800940 while (it.HasNextMethod()) {
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700941 if (it.GetMethodCodeItemOffset() != 0) {
942 // Add all of the methods that have code to the profile.
943 const uint32_t method_idx = it.GetMemberIndex();
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700944 methods.push_back(ProfileMethodInfo(MethodReference(dex_file, method_idx)));
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700945 }
946 it.Next();
947 }
948 }
949 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700950 // TODO: Check return values?
Calin Juravleee9cb412018-02-13 20:32:35 -0800951 profile->AddMethods(methods, static_cast<ProfileCompilationInfo::MethodHotness::Flag>(flags));
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700952 profile->AddClasses(resolved_class_set);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800953 return true;
954 }
955
956 // Process the method.
957 std::string method_spec;
958 std::vector<std::string> inline_cache_elems;
959
Mathieu Chartierea650f32017-05-24 12:04:13 -0700960 // If none of the flags are set, default to hot.
961 is_hot = is_hot || (!is_hot && !is_startup && !is_post_startup);
962
Calin Juravlee0ac1152017-02-13 19:03:47 -0800963 std::vector<std::string> method_elems;
Calin Juravle589e71e2017-03-03 16:05:05 -0800964 bool is_missing_types = false;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800965 Split(method_str, kProfileParsingInlineChacheSep, &method_elems);
966 if (method_elems.size() == 2) {
967 method_spec = method_elems[0];
Calin Juravle589e71e2017-03-03 16:05:05 -0800968 is_missing_types = method_elems[1] == kMissingTypesMarker;
969 if (!is_missing_types) {
970 Split(method_elems[1], kProfileParsingTypeSep, &inline_cache_elems);
971 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800972 } else if (method_elems.size() == 1) {
973 method_spec = method_elems[0];
974 } else {
975 LOG(ERROR) << "Invalid method line: " << line;
976 return false;
977 }
978
Mathieu Chartier34067262017-04-06 13:55:46 -0700979 const uint32_t method_index = FindMethodIndex(class_ref, method_spec);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700980 if (method_index == dex::kDexNoIndex) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800981 return false;
982 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700983
Mathieu Chartier34067262017-04-06 13:55:46 -0700984 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
985 if (is_missing_types || !inline_cache_elems.empty()) {
986 uint32_t dex_pc;
987 if (!HasSingleInvoke(class_ref, method_index, &dex_pc)) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800988 return false;
989 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000990 std::vector<TypeReference> classes(inline_cache_elems.size(),
991 TypeReference(/* dex_file */ nullptr, dex::TypeIndex()));
Mathieu Chartier34067262017-04-06 13:55:46 -0700992 size_t class_it = 0;
993 for (const std::string& ic_class : inline_cache_elems) {
994 if (!FindClass(dex_files, ic_class, &(classes[class_it++]))) {
995 LOG(ERROR) << "Could not find class: " << ic_class;
996 return false;
997 }
998 }
999 inline_caches.emplace_back(dex_pc, is_missing_types, classes);
Calin Juravlee0ac1152017-02-13 19:03:47 -08001000 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001001 MethodReference ref(class_ref.dex_file, method_index);
Mathieu Chartierea650f32017-05-24 12:04:13 -07001002 if (is_hot) {
Calin Juravleee9cb412018-02-13 20:32:35 -08001003 profile->AddMethod(ProfileMethodInfo(ref, inline_caches),
1004 static_cast<ProfileCompilationInfo::MethodHotness::Flag>(flags));
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001005 }
1006 if (flags != 0) {
Calin Juravleee9cb412018-02-13 20:32:35 -08001007 if (!profile->AddMethodIndex(
1008 static_cast<ProfileCompilationInfo::MethodHotness::Flag>(flags), ref)) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001009 return false;
1010 }
Mathieu Chartiere46f3a82017-06-19 19:54:12 -07001011 DCHECK(profile->GetMethodHotness(ref).IsInProfile());
Mathieu Chartierea650f32017-05-24 12:04:13 -07001012 }
Calin Juravlee0ac1152017-02-13 19:03:47 -08001013 return true;
1014 }
1015
Mathieu Chartier2f794552017-06-19 10:58:08 -07001016 int OpenReferenceProfile() const {
1017 int fd = reference_profile_file_fd_;
1018 if (!FdIsValid(fd)) {
1019 CHECK(!reference_profile_file_.empty());
1020 fd = open(reference_profile_file_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
1021 if (fd < 0) {
1022 LOG(ERROR) << "Cannot open " << reference_profile_file_ << strerror(errno);
1023 return kInvalidFd;
1024 }
1025 }
1026 return fd;
1027 }
1028
Calin Juravlee0ac1152017-02-13 19:03:47 -08001029 // Creates a profile from a human friendly textual representation.
1030 // The expected input format is:
1031 // # Classes
1032 // Ljava/lang/Comparable;
1033 // Ljava/lang/Math;
1034 // # Methods with inline caches
1035 // LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;
1036 // LTestInline;->noInlineCache(LSuper;)I
David Sehr7c80f2d2017-02-07 16:47:58 -08001037 int CreateProfile() {
David Sehr153da0e2017-02-15 08:54:51 -08001038 // Validate parameters for this command.
1039 if (apk_files_.empty() && apks_fd_.empty()) {
1040 Usage("APK files must be specified");
1041 }
1042 if (dex_locations_.empty()) {
1043 Usage("DEX locations must be specified");
1044 }
1045 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
1046 Usage("Reference profile must be specified with --reference-profile-file or "
1047 "--reference-profile-file-fd");
1048 }
1049 if (!profile_files_.empty() || !profile_files_fd_.empty()) {
1050 Usage("Profile must be specified with --reference-profile-file or "
1051 "--reference-profile-file-fd");
1052 }
David Sehr7c80f2d2017-02-07 16:47:58 -08001053 // Open the profile output file if needed.
Mathieu Chartier2f794552017-06-19 10:58:08 -07001054 int fd = OpenReferenceProfile();
David Sehr7c80f2d2017-02-07 16:47:58 -08001055 if (!FdIsValid(fd)) {
David Sehr7c80f2d2017-02-07 16:47:58 -08001056 return -1;
David Sehr7c80f2d2017-02-07 16:47:58 -08001057 }
Calin Juravlee0ac1152017-02-13 19:03:47 -08001058 // Read the user-specified list of classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -08001059 std::unique_ptr<std::unordered_set<std::string>>
Calin Juravlee0ac1152017-02-13 19:03:47 -08001060 user_lines(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
David Sehr7c80f2d2017-02-07 16:47:58 -08001061 create_profile_from_file_.c_str(), nullptr)); // No post-processing.
Calin Juravlee0ac1152017-02-13 19:03:47 -08001062
1063 // Open the dex files to look up classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -08001064 std::vector<std::unique_ptr<const DexFile>> dex_files;
1065 OpenApkFilesFromLocations(&dex_files);
Calin Juravlee0ac1152017-02-13 19:03:47 -08001066
1067 // Process the lines one by one and add the successful ones to the profile.
David Sehr7c80f2d2017-02-07 16:47:58 -08001068 ProfileCompilationInfo info;
Calin Juravlee0ac1152017-02-13 19:03:47 -08001069
1070 for (const auto& line : *user_lines) {
1071 ProcessLine(dex_files, line, &info);
1072 }
1073
David Sehr7c80f2d2017-02-07 16:47:58 -08001074 // Write the profile file.
1075 CHECK(info.Save(fd));
1076 if (close(fd) < 0) {
1077 PLOG(WARNING) << "Failed to close descriptor";
1078 }
1079 return 0;
1080 }
1081
Mathieu Chartier2f794552017-06-19 10:58:08 -07001082 bool ShouldCreateBootProfile() const {
1083 return generate_boot_image_profile_;
1084 }
1085
1086 int CreateBootProfile() {
Mathieu Chartier2f794552017-06-19 10:58:08 -07001087 // Open the profile output file.
1088 const int reference_fd = OpenReferenceProfile();
1089 if (!FdIsValid(reference_fd)) {
1090 PLOG(ERROR) << "Error opening reference profile";
1091 return -1;
1092 }
1093 // Open the dex files.
1094 std::vector<std::unique_ptr<const DexFile>> dex_files;
1095 OpenApkFilesFromLocations(&dex_files);
1096 if (dex_files.empty()) {
1097 PLOG(ERROR) << "Expected dex files for creating boot profile";
1098 return -2;
1099 }
1100 // Open the input profiles.
1101 std::vector<std::unique_ptr<const ProfileCompilationInfo>> profiles;
1102 if (!profile_files_fd_.empty()) {
1103 for (int profile_file_fd : profile_files_fd_) {
1104 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile("", profile_file_fd));
1105 if (profile == nullptr) {
1106 return -3;
1107 }
1108 profiles.emplace_back(std::move(profile));
1109 }
1110 }
1111 if (!profile_files_.empty()) {
1112 for (const std::string& profile_file : profile_files_) {
1113 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile(profile_file, kInvalidFd));
1114 if (profile == nullptr) {
1115 return -4;
1116 }
1117 profiles.emplace_back(std::move(profile));
1118 }
1119 }
1120 ProfileCompilationInfo out_profile;
1121 GenerateBootImageProfile(dex_files,
1122 profiles,
1123 boot_image_options_,
1124 VLOG_IS_ON(profiler),
1125 &out_profile);
1126 out_profile.Save(reference_fd);
1127 close(reference_fd);
1128 return 0;
1129 }
1130
David Sehr7c80f2d2017-02-07 16:47:58 -08001131 bool ShouldCreateProfile() {
1132 return !create_profile_from_file_.empty();
1133 }
1134
Calin Juravle7bcdb532016-06-07 16:14:47 +01001135 int GenerateTestProfile() {
David Sehr153da0e2017-02-15 08:54:51 -08001136 // Validate parameters for this command.
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001137 if (test_profile_method_percerntage_ > 100) {
1138 Usage("Invalid percentage for --generate-test-profile-method-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001139 }
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001140 if (test_profile_class_percentage_ > 100) {
1141 Usage("Invalid percentage for --generate-test-profile-class-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001142 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001143 // If given APK files or DEX locations, check that they're ok.
1144 if (!apk_files_.empty() || !apks_fd_.empty() || !dex_locations_.empty()) {
1145 if (apk_files_.empty() && apks_fd_.empty()) {
1146 Usage("APK files must be specified when passing DEX locations to --generate-test-profile");
1147 }
1148 if (dex_locations_.empty()) {
1149 Usage("DEX locations must be specified when passing APK files to --generate-test-profile");
1150 }
1151 }
David Sehr153da0e2017-02-15 08:54:51 -08001152 // ShouldGenerateTestProfile confirms !test_profile_.empty().
George Burgess IV71f77262016-10-25 13:08:17 -07001153 int profile_test_fd = open(test_profile_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001154 if (profile_test_fd < 0) {
David Sehr7c80f2d2017-02-07 16:47:58 -08001155 LOG(ERROR) << "Cannot open " << test_profile_ << strerror(errno);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001156 return -1;
1157 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001158 bool result;
1159 if (apk_files_.empty() && apks_fd_.empty() && dex_locations_.empty()) {
1160 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1161 test_profile_num_dex_,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001162 test_profile_method_percerntage_,
1163 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001164 test_profile_seed_);
1165 } else {
Jeff Haof0a31f82017-03-27 15:50:37 -07001166 // Open the dex files to look up classes and methods.
1167 std::vector<std::unique_ptr<const DexFile>> dex_files;
1168 OpenApkFilesFromLocations(&dex_files);
1169 // Create a random profile file based on the set of dex files.
1170 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1171 dex_files,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001172 test_profile_method_percerntage_,
1173 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001174 test_profile_seed_);
1175 }
Calin Juravle7bcdb532016-06-07 16:14:47 +01001176 close(profile_test_fd); // ignore close result.
1177 return result ? 0 : -1;
1178 }
1179
1180 bool ShouldGenerateTestProfile() {
1181 return !test_profile_.empty();
1182 }
1183
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001184 bool ShouldCopyAndUpdateProfileKey() const {
1185 return copy_and_update_profile_key_;
1186 }
1187
Calin Juravle02c08792018-02-15 19:40:48 -08001188 int32_t CopyAndUpdateProfileKey() {
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001189 // Validate that at least one profile file was passed, as well as a reference profile.
1190 if (!(profile_files_.size() == 1 ^ profile_files_fd_.size() == 1)) {
1191 Usage("Only one profile file should be specified.");
1192 }
1193 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
1194 Usage("No reference profile file specified.");
1195 }
1196
1197 if (apk_files_.empty() && apks_fd_.empty()) {
1198 Usage("No apk files specified");
1199 }
1200
Calin Juravle02c08792018-02-15 19:40:48 -08001201 static constexpr int32_t kErrorFailedToUpdateProfile = -1;
1202 static constexpr int32_t kErrorFailedToSaveProfile = -2;
1203 static constexpr int32_t kErrorFailedToLoadProfile = -3;
1204
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001205 bool use_fds = profile_files_fd_.size() == 1;
1206
1207 ProfileCompilationInfo profile;
1208 // Do not clear if invalid. The input might be an archive.
Calin Juravle02c08792018-02-15 19:40:48 -08001209 bool load_ok = use_fds
1210 ? profile.Load(profile_files_fd_[0])
1211 : profile.Load(profile_files_[0], /*clear_if_invalid*/ false);
1212 if (load_ok) {
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001213 // Open the dex files to look up classes and methods.
1214 std::vector<std::unique_ptr<const DexFile>> dex_files;
1215 OpenApkFilesFromLocations(&dex_files);
1216 if (!profile.UpdateProfileKeys(dex_files)) {
Calin Juravle02c08792018-02-15 19:40:48 -08001217 return kErrorFailedToUpdateProfile;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001218 }
Calin Juravle02c08792018-02-15 19:40:48 -08001219 bool result = use_fds
1220 ? profile.Save(reference_profile_file_fd_)
1221 : profile.Save(reference_profile_file_, /*bytes_written*/ nullptr);
1222 return result ? 0 : kErrorFailedToSaveProfile;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001223 } else {
Calin Juravle02c08792018-02-15 19:40:48 -08001224 return kErrorFailedToLoadProfile;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001225 }
1226 }
1227
Calin Juravle2e2db782016-02-23 12:00:03 +00001228 private:
1229 static void ParseFdForCollection(const StringPiece& option,
1230 const char* arg_name,
1231 std::vector<int>* fds) {
1232 int fd;
1233 ParseUintOption(option, arg_name, &fd, Usage);
1234 fds->push_back(fd);
1235 }
1236
1237 static void CloseAllFds(const std::vector<int>& fds, const char* descriptor) {
1238 for (size_t i = 0; i < fds.size(); i++) {
1239 if (close(fds[i]) < 0) {
Calin Juravlee10c1e22018-01-26 20:10:15 -08001240 PLOG(WARNING) << "Failed to close descriptor for "
1241 << descriptor << " at index " << i << ": " << fds[i];
Calin Juravle2e2db782016-02-23 12:00:03 +00001242 }
1243 }
1244 }
1245
1246 void LogCompletionTime() {
David Sehr52683cf2016-05-05 09:02:38 -07001247 static constexpr uint64_t kLogThresholdTime = MsToNs(100); // 100ms
1248 uint64_t time_taken = NanoTime() - start_ns_;
David Sehred793012016-05-05 13:39:43 -07001249 if (time_taken > kLogThresholdTime) {
David Sehrd8557182016-05-06 12:29:35 -07001250 LOG(WARNING) << "profman took " << PrettyDuration(time_taken);
David Sehred793012016-05-05 13:39:43 -07001251 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001252 }
1253
1254 std::vector<std::string> profile_files_;
1255 std::vector<int> profile_files_fd_;
David Sehr546d24f2016-06-02 10:46:19 -07001256 std::vector<std::string> dex_locations_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001257 std::vector<std::string> apk_files_;
David Sehr546d24f2016-06-02 10:46:19 -07001258 std::vector<int> apks_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001259 std::string reference_profile_file_;
1260 int reference_profile_file_fd_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001261 bool dump_only_;
Mathieu Chartier34067262017-04-06 13:55:46 -07001262 bool dump_classes_and_methods_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001263 bool generate_boot_image_profile_;
David Brazdilf13ac7c2018-01-30 10:09:08 +00001264 bool skip_apk_verification_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001265 int dump_output_to_fd_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001266 BootImageOptions boot_image_options_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001267 std::string test_profile_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001268 std::string create_profile_from_file_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001269 uint16_t test_profile_num_dex_;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001270 uint16_t test_profile_method_percerntage_;
1271 uint16_t test_profile_class_percentage_;
Jeff Haof0a31f82017-03-27 15:50:37 -07001272 uint32_t test_profile_seed_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001273 uint64_t start_ns_;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001274 bool copy_and_update_profile_key_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001275};
1276
1277// See ProfileAssistant::ProcessingResult for return codes.
1278static int profman(int argc, char** argv) {
1279 ProfMan profman;
1280
1281 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1282 profman.ParseArgs(argc, argv);
1283
Calin Juravlee10c1e22018-01-26 20:10:15 -08001284 // Initialize MemMap for ZipArchive::OpenFromFd.
1285 MemMap::Init();
1286
Calin Juravle7bcdb532016-06-07 16:14:47 +01001287 if (profman.ShouldGenerateTestProfile()) {
1288 return profman.GenerateTestProfile();
1289 }
Calin Juravle876f3502016-03-24 16:16:34 +00001290 if (profman.ShouldOnlyDumpProfile()) {
1291 return profman.DumpProfileInfo();
1292 }
Mathieu Chartier34067262017-04-06 13:55:46 -07001293 if (profman.ShouldOnlyDumpClassesAndMethods()) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001294 return profman.DumpClassesAndMethods();
David Sehr7c80f2d2017-02-07 16:47:58 -08001295 }
1296 if (profman.ShouldCreateProfile()) {
1297 return profman.CreateProfile();
1298 }
Mathieu Chartier2f794552017-06-19 10:58:08 -07001299
1300 if (profman.ShouldCreateBootProfile()) {
1301 return profman.CreateBootProfile();
1302 }
Calin Juravle02c08792018-02-15 19:40:48 -08001303
1304 if (profman.ShouldCopyAndUpdateProfileKey()) {
1305 return profman.CopyAndUpdateProfileKey();
1306 }
1307
Calin Juravle2e2db782016-02-23 12:00:03 +00001308 // Process profile information and assess if we need to do a profile guided compilation.
1309 // This operation involves I/O.
1310 return profman.ProcessProfiles();
1311}
1312
1313} // namespace art
1314
1315int main(int argc, char **argv) {
1316 return art::profman(argc, argv);
1317}
1318