blob: b76bb2edf3d214b54ae799672a7b072191ac085e [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>
Vladimir Markoe5125562019-02-06 17:38:26 +000028#include <string_view>
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 Sehr671af6c2018-05-17 11:00:35 -070037#include "base/mem_map.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000038#include "base/scoped_flock.h"
Mathieu Chartier0573f852018-10-01 13:52:12 -070039#include "base/stl_util.h"
Vladimir Markoe5125562019-02-06 17:38:26 +000040#include "base/string_view_cpp20.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000041#include "base/time_utils.h"
42#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080043#include "base/utils.h"
David Sehr79e26072018-04-06 17:58:50 -070044#include "base/zip_archive.h"
Mathieu Chartier2f794552017-06-19 10:58:08 -070045#include "boot_image_profile.h"
Mathieu Chartier818cb802018-05-11 05:30:16 +000046#include "dex/art_dex_file_loader.h"
David Sehr312f3b22018-03-19 08:39:26 -070047#include "dex/bytecode_utils.h"
Mathieu Chartier20f49922018-05-24 16:04:17 -070048#include "dex/class_accessor-inl.h"
David Sehr9e734c72018-01-04 17:56:19 -080049#include "dex/code_item_accessors-inl.h"
50#include "dex/dex_file.h"
51#include "dex/dex_file_loader.h"
52#include "dex/dex_file_types.h"
David Sehr312f3b22018-03-19 08:39:26 -070053#include "dex/type_reference.h"
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +010054#include "profile/profile_boot_info.h"
David Sehr82d046e2018-04-23 08:14:19 -070055#include "profile/profile_compilation_info.h"
Mathieu Chartierdbddc222017-05-24 12:04:13 -070056#include "profile_assistant.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000057
58namespace art {
59
60static int original_argc;
61static char** original_argv;
62
63static std::string CommandLine() {
64 std::vector<std::string> command;
Andreas Gampe2a487eb2018-11-19 11:41:22 -080065 command.reserve(original_argc);
Calin Juravle2e2db782016-02-23 12:00:03 +000066 for (int i = 0; i < original_argc; ++i) {
67 command.push_back(original_argv[i]);
68 }
Andreas Gampe9186ced2016-12-12 14:28:21 -080069 return android::base::Join(command, ' ');
Calin Juravle2e2db782016-02-23 12:00:03 +000070}
71
David Sehr4fcdd6d2016-05-24 14:52:31 -070072static constexpr int kInvalidFd = -1;
73
74static bool FdIsValid(int fd) {
75 return fd != kInvalidFd;
76}
77
Calin Juravle2e2db782016-02-23 12:00:03 +000078static void UsageErrorV(const char* fmt, va_list ap) {
79 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080080 android::base::StringAppendV(&error, fmt, ap);
Calin Juravle2e2db782016-02-23 12:00:03 +000081 LOG(ERROR) << error;
82}
83
84static void UsageError(const char* fmt, ...) {
85 va_list ap;
86 va_start(ap, fmt);
87 UsageErrorV(fmt, ap);
88 va_end(ap);
89}
90
91NO_RETURN static void Usage(const char *fmt, ...) {
92 va_list ap;
93 va_start(ap, fmt);
94 UsageErrorV(fmt, ap);
95 va_end(ap);
96
97 UsageError("Command: %s", CommandLine().c_str());
98 UsageError("Usage: profman [options]...");
99 UsageError("");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700100 UsageError(" --dump-only: dumps the content of the specified profile files");
101 UsageError(" to standard output (default) in a human readable form.");
102 UsageError("");
David Sehr7c80f2d2017-02-07 16:47:58 -0800103 UsageError(" --dump-output-to-fd=<number>: redirects --dump-only output to a file descriptor.");
104 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -0700105 UsageError(" --dump-classes-and-methods: dumps a sorted list of classes and methods that are");
106 UsageError(" in the specified profile file to standard output (default) in a human");
107 UsageError(" readable form. The output is valid input for --create-profile-from");
Calin Juravle876f3502016-03-24 16:16:34 +0000108 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000109 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
110 UsageError(" Can be specified multiple time, in which case the data from the different");
111 UsageError(" profiles will be aggregated.");
112 UsageError("");
113 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
114 UsageError(" Cannot be used together with --profile-file.");
115 UsageError("");
116 UsageError(" --reference-profile-file=<filename>: specify a reference profile.");
117 UsageError(" The data in this file will be compared with the data obtained by merging");
118 UsageError(" all the files specified with --profile-file or --profile-file-fd.");
119 UsageError(" If the exit code is EXIT_COMPILE then all --profile-file will be merged into");
120 UsageError(" --reference-profile-file. ");
121 UsageError("");
122 UsageError(" --reference-profile-file-fd=<number>: same as --reference-profile-file but");
123 UsageError(" accepts a file descriptor. Cannot be used together with");
124 UsageError(" --reference-profile-file.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800125 UsageError("");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100126 UsageError(" --generate-test-profile=<filename>: generates a random profile file for testing.");
127 UsageError(" --generate-test-profile-num-dex=<number>: number of dex files that should be");
128 UsageError(" included in the generated profile. Defaults to 20.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700129 UsageError(" --generate-test-profile-method-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100130 UsageError(" number of methods that should be generated. Defaults to 5.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700131 UsageError(" --generate-test-profile-class-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100132 UsageError(" number of classes that should be generated. Defaults to 5.");
Jeff Haof0a31f82017-03-27 15:50:37 -0700133 UsageError(" --generate-test-profile-seed=<number>: seed for random number generator used when");
134 UsageError(" generating random test profiles. Defaults to using NanoTime.");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100135 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -0700136 UsageError(" --create-profile-from=<filename>: creates a profile from a list of classes and");
137 UsageError(" methods.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800138 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700139 UsageError(" --dex-location=<string>: location string to use with corresponding");
140 UsageError(" apk-fd to find dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700141 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700142 UsageError(" --apk-fd=<number>: file descriptor containing an open APK to");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700143 UsageError(" search for dex files");
David Sehr7c80f2d2017-02-07 16:47:58 -0800144 UsageError(" --apk-=<filename>: an APK to search for dex files");
David Brazdilf13ac7c2018-01-30 10:09:08 +0000145 UsageError(" --skip-apk-verification: do not attempt to verify APKs");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700146 UsageError("");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700147 UsageError(" --generate-boot-image-profile: Generate a boot image profile based on input");
148 UsageError(" profiles. Requires passing in dex files to inspect properties of classes.");
149 UsageError(" --boot-image-class-threshold=<value>: specify minimum number of class occurrences");
150 UsageError(" to include a class in the boot image profile. Default is 10.");
151 UsageError(" --boot-image-clean-class-threshold=<value>: specify minimum number of clean class");
152 UsageError(" occurrences to include a class in the boot image profile. A clean class is a");
153 UsageError(" class that doesn't have any static fields or native methods and is likely to");
154 UsageError(" remain clean in the image. Default is 3.");
Mathieu Chartier8eecddf2017-07-12 16:05:54 -0700155 UsageError(" --boot-image-sampled-method-threshold=<value>: minimum number of profiles a");
156 UsageError(" non-hot method needs to be in order to be hot in the output profile. The");
157 UsageError(" default is max int.");
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800158 UsageError(" --copy-and-update-profile-key: if present, profman will copy the profile from");
159 UsageError(" the file passed with --profile-fd(file) to the profile passed with");
160 UsageError(" --reference-profile-fd(file) and update at the same time the profile-key");
161 UsageError(" of entries corresponding to the apks passed with --apk(-fd).");
Calin Juravle0e82e0f2019-11-11 18:34:10 -0800162 UsageError(" --boot-image-merge: indicates that this merge is for a boot image profile.");
163 UsageError(" In this case, the reference profile must have a boot profile version.");
164 UsageError(" --force-merge: performs a forced merge, without analyzing if there is a");
165 UsageError(" significant difference between the current profile and the reference profile.");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700166 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000167
168 exit(EXIT_FAILURE);
169}
170
Calin Juravle7bcdb532016-06-07 16:14:47 +0100171// Note: make sure you update the Usage if you change these values.
172static constexpr uint16_t kDefaultTestProfileNumDex = 20;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700173static constexpr uint16_t kDefaultTestProfileMethodPercentage = 5;
174static constexpr uint16_t kDefaultTestProfileClassPercentage = 5;
Calin Juravle7bcdb532016-06-07 16:14:47 +0100175
Calin Juravlee0ac1152017-02-13 19:03:47 -0800176// Separators used when parsing human friendly representation of profiles.
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800177static const std::string kMethodSep = "->"; // NOLINT [runtime/string] [4]
178static const std::string kMissingTypesMarker = "missing_types"; // NOLINT [runtime/string] [4]
179static const std::string kInvalidClassDescriptor = "invalid_class"; // NOLINT [runtime/string] [4]
180static const std::string kInvalidMethod = "invalid_method"; // NOLINT [runtime/string] [4]
181static const std::string kClassAllMethods = "*"; // NOLINT [runtime/string] [4]
Calin Juravlee0ac1152017-02-13 19:03:47 -0800182static constexpr char kProfileParsingInlineChacheSep = '+';
183static constexpr char kProfileParsingTypeSep = ',';
184static constexpr char kProfileParsingFirstCharInSignature = '(';
Mathieu Chartierea650f32017-05-24 12:04:13 -0700185static constexpr char kMethodFlagStringHot = 'H';
186static constexpr char kMethodFlagStringStartup = 'S';
187static constexpr char kMethodFlagStringPostStartup = 'P';
Calin Juravlee0ac1152017-02-13 19:03:47 -0800188
David Sehr671af6c2018-05-17 11:00:35 -0700189NO_RETURN static void Abort(const char* msg) {
190 LOG(ERROR) << msg;
191 exit(1);
192}
193
Vladimir Markoe5125562019-02-06 17:38:26 +0000194template <typename T>
195static void ParseUintOption(const char* raw_option,
196 std::string_view option_prefix,
197 T* out) {
198 DCHECK(EndsWith(option_prefix, "="));
199 DCHECK(StartsWith(raw_option, option_prefix)) << raw_option << " " << option_prefix;
200 const char* value_string = raw_option + option_prefix.size();
201 int64_t parsed_integer_value = 0;
202 if (!android::base::ParseInt(value_string, &parsed_integer_value)) {
203 std::string option_name(option_prefix.substr(option_prefix.size() - 1u));
204 Usage("Failed to parse %s '%s' as an integer", option_name.c_str(), value_string);
205 }
206 if (parsed_integer_value < 0) {
207 std::string option_name(option_prefix.substr(option_prefix.size() - 1u));
208 Usage("%s passed a negative value %" PRId64, option_name.c_str(), parsed_integer_value);
209 }
210 if (static_cast<uint64_t>(parsed_integer_value) >
211 static_cast<std::make_unsigned_t<T>>(std::numeric_limits<T>::max())) {
212 std::string option_name(option_prefix.substr(option_prefix.size() - 1u));
213 Usage("%s passed a value %" PRIu64 " above max (%" PRIu64 ")",
214 option_name.c_str(),
215 static_cast<uint64_t>(parsed_integer_value),
216 static_cast<uint64_t>(std::numeric_limits<T>::max()));
217 }
218 *out = dchecked_integral_cast<T>(parsed_integer_value);
219}
220
Calin Juravlee0ac1152017-02-13 19:03:47 -0800221// TODO(calin): This class has grown too much from its initial design. Split the functionality
222// into smaller, more contained pieces.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100223class ProfMan final {
Calin Juravle2e2db782016-02-23 12:00:03 +0000224 public:
225 ProfMan() :
David Sehr4fcdd6d2016-05-24 14:52:31 -0700226 reference_profile_file_fd_(kInvalidFd),
227 dump_only_(false),
Mathieu Chartier34067262017-04-06 13:55:46 -0700228 dump_classes_and_methods_(false),
Mathieu Chartier2f794552017-06-19 10:58:08 -0700229 generate_boot_image_profile_(false),
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +0100230 generate_boot_profile_(false),
David Sehr4fcdd6d2016-05-24 14:52:31 -0700231 dump_output_to_fd_(kInvalidFd),
Calin Juravle7bcdb532016-06-07 16:14:47 +0100232 test_profile_num_dex_(kDefaultTestProfileNumDex),
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700233 test_profile_method_percerntage_(kDefaultTestProfileMethodPercentage),
234 test_profile_class_percentage_(kDefaultTestProfileClassPercentage),
Jeff Haof0a31f82017-03-27 15:50:37 -0700235 test_profile_seed_(NanoTime()),
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800236 start_ns_(NanoTime()),
Calin Juravle0e82e0f2019-11-11 18:34:10 -0800237 copy_and_update_profile_key_(false),
238 profile_assistant_options_(ProfileAssistant::Options()) {}
Calin Juravle2e2db782016-02-23 12:00:03 +0000239
240 ~ProfMan() {
241 LogCompletionTime();
242 }
243
244 void ParseArgs(int argc, char **argv) {
245 original_argc = argc;
246 original_argv = argv;
247
David Sehr671af6c2018-05-17 11:00:35 -0700248 MemMap::Init();
249 InitLogging(argv, Abort);
Calin Juravle2e2db782016-02-23 12:00:03 +0000250
251 // Skip over the command name.
252 argv++;
253 argc--;
254
255 if (argc == 0) {
256 Usage("No arguments specified");
257 }
258
259 for (int i = 0; i < argc; ++i) {
Vladimir Markoe5125562019-02-06 17:38:26 +0000260 const char* raw_option = argv[i];
261 const std::string_view option(raw_option);
Calin Juravle2e2db782016-02-23 12:00:03 +0000262 const bool log_options = false;
263 if (log_options) {
Calin Juravle876f3502016-03-24 16:16:34 +0000264 LOG(INFO) << "profman: option[" << i << "]=" << argv[i];
Calin Juravle2e2db782016-02-23 12:00:03 +0000265 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700266 if (option == "--dump-only") {
267 dump_only_ = true;
Mathieu Chartier34067262017-04-06 13:55:46 -0700268 } else if (option == "--dump-classes-and-methods") {
269 dump_classes_and_methods_ = true;
Vladimir Markoe5125562019-02-06 17:38:26 +0000270 } else if (StartsWith(option, "--create-profile-from=")) {
271 create_profile_from_file_ = std::string(option.substr(strlen("--create-profile-from=")));
272 } else if (StartsWith(option, "--dump-output-to-fd=")) {
273 ParseUintOption(raw_option, "--dump-output-to-fd=", &dump_output_to_fd_);
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +0100274 } else if (option == "--generate-boot-profile") {
275 generate_boot_profile_ = true;
Mathieu Chartier2f794552017-06-19 10:58:08 -0700276 } else if (option == "--generate-boot-image-profile") {
277 generate_boot_image_profile_ = true;
Vladimir Markoe5125562019-02-06 17:38:26 +0000278 } else if (StartsWith(option, "--boot-image-class-threshold=")) {
279 ParseUintOption(raw_option,
280 "--boot-image-class-threshold=",
281 &boot_image_options_.image_class_theshold);
282 } else if (StartsWith(option, "--boot-image-clean-class-threshold=")) {
283 ParseUintOption(raw_option,
284 "--boot-image-clean-class-threshold=",
285 &boot_image_options_.image_class_clean_theshold);
286 } else if (StartsWith(option, "--boot-image-sampled-method-threshold=")) {
287 ParseUintOption(raw_option,
288 "--boot-image-sampled-method-threshold=",
289 &boot_image_options_.compiled_method_threshold);
290 } else if (StartsWith(option, "--profile-file=")) {
291 profile_files_.push_back(std::string(option.substr(strlen("--profile-file="))));
292 } else if (StartsWith(option, "--profile-file-fd=")) {
293 ParseFdForCollection(raw_option, "--profile-file-fd=", &profile_files_fd_);
294 } else if (StartsWith(option, "--reference-profile-file=")) {
295 reference_profile_file_ = std::string(option.substr(strlen("--reference-profile-file=")));
296 } else if (StartsWith(option, "--reference-profile-file-fd=")) {
297 ParseUintOption(raw_option, "--reference-profile-file-fd=", &reference_profile_file_fd_);
298 } else if (StartsWith(option, "--dex-location=")) {
299 dex_locations_.push_back(std::string(option.substr(strlen("--dex-location="))));
300 } else if (StartsWith(option, "--apk-fd=")) {
301 ParseFdForCollection(raw_option, "--apk-fd=", &apks_fd_);
302 } else if (StartsWith(option, "--apk=")) {
303 apk_files_.push_back(std::string(option.substr(strlen("--apk="))));
304 } else if (StartsWith(option, "--generate-test-profile=")) {
305 test_profile_ = std::string(option.substr(strlen("--generate-test-profile=")));
306 } else if (StartsWith(option, "--generate-test-profile-num-dex=")) {
307 ParseUintOption(raw_option,
308 "--generate-test-profile-num-dex=",
309 &test_profile_num_dex_);
310 } else if (StartsWith(option, "--generate-test-profile-method-percentage=")) {
311 ParseUintOption(raw_option,
312 "--generate-test-profile-method-percentage=",
313 &test_profile_method_percerntage_);
314 } else if (StartsWith(option, "--generate-test-profile-class-percentage=")) {
315 ParseUintOption(raw_option,
316 "--generate-test-profile-class-percentage=",
317 &test_profile_class_percentage_);
318 } else if (StartsWith(option, "--generate-test-profile-seed=")) {
319 ParseUintOption(raw_option, "--generate-test-profile-seed=", &test_profile_seed_);
320 } else if (option == "--copy-and-update-profile-key") {
Calin Juravle02c08792018-02-15 19:40:48 -0800321 copy_and_update_profile_key_ = true;
Calin Juravle0e82e0f2019-11-11 18:34:10 -0800322 } else if (option == "--boot-image-merge") {
323 profile_assistant_options_.SetBootImageMerge(true);
324 } else if (option == "--force-merge") {
325 profile_assistant_options_.SetForceMerge(true);
Calin Juravle2e2db782016-02-23 12:00:03 +0000326 } else {
Vladimir Markoe5125562019-02-06 17:38:26 +0000327 Usage("Unknown argument '%s'", raw_option);
Calin Juravle2e2db782016-02-23 12:00:03 +0000328 }
329 }
330
David Sehr153da0e2017-02-15 08:54:51 -0800331 // Validate global consistency between file/fd options.
Calin Juravle2e2db782016-02-23 12:00:03 +0000332 if (!profile_files_.empty() && !profile_files_fd_.empty()) {
333 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
334 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700335 if (!reference_profile_file_.empty() && FdIsValid(reference_profile_file_fd_)) {
336 Usage("Reference profile should not be specified with both "
337 "--reference-profile-file-fd and --reference-profile-file");
338 }
David Sehr153da0e2017-02-15 08:54:51 -0800339 if (!apk_files_.empty() && !apks_fd_.empty()) {
340 Usage("APK files should not be specified with both --apk-fd and --apk");
Calin Juravle2e2db782016-02-23 12:00:03 +0000341 }
342 }
343
Calin Juravlee10c1e22018-01-26 20:10:15 -0800344 struct ProfileFilterKey {
345 ProfileFilterKey(const std::string& dex_location, uint32_t checksum)
346 : dex_location_(dex_location), checksum_(checksum) {}
347 const std::string dex_location_;
348 uint32_t checksum_;
349
350 bool operator==(const ProfileFilterKey& other) const {
351 return checksum_ == other.checksum_ && dex_location_ == other.dex_location_;
352 }
353 bool operator<(const ProfileFilterKey& other) const {
354 return checksum_ == other.checksum_
355 ? dex_location_ < other.dex_location_
356 : checksum_ < other.checksum_;
357 }
358 };
359
Calin Juravle2e2db782016-02-23 12:00:03 +0000360 ProfileAssistant::ProcessingResult ProcessProfiles() {
David Sehr153da0e2017-02-15 08:54:51 -0800361 // Validate that at least one profile file was passed, as well as a reference profile.
362 if (profile_files_.empty() && profile_files_fd_.empty()) {
363 Usage("No profile files specified.");
364 }
365 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
366 Usage("No reference profile file specified.");
367 }
368 if ((!profile_files_.empty() && FdIsValid(reference_profile_file_fd_)) ||
369 (!profile_files_fd_.empty() && !FdIsValid(reference_profile_file_fd_))) {
370 Usage("Options --profile-file-fd and --reference-profile-file-fd "
371 "should only be used together");
372 }
Calin Juravlee10c1e22018-01-26 20:10:15 -0800373
374 // Check if we have any apks which we should use to filter the profile data.
375 std::set<ProfileFilterKey> profile_filter_keys;
376 if (!GetProfileFilterKeyFromApks(&profile_filter_keys)) {
377 return ProfileAssistant::kErrorIO;
378 }
379
380 // Build the profile filter function. If the set of keys is empty it means we
381 // don't have any apks; as such we do not filter anything.
382 const ProfileCompilationInfo::ProfileLoadFilterFn& filter_fn =
Calin Juravlead88cbe2019-11-11 18:43:15 -0800383 [profile_filter_keys](const std::string& profile_key, uint32_t checksum) {
Calin Juravlee10c1e22018-01-26 20:10:15 -0800384 if (profile_filter_keys.empty()) {
385 // No --apk was specified. Accept all dex files.
386 return true;
387 } else {
Calin Juravlead88cbe2019-11-11 18:43:15 -0800388 // Remove any annotations from the profile key before comparing with the keys we get from apks.
389 std::string base_key = ProfileCompilationInfo::GetBaseKeyFromAugmentedKey(profile_key);
390 return profile_filter_keys.find(ProfileFilterKey(base_key, checksum)) !=
391 profile_filter_keys.end();
Calin Juravlee10c1e22018-01-26 20:10:15 -0800392 }
393 };
394
Calin Juravle2e2db782016-02-23 12:00:03 +0000395 ProfileAssistant::ProcessingResult result;
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800396
Calin Juravle2e2db782016-02-23 12:00:03 +0000397 if (profile_files_.empty()) {
398 // The file doesn't need to be flushed here (ProcessProfiles will do it)
399 // so don't check the usage.
400 File file(reference_profile_file_fd_, false);
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800401 result = ProfileAssistant::ProcessProfiles(profile_files_fd_,
Calin Juravlee10c1e22018-01-26 20:10:15 -0800402 reference_profile_file_fd_,
Calin Juravle0e82e0f2019-11-11 18:34:10 -0800403 filter_fn,
404 profile_assistant_options_);
Calin Juravle2e2db782016-02-23 12:00:03 +0000405 CloseAllFds(profile_files_fd_, "profile_files_fd_");
406 } else {
Calin Juravlee10c1e22018-01-26 20:10:15 -0800407 result = ProfileAssistant::ProcessProfiles(profile_files_,
408 reference_profile_file_,
Calin Juravle0e82e0f2019-11-11 18:34:10 -0800409 filter_fn,
410 profile_assistant_options_);
Calin Juravle2e2db782016-02-23 12:00:03 +0000411 }
412 return result;
413 }
414
Calin Juravlee10c1e22018-01-26 20:10:15 -0800415 bool GetProfileFilterKeyFromApks(std::set<ProfileFilterKey>* profile_filter_keys) {
416 auto process_fn = [profile_filter_keys](std::unique_ptr<const DexFile>&& dex_file) {
417 // Store the profile key of the location instead of the location itself.
418 // This will make the matching in the profile filter method much easier.
Calin Juravle849439a2019-09-16 15:09:16 -0700419 profile_filter_keys->emplace(ProfileCompilationInfo::GetProfileDexFileBaseKey(
Calin Juravlee10c1e22018-01-26 20:10:15 -0800420 dex_file->GetLocation()), dex_file->GetLocationChecksum());
421 };
422 return OpenApkFilesFromLocations(process_fn);
423 }
424
425 bool OpenApkFilesFromLocations(std::vector<std::unique_ptr<const DexFile>>* dex_files) {
426 auto process_fn = [dex_files](std::unique_ptr<const DexFile>&& dex_file) {
427 dex_files->emplace_back(std::move(dex_file));
428 };
429 return OpenApkFilesFromLocations(process_fn);
430 }
431
432 bool OpenApkFilesFromLocations(
Andreas Gampebc802de2018-06-20 17:24:11 -0700433 const std::function<void(std::unique_ptr<const DexFile>&&)>& process_fn) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800434 bool use_apk_fd_list = !apks_fd_.empty();
435 if (use_apk_fd_list) {
David Sehr153da0e2017-02-15 08:54:51 -0800436 // Get the APKs from the collection of FDs.
Calin Juravlee10c1e22018-01-26 20:10:15 -0800437 if (dex_locations_.empty()) {
438 // Try to compute the dex locations from the file paths of the descriptions.
439 // This will make it easier to invoke profman with --apk-fd and without
440 // being force to pass --dex-location when the location would be the apk path.
441 if (!ComputeDexLocationsFromApkFds()) {
442 return false;
443 }
444 } else {
445 if (dex_locations_.size() != apks_fd_.size()) {
446 Usage("The number of apk-fds must match the number of dex-locations.");
447 }
448 }
David Sehr153da0e2017-02-15 08:54:51 -0800449 } else if (!apk_files_.empty()) {
Calin Juravle02c08792018-02-15 19:40:48 -0800450 if (dex_locations_.empty()) {
451 // If no dex locations are specified use the apk names as locations.
452 dex_locations_ = apk_files_;
453 } else if (dex_locations_.size() != apk_files_.size()) {
454 Usage("The number of apk-fds must match the number of dex-locations.");
455 }
David Sehr153da0e2017-02-15 08:54:51 -0800456 } else {
457 // No APKs were specified.
458 CHECK(dex_locations_.empty());
Calin Juravlee10c1e22018-01-26 20:10:15 -0800459 return true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800460 }
461 static constexpr bool kVerifyChecksum = true;
462 for (size_t i = 0; i < dex_locations_.size(); ++i) {
Mathieu Chartier818cb802018-05-11 05:30:16 +0000463 std::string error_msg;
464 const ArtDexFileLoader dex_file_loader;
465 std::vector<std::unique_ptr<const DexFile>> dex_files_for_location;
Calin Juravle1bfe4bd2018-04-26 16:00:11 -0700466 // We do not need to verify the apk for processing profiles.
David Sehr7c80f2d2017-02-07 16:47:58 -0800467 if (use_apk_fd_list) {
Mathieu Chartier818cb802018-05-11 05:30:16 +0000468 if (dex_file_loader.OpenZip(apks_fd_[i],
469 dex_locations_[i],
Andreas Gampe9b031f72018-10-04 11:03:34 -0700470 /* verify= */ false,
Mathieu Chartier818cb802018-05-11 05:30:16 +0000471 kVerifyChecksum,
472 &error_msg,
473 &dex_files_for_location)) {
474 } else {
475 LOG(ERROR) << "OpenZip failed for '" << dex_locations_[i] << "' " << error_msg;
Calin Juravlee10c1e22018-01-26 20:10:15 -0800476 return false;
David Sehr7c80f2d2017-02-07 16:47:58 -0800477 }
Mathieu Chartier818cb802018-05-11 05:30:16 +0000478 } else {
479 if (dex_file_loader.Open(apk_files_[i].c_str(),
480 dex_locations_[i],
Andreas Gampe9b031f72018-10-04 11:03:34 -0700481 /* verify= */ false,
Mathieu Chartier818cb802018-05-11 05:30:16 +0000482 kVerifyChecksum,
483 &error_msg,
484 &dex_files_for_location)) {
485 } else {
486 LOG(ERROR) << "Open failed for '" << dex_locations_[i] << "' " << error_msg;
487 return false;
488 }
David Sehr2b80ed42018-05-08 08:58:15 -0700489 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800490 for (std::unique_ptr<const DexFile>& dex_file : dex_files_for_location) {
Calin Juravlee10c1e22018-01-26 20:10:15 -0800491 process_fn(std::move(dex_file));
David Sehr7c80f2d2017-02-07 16:47:58 -0800492 }
493 }
Calin Juravlee10c1e22018-01-26 20:10:15 -0800494 return true;
495 }
496
497 // Get the dex locations from the apk fds.
498 // The methods reads the links from /proc/self/fd/ to find the original apk paths
499 // and puts them in the dex_locations_ vector.
500 bool ComputeDexLocationsFromApkFds() {
David Sehr9d9227a2018-12-19 12:32:50 -0800501#ifdef _WIN32
502 PLOG(ERROR) << "ComputeDexLocationsFromApkFds is unsupported on Windows.";
503 return false;
504#else
Calin Juravlee10c1e22018-01-26 20:10:15 -0800505 // We can't use a char array of PATH_MAX size without exceeding the frame size.
506 // So we use a vector as the buffer for the path.
507 std::vector<char> buffer(PATH_MAX, 0);
508 for (size_t i = 0; i < apks_fd_.size(); ++i) {
509 std::string fd_path = "/proc/self/fd/" + std::to_string(apks_fd_[i]);
510 ssize_t len = readlink(fd_path.c_str(), buffer.data(), buffer.size() - 1);
511 if (len == -1) {
512 PLOG(ERROR) << "Could not open path from fd";
513 return false;
514 }
515
516 buffer[len] = '\0';
517 dex_locations_.push_back(buffer.data());
518 }
519 return true;
David Sehr9d9227a2018-12-19 12:32:50 -0800520#endif
David Sehr7c80f2d2017-02-07 16:47:58 -0800521 }
522
Mathieu Chartier2f794552017-06-19 10:58:08 -0700523 std::unique_ptr<const ProfileCompilationInfo> LoadProfile(const std::string& filename, int fd) {
524 if (!filename.empty()) {
David Sehr9d9227a2018-12-19 12:32:50 -0800525#ifdef _WIN32
526 int flags = O_RDWR;
527#else
528 int flags = O_RDWR | O_CLOEXEC;
529#endif
530 fd = open(filename.c_str(), flags);
Mathieu Chartier2f794552017-06-19 10:58:08 -0700531 if (fd < 0) {
Elliott Hughes23a8eb62019-03-08 12:37:33 -0800532 PLOG(ERROR) << "Cannot open " << filename;
Mathieu Chartier2f794552017-06-19 10:58:08 -0700533 return nullptr;
534 }
535 }
536 std::unique_ptr<ProfileCompilationInfo> info(new ProfileCompilationInfo);
537 if (!info->Load(fd)) {
538 LOG(ERROR) << "Cannot load profile info from fd=" << fd << "\n";
539 return nullptr;
540 }
541 return info;
542 }
543
David Sehrb18991b2017-02-08 20:58:10 -0800544 int DumpOneProfile(const std::string& banner,
545 const std::string& filename,
546 int fd,
547 const std::vector<std::unique_ptr<const DexFile>>* dex_files,
548 std::string* dump) {
Mathieu Chartier2f794552017-06-19 10:58:08 -0700549 std::unique_ptr<const ProfileCompilationInfo> info(LoadProfile(filename, fd));
550 if (info == nullptr) {
551 LOG(ERROR) << "Cannot load profile info from filename=" << filename << " fd=" << fd;
Calin Juravle876f3502016-03-24 16:16:34 +0000552 return -1;
553 }
Mathieu Chartier0573f852018-10-01 13:52:12 -0700554 *dump += banner + "\n" + info->DumpInfo(MakeNonOwningPointerVector(*dex_files)) + "\n";
David Sehr4fcdd6d2016-05-24 14:52:31 -0700555 return 0;
556 }
557
558 int DumpProfileInfo() {
David Sehr153da0e2017-02-15 08:54:51 -0800559 // Validate that at least one profile file or reference was specified.
560 if (profile_files_.empty() && profile_files_fd_.empty() &&
561 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
562 Usage("No profile files or reference profile specified.");
563 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700564 static const char* kEmptyString = "";
David Sehr546d24f2016-06-02 10:46:19 -0700565 static const char* kOrdinaryProfile = "=== profile ===";
566 static const char* kReferenceProfile = "=== reference profile ===";
Mathieu Chartier0573f852018-10-01 13:52:12 -0700567 static const char* kDexFiles = "=== Dex files ===";
David Sehr546d24f2016-06-02 10:46:19 -0700568
David Sehrb18991b2017-02-08 20:58:10 -0800569 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7c80f2d2017-02-07 16:47:58 -0800570 OpenApkFilesFromLocations(&dex_files);
Mathieu Chartier0573f852018-10-01 13:52:12 -0700571
David Sehr4fcdd6d2016-05-24 14:52:31 -0700572 std::string dump;
Mathieu Chartier0573f852018-10-01 13:52:12 -0700573
574 // Dump checkfiles and corresponding checksums.
575 dump += kDexFiles;
576 dump += "\n";
577 for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
578 std::ostringstream oss;
579 oss << dex_file->GetLocation()
580 << " [checksum=" << std::hex << dex_file->GetLocationChecksum() << "]\n";
581 dump += oss.str();
582 }
583
David Sehr4fcdd6d2016-05-24 14:52:31 -0700584 // Dump individual profile files.
585 if (!profile_files_fd_.empty()) {
586 for (int profile_file_fd : profile_files_fd_) {
David Sehr546d24f2016-06-02 10:46:19 -0700587 int ret = DumpOneProfile(kOrdinaryProfile,
588 kEmptyString,
589 profile_file_fd,
590 &dex_files,
591 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700592 if (ret != 0) {
593 return ret;
594 }
595 }
596 }
Mathieu Chartier0573f852018-10-01 13:52:12 -0700597 for (const std::string& profile_file : profile_files_) {
598 int ret = DumpOneProfile(kOrdinaryProfile, profile_file, kInvalidFd, &dex_files, &dump);
599 if (ret != 0) {
600 return ret;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700601 }
602 }
603 // Dump reference profile file.
604 if (FdIsValid(reference_profile_file_fd_)) {
David Sehr546d24f2016-06-02 10:46:19 -0700605 int ret = DumpOneProfile(kReferenceProfile,
606 kEmptyString,
607 reference_profile_file_fd_,
608 &dex_files,
609 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700610 if (ret != 0) {
611 return ret;
612 }
613 }
614 if (!reference_profile_file_.empty()) {
David Sehr546d24f2016-06-02 10:46:19 -0700615 int ret = DumpOneProfile(kReferenceProfile,
616 reference_profile_file_,
617 kInvalidFd,
618 &dex_files,
David Sehr4fcdd6d2016-05-24 14:52:31 -0700619 &dump);
620 if (ret != 0) {
621 return ret;
622 }
623 }
624 if (!FdIsValid(dump_output_to_fd_)) {
625 std::cout << dump;
626 } else {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700627 unix_file::FdFile out_fd(dump_output_to_fd_, /*check_usage=*/ false);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700628 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
629 return -1;
630 }
631 }
Calin Juravle876f3502016-03-24 16:16:34 +0000632 return 0;
633 }
634
635 bool ShouldOnlyDumpProfile() {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700636 return dump_only_;
Calin Juravle876f3502016-03-24 16:16:34 +0000637 }
638
Mathieu Chartier34067262017-04-06 13:55:46 -0700639 bool GetClassNamesAndMethods(int fd,
640 std::vector<std::unique_ptr<const DexFile>>* dex_files,
641 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800642 ProfileCompilationInfo profile_info;
643 if (!profile_info.Load(fd)) {
644 LOG(ERROR) << "Cannot load profile info";
645 return false;
646 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700647 for (const std::unique_ptr<const DexFile>& dex_file : *dex_files) {
648 std::set<dex::TypeIndex> class_types;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700649 std::set<uint16_t> hot_methods;
650 std::set<uint16_t> startup_methods;
651 std::set<uint16_t> post_startup_methods;
652 std::set<uint16_t> combined_methods;
653 if (profile_info.GetClassesAndMethods(*dex_file.get(),
654 &class_types,
655 &hot_methods,
656 &startup_methods,
657 &post_startup_methods)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700658 for (const dex::TypeIndex& type_index : class_types) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800659 const dex::TypeId& type_id = dex_file->GetTypeId(type_index);
Mathieu Chartier34067262017-04-06 13:55:46 -0700660 out_lines->insert(std::string(dex_file->GetTypeDescriptor(type_id)));
661 }
Mathieu Chartierea650f32017-05-24 12:04:13 -0700662 combined_methods = hot_methods;
663 combined_methods.insert(startup_methods.begin(), startup_methods.end());
664 combined_methods.insert(post_startup_methods.begin(), post_startup_methods.end());
665 for (uint16_t dex_method_idx : combined_methods) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800666 const dex::MethodId& id = dex_file->GetMethodId(dex_method_idx);
Mathieu Chartier34067262017-04-06 13:55:46 -0700667 std::string signature_string(dex_file->GetMethodSignature(id).ToString());
668 std::string type_string(dex_file->GetTypeDescriptor(dex_file->GetTypeId(id.class_idx_)));
669 std::string method_name(dex_file->GetMethodName(id));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700670 std::string flags_string;
671 if (hot_methods.find(dex_method_idx) != hot_methods.end()) {
672 flags_string += kMethodFlagStringHot;
673 }
674 if (startup_methods.find(dex_method_idx) != startup_methods.end()) {
675 flags_string += kMethodFlagStringStartup;
676 }
677 if (post_startup_methods.find(dex_method_idx) != post_startup_methods.end()) {
678 flags_string += kMethodFlagStringPostStartup;
679 }
680 out_lines->insert(flags_string +
681 type_string +
682 kMethodSep +
683 method_name +
684 signature_string);
Mathieu Chartier34067262017-04-06 13:55:46 -0700685 }
686 }
687 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800688 return true;
689 }
690
Mathieu Chartier34067262017-04-06 13:55:46 -0700691 bool GetClassNamesAndMethods(const std::string& profile_file,
692 std::vector<std::unique_ptr<const DexFile>>* dex_files,
693 std::set<std::string>* out_lines) {
David Sehr9d9227a2018-12-19 12:32:50 -0800694#ifdef _WIN32
695 int flags = O_RDONLY;
696#else
697 int flags = O_RDONLY | O_CLOEXEC;
698#endif
699 int fd = open(profile_file.c_str(), flags);
David Sehr7c80f2d2017-02-07 16:47:58 -0800700 if (!FdIsValid(fd)) {
Elliott Hughes23a8eb62019-03-08 12:37:33 -0800701 PLOG(ERROR) << "Cannot open " << profile_file;
David Sehr7c80f2d2017-02-07 16:47:58 -0800702 return false;
703 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700704 if (!GetClassNamesAndMethods(fd, dex_files, out_lines)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800705 return false;
706 }
707 if (close(fd) < 0) {
708 PLOG(WARNING) << "Failed to close descriptor";
709 }
710 return true;
711 }
712
Mathieu Chartierea650f32017-05-24 12:04:13 -0700713 int DumpClassesAndMethods() {
David Sehr153da0e2017-02-15 08:54:51 -0800714 // Validate that at least one profile file or reference was specified.
715 if (profile_files_.empty() && profile_files_fd_.empty() &&
716 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
717 Usage("No profile files or reference profile specified.");
718 }
Calin Juravlee10c1e22018-01-26 20:10:15 -0800719
David Sehr7c80f2d2017-02-07 16:47:58 -0800720 // Open the dex files to get the names for classes.
721 std::vector<std::unique_ptr<const DexFile>> dex_files;
722 OpenApkFilesFromLocations(&dex_files);
723 // Build a vector of class names from individual profile files.
724 std::set<std::string> class_names;
725 if (!profile_files_fd_.empty()) {
726 for (int profile_file_fd : profile_files_fd_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700727 if (!GetClassNamesAndMethods(profile_file_fd, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800728 return -1;
729 }
730 }
731 }
732 if (!profile_files_.empty()) {
733 for (const std::string& profile_file : profile_files_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700734 if (!GetClassNamesAndMethods(profile_file, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800735 return -1;
736 }
737 }
738 }
739 // Concatenate class names from reference profile file.
740 if (FdIsValid(reference_profile_file_fd_)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700741 if (!GetClassNamesAndMethods(reference_profile_file_fd_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800742 return -1;
743 }
744 }
745 if (!reference_profile_file_.empty()) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700746 if (!GetClassNamesAndMethods(reference_profile_file_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800747 return -1;
748 }
749 }
750 // Dump the class names.
751 std::string dump;
752 for (const std::string& class_name : class_names) {
753 dump += class_name + std::string("\n");
754 }
755 if (!FdIsValid(dump_output_to_fd_)) {
756 std::cout << dump;
757 } else {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700758 unix_file::FdFile out_fd(dump_output_to_fd_, /*check_usage=*/ false);
David Sehr7c80f2d2017-02-07 16:47:58 -0800759 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
760 return -1;
761 }
762 }
763 return 0;
764 }
765
Mathieu Chartier34067262017-04-06 13:55:46 -0700766 bool ShouldOnlyDumpClassesAndMethods() {
767 return dump_classes_and_methods_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800768 }
769
770 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
771 // the given function.
772 template <typename T>
773 static T* ReadCommentedInputFromFile(
774 const char* input_filename, std::function<std::string(const char*)>* process) {
775 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
776 if (input_file.get() == nullptr) {
777 LOG(ERROR) << "Failed to open input file " << input_filename;
778 return nullptr;
779 }
780 std::unique_ptr<T> result(
781 ReadCommentedInputStream<T>(*input_file, process));
782 input_file->close();
783 return result.release();
784 }
785
786 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
787 // with the given function.
788 template <typename T>
789 static T* ReadCommentedInputStream(
790 std::istream& in_stream,
791 std::function<std::string(const char*)>* process) {
792 std::unique_ptr<T> output(new T());
793 while (in_stream.good()) {
794 std::string dot;
795 std::getline(in_stream, dot);
796 if (android::base::StartsWith(dot, "#") || dot.empty()) {
797 continue;
798 }
799 if (process != nullptr) {
800 std::string descriptor((*process)(dot.c_str()));
801 output->insert(output->end(), descriptor);
802 } else {
803 output->insert(output->end(), dot);
804 }
805 }
806 return output.release();
807 }
808
Calin Juravlee0ac1152017-02-13 19:03:47 -0800809 // Find class klass_descriptor in the given dex_files and store its reference
810 // in the out parameter class_ref.
Nicolas Geoffrayf5e26f82019-08-13 15:21:05 +0100811 // Return true if the definition or a reference of the class was found in any
812 // of the dex_files.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800813 bool FindClass(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
814 const std::string& klass_descriptor,
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700815 /*out*/TypeReference* class_ref) {
Calin Juravle08556882017-05-26 16:40:45 -0700816 constexpr uint16_t kInvalidTypeIndex = std::numeric_limits<uint16_t>::max() - 1;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800817 for (const std::unique_ptr<const DexFile>& dex_file_ptr : dex_files) {
818 const DexFile* dex_file = dex_file_ptr.get();
Calin Juravle08556882017-05-26 16:40:45 -0700819 if (klass_descriptor == kInvalidClassDescriptor) {
820 if (kInvalidTypeIndex >= dex_file->NumTypeIds()) {
821 // The dex file does not contain all possible type ids which leaves us room
822 // to add an "invalid" type id.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700823 *class_ref = TypeReference(dex_file, dex::TypeIndex(kInvalidTypeIndex));
Calin Juravle08556882017-05-26 16:40:45 -0700824 return true;
825 } else {
826 // The dex file contains all possible type ids. We don't have any free type id
827 // that we can use as invalid.
828 continue;
829 }
830 }
831
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800832 const dex::TypeId* type_id = dex_file->FindTypeId(klass_descriptor.c_str());
Calin Juravlee0ac1152017-02-13 19:03:47 -0800833 if (type_id == nullptr) {
834 continue;
835 }
836 dex::TypeIndex type_index = dex_file->GetIndexForTypeId(*type_id);
Nicolas Geoffrayf5e26f82019-08-13 15:21:05 +0100837 *class_ref = TypeReference(dex_file, type_index);
838
Calin Juravlee0ac1152017-02-13 19:03:47 -0800839 if (dex_file->FindClassDef(type_index) == nullptr) {
840 // Class is only referenced in the current dex file but not defined in it.
Nicolas Geoffrayf5e26f82019-08-13 15:21:05 +0100841 // We use its current type reference, but keep looking for its
842 // definition.
843 // Note that array classes fall into that category, as they do not have
844 // a class definition.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800845 continue;
846 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800847 return true;
848 }
Nicolas Geoffrayf5e26f82019-08-13 15:21:05 +0100849 // If we arrive here, we haven't found a class definition. If the dex file
850 // of the class reference is not null, then we have found a type reference,
851 // and we return that to the caller.
852 return (class_ref->dex_file != nullptr);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800853 }
854
Mathieu Chartier34067262017-04-06 13:55:46 -0700855 // Find the method specified by method_spec in the class class_ref.
Calin Juravle08556882017-05-26 16:40:45 -0700856 uint32_t FindMethodIndex(const TypeReference& class_ref,
857 const std::string& method_spec) {
858 const DexFile* dex_file = class_ref.dex_file;
859 if (method_spec == kInvalidMethod) {
860 constexpr uint16_t kInvalidMethodIndex = std::numeric_limits<uint16_t>::max() - 1;
861 return kInvalidMethodIndex >= dex_file->NumMethodIds()
862 ? kInvalidMethodIndex
Andreas Gampee2abbc62017-09-15 11:59:26 -0700863 : dex::kDexNoIndex;
Calin Juravle08556882017-05-26 16:40:45 -0700864 }
865
Calin Juravlee0ac1152017-02-13 19:03:47 -0800866 std::vector<std::string> name_and_signature;
867 Split(method_spec, kProfileParsingFirstCharInSignature, &name_and_signature);
868 if (name_and_signature.size() != 2) {
869 LOG(ERROR) << "Invalid method name and signature " << method_spec;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700870 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800871 }
Calin Juravle08556882017-05-26 16:40:45 -0700872
Calin Juravlee0ac1152017-02-13 19:03:47 -0800873 const std::string& name = name_and_signature[0];
874 const std::string& signature = kProfileParsingFirstCharInSignature + name_and_signature[1];
Calin Juravlee0ac1152017-02-13 19:03:47 -0800875
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800876 const dex::StringId* name_id = dex_file->FindStringId(name.c_str());
Calin Juravlee0ac1152017-02-13 19:03:47 -0800877 if (name_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700878 LOG(WARNING) << "Could not find name: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700879 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800880 }
881 dex::TypeIndex return_type_idx;
882 std::vector<dex::TypeIndex> param_type_idxs;
883 if (!dex_file->CreateTypeList(signature, &return_type_idx, &param_type_idxs)) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700884 LOG(WARNING) << "Could not create type list" << signature;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700885 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800886 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800887 const dex::ProtoId* proto_id = dex_file->FindProtoId(return_type_idx, param_type_idxs);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800888 if (proto_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700889 LOG(WARNING) << "Could not find proto_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700890 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800891 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800892 const dex::MethodId* method_id = dex_file->FindMethodId(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700893 dex_file->GetTypeId(class_ref.TypeIndex()), *name_id, *proto_id);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800894 if (method_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700895 LOG(WARNING) << "Could not find method_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700896 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800897 }
898
Mathieu Chartier34067262017-04-06 13:55:46 -0700899 return dex_file->GetIndexForMethodId(*method_id);
900 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800901
Mathieu Chartier34067262017-04-06 13:55:46 -0700902 // Given a method, return true if the method has a single INVOKE_VIRTUAL in its byte code.
903 // Upon success it returns true and stores the method index and the invoke dex pc
904 // in the output parameters.
905 // The format of the method spec is "inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
906 //
907 // TODO(calin): support INVOKE_INTERFACE and the range variants.
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700908 bool HasSingleInvoke(const TypeReference& class_ref,
Mathieu Chartier34067262017-04-06 13:55:46 -0700909 uint16_t method_index,
910 /*out*/uint32_t* dex_pc) {
911 const DexFile* dex_file = class_ref.dex_file;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800912 uint32_t offset = dex_file->FindCodeItemOffset(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700913 *dex_file->FindClassDef(class_ref.TypeIndex()),
Mathieu Chartier34067262017-04-06 13:55:46 -0700914 method_index);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800915 const dex::CodeItem* code_item = dex_file->GetCodeItem(offset);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800916
917 bool found_invoke = false;
Mathieu Chartier698ebbc2018-01-05 11:00:42 -0800918 for (const DexInstructionPcPair& inst : CodeItemInstructionAccessor(*dex_file, code_item)) {
Rico Windc24fa5d2018-04-25 12:44:58 +0200919 if (inst->Opcode() == Instruction::INVOKE_VIRTUAL ||
920 inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800921 if (found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700922 LOG(ERROR) << "Multiple invoke INVOKE_VIRTUAL found: "
923 << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800924 return false;
925 }
926 found_invoke = true;
Mathieu Chartier0021feb2017-11-07 00:08:52 -0800927 *dex_pc = inst.DexPc();
Calin Juravlee0ac1152017-02-13 19:03:47 -0800928 }
929 }
930 if (!found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700931 LOG(ERROR) << "Could not find any INVOKE_VIRTUAL: " << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800932 }
933 return found_invoke;
934 }
935
936 // Process a line defining a class or a method and its inline caches.
937 // Upon success return true and add the class or the method info to profile.
Calin Juravle589e71e2017-03-03 16:05:05 -0800938 // The possible line formats are:
939 // "LJustTheCass;".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800940 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
Calin Juravle08556882017-05-26 16:40:45 -0700941 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,invalid_class".
Calin Juravle589e71e2017-03-03 16:05:05 -0800942 // "LTestInline;->inlineMissingTypes(LSuper;)I+missing_types".
943 // "LTestInline;->inlineNoInlineCaches(LSuper;)I".
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700944 // "LTestInline;->*".
Calin Juravle08556882017-05-26 16:40:45 -0700945 // "invalid_class".
946 // "LTestInline;->invalid_method".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800947 // The method and classes are searched only in the given dex files.
948 bool ProcessLine(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
949 const std::string& line,
950 /*out*/ProfileCompilationInfo* profile) {
951 std::string klass;
952 std::string method_str;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700953 bool is_hot = false;
954 bool is_startup = false;
955 bool is_post_startup = false;
956 const size_t method_sep_index = line.find(kMethodSep, 0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800957 if (method_sep_index == std::string::npos) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700958 klass = line.substr(0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800959 } else {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700960 // The method prefix flags are only valid for method strings.
961 size_t start_index = 0;
962 while (start_index < line.size() && line[start_index] != 'L') {
963 const char c = line[start_index];
964 if (c == kMethodFlagStringHot) {
965 is_hot = true;
966 } else if (c == kMethodFlagStringStartup) {
967 is_startup = true;
968 } else if (c == kMethodFlagStringPostStartup) {
969 is_post_startup = true;
970 } else {
971 LOG(WARNING) << "Invalid flag " << c;
972 return false;
973 }
974 ++start_index;
975 }
976 klass = line.substr(start_index, method_sep_index - start_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800977 method_str = line.substr(method_sep_index + kMethodSep.size());
978 }
979
Calin Juravleee9cb412018-02-13 20:32:35 -0800980 uint32_t flags = 0;
981 if (is_hot) {
982 flags |= ProfileCompilationInfo::MethodHotness::kFlagHot;
983 }
984 if (is_startup) {
985 flags |= ProfileCompilationInfo::MethodHotness::kFlagStartup;
986 }
987 if (is_post_startup) {
988 flags |= ProfileCompilationInfo::MethodHotness::kFlagPostStartup;
989 }
990
Andreas Gampe9b031f72018-10-04 11:03:34 -0700991 TypeReference class_ref(/* dex_file= */ nullptr, dex::TypeIndex());
Calin Juravlee0ac1152017-02-13 19:03:47 -0800992 if (!FindClass(dex_files, klass, &class_ref)) {
Mathieu Chartier3f121342017-03-06 11:16:20 -0800993 LOG(WARNING) << "Could not find class: " << klass;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800994 return false;
995 }
996
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700997 if (method_str.empty() || method_str == kClassAllMethods) {
998 // Start by adding the class.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800999 const DexFile* dex_file = class_ref.dex_file;
Mathieu Chartierd808e8b2017-03-21 13:37:41 -07001000 std::vector<ProfileMethodInfo> methods;
1001 if (method_str == kClassAllMethods) {
Mathieu Chartier18e26872018-06-04 17:19:02 -07001002 ClassAccessor accessor(
1003 *dex_file,
1004 dex_file->GetIndexForClassDef(*dex_file->FindClassDef(class_ref.TypeIndex())));
Mathieu Chartier0d896bd2018-05-25 00:20:27 -07001005 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
Mathieu Chartier20f49922018-05-24 16:04:17 -07001006 if (method.GetCodeItemOffset() != 0) {
1007 // Add all of the methods that have code to the profile.
1008 methods.push_back(ProfileMethodInfo(method.GetReference()));
Mathieu Chartierd808e8b2017-03-21 13:37:41 -07001009 }
Mathieu Chartier0d896bd2018-05-25 00:20:27 -07001010 }
Mathieu Chartierd808e8b2017-03-21 13:37:41 -07001011 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001012 // TODO: Check return values?
Calin Juravleee9cb412018-02-13 20:32:35 -08001013 profile->AddMethods(methods, static_cast<ProfileCompilationInfo::MethodHotness::Flag>(flags));
Calin Juravlea6c9b782019-09-16 18:57:26 -07001014 std::set<dex::TypeIndex> classes;
1015 classes.insert(class_ref.TypeIndex());
1016 profile->AddClassesForDex(dex_file, classes.begin(), classes.end());
Calin Juravlee0ac1152017-02-13 19:03:47 -08001017 return true;
1018 }
1019
1020 // Process the method.
1021 std::string method_spec;
1022 std::vector<std::string> inline_cache_elems;
1023
Mathieu Chartierea650f32017-05-24 12:04:13 -07001024 // If none of the flags are set, default to hot.
1025 is_hot = is_hot || (!is_hot && !is_startup && !is_post_startup);
1026
Calin Juravlee0ac1152017-02-13 19:03:47 -08001027 std::vector<std::string> method_elems;
Calin Juravle589e71e2017-03-03 16:05:05 -08001028 bool is_missing_types = false;
Calin Juravlee0ac1152017-02-13 19:03:47 -08001029 Split(method_str, kProfileParsingInlineChacheSep, &method_elems);
1030 if (method_elems.size() == 2) {
1031 method_spec = method_elems[0];
Calin Juravle589e71e2017-03-03 16:05:05 -08001032 is_missing_types = method_elems[1] == kMissingTypesMarker;
1033 if (!is_missing_types) {
1034 Split(method_elems[1], kProfileParsingTypeSep, &inline_cache_elems);
1035 }
Calin Juravlee0ac1152017-02-13 19:03:47 -08001036 } else if (method_elems.size() == 1) {
1037 method_spec = method_elems[0];
1038 } else {
1039 LOG(ERROR) << "Invalid method line: " << line;
1040 return false;
1041 }
1042
Mathieu Chartier34067262017-04-06 13:55:46 -07001043 const uint32_t method_index = FindMethodIndex(class_ref, method_spec);
Andreas Gampee2abbc62017-09-15 11:59:26 -07001044 if (method_index == dex::kDexNoIndex) {
Calin Juravlee0ac1152017-02-13 19:03:47 -08001045 return false;
1046 }
Mathieu Chartier34067262017-04-06 13:55:46 -07001047
Mathieu Chartier34067262017-04-06 13:55:46 -07001048 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
1049 if (is_missing_types || !inline_cache_elems.empty()) {
1050 uint32_t dex_pc;
1051 if (!HasSingleInvoke(class_ref, method_index, &dex_pc)) {
Calin Juravlee0ac1152017-02-13 19:03:47 -08001052 return false;
1053 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00001054 std::vector<TypeReference> classes(inline_cache_elems.size(),
Andreas Gampe9b031f72018-10-04 11:03:34 -07001055 TypeReference(/* dex_file= */ nullptr, dex::TypeIndex()));
Mathieu Chartier34067262017-04-06 13:55:46 -07001056 size_t class_it = 0;
1057 for (const std::string& ic_class : inline_cache_elems) {
1058 if (!FindClass(dex_files, ic_class, &(classes[class_it++]))) {
1059 LOG(ERROR) << "Could not find class: " << ic_class;
1060 return false;
1061 }
1062 }
1063 inline_caches.emplace_back(dex_pc, is_missing_types, classes);
Calin Juravlee0ac1152017-02-13 19:03:47 -08001064 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001065 MethodReference ref(class_ref.dex_file, method_index);
Mathieu Chartierea650f32017-05-24 12:04:13 -07001066 if (is_hot) {
Calin Juravleee9cb412018-02-13 20:32:35 -08001067 profile->AddMethod(ProfileMethodInfo(ref, inline_caches),
1068 static_cast<ProfileCompilationInfo::MethodHotness::Flag>(flags));
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001069 }
1070 if (flags != 0) {
Calin Juravlea6c9b782019-09-16 18:57:26 -07001071 if (!profile->AddMethod(ProfileMethodInfo(ref),
1072 static_cast<ProfileCompilationInfo::MethodHotness::Flag>(flags))) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001073 return false;
1074 }
Mathieu Chartiere46f3a82017-06-19 19:54:12 -07001075 DCHECK(profile->GetMethodHotness(ref).IsInProfile());
Mathieu Chartierea650f32017-05-24 12:04:13 -07001076 }
Calin Juravlee0ac1152017-02-13 19:03:47 -08001077 return true;
1078 }
1079
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +01001080 bool ProcessBootLine(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
1081 const std::string& line,
1082 ProfileBootInfo* boot_profiling_info) {
1083 const size_t method_sep_index = line.find(kMethodSep, 0);
1084 std::string klass_str = line.substr(0, method_sep_index);
1085 std::string method_str = line.substr(method_sep_index + kMethodSep.size());
1086
1087 TypeReference class_ref(/* dex_file= */ nullptr, dex::TypeIndex());
1088 if (!FindClass(dex_files, klass_str, &class_ref)) {
1089 LOG(WARNING) << "Could not find class: " << klass_str;
1090 return false;
1091 }
1092
1093 const uint32_t method_index = FindMethodIndex(class_ref, method_str);
1094 if (method_index == dex::kDexNoIndex) {
1095 LOG(WARNING) << "Could not find method: " << line;
1096 return false;
1097 }
1098 boot_profiling_info->Add(class_ref.dex_file, method_index);
1099 return true;
1100 }
1101
Mathieu Chartier2f794552017-06-19 10:58:08 -07001102 int OpenReferenceProfile() const {
1103 int fd = reference_profile_file_fd_;
1104 if (!FdIsValid(fd)) {
1105 CHECK(!reference_profile_file_.empty());
David Sehr9d9227a2018-12-19 12:32:50 -08001106#ifdef _WIN32
1107 int flags = O_CREAT | O_TRUNC | O_WRONLY;
1108#else
1109 int flags = O_CREAT | O_TRUNC | O_WRONLY | O_CLOEXEC;
1110#endif
1111 fd = open(reference_profile_file_.c_str(), flags, 0644);
Mathieu Chartier2f794552017-06-19 10:58:08 -07001112 if (fd < 0) {
Elliott Hughes23a8eb62019-03-08 12:37:33 -08001113 PLOG(ERROR) << "Cannot open " << reference_profile_file_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001114 return kInvalidFd;
1115 }
1116 }
1117 return fd;
1118 }
1119
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +01001120 // Create and store a ProfileBootInfo.
1121 int CreateBootProfile() {
1122 // Validate parameters for this command.
1123 if (apk_files_.empty() && apks_fd_.empty()) {
1124 Usage("APK files must be specified");
1125 }
1126 if (dex_locations_.empty()) {
1127 Usage("DEX locations must be specified");
1128 }
1129 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
1130 Usage("Reference profile must be specified with --reference-profile-file or "
1131 "--reference-profile-file-fd");
1132 }
1133 if (!profile_files_.empty() || !profile_files_fd_.empty()) {
1134 Usage("Profile must be specified with --reference-profile-file or "
1135 "--reference-profile-file-fd");
1136 }
1137 // Open the profile output file if needed.
1138 int fd = OpenReferenceProfile();
1139 if (!FdIsValid(fd)) {
1140 return -1;
1141 }
1142 // Read the user-specified list of methods.
1143 std::unique_ptr<std::vector<std::string>>
1144 user_lines(ReadCommentedInputFromFile<std::vector<std::string>>(
1145 create_profile_from_file_.c_str(), nullptr)); // No post-processing.
1146
1147 // Open the dex files to look up classes and methods.
1148 std::vector<std::unique_ptr<const DexFile>> dex_files;
1149 OpenApkFilesFromLocations(&dex_files);
1150
1151 // Process the lines one by one and add the successful ones to the profile.
1152 ProfileBootInfo info;
1153
1154 for (const auto& line : *user_lines) {
1155 ProcessBootLine(dex_files, line, &info);
1156 }
1157
1158 // Write the profile file.
1159 CHECK(info.Save(fd));
1160
1161 if (close(fd) < 0) {
1162 PLOG(WARNING) << "Failed to close descriptor";
1163 }
1164
1165 return 0;
1166 }
1167
Calin Juravlee0ac1152017-02-13 19:03:47 -08001168 // Creates a profile from a human friendly textual representation.
1169 // The expected input format is:
1170 // # Classes
1171 // Ljava/lang/Comparable;
1172 // Ljava/lang/Math;
1173 // # Methods with inline caches
1174 // LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;
1175 // LTestInline;->noInlineCache(LSuper;)I
David Sehr7c80f2d2017-02-07 16:47:58 -08001176 int CreateProfile() {
David Sehr153da0e2017-02-15 08:54:51 -08001177 // Validate parameters for this command.
1178 if (apk_files_.empty() && apks_fd_.empty()) {
1179 Usage("APK files must be specified");
1180 }
1181 if (dex_locations_.empty()) {
1182 Usage("DEX locations must be specified");
1183 }
1184 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
1185 Usage("Reference profile must be specified with --reference-profile-file or "
1186 "--reference-profile-file-fd");
1187 }
1188 if (!profile_files_.empty() || !profile_files_fd_.empty()) {
1189 Usage("Profile must be specified with --reference-profile-file or "
1190 "--reference-profile-file-fd");
1191 }
David Sehr7c80f2d2017-02-07 16:47:58 -08001192 // Open the profile output file if needed.
Mathieu Chartier2f794552017-06-19 10:58:08 -07001193 int fd = OpenReferenceProfile();
David Sehr7c80f2d2017-02-07 16:47:58 -08001194 if (!FdIsValid(fd)) {
David Sehr7c80f2d2017-02-07 16:47:58 -08001195 return -1;
David Sehr7c80f2d2017-02-07 16:47:58 -08001196 }
Calin Juravlee0ac1152017-02-13 19:03:47 -08001197 // Read the user-specified list of classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -08001198 std::unique_ptr<std::unordered_set<std::string>>
Calin Juravlee0ac1152017-02-13 19:03:47 -08001199 user_lines(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
David Sehr7c80f2d2017-02-07 16:47:58 -08001200 create_profile_from_file_.c_str(), nullptr)); // No post-processing.
Calin Juravlee0ac1152017-02-13 19:03:47 -08001201
1202 // Open the dex files to look up classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -08001203 std::vector<std::unique_ptr<const DexFile>> dex_files;
1204 OpenApkFilesFromLocations(&dex_files);
Calin Juravlee0ac1152017-02-13 19:03:47 -08001205
1206 // Process the lines one by one and add the successful ones to the profile.
David Sehr7c80f2d2017-02-07 16:47:58 -08001207 ProfileCompilationInfo info;
Calin Juravlee0ac1152017-02-13 19:03:47 -08001208
1209 for (const auto& line : *user_lines) {
1210 ProcessLine(dex_files, line, &info);
1211 }
1212
David Sehr7c80f2d2017-02-07 16:47:58 -08001213 // Write the profile file.
1214 CHECK(info.Save(fd));
1215 if (close(fd) < 0) {
1216 PLOG(WARNING) << "Failed to close descriptor";
1217 }
1218 return 0;
1219 }
1220
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +01001221 bool ShouldCreateBootImageProfile() const {
Mathieu Chartier2f794552017-06-19 10:58:08 -07001222 return generate_boot_image_profile_;
1223 }
1224
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +01001225 bool ShouldCreateBootProfile() const {
1226 return generate_boot_profile_;
1227 }
1228
1229 // Create and store a ProfileCompilationInfo for the boot image.
1230 int CreateBootImageProfile() {
Mathieu Chartier2f794552017-06-19 10:58:08 -07001231 // Open the profile output file.
1232 const int reference_fd = OpenReferenceProfile();
1233 if (!FdIsValid(reference_fd)) {
1234 PLOG(ERROR) << "Error opening reference profile";
1235 return -1;
1236 }
1237 // Open the dex files.
1238 std::vector<std::unique_ptr<const DexFile>> dex_files;
1239 OpenApkFilesFromLocations(&dex_files);
1240 if (dex_files.empty()) {
1241 PLOG(ERROR) << "Expected dex files for creating boot profile";
1242 return -2;
1243 }
1244 // Open the input profiles.
1245 std::vector<std::unique_ptr<const ProfileCompilationInfo>> profiles;
1246 if (!profile_files_fd_.empty()) {
1247 for (int profile_file_fd : profile_files_fd_) {
1248 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile("", profile_file_fd));
1249 if (profile == nullptr) {
1250 return -3;
1251 }
1252 profiles.emplace_back(std::move(profile));
1253 }
1254 }
1255 if (!profile_files_.empty()) {
1256 for (const std::string& profile_file : profile_files_) {
1257 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile(profile_file, kInvalidFd));
1258 if (profile == nullptr) {
1259 return -4;
1260 }
1261 profiles.emplace_back(std::move(profile));
1262 }
1263 }
1264 ProfileCompilationInfo out_profile;
1265 GenerateBootImageProfile(dex_files,
1266 profiles,
1267 boot_image_options_,
1268 VLOG_IS_ON(profiler),
1269 &out_profile);
1270 out_profile.Save(reference_fd);
1271 close(reference_fd);
1272 return 0;
1273 }
1274
David Sehr7c80f2d2017-02-07 16:47:58 -08001275 bool ShouldCreateProfile() {
1276 return !create_profile_from_file_.empty();
1277 }
1278
Calin Juravle7bcdb532016-06-07 16:14:47 +01001279 int GenerateTestProfile() {
David Sehr153da0e2017-02-15 08:54:51 -08001280 // Validate parameters for this command.
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001281 if (test_profile_method_percerntage_ > 100) {
1282 Usage("Invalid percentage for --generate-test-profile-method-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001283 }
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001284 if (test_profile_class_percentage_ > 100) {
1285 Usage("Invalid percentage for --generate-test-profile-class-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001286 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001287 // If given APK files or DEX locations, check that they're ok.
1288 if (!apk_files_.empty() || !apks_fd_.empty() || !dex_locations_.empty()) {
1289 if (apk_files_.empty() && apks_fd_.empty()) {
1290 Usage("APK files must be specified when passing DEX locations to --generate-test-profile");
1291 }
1292 if (dex_locations_.empty()) {
1293 Usage("DEX locations must be specified when passing APK files to --generate-test-profile");
1294 }
1295 }
David Sehr153da0e2017-02-15 08:54:51 -08001296 // ShouldGenerateTestProfile confirms !test_profile_.empty().
David Sehr9d9227a2018-12-19 12:32:50 -08001297#ifdef _WIN32
1298 int flags = O_CREAT | O_TRUNC | O_WRONLY;
1299#else
1300 int flags = O_CREAT | O_TRUNC | O_WRONLY | O_CLOEXEC;
1301#endif
1302 int profile_test_fd = open(test_profile_.c_str(), flags, 0644);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001303 if (profile_test_fd < 0) {
Elliott Hughes23a8eb62019-03-08 12:37:33 -08001304 PLOG(ERROR) << "Cannot open " << test_profile_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001305 return -1;
1306 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001307 bool result;
1308 if (apk_files_.empty() && apks_fd_.empty() && dex_locations_.empty()) {
1309 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1310 test_profile_num_dex_,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001311 test_profile_method_percerntage_,
1312 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001313 test_profile_seed_);
1314 } else {
Jeff Haof0a31f82017-03-27 15:50:37 -07001315 // Open the dex files to look up classes and methods.
1316 std::vector<std::unique_ptr<const DexFile>> dex_files;
1317 OpenApkFilesFromLocations(&dex_files);
1318 // Create a random profile file based on the set of dex files.
1319 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1320 dex_files,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001321 test_profile_method_percerntage_,
1322 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001323 test_profile_seed_);
1324 }
Calin Juravle7bcdb532016-06-07 16:14:47 +01001325 close(profile_test_fd); // ignore close result.
1326 return result ? 0 : -1;
1327 }
1328
1329 bool ShouldGenerateTestProfile() {
1330 return !test_profile_.empty();
1331 }
1332
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001333 bool ShouldCopyAndUpdateProfileKey() const {
1334 return copy_and_update_profile_key_;
1335 }
1336
Calin Juravle02c08792018-02-15 19:40:48 -08001337 int32_t CopyAndUpdateProfileKey() {
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001338 // Validate that at least one profile file was passed, as well as a reference profile.
1339 if (!(profile_files_.size() == 1 ^ profile_files_fd_.size() == 1)) {
1340 Usage("Only one profile file should be specified.");
1341 }
1342 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
1343 Usage("No reference profile file specified.");
1344 }
1345
1346 if (apk_files_.empty() && apks_fd_.empty()) {
1347 Usage("No apk files specified");
1348 }
1349
Calin Juravle02c08792018-02-15 19:40:48 -08001350 static constexpr int32_t kErrorFailedToUpdateProfile = -1;
1351 static constexpr int32_t kErrorFailedToSaveProfile = -2;
1352 static constexpr int32_t kErrorFailedToLoadProfile = -3;
1353
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001354 bool use_fds = profile_files_fd_.size() == 1;
1355
1356 ProfileCompilationInfo profile;
1357 // Do not clear if invalid. The input might be an archive.
Calin Juravle02c08792018-02-15 19:40:48 -08001358 bool load_ok = use_fds
1359 ? profile.Load(profile_files_fd_[0])
Andreas Gampe9b031f72018-10-04 11:03:34 -07001360 : profile.Load(profile_files_[0], /*clear_if_invalid=*/ false);
Calin Juravle02c08792018-02-15 19:40:48 -08001361 if (load_ok) {
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001362 // Open the dex files to look up classes and methods.
1363 std::vector<std::unique_ptr<const DexFile>> dex_files;
1364 OpenApkFilesFromLocations(&dex_files);
1365 if (!profile.UpdateProfileKeys(dex_files)) {
Calin Juravle02c08792018-02-15 19:40:48 -08001366 return kErrorFailedToUpdateProfile;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001367 }
Calin Juravle02c08792018-02-15 19:40:48 -08001368 bool result = use_fds
1369 ? profile.Save(reference_profile_file_fd_)
Andreas Gampe9b031f72018-10-04 11:03:34 -07001370 : profile.Save(reference_profile_file_, /*bytes_written=*/ nullptr);
Calin Juravle02c08792018-02-15 19:40:48 -08001371 return result ? 0 : kErrorFailedToSaveProfile;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001372 } else {
Calin Juravle02c08792018-02-15 19:40:48 -08001373 return kErrorFailedToLoadProfile;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001374 }
1375 }
1376
Calin Juravle2e2db782016-02-23 12:00:03 +00001377 private:
Vladimir Markoe5125562019-02-06 17:38:26 +00001378 static void ParseFdForCollection(const char* raw_option,
1379 std::string_view option_prefix,
Calin Juravle2e2db782016-02-23 12:00:03 +00001380 std::vector<int>* fds) {
1381 int fd;
Vladimir Markoe5125562019-02-06 17:38:26 +00001382 ParseUintOption(raw_option, option_prefix, &fd);
Calin Juravle2e2db782016-02-23 12:00:03 +00001383 fds->push_back(fd);
1384 }
1385
1386 static void CloseAllFds(const std::vector<int>& fds, const char* descriptor) {
1387 for (size_t i = 0; i < fds.size(); i++) {
1388 if (close(fds[i]) < 0) {
Calin Juravlee10c1e22018-01-26 20:10:15 -08001389 PLOG(WARNING) << "Failed to close descriptor for "
1390 << descriptor << " at index " << i << ": " << fds[i];
Calin Juravle2e2db782016-02-23 12:00:03 +00001391 }
1392 }
1393 }
1394
1395 void LogCompletionTime() {
David Sehr52683cf2016-05-05 09:02:38 -07001396 static constexpr uint64_t kLogThresholdTime = MsToNs(100); // 100ms
1397 uint64_t time_taken = NanoTime() - start_ns_;
David Sehred793012016-05-05 13:39:43 -07001398 if (time_taken > kLogThresholdTime) {
David Sehrd8557182016-05-06 12:29:35 -07001399 LOG(WARNING) << "profman took " << PrettyDuration(time_taken);
David Sehred793012016-05-05 13:39:43 -07001400 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001401 }
1402
1403 std::vector<std::string> profile_files_;
1404 std::vector<int> profile_files_fd_;
David Sehr546d24f2016-06-02 10:46:19 -07001405 std::vector<std::string> dex_locations_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001406 std::vector<std::string> apk_files_;
David Sehr546d24f2016-06-02 10:46:19 -07001407 std::vector<int> apks_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001408 std::string reference_profile_file_;
1409 int reference_profile_file_fd_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001410 bool dump_only_;
Mathieu Chartier34067262017-04-06 13:55:46 -07001411 bool dump_classes_and_methods_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001412 bool generate_boot_image_profile_;
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +01001413 bool generate_boot_profile_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001414 int dump_output_to_fd_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001415 BootImageOptions boot_image_options_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001416 std::string test_profile_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001417 std::string create_profile_from_file_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001418 uint16_t test_profile_num_dex_;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001419 uint16_t test_profile_method_percerntage_;
1420 uint16_t test_profile_class_percentage_;
Jeff Haof0a31f82017-03-27 15:50:37 -07001421 uint32_t test_profile_seed_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001422 uint64_t start_ns_;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001423 bool copy_and_update_profile_key_;
Calin Juravle0e82e0f2019-11-11 18:34:10 -08001424 ProfileAssistant::Options profile_assistant_options_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001425};
1426
1427// See ProfileAssistant::ProcessingResult for return codes.
1428static int profman(int argc, char** argv) {
1429 ProfMan profman;
1430
1431 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1432 profman.ParseArgs(argc, argv);
1433
Calin Juravlee10c1e22018-01-26 20:10:15 -08001434 // Initialize MemMap for ZipArchive::OpenFromFd.
1435 MemMap::Init();
1436
Calin Juravle7bcdb532016-06-07 16:14:47 +01001437 if (profman.ShouldGenerateTestProfile()) {
1438 return profman.GenerateTestProfile();
1439 }
Calin Juravle876f3502016-03-24 16:16:34 +00001440 if (profman.ShouldOnlyDumpProfile()) {
1441 return profman.DumpProfileInfo();
1442 }
Mathieu Chartier34067262017-04-06 13:55:46 -07001443 if (profman.ShouldOnlyDumpClassesAndMethods()) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001444 return profman.DumpClassesAndMethods();
David Sehr7c80f2d2017-02-07 16:47:58 -08001445 }
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +01001446 if (profman.ShouldCreateBootProfile()) {
1447 return profman.CreateBootProfile();
1448 }
David Sehr7c80f2d2017-02-07 16:47:58 -08001449 if (profman.ShouldCreateProfile()) {
1450 return profman.CreateProfile();
1451 }
Mathieu Chartier2f794552017-06-19 10:58:08 -07001452
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +01001453 if (profman.ShouldCreateBootImageProfile()) {
1454 return profman.CreateBootImageProfile();
Mathieu Chartier2f794552017-06-19 10:58:08 -07001455 }
Calin Juravle02c08792018-02-15 19:40:48 -08001456
1457 if (profman.ShouldCopyAndUpdateProfileKey()) {
1458 return profman.CopyAndUpdateProfileKey();
1459 }
1460
Calin Juravle2e2db782016-02-23 12:00:03 +00001461 // Process profile information and assess if we need to do a profile guided compilation.
1462 // This operation involves I/O.
1463 return profman.ProcessProfiles();
1464}
1465
1466} // namespace art
1467
1468int main(int argc, char **argv) {
1469 return art::profman(argc, argv);
1470}