blob: 1f7723946caaf8bc3c4242b89942b31575573fc3 [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 Sehr671af6c2018-05-17 11:00:35 -070036#include "base/mem_map.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"
Mathieu Chartier818cb802018-05-11 05:30:16 +000044#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"
David Sehr82d046e2018-04-23 08:14:19 -070051#include "profile/profile_compilation_info.h"
Mathieu Chartierdbddc222017-05-24 12:04:13 -070052#include "profile_assistant.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000053
54namespace art {
55
56static int original_argc;
57static char** original_argv;
58
59static std::string CommandLine() {
60 std::vector<std::string> command;
61 for (int i = 0; i < original_argc; ++i) {
62 command.push_back(original_argv[i]);
63 }
Andreas Gampe9186ced2016-12-12 14:28:21 -080064 return android::base::Join(command, ' ');
Calin Juravle2e2db782016-02-23 12:00:03 +000065}
66
David Sehr4fcdd6d2016-05-24 14:52:31 -070067static constexpr int kInvalidFd = -1;
68
69static bool FdIsValid(int fd) {
70 return fd != kInvalidFd;
71}
72
Calin Juravle2e2db782016-02-23 12:00:03 +000073static void UsageErrorV(const char* fmt, va_list ap) {
74 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080075 android::base::StringAppendV(&error, fmt, ap);
Calin Juravle2e2db782016-02-23 12:00:03 +000076 LOG(ERROR) << error;
77}
78
79static void UsageError(const char* fmt, ...) {
80 va_list ap;
81 va_start(ap, fmt);
82 UsageErrorV(fmt, ap);
83 va_end(ap);
84}
85
86NO_RETURN static void Usage(const char *fmt, ...) {
87 va_list ap;
88 va_start(ap, fmt);
89 UsageErrorV(fmt, ap);
90 va_end(ap);
91
92 UsageError("Command: %s", CommandLine().c_str());
93 UsageError("Usage: profman [options]...");
94 UsageError("");
David Sehr4fcdd6d2016-05-24 14:52:31 -070095 UsageError(" --dump-only: dumps the content of the specified profile files");
96 UsageError(" to standard output (default) in a human readable form.");
97 UsageError("");
David Sehr7c80f2d2017-02-07 16:47:58 -080098 UsageError(" --dump-output-to-fd=<number>: redirects --dump-only output to a file descriptor.");
99 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -0700100 UsageError(" --dump-classes-and-methods: dumps a sorted list of classes and methods that are");
101 UsageError(" in the specified profile file to standard output (default) in a human");
102 UsageError(" readable form. The output is valid input for --create-profile-from");
Calin Juravle876f3502016-03-24 16:16:34 +0000103 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000104 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
105 UsageError(" Can be specified multiple time, in which case the data from the different");
106 UsageError(" profiles will be aggregated.");
107 UsageError("");
108 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
109 UsageError(" Cannot be used together with --profile-file.");
110 UsageError("");
111 UsageError(" --reference-profile-file=<filename>: specify a reference profile.");
112 UsageError(" The data in this file will be compared with the data obtained by merging");
113 UsageError(" all the files specified with --profile-file or --profile-file-fd.");
114 UsageError(" If the exit code is EXIT_COMPILE then all --profile-file will be merged into");
115 UsageError(" --reference-profile-file. ");
116 UsageError("");
117 UsageError(" --reference-profile-file-fd=<number>: same as --reference-profile-file but");
118 UsageError(" accepts a file descriptor. Cannot be used together with");
119 UsageError(" --reference-profile-file.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800120 UsageError("");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100121 UsageError(" --generate-test-profile=<filename>: generates a random profile file for testing.");
122 UsageError(" --generate-test-profile-num-dex=<number>: number of dex files that should be");
123 UsageError(" included in the generated profile. Defaults to 20.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700124 UsageError(" --generate-test-profile-method-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100125 UsageError(" number of methods that should be generated. Defaults to 5.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700126 UsageError(" --generate-test-profile-class-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100127 UsageError(" number of classes that should be generated. Defaults to 5.");
Jeff Haof0a31f82017-03-27 15:50:37 -0700128 UsageError(" --generate-test-profile-seed=<number>: seed for random number generator used when");
129 UsageError(" generating random test profiles. Defaults to using NanoTime.");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100130 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -0700131 UsageError(" --create-profile-from=<filename>: creates a profile from a list of classes and");
132 UsageError(" methods.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800133 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700134 UsageError(" --dex-location=<string>: location string to use with corresponding");
135 UsageError(" apk-fd to find dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700136 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700137 UsageError(" --apk-fd=<number>: file descriptor containing an open APK to");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700138 UsageError(" search for dex files");
David Sehr7c80f2d2017-02-07 16:47:58 -0800139 UsageError(" --apk-=<filename>: an APK to search for dex files");
David Brazdilf13ac7c2018-01-30 10:09:08 +0000140 UsageError(" --skip-apk-verification: do not attempt to verify APKs");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700141 UsageError("");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700142 UsageError(" --generate-boot-image-profile: Generate a boot image profile based on input");
143 UsageError(" profiles. Requires passing in dex files to inspect properties of classes.");
144 UsageError(" --boot-image-class-threshold=<value>: specify minimum number of class occurrences");
145 UsageError(" to include a class in the boot image profile. Default is 10.");
146 UsageError(" --boot-image-clean-class-threshold=<value>: specify minimum number of clean class");
147 UsageError(" occurrences to include a class in the boot image profile. A clean class is a");
148 UsageError(" class that doesn't have any static fields or native methods and is likely to");
149 UsageError(" remain clean in the image. Default is 3.");
Mathieu Chartier8eecddf2017-07-12 16:05:54 -0700150 UsageError(" --boot-image-sampled-method-threshold=<value>: minimum number of profiles a");
151 UsageError(" non-hot method needs to be in order to be hot in the output profile. The");
152 UsageError(" default is max int.");
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800153 UsageError(" --copy-and-update-profile-key: if present, profman will copy the profile from");
154 UsageError(" the file passed with --profile-fd(file) to the profile passed with");
155 UsageError(" --reference-profile-fd(file) and update at the same time the profile-key");
156 UsageError(" of entries corresponding to the apks passed with --apk(-fd).");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700157 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000158
159 exit(EXIT_FAILURE);
160}
161
Calin Juravle7bcdb532016-06-07 16:14:47 +0100162// Note: make sure you update the Usage if you change these values.
163static constexpr uint16_t kDefaultTestProfileNumDex = 20;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700164static constexpr uint16_t kDefaultTestProfileMethodPercentage = 5;
165static constexpr uint16_t kDefaultTestProfileClassPercentage = 5;
Calin Juravle7bcdb532016-06-07 16:14:47 +0100166
Calin Juravlee0ac1152017-02-13 19:03:47 -0800167// Separators used when parsing human friendly representation of profiles.
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800168static const std::string kMethodSep = "->"; // NOLINT [runtime/string] [4]
169static const std::string kMissingTypesMarker = "missing_types"; // NOLINT [runtime/string] [4]
170static const std::string kInvalidClassDescriptor = "invalid_class"; // NOLINT [runtime/string] [4]
171static const std::string kInvalidMethod = "invalid_method"; // NOLINT [runtime/string] [4]
172static const std::string kClassAllMethods = "*"; // NOLINT [runtime/string] [4]
Calin Juravlee0ac1152017-02-13 19:03:47 -0800173static constexpr char kProfileParsingInlineChacheSep = '+';
174static constexpr char kProfileParsingTypeSep = ',';
175static constexpr char kProfileParsingFirstCharInSignature = '(';
Mathieu Chartierea650f32017-05-24 12:04:13 -0700176static constexpr char kMethodFlagStringHot = 'H';
177static constexpr char kMethodFlagStringStartup = 'S';
178static constexpr char kMethodFlagStringPostStartup = 'P';
Calin Juravlee0ac1152017-02-13 19:03:47 -0800179
David Sehr671af6c2018-05-17 11:00:35 -0700180NO_RETURN static void Abort(const char* msg) {
181 LOG(ERROR) << msg;
182 exit(1);
183}
184
Calin Juravlee0ac1152017-02-13 19:03:47 -0800185// TODO(calin): This class has grown too much from its initial design. Split the functionality
186// into smaller, more contained pieces.
Calin Juravle2e2db782016-02-23 12:00:03 +0000187class ProfMan FINAL {
188 public:
189 ProfMan() :
David Sehr4fcdd6d2016-05-24 14:52:31 -0700190 reference_profile_file_fd_(kInvalidFd),
191 dump_only_(false),
Mathieu Chartier34067262017-04-06 13:55:46 -0700192 dump_classes_and_methods_(false),
Mathieu Chartier2f794552017-06-19 10:58:08 -0700193 generate_boot_image_profile_(false),
David Sehr4fcdd6d2016-05-24 14:52:31 -0700194 dump_output_to_fd_(kInvalidFd),
Calin Juravle7bcdb532016-06-07 16:14:47 +0100195 test_profile_num_dex_(kDefaultTestProfileNumDex),
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700196 test_profile_method_percerntage_(kDefaultTestProfileMethodPercentage),
197 test_profile_class_percentage_(kDefaultTestProfileClassPercentage),
Jeff Haof0a31f82017-03-27 15:50:37 -0700198 test_profile_seed_(NanoTime()),
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800199 start_ns_(NanoTime()),
200 copy_and_update_profile_key_(false) {}
Calin Juravle2e2db782016-02-23 12:00:03 +0000201
202 ~ProfMan() {
203 LogCompletionTime();
204 }
205
206 void ParseArgs(int argc, char **argv) {
207 original_argc = argc;
208 original_argv = argv;
209
David Sehr671af6c2018-05-17 11:00:35 -0700210 MemMap::Init();
211 InitLogging(argv, Abort);
Calin Juravle2e2db782016-02-23 12:00:03 +0000212
213 // Skip over the command name.
214 argv++;
215 argc--;
216
217 if (argc == 0) {
218 Usage("No arguments specified");
219 }
220
221 for (int i = 0; i < argc; ++i) {
222 const StringPiece option(argv[i]);
223 const bool log_options = false;
224 if (log_options) {
Calin Juravle876f3502016-03-24 16:16:34 +0000225 LOG(INFO) << "profman: option[" << i << "]=" << argv[i];
Calin Juravle2e2db782016-02-23 12:00:03 +0000226 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700227 if (option == "--dump-only") {
228 dump_only_ = true;
Mathieu Chartier34067262017-04-06 13:55:46 -0700229 } else if (option == "--dump-classes-and-methods") {
230 dump_classes_and_methods_ = true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800231 } else if (option.starts_with("--create-profile-from=")) {
232 create_profile_from_file_ = option.substr(strlen("--create-profile-from=")).ToString();
David Sehr4fcdd6d2016-05-24 14:52:31 -0700233 } else if (option.starts_with("--dump-output-to-fd=")) {
234 ParseUintOption(option, "--dump-output-to-fd", &dump_output_to_fd_, Usage);
Mathieu Chartier2f794552017-06-19 10:58:08 -0700235 } else if (option == "--generate-boot-image-profile") {
236 generate_boot_image_profile_ = true;
237 } 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
Calin Juravlee10c1e22018-01-26 20:10:15 -0800373 bool GetProfileFilterKeyFromApks(std::set<ProfileFilterKey>* profile_filter_keys) {
374 auto process_fn = [profile_filter_keys](std::unique_ptr<const DexFile>&& dex_file) {
375 // Store the profile key of the location instead of the location itself.
376 // This will make the matching in the profile filter method much easier.
377 profile_filter_keys->emplace(ProfileCompilationInfo::GetProfileDexFileKey(
378 dex_file->GetLocation()), dex_file->GetLocationChecksum());
379 };
380 return OpenApkFilesFromLocations(process_fn);
381 }
382
383 bool OpenApkFilesFromLocations(std::vector<std::unique_ptr<const DexFile>>* dex_files) {
384 auto process_fn = [dex_files](std::unique_ptr<const DexFile>&& dex_file) {
385 dex_files->emplace_back(std::move(dex_file));
386 };
387 return OpenApkFilesFromLocations(process_fn);
388 }
389
390 bool OpenApkFilesFromLocations(
391 std::function<void(std::unique_ptr<const DexFile>&&)> process_fn) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800392 bool use_apk_fd_list = !apks_fd_.empty();
393 if (use_apk_fd_list) {
David Sehr153da0e2017-02-15 08:54:51 -0800394 // Get the APKs from the collection of FDs.
Calin Juravlee10c1e22018-01-26 20:10:15 -0800395 if (dex_locations_.empty()) {
396 // Try to compute the dex locations from the file paths of the descriptions.
397 // This will make it easier to invoke profman with --apk-fd and without
398 // being force to pass --dex-location when the location would be the apk path.
399 if (!ComputeDexLocationsFromApkFds()) {
400 return false;
401 }
402 } else {
403 if (dex_locations_.size() != apks_fd_.size()) {
404 Usage("The number of apk-fds must match the number of dex-locations.");
405 }
406 }
David Sehr153da0e2017-02-15 08:54:51 -0800407 } else if (!apk_files_.empty()) {
Calin Juravle02c08792018-02-15 19:40:48 -0800408 if (dex_locations_.empty()) {
409 // If no dex locations are specified use the apk names as locations.
410 dex_locations_ = apk_files_;
411 } else if (dex_locations_.size() != apk_files_.size()) {
412 Usage("The number of apk-fds must match the number of dex-locations.");
413 }
David Sehr153da0e2017-02-15 08:54:51 -0800414 } else {
415 // No APKs were specified.
416 CHECK(dex_locations_.empty());
Calin Juravlee10c1e22018-01-26 20:10:15 -0800417 return true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800418 }
419 static constexpr bool kVerifyChecksum = true;
420 for (size_t i = 0; i < dex_locations_.size(); ++i) {
Mathieu Chartier818cb802018-05-11 05:30:16 +0000421 std::string error_msg;
422 const ArtDexFileLoader dex_file_loader;
423 std::vector<std::unique_ptr<const DexFile>> dex_files_for_location;
Calin Juravle1bfe4bd2018-04-26 16:00:11 -0700424 // We do not need to verify the apk for processing profiles.
David Sehr7c80f2d2017-02-07 16:47:58 -0800425 if (use_apk_fd_list) {
Mathieu Chartier818cb802018-05-11 05:30:16 +0000426 if (dex_file_loader.OpenZip(apks_fd_[i],
427 dex_locations_[i],
428 /* verify */ false,
429 kVerifyChecksum,
430 &error_msg,
431 &dex_files_for_location)) {
432 } else {
433 LOG(ERROR) << "OpenZip failed for '" << dex_locations_[i] << "' " << error_msg;
Calin Juravlee10c1e22018-01-26 20:10:15 -0800434 return false;
David Sehr7c80f2d2017-02-07 16:47:58 -0800435 }
Mathieu Chartier818cb802018-05-11 05:30:16 +0000436 } else {
437 if (dex_file_loader.Open(apk_files_[i].c_str(),
438 dex_locations_[i],
439 /* verify */ false,
440 kVerifyChecksum,
441 &error_msg,
442 &dex_files_for_location)) {
443 } else {
444 LOG(ERROR) << "Open failed for '" << dex_locations_[i] << "' " << error_msg;
445 return false;
446 }
David Sehr2b80ed42018-05-08 08:58:15 -0700447 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800448 for (std::unique_ptr<const DexFile>& dex_file : dex_files_for_location) {
Calin Juravlee10c1e22018-01-26 20:10:15 -0800449 process_fn(std::move(dex_file));
David Sehr7c80f2d2017-02-07 16:47:58 -0800450 }
451 }
Calin Juravlee10c1e22018-01-26 20:10:15 -0800452 return true;
453 }
454
455 // Get the dex locations from the apk fds.
456 // The methods reads the links from /proc/self/fd/ to find the original apk paths
457 // and puts them in the dex_locations_ vector.
458 bool ComputeDexLocationsFromApkFds() {
459 // We can't use a char array of PATH_MAX size without exceeding the frame size.
460 // So we use a vector as the buffer for the path.
461 std::vector<char> buffer(PATH_MAX, 0);
462 for (size_t i = 0; i < apks_fd_.size(); ++i) {
463 std::string fd_path = "/proc/self/fd/" + std::to_string(apks_fd_[i]);
464 ssize_t len = readlink(fd_path.c_str(), buffer.data(), buffer.size() - 1);
465 if (len == -1) {
466 PLOG(ERROR) << "Could not open path from fd";
467 return false;
468 }
469
470 buffer[len] = '\0';
471 dex_locations_.push_back(buffer.data());
472 }
473 return true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800474 }
475
Mathieu Chartier2f794552017-06-19 10:58:08 -0700476 std::unique_ptr<const ProfileCompilationInfo> LoadProfile(const std::string& filename, int fd) {
477 if (!filename.empty()) {
478 fd = open(filename.c_str(), O_RDWR);
479 if (fd < 0) {
480 LOG(ERROR) << "Cannot open " << filename << strerror(errno);
481 return nullptr;
482 }
483 }
484 std::unique_ptr<ProfileCompilationInfo> info(new ProfileCompilationInfo);
485 if (!info->Load(fd)) {
486 LOG(ERROR) << "Cannot load profile info from fd=" << fd << "\n";
487 return nullptr;
488 }
489 return info;
490 }
491
David Sehrb18991b2017-02-08 20:58:10 -0800492 int DumpOneProfile(const std::string& banner,
493 const std::string& filename,
494 int fd,
495 const std::vector<std::unique_ptr<const DexFile>>* dex_files,
496 std::string* dump) {
Mathieu Chartier2f794552017-06-19 10:58:08 -0700497 std::unique_ptr<const ProfileCompilationInfo> info(LoadProfile(filename, fd));
498 if (info == nullptr) {
499 LOG(ERROR) << "Cannot load profile info from filename=" << filename << " fd=" << fd;
Calin Juravle876f3502016-03-24 16:16:34 +0000500 return -1;
501 }
Mathieu Chartier2f794552017-06-19 10:58:08 -0700502 *dump += banner + "\n" + info->DumpInfo(dex_files) + "\n";
David Sehr4fcdd6d2016-05-24 14:52:31 -0700503 return 0;
504 }
505
506 int DumpProfileInfo() {
David Sehr153da0e2017-02-15 08:54:51 -0800507 // Validate that at least one profile file or reference was specified.
508 if (profile_files_.empty() && profile_files_fd_.empty() &&
509 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
510 Usage("No profile files or reference profile specified.");
511 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700512 static const char* kEmptyString = "";
David Sehr546d24f2016-06-02 10:46:19 -0700513 static const char* kOrdinaryProfile = "=== profile ===";
514 static const char* kReferenceProfile = "=== reference profile ===";
515
David Sehrb18991b2017-02-08 20:58:10 -0800516 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7c80f2d2017-02-07 16:47:58 -0800517 OpenApkFilesFromLocations(&dex_files);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700518 std::string dump;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700519 // Dump individual profile files.
520 if (!profile_files_fd_.empty()) {
521 for (int profile_file_fd : profile_files_fd_) {
David Sehr546d24f2016-06-02 10:46:19 -0700522 int ret = DumpOneProfile(kOrdinaryProfile,
523 kEmptyString,
524 profile_file_fd,
525 &dex_files,
526 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700527 if (ret != 0) {
528 return ret;
529 }
530 }
531 }
532 if (!profile_files_.empty()) {
533 for (const std::string& profile_file : profile_files_) {
David Sehr546d24f2016-06-02 10:46:19 -0700534 int ret = DumpOneProfile(kOrdinaryProfile, profile_file, kInvalidFd, &dex_files, &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700535 if (ret != 0) {
536 return ret;
537 }
538 }
539 }
540 // Dump reference profile file.
541 if (FdIsValid(reference_profile_file_fd_)) {
David Sehr546d24f2016-06-02 10:46:19 -0700542 int ret = DumpOneProfile(kReferenceProfile,
543 kEmptyString,
544 reference_profile_file_fd_,
545 &dex_files,
546 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700547 if (ret != 0) {
548 return ret;
549 }
550 }
551 if (!reference_profile_file_.empty()) {
David Sehr546d24f2016-06-02 10:46:19 -0700552 int ret = DumpOneProfile(kReferenceProfile,
553 reference_profile_file_,
554 kInvalidFd,
555 &dex_files,
David Sehr4fcdd6d2016-05-24 14:52:31 -0700556 &dump);
557 if (ret != 0) {
558 return ret;
559 }
560 }
561 if (!FdIsValid(dump_output_to_fd_)) {
562 std::cout << dump;
563 } else {
564 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
565 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
566 return -1;
567 }
568 }
Calin Juravle876f3502016-03-24 16:16:34 +0000569 return 0;
570 }
571
572 bool ShouldOnlyDumpProfile() {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700573 return dump_only_;
Calin Juravle876f3502016-03-24 16:16:34 +0000574 }
575
Mathieu Chartier34067262017-04-06 13:55:46 -0700576 bool GetClassNamesAndMethods(int fd,
577 std::vector<std::unique_ptr<const DexFile>>* dex_files,
578 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800579 ProfileCompilationInfo profile_info;
580 if (!profile_info.Load(fd)) {
581 LOG(ERROR) << "Cannot load profile info";
582 return false;
583 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700584 for (const std::unique_ptr<const DexFile>& dex_file : *dex_files) {
585 std::set<dex::TypeIndex> class_types;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700586 std::set<uint16_t> hot_methods;
587 std::set<uint16_t> startup_methods;
588 std::set<uint16_t> post_startup_methods;
589 std::set<uint16_t> combined_methods;
590 if (profile_info.GetClassesAndMethods(*dex_file.get(),
591 &class_types,
592 &hot_methods,
593 &startup_methods,
594 &post_startup_methods)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700595 for (const dex::TypeIndex& type_index : class_types) {
596 const DexFile::TypeId& type_id = dex_file->GetTypeId(type_index);
597 out_lines->insert(std::string(dex_file->GetTypeDescriptor(type_id)));
598 }
Mathieu Chartierea650f32017-05-24 12:04:13 -0700599 combined_methods = hot_methods;
600 combined_methods.insert(startup_methods.begin(), startup_methods.end());
601 combined_methods.insert(post_startup_methods.begin(), post_startup_methods.end());
602 for (uint16_t dex_method_idx : combined_methods) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700603 const DexFile::MethodId& id = dex_file->GetMethodId(dex_method_idx);
604 std::string signature_string(dex_file->GetMethodSignature(id).ToString());
605 std::string type_string(dex_file->GetTypeDescriptor(dex_file->GetTypeId(id.class_idx_)));
606 std::string method_name(dex_file->GetMethodName(id));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700607 std::string flags_string;
608 if (hot_methods.find(dex_method_idx) != hot_methods.end()) {
609 flags_string += kMethodFlagStringHot;
610 }
611 if (startup_methods.find(dex_method_idx) != startup_methods.end()) {
612 flags_string += kMethodFlagStringStartup;
613 }
614 if (post_startup_methods.find(dex_method_idx) != post_startup_methods.end()) {
615 flags_string += kMethodFlagStringPostStartup;
616 }
617 out_lines->insert(flags_string +
618 type_string +
619 kMethodSep +
620 method_name +
621 signature_string);
Mathieu Chartier34067262017-04-06 13:55:46 -0700622 }
623 }
624 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800625 return true;
626 }
627
Mathieu Chartier34067262017-04-06 13:55:46 -0700628 bool GetClassNamesAndMethods(const std::string& profile_file,
629 std::vector<std::unique_ptr<const DexFile>>* dex_files,
630 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800631 int fd = open(profile_file.c_str(), O_RDONLY);
632 if (!FdIsValid(fd)) {
633 LOG(ERROR) << "Cannot open " << profile_file << strerror(errno);
634 return false;
635 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700636 if (!GetClassNamesAndMethods(fd, dex_files, out_lines)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800637 return false;
638 }
639 if (close(fd) < 0) {
640 PLOG(WARNING) << "Failed to close descriptor";
641 }
642 return true;
643 }
644
Mathieu Chartierea650f32017-05-24 12:04:13 -0700645 int DumpClassesAndMethods() {
David Sehr153da0e2017-02-15 08:54:51 -0800646 // Validate that at least one profile file or reference was specified.
647 if (profile_files_.empty() && profile_files_fd_.empty() &&
648 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
649 Usage("No profile files or reference profile specified.");
650 }
Calin Juravlee10c1e22018-01-26 20:10:15 -0800651
David Sehr7c80f2d2017-02-07 16:47:58 -0800652 // Open the dex files to get the names for classes.
653 std::vector<std::unique_ptr<const DexFile>> dex_files;
654 OpenApkFilesFromLocations(&dex_files);
655 // Build a vector of class names from individual profile files.
656 std::set<std::string> class_names;
657 if (!profile_files_fd_.empty()) {
658 for (int profile_file_fd : profile_files_fd_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700659 if (!GetClassNamesAndMethods(profile_file_fd, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800660 return -1;
661 }
662 }
663 }
664 if (!profile_files_.empty()) {
665 for (const std::string& profile_file : profile_files_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700666 if (!GetClassNamesAndMethods(profile_file, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800667 return -1;
668 }
669 }
670 }
671 // Concatenate class names from reference profile file.
672 if (FdIsValid(reference_profile_file_fd_)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700673 if (!GetClassNamesAndMethods(reference_profile_file_fd_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800674 return -1;
675 }
676 }
677 if (!reference_profile_file_.empty()) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700678 if (!GetClassNamesAndMethods(reference_profile_file_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800679 return -1;
680 }
681 }
682 // Dump the class names.
683 std::string dump;
684 for (const std::string& class_name : class_names) {
685 dump += class_name + std::string("\n");
686 }
687 if (!FdIsValid(dump_output_to_fd_)) {
688 std::cout << dump;
689 } else {
690 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
691 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
692 return -1;
693 }
694 }
695 return 0;
696 }
697
Mathieu Chartier34067262017-04-06 13:55:46 -0700698 bool ShouldOnlyDumpClassesAndMethods() {
699 return dump_classes_and_methods_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800700 }
701
702 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
703 // the given function.
704 template <typename T>
705 static T* ReadCommentedInputFromFile(
706 const char* input_filename, std::function<std::string(const char*)>* process) {
707 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
708 if (input_file.get() == nullptr) {
709 LOG(ERROR) << "Failed to open input file " << input_filename;
710 return nullptr;
711 }
712 std::unique_ptr<T> result(
713 ReadCommentedInputStream<T>(*input_file, process));
714 input_file->close();
715 return result.release();
716 }
717
718 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
719 // with the given function.
720 template <typename T>
721 static T* ReadCommentedInputStream(
722 std::istream& in_stream,
723 std::function<std::string(const char*)>* process) {
724 std::unique_ptr<T> output(new T());
725 while (in_stream.good()) {
726 std::string dot;
727 std::getline(in_stream, dot);
728 if (android::base::StartsWith(dot, "#") || dot.empty()) {
729 continue;
730 }
731 if (process != nullptr) {
732 std::string descriptor((*process)(dot.c_str()));
733 output->insert(output->end(), descriptor);
734 } else {
735 output->insert(output->end(), dot);
736 }
737 }
738 return output.release();
739 }
740
Calin Juravlee0ac1152017-02-13 19:03:47 -0800741 // Find class klass_descriptor in the given dex_files and store its reference
742 // in the out parameter class_ref.
743 // Return true if the definition of the class was found in any of the dex_files.
744 bool FindClass(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
745 const std::string& klass_descriptor,
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700746 /*out*/TypeReference* class_ref) {
Calin Juravle08556882017-05-26 16:40:45 -0700747 constexpr uint16_t kInvalidTypeIndex = std::numeric_limits<uint16_t>::max() - 1;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800748 for (const std::unique_ptr<const DexFile>& dex_file_ptr : dex_files) {
749 const DexFile* dex_file = dex_file_ptr.get();
Calin Juravle08556882017-05-26 16:40:45 -0700750 if (klass_descriptor == kInvalidClassDescriptor) {
751 if (kInvalidTypeIndex >= dex_file->NumTypeIds()) {
752 // The dex file does not contain all possible type ids which leaves us room
753 // to add an "invalid" type id.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700754 *class_ref = TypeReference(dex_file, dex::TypeIndex(kInvalidTypeIndex));
Calin Juravle08556882017-05-26 16:40:45 -0700755 return true;
756 } else {
757 // The dex file contains all possible type ids. We don't have any free type id
758 // that we can use as invalid.
759 continue;
760 }
761 }
762
Calin Juravlee0ac1152017-02-13 19:03:47 -0800763 const DexFile::TypeId* type_id = dex_file->FindTypeId(klass_descriptor.c_str());
764 if (type_id == nullptr) {
765 continue;
766 }
767 dex::TypeIndex type_index = dex_file->GetIndexForTypeId(*type_id);
768 if (dex_file->FindClassDef(type_index) == nullptr) {
769 // Class is only referenced in the current dex file but not defined in it.
770 continue;
771 }
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700772 *class_ref = TypeReference(dex_file, type_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800773 return true;
774 }
775 return false;
776 }
777
Mathieu Chartier34067262017-04-06 13:55:46 -0700778 // Find the method specified by method_spec in the class class_ref.
Calin Juravle08556882017-05-26 16:40:45 -0700779 uint32_t FindMethodIndex(const TypeReference& class_ref,
780 const std::string& method_spec) {
781 const DexFile* dex_file = class_ref.dex_file;
782 if (method_spec == kInvalidMethod) {
783 constexpr uint16_t kInvalidMethodIndex = std::numeric_limits<uint16_t>::max() - 1;
784 return kInvalidMethodIndex >= dex_file->NumMethodIds()
785 ? kInvalidMethodIndex
Andreas Gampee2abbc62017-09-15 11:59:26 -0700786 : dex::kDexNoIndex;
Calin Juravle08556882017-05-26 16:40:45 -0700787 }
788
Calin Juravlee0ac1152017-02-13 19:03:47 -0800789 std::vector<std::string> name_and_signature;
790 Split(method_spec, kProfileParsingFirstCharInSignature, &name_and_signature);
791 if (name_and_signature.size() != 2) {
792 LOG(ERROR) << "Invalid method name and signature " << method_spec;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700793 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800794 }
Calin Juravle08556882017-05-26 16:40:45 -0700795
Calin Juravlee0ac1152017-02-13 19:03:47 -0800796 const std::string& name = name_and_signature[0];
797 const std::string& signature = kProfileParsingFirstCharInSignature + name_and_signature[1];
Calin Juravlee0ac1152017-02-13 19:03:47 -0800798
799 const DexFile::StringId* name_id = dex_file->FindStringId(name.c_str());
800 if (name_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700801 LOG(WARNING) << "Could not find name: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700802 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800803 }
804 dex::TypeIndex return_type_idx;
805 std::vector<dex::TypeIndex> param_type_idxs;
806 if (!dex_file->CreateTypeList(signature, &return_type_idx, &param_type_idxs)) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700807 LOG(WARNING) << "Could not create type list" << signature;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700808 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800809 }
810 const DexFile::ProtoId* proto_id = dex_file->FindProtoId(return_type_idx, param_type_idxs);
811 if (proto_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700812 LOG(WARNING) << "Could not find proto_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700813 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800814 }
815 const DexFile::MethodId* method_id = dex_file->FindMethodId(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700816 dex_file->GetTypeId(class_ref.TypeIndex()), *name_id, *proto_id);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800817 if (method_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700818 LOG(WARNING) << "Could not find method_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700819 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800820 }
821
Mathieu Chartier34067262017-04-06 13:55:46 -0700822 return dex_file->GetIndexForMethodId(*method_id);
823 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800824
Mathieu Chartier34067262017-04-06 13:55:46 -0700825 // Given a method, return true if the method has a single INVOKE_VIRTUAL in its byte code.
826 // Upon success it returns true and stores the method index and the invoke dex pc
827 // in the output parameters.
828 // The format of the method spec is "inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
829 //
830 // TODO(calin): support INVOKE_INTERFACE and the range variants.
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700831 bool HasSingleInvoke(const TypeReference& class_ref,
Mathieu Chartier34067262017-04-06 13:55:46 -0700832 uint16_t method_index,
833 /*out*/uint32_t* dex_pc) {
834 const DexFile* dex_file = class_ref.dex_file;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800835 uint32_t offset = dex_file->FindCodeItemOffset(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700836 *dex_file->FindClassDef(class_ref.TypeIndex()),
Mathieu Chartier34067262017-04-06 13:55:46 -0700837 method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800838 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(offset);
839
840 bool found_invoke = false;
Mathieu Chartier698ebbc2018-01-05 11:00:42 -0800841 for (const DexInstructionPcPair& inst : CodeItemInstructionAccessor(*dex_file, code_item)) {
Rico Windc24fa5d2018-04-25 12:44:58 +0200842 if (inst->Opcode() == Instruction::INVOKE_VIRTUAL ||
843 inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800844 if (found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700845 LOG(ERROR) << "Multiple invoke INVOKE_VIRTUAL found: "
846 << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800847 return false;
848 }
849 found_invoke = true;
Mathieu Chartier0021feb2017-11-07 00:08:52 -0800850 *dex_pc = inst.DexPc();
Calin Juravlee0ac1152017-02-13 19:03:47 -0800851 }
852 }
853 if (!found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700854 LOG(ERROR) << "Could not find any INVOKE_VIRTUAL: " << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800855 }
856 return found_invoke;
857 }
858
859 // Process a line defining a class or a method and its inline caches.
860 // Upon success return true and add the class or the method info to profile.
Calin Juravle589e71e2017-03-03 16:05:05 -0800861 // The possible line formats are:
862 // "LJustTheCass;".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800863 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
Calin Juravle08556882017-05-26 16:40:45 -0700864 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,invalid_class".
Calin Juravle589e71e2017-03-03 16:05:05 -0800865 // "LTestInline;->inlineMissingTypes(LSuper;)I+missing_types".
866 // "LTestInline;->inlineNoInlineCaches(LSuper;)I".
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700867 // "LTestInline;->*".
Calin Juravle08556882017-05-26 16:40:45 -0700868 // "invalid_class".
869 // "LTestInline;->invalid_method".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800870 // The method and classes are searched only in the given dex files.
871 bool ProcessLine(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
872 const std::string& line,
873 /*out*/ProfileCompilationInfo* profile) {
874 std::string klass;
875 std::string method_str;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700876 bool is_hot = false;
877 bool is_startup = false;
878 bool is_post_startup = false;
879 const size_t method_sep_index = line.find(kMethodSep, 0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800880 if (method_sep_index == std::string::npos) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700881 klass = line.substr(0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800882 } else {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700883 // The method prefix flags are only valid for method strings.
884 size_t start_index = 0;
885 while (start_index < line.size() && line[start_index] != 'L') {
886 const char c = line[start_index];
887 if (c == kMethodFlagStringHot) {
888 is_hot = true;
889 } else if (c == kMethodFlagStringStartup) {
890 is_startup = true;
891 } else if (c == kMethodFlagStringPostStartup) {
892 is_post_startup = true;
893 } else {
894 LOG(WARNING) << "Invalid flag " << c;
895 return false;
896 }
897 ++start_index;
898 }
899 klass = line.substr(start_index, method_sep_index - start_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800900 method_str = line.substr(method_sep_index + kMethodSep.size());
901 }
902
Calin Juravleee9cb412018-02-13 20:32:35 -0800903 uint32_t flags = 0;
904 if (is_hot) {
905 flags |= ProfileCompilationInfo::MethodHotness::kFlagHot;
906 }
907 if (is_startup) {
908 flags |= ProfileCompilationInfo::MethodHotness::kFlagStartup;
909 }
910 if (is_post_startup) {
911 flags |= ProfileCompilationInfo::MethodHotness::kFlagPostStartup;
912 }
913
Vladimir Markof3c52b42017-11-17 17:32:12 +0000914 TypeReference class_ref(/* dex_file */ nullptr, dex::TypeIndex());
Calin Juravlee0ac1152017-02-13 19:03:47 -0800915 if (!FindClass(dex_files, klass, &class_ref)) {
Mathieu Chartier3f121342017-03-06 11:16:20 -0800916 LOG(WARNING) << "Could not find class: " << klass;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800917 return false;
918 }
919
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700920 if (method_str.empty() || method_str == kClassAllMethods) {
921 // Start by adding the class.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800922 std::set<DexCacheResolvedClasses> resolved_class_set;
923 const DexFile* dex_file = class_ref.dex_file;
924 const auto& dex_resolved_classes = resolved_class_set.emplace(
925 dex_file->GetLocation(),
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700926 DexFileLoader::GetBaseLocation(dex_file->GetLocation()),
Mathieu Chartierea650f32017-05-24 12:04:13 -0700927 dex_file->GetLocationChecksum(),
928 dex_file->NumMethodIds());
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700929 dex_resolved_classes.first->AddClass(class_ref.TypeIndex());
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700930 std::vector<ProfileMethodInfo> methods;
931 if (method_str == kClassAllMethods) {
932 // Add all of the methods.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700933 const DexFile::ClassDef* class_def = dex_file->FindClassDef(class_ref.TypeIndex());
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700934 const uint8_t* class_data = dex_file->GetClassData(*class_def);
935 if (class_data != nullptr) {
936 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700937 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800938 while (it.HasNextMethod()) {
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700939 if (it.GetMethodCodeItemOffset() != 0) {
940 // Add all of the methods that have code to the profile.
941 const uint32_t method_idx = it.GetMemberIndex();
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700942 methods.push_back(ProfileMethodInfo(MethodReference(dex_file, method_idx)));
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700943 }
944 it.Next();
945 }
946 }
947 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700948 // TODO: Check return values?
Calin Juravleee9cb412018-02-13 20:32:35 -0800949 profile->AddMethods(methods, static_cast<ProfileCompilationInfo::MethodHotness::Flag>(flags));
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700950 profile->AddClasses(resolved_class_set);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800951 return true;
952 }
953
954 // Process the method.
955 std::string method_spec;
956 std::vector<std::string> inline_cache_elems;
957
Mathieu Chartierea650f32017-05-24 12:04:13 -0700958 // If none of the flags are set, default to hot.
959 is_hot = is_hot || (!is_hot && !is_startup && !is_post_startup);
960
Calin Juravlee0ac1152017-02-13 19:03:47 -0800961 std::vector<std::string> method_elems;
Calin Juravle589e71e2017-03-03 16:05:05 -0800962 bool is_missing_types = false;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800963 Split(method_str, kProfileParsingInlineChacheSep, &method_elems);
964 if (method_elems.size() == 2) {
965 method_spec = method_elems[0];
Calin Juravle589e71e2017-03-03 16:05:05 -0800966 is_missing_types = method_elems[1] == kMissingTypesMarker;
967 if (!is_missing_types) {
968 Split(method_elems[1], kProfileParsingTypeSep, &inline_cache_elems);
969 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800970 } else if (method_elems.size() == 1) {
971 method_spec = method_elems[0];
972 } else {
973 LOG(ERROR) << "Invalid method line: " << line;
974 return false;
975 }
976
Mathieu Chartier34067262017-04-06 13:55:46 -0700977 const uint32_t method_index = FindMethodIndex(class_ref, method_spec);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700978 if (method_index == dex::kDexNoIndex) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800979 return false;
980 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700981
Mathieu Chartier34067262017-04-06 13:55:46 -0700982 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
983 if (is_missing_types || !inline_cache_elems.empty()) {
984 uint32_t dex_pc;
985 if (!HasSingleInvoke(class_ref, method_index, &dex_pc)) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800986 return false;
987 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000988 std::vector<TypeReference> classes(inline_cache_elems.size(),
989 TypeReference(/* dex_file */ nullptr, dex::TypeIndex()));
Mathieu Chartier34067262017-04-06 13:55:46 -0700990 size_t class_it = 0;
991 for (const std::string& ic_class : inline_cache_elems) {
992 if (!FindClass(dex_files, ic_class, &(classes[class_it++]))) {
993 LOG(ERROR) << "Could not find class: " << ic_class;
994 return false;
995 }
996 }
997 inline_caches.emplace_back(dex_pc, is_missing_types, classes);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800998 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700999 MethodReference ref(class_ref.dex_file, method_index);
Mathieu Chartierea650f32017-05-24 12:04:13 -07001000 if (is_hot) {
Calin Juravleee9cb412018-02-13 20:32:35 -08001001 profile->AddMethod(ProfileMethodInfo(ref, inline_caches),
1002 static_cast<ProfileCompilationInfo::MethodHotness::Flag>(flags));
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001003 }
1004 if (flags != 0) {
Calin Juravleee9cb412018-02-13 20:32:35 -08001005 if (!profile->AddMethodIndex(
1006 static_cast<ProfileCompilationInfo::MethodHotness::Flag>(flags), ref)) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001007 return false;
1008 }
Mathieu Chartiere46f3a82017-06-19 19:54:12 -07001009 DCHECK(profile->GetMethodHotness(ref).IsInProfile());
Mathieu Chartierea650f32017-05-24 12:04:13 -07001010 }
Calin Juravlee0ac1152017-02-13 19:03:47 -08001011 return true;
1012 }
1013
Mathieu Chartier2f794552017-06-19 10:58:08 -07001014 int OpenReferenceProfile() const {
1015 int fd = reference_profile_file_fd_;
1016 if (!FdIsValid(fd)) {
1017 CHECK(!reference_profile_file_.empty());
1018 fd = open(reference_profile_file_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
1019 if (fd < 0) {
1020 LOG(ERROR) << "Cannot open " << reference_profile_file_ << strerror(errno);
1021 return kInvalidFd;
1022 }
1023 }
1024 return fd;
1025 }
1026
Calin Juravlee0ac1152017-02-13 19:03:47 -08001027 // Creates a profile from a human friendly textual representation.
1028 // The expected input format is:
1029 // # Classes
1030 // Ljava/lang/Comparable;
1031 // Ljava/lang/Math;
1032 // # Methods with inline caches
1033 // LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;
1034 // LTestInline;->noInlineCache(LSuper;)I
David Sehr7c80f2d2017-02-07 16:47:58 -08001035 int CreateProfile() {
David Sehr153da0e2017-02-15 08:54:51 -08001036 // Validate parameters for this command.
1037 if (apk_files_.empty() && apks_fd_.empty()) {
1038 Usage("APK files must be specified");
1039 }
1040 if (dex_locations_.empty()) {
1041 Usage("DEX locations must be specified");
1042 }
1043 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
1044 Usage("Reference profile must be specified with --reference-profile-file or "
1045 "--reference-profile-file-fd");
1046 }
1047 if (!profile_files_.empty() || !profile_files_fd_.empty()) {
1048 Usage("Profile must be specified with --reference-profile-file or "
1049 "--reference-profile-file-fd");
1050 }
David Sehr7c80f2d2017-02-07 16:47:58 -08001051 // Open the profile output file if needed.
Mathieu Chartier2f794552017-06-19 10:58:08 -07001052 int fd = OpenReferenceProfile();
David Sehr7c80f2d2017-02-07 16:47:58 -08001053 if (!FdIsValid(fd)) {
David Sehr7c80f2d2017-02-07 16:47:58 -08001054 return -1;
David Sehr7c80f2d2017-02-07 16:47:58 -08001055 }
Calin Juravlee0ac1152017-02-13 19:03:47 -08001056 // Read the user-specified list of classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -08001057 std::unique_ptr<std::unordered_set<std::string>>
Calin Juravlee0ac1152017-02-13 19:03:47 -08001058 user_lines(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
David Sehr7c80f2d2017-02-07 16:47:58 -08001059 create_profile_from_file_.c_str(), nullptr)); // No post-processing.
Calin Juravlee0ac1152017-02-13 19:03:47 -08001060
1061 // Open the dex files to look up classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -08001062 std::vector<std::unique_ptr<const DexFile>> dex_files;
1063 OpenApkFilesFromLocations(&dex_files);
Calin Juravlee0ac1152017-02-13 19:03:47 -08001064
1065 // Process the lines one by one and add the successful ones to the profile.
David Sehr7c80f2d2017-02-07 16:47:58 -08001066 ProfileCompilationInfo info;
Calin Juravlee0ac1152017-02-13 19:03:47 -08001067
1068 for (const auto& line : *user_lines) {
1069 ProcessLine(dex_files, line, &info);
1070 }
1071
David Sehr7c80f2d2017-02-07 16:47:58 -08001072 // Write the profile file.
1073 CHECK(info.Save(fd));
1074 if (close(fd) < 0) {
1075 PLOG(WARNING) << "Failed to close descriptor";
1076 }
1077 return 0;
1078 }
1079
Mathieu Chartier2f794552017-06-19 10:58:08 -07001080 bool ShouldCreateBootProfile() const {
1081 return generate_boot_image_profile_;
1082 }
1083
1084 int CreateBootProfile() {
Mathieu Chartier2f794552017-06-19 10:58:08 -07001085 // Open the profile output file.
1086 const int reference_fd = OpenReferenceProfile();
1087 if (!FdIsValid(reference_fd)) {
1088 PLOG(ERROR) << "Error opening reference profile";
1089 return -1;
1090 }
1091 // Open the dex files.
1092 std::vector<std::unique_ptr<const DexFile>> dex_files;
1093 OpenApkFilesFromLocations(&dex_files);
1094 if (dex_files.empty()) {
1095 PLOG(ERROR) << "Expected dex files for creating boot profile";
1096 return -2;
1097 }
1098 // Open the input profiles.
1099 std::vector<std::unique_ptr<const ProfileCompilationInfo>> profiles;
1100 if (!profile_files_fd_.empty()) {
1101 for (int profile_file_fd : profile_files_fd_) {
1102 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile("", profile_file_fd));
1103 if (profile == nullptr) {
1104 return -3;
1105 }
1106 profiles.emplace_back(std::move(profile));
1107 }
1108 }
1109 if (!profile_files_.empty()) {
1110 for (const std::string& profile_file : profile_files_) {
1111 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile(profile_file, kInvalidFd));
1112 if (profile == nullptr) {
1113 return -4;
1114 }
1115 profiles.emplace_back(std::move(profile));
1116 }
1117 }
1118 ProfileCompilationInfo out_profile;
1119 GenerateBootImageProfile(dex_files,
1120 profiles,
1121 boot_image_options_,
1122 VLOG_IS_ON(profiler),
1123 &out_profile);
1124 out_profile.Save(reference_fd);
1125 close(reference_fd);
1126 return 0;
1127 }
1128
David Sehr7c80f2d2017-02-07 16:47:58 -08001129 bool ShouldCreateProfile() {
1130 return !create_profile_from_file_.empty();
1131 }
1132
Calin Juravle7bcdb532016-06-07 16:14:47 +01001133 int GenerateTestProfile() {
David Sehr153da0e2017-02-15 08:54:51 -08001134 // Validate parameters for this command.
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001135 if (test_profile_method_percerntage_ > 100) {
1136 Usage("Invalid percentage for --generate-test-profile-method-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001137 }
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001138 if (test_profile_class_percentage_ > 100) {
1139 Usage("Invalid percentage for --generate-test-profile-class-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001140 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001141 // If given APK files or DEX locations, check that they're ok.
1142 if (!apk_files_.empty() || !apks_fd_.empty() || !dex_locations_.empty()) {
1143 if (apk_files_.empty() && apks_fd_.empty()) {
1144 Usage("APK files must be specified when passing DEX locations to --generate-test-profile");
1145 }
1146 if (dex_locations_.empty()) {
1147 Usage("DEX locations must be specified when passing APK files to --generate-test-profile");
1148 }
1149 }
David Sehr153da0e2017-02-15 08:54:51 -08001150 // ShouldGenerateTestProfile confirms !test_profile_.empty().
George Burgess IV71f77262016-10-25 13:08:17 -07001151 int profile_test_fd = open(test_profile_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001152 if (profile_test_fd < 0) {
David Sehr7c80f2d2017-02-07 16:47:58 -08001153 LOG(ERROR) << "Cannot open " << test_profile_ << strerror(errno);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001154 return -1;
1155 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001156 bool result;
1157 if (apk_files_.empty() && apks_fd_.empty() && dex_locations_.empty()) {
1158 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1159 test_profile_num_dex_,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001160 test_profile_method_percerntage_,
1161 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001162 test_profile_seed_);
1163 } else {
Jeff Haof0a31f82017-03-27 15:50:37 -07001164 // Open the dex files to look up classes and methods.
1165 std::vector<std::unique_ptr<const DexFile>> dex_files;
1166 OpenApkFilesFromLocations(&dex_files);
1167 // Create a random profile file based on the set of dex files.
1168 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1169 dex_files,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001170 test_profile_method_percerntage_,
1171 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001172 test_profile_seed_);
1173 }
Calin Juravle7bcdb532016-06-07 16:14:47 +01001174 close(profile_test_fd); // ignore close result.
1175 return result ? 0 : -1;
1176 }
1177
1178 bool ShouldGenerateTestProfile() {
1179 return !test_profile_.empty();
1180 }
1181
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001182 bool ShouldCopyAndUpdateProfileKey() const {
1183 return copy_and_update_profile_key_;
1184 }
1185
Calin Juravle02c08792018-02-15 19:40:48 -08001186 int32_t CopyAndUpdateProfileKey() {
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001187 // Validate that at least one profile file was passed, as well as a reference profile.
1188 if (!(profile_files_.size() == 1 ^ profile_files_fd_.size() == 1)) {
1189 Usage("Only one profile file should be specified.");
1190 }
1191 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
1192 Usage("No reference profile file specified.");
1193 }
1194
1195 if (apk_files_.empty() && apks_fd_.empty()) {
1196 Usage("No apk files specified");
1197 }
1198
Calin Juravle02c08792018-02-15 19:40:48 -08001199 static constexpr int32_t kErrorFailedToUpdateProfile = -1;
1200 static constexpr int32_t kErrorFailedToSaveProfile = -2;
1201 static constexpr int32_t kErrorFailedToLoadProfile = -3;
1202
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001203 bool use_fds = profile_files_fd_.size() == 1;
1204
1205 ProfileCompilationInfo profile;
1206 // Do not clear if invalid. The input might be an archive.
Calin Juravle02c08792018-02-15 19:40:48 -08001207 bool load_ok = use_fds
1208 ? profile.Load(profile_files_fd_[0])
1209 : profile.Load(profile_files_[0], /*clear_if_invalid*/ false);
1210 if (load_ok) {
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001211 // Open the dex files to look up classes and methods.
1212 std::vector<std::unique_ptr<const DexFile>> dex_files;
1213 OpenApkFilesFromLocations(&dex_files);
1214 if (!profile.UpdateProfileKeys(dex_files)) {
Calin Juravle02c08792018-02-15 19:40:48 -08001215 return kErrorFailedToUpdateProfile;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001216 }
Calin Juravle02c08792018-02-15 19:40:48 -08001217 bool result = use_fds
1218 ? profile.Save(reference_profile_file_fd_)
1219 : profile.Save(reference_profile_file_, /*bytes_written*/ nullptr);
1220 return result ? 0 : kErrorFailedToSaveProfile;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001221 } else {
Calin Juravle02c08792018-02-15 19:40:48 -08001222 return kErrorFailedToLoadProfile;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001223 }
1224 }
1225
Calin Juravle2e2db782016-02-23 12:00:03 +00001226 private:
1227 static void ParseFdForCollection(const StringPiece& option,
1228 const char* arg_name,
1229 std::vector<int>* fds) {
1230 int fd;
1231 ParseUintOption(option, arg_name, &fd, Usage);
1232 fds->push_back(fd);
1233 }
1234
1235 static void CloseAllFds(const std::vector<int>& fds, const char* descriptor) {
1236 for (size_t i = 0; i < fds.size(); i++) {
1237 if (close(fds[i]) < 0) {
Calin Juravlee10c1e22018-01-26 20:10:15 -08001238 PLOG(WARNING) << "Failed to close descriptor for "
1239 << descriptor << " at index " << i << ": " << fds[i];
Calin Juravle2e2db782016-02-23 12:00:03 +00001240 }
1241 }
1242 }
1243
1244 void LogCompletionTime() {
David Sehr52683cf2016-05-05 09:02:38 -07001245 static constexpr uint64_t kLogThresholdTime = MsToNs(100); // 100ms
1246 uint64_t time_taken = NanoTime() - start_ns_;
David Sehred793012016-05-05 13:39:43 -07001247 if (time_taken > kLogThresholdTime) {
David Sehrd8557182016-05-06 12:29:35 -07001248 LOG(WARNING) << "profman took " << PrettyDuration(time_taken);
David Sehred793012016-05-05 13:39:43 -07001249 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001250 }
1251
1252 std::vector<std::string> profile_files_;
1253 std::vector<int> profile_files_fd_;
David Sehr546d24f2016-06-02 10:46:19 -07001254 std::vector<std::string> dex_locations_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001255 std::vector<std::string> apk_files_;
David Sehr546d24f2016-06-02 10:46:19 -07001256 std::vector<int> apks_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001257 std::string reference_profile_file_;
1258 int reference_profile_file_fd_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001259 bool dump_only_;
Mathieu Chartier34067262017-04-06 13:55:46 -07001260 bool dump_classes_and_methods_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001261 bool generate_boot_image_profile_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001262 int dump_output_to_fd_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001263 BootImageOptions boot_image_options_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001264 std::string test_profile_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001265 std::string create_profile_from_file_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001266 uint16_t test_profile_num_dex_;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001267 uint16_t test_profile_method_percerntage_;
1268 uint16_t test_profile_class_percentage_;
Jeff Haof0a31f82017-03-27 15:50:37 -07001269 uint32_t test_profile_seed_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001270 uint64_t start_ns_;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001271 bool copy_and_update_profile_key_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001272};
1273
1274// See ProfileAssistant::ProcessingResult for return codes.
1275static int profman(int argc, char** argv) {
1276 ProfMan profman;
1277
1278 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1279 profman.ParseArgs(argc, argv);
1280
Calin Juravlee10c1e22018-01-26 20:10:15 -08001281 // Initialize MemMap for ZipArchive::OpenFromFd.
1282 MemMap::Init();
1283
Calin Juravle7bcdb532016-06-07 16:14:47 +01001284 if (profman.ShouldGenerateTestProfile()) {
1285 return profman.GenerateTestProfile();
1286 }
Calin Juravle876f3502016-03-24 16:16:34 +00001287 if (profman.ShouldOnlyDumpProfile()) {
1288 return profman.DumpProfileInfo();
1289 }
Mathieu Chartier34067262017-04-06 13:55:46 -07001290 if (profman.ShouldOnlyDumpClassesAndMethods()) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001291 return profman.DumpClassesAndMethods();
David Sehr7c80f2d2017-02-07 16:47:58 -08001292 }
1293 if (profman.ShouldCreateProfile()) {
1294 return profman.CreateProfile();
1295 }
Mathieu Chartier2f794552017-06-19 10:58:08 -07001296
1297 if (profman.ShouldCreateBootProfile()) {
1298 return profman.CreateBootProfile();
1299 }
Calin Juravle02c08792018-02-15 19:40:48 -08001300
1301 if (profman.ShouldCopyAndUpdateProfileKey()) {
1302 return profman.CopyAndUpdateProfileKey();
1303 }
1304
Calin Juravle2e2db782016-02-23 12:00:03 +00001305 // Process profile information and assess if we need to do a profile guided compilation.
1306 // This operation involves I/O.
1307 return profman.ProcessProfiles();
1308}
1309
1310} // namespace art
1311
1312int main(int argc, char **argv) {
1313 return art::profman(argc, argv);
1314}