blob: 3e7e0281aaad8bf2fc3b484d280e67dbdf98b69c [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
Alex Lighta2f13192021-02-03 18:19:03 -080024#include <cstdint>
David Sehr7c80f2d2017-02-07 16:47:58 -080025#include <fstream>
Calin Juravle876f3502016-03-24 16:16:34 +000026#include <iostream>
Alex Lighta2f13192021-02-03 18:19:03 -080027#include <ostream>
David Sehr7c80f2d2017-02-07 16:47:58 -080028#include <set>
Calin Juravle2e2db782016-02-23 12:00:03 +000029#include <string>
Vladimir Markoe5125562019-02-06 17:38:26 +000030#include <string_view>
David Sehr7c80f2d2017-02-07 16:47:58 -080031#include <unordered_set>
Calin Juravle2e2db782016-02-23 12:00:03 +000032#include <vector>
33
Calin Juravle0f7f4fc2020-05-11 20:16:50 -070034#include "android-base/parsebool.h"
Andreas Gampe46ee31b2016-12-14 10:11:49 -080035#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080036#include "android-base/strings.h"
37
Alex Lighta2f13192021-02-03 18:19:03 -080038#include "base/array_ref.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000039#include "base/dumpable.h"
Andreas Gampe57943812017-12-06 21:39:13 -080040#include "base/logging.h" // For InitLogging.
David Sehr671af6c2018-05-17 11:00:35 -070041#include "base/mem_map.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000042#include "base/scoped_flock.h"
Mathieu Chartier0573f852018-10-01 13:52:12 -070043#include "base/stl_util.h"
Vladimir Markoe5125562019-02-06 17:38:26 +000044#include "base/string_view_cpp20.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000045#include "base/time_utils.h"
46#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080047#include "base/utils.h"
David Sehr79e26072018-04-06 17:58:50 -070048#include "base/zip_archive.h"
Mathieu Chartier2f794552017-06-19 10:58:08 -070049#include "boot_image_profile.h"
Mathieu Chartier818cb802018-05-11 05:30:16 +000050#include "dex/art_dex_file_loader.h"
David Sehr312f3b22018-03-19 08:39:26 -070051#include "dex/bytecode_utils.h"
Mathieu Chartier20f49922018-05-24 16:04:17 -070052#include "dex/class_accessor-inl.h"
Alex Lighta2f13192021-02-03 18:19:03 -080053#include "dex/class_reference.h"
David Sehr9e734c72018-01-04 17:56:19 -080054#include "dex/code_item_accessors-inl.h"
55#include "dex/dex_file.h"
56#include "dex/dex_file_loader.h"
Alex Lighta2f13192021-02-03 18:19:03 -080057#include "dex/dex_file_structs.h"
David Sehr9e734c72018-01-04 17:56:19 -080058#include "dex/dex_file_types.h"
Alex Lighta2f13192021-02-03 18:19:03 -080059#include "dex/method_reference.h"
David Sehr312f3b22018-03-19 08:39:26 -070060#include "dex/type_reference.h"
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +010061#include "profile/profile_boot_info.h"
David Sehr82d046e2018-04-23 08:14:19 -070062#include "profile/profile_compilation_info.h"
Mathieu Chartierdbddc222017-05-24 12:04:13 -070063#include "profile_assistant.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000064
65namespace art {
66
Calin Juravle0fee1fb2020-05-11 20:03:20 -070067using ProfileSampleAnnotation = ProfileCompilationInfo::ProfileSampleAnnotation;
68
Calin Juravle2e2db782016-02-23 12:00:03 +000069static int original_argc;
70static char** original_argv;
71
72static std::string CommandLine() {
73 std::vector<std::string> command;
Andreas Gampe2a487eb2018-11-19 11:41:22 -080074 command.reserve(original_argc);
Calin Juravle2e2db782016-02-23 12:00:03 +000075 for (int i = 0; i < original_argc; ++i) {
76 command.push_back(original_argv[i]);
77 }
Andreas Gampe9186ced2016-12-12 14:28:21 -080078 return android::base::Join(command, ' ');
Calin Juravle2e2db782016-02-23 12:00:03 +000079}
80
David Sehr4fcdd6d2016-05-24 14:52:31 -070081static bool FdIsValid(int fd) {
Orion Hodson365f94f2021-01-13 16:27:57 +000082 return fd != File::kInvalidFd;
David Sehr4fcdd6d2016-05-24 14:52:31 -070083}
84
Calin Juravle2e2db782016-02-23 12:00:03 +000085static void UsageErrorV(const char* fmt, va_list ap) {
86 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080087 android::base::StringAppendV(&error, fmt, ap);
Calin Juravle2e2db782016-02-23 12:00:03 +000088 LOG(ERROR) << error;
89}
90
91static void UsageError(const char* fmt, ...) {
92 va_list ap;
93 va_start(ap, fmt);
94 UsageErrorV(fmt, ap);
95 va_end(ap);
96}
97
98NO_RETURN static void Usage(const char *fmt, ...) {
99 va_list ap;
100 va_start(ap, fmt);
101 UsageErrorV(fmt, ap);
102 va_end(ap);
103
104 UsageError("Command: %s", CommandLine().c_str());
105 UsageError("Usage: profman [options]...");
106 UsageError("");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700107 UsageError(" --dump-only: dumps the content of the specified profile files");
108 UsageError(" to standard output (default) in a human readable form.");
109 UsageError("");
David Sehr7c80f2d2017-02-07 16:47:58 -0800110 UsageError(" --dump-output-to-fd=<number>: redirects --dump-only output to a file descriptor.");
111 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -0700112 UsageError(" --dump-classes-and-methods: dumps a sorted list of classes and methods that are");
113 UsageError(" in the specified profile file to standard output (default) in a human");
114 UsageError(" readable form. The output is valid input for --create-profile-from");
Calin Juravle876f3502016-03-24 16:16:34 +0000115 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000116 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
117 UsageError(" Can be specified multiple time, in which case the data from the different");
118 UsageError(" profiles will be aggregated.");
119 UsageError("");
120 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
121 UsageError(" Cannot be used together with --profile-file.");
122 UsageError("");
123 UsageError(" --reference-profile-file=<filename>: specify a reference profile.");
124 UsageError(" The data in this file will be compared with the data obtained by merging");
125 UsageError(" all the files specified with --profile-file or --profile-file-fd.");
126 UsageError(" If the exit code is EXIT_COMPILE then all --profile-file will be merged into");
127 UsageError(" --reference-profile-file. ");
128 UsageError("");
129 UsageError(" --reference-profile-file-fd=<number>: same as --reference-profile-file but");
130 UsageError(" accepts a file descriptor. Cannot be used together with");
131 UsageError(" --reference-profile-file.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800132 UsageError("");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100133 UsageError(" --generate-test-profile=<filename>: generates a random profile file for testing.");
134 UsageError(" --generate-test-profile-num-dex=<number>: number of dex files that should be");
135 UsageError(" included in the generated profile. Defaults to 20.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700136 UsageError(" --generate-test-profile-method-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100137 UsageError(" number of methods that should be generated. Defaults to 5.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700138 UsageError(" --generate-test-profile-class-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100139 UsageError(" number of classes that should be generated. Defaults to 5.");
Jeff Haof0a31f82017-03-27 15:50:37 -0700140 UsageError(" --generate-test-profile-seed=<number>: seed for random number generator used when");
141 UsageError(" generating random test profiles. Defaults to using NanoTime.");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100142 UsageError("");
Alex Lighta2f13192021-02-03 18:19:03 -0800143 UsageError(" --create-profile-from=<filename>: creates a profile from a list of classes,");
144 UsageError(" methods and inline caches.");
145 UsageError(" --generate-boot-android-profile: Generate a 012 version profile based on input");
146 UsageError(" profile. Requires --create-profile-from");
David Sehr7c80f2d2017-02-07 16:47:58 -0800147 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700148 UsageError(" --dex-location=<string>: location string to use with corresponding");
149 UsageError(" apk-fd to find dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700150 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700151 UsageError(" --apk-fd=<number>: file descriptor containing an open APK to");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700152 UsageError(" search for dex files");
David Sehr7c80f2d2017-02-07 16:47:58 -0800153 UsageError(" --apk-=<filename>: an APK to search for dex files");
David Brazdilf13ac7c2018-01-30 10:09:08 +0000154 UsageError(" --skip-apk-verification: do not attempt to verify APKs");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700155 UsageError("");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700156 UsageError(" --generate-boot-image-profile: Generate a boot image profile based on input");
157 UsageError(" profiles. Requires passing in dex files to inspect properties of classes.");
Calin Juravle48030c42020-06-17 19:16:01 -0700158 UsageError(" --method-threshold=percentage between 0 and 100");
159 UsageError(" what threshold to apply to the methods when deciding whether or not to");
160 UsageError(" include it in the final profile.");
161 UsageError(" --class-threshold=percentage between 0 and 100");
162 UsageError(" what threshold to apply to the classes when deciding whether or not to");
163 UsageError(" include it in the final profile.");
164 UsageError(" --clean-class-threshold=percentage between 0 and 100");
165 UsageError(" what threshold to apply to the clean classes when deciding whether or not to");
166 UsageError(" include it in the final profile.");
167 UsageError(" --preloaded-class-threshold=percentage between 0 and 100");
168 UsageError(" what threshold to apply to the classes when deciding whether or not to");
169 UsageError(" include it in the final preloaded classes.");
Orion Hodson3e8caeb2020-08-07 15:41:24 +0100170 UsageError(" --preloaded-classes-denylist=file");
Calin Juravle48030c42020-06-17 19:16:01 -0700171 UsageError(" a file listing the classes that should not be preloaded in Zygote");
172 UsageError(" --upgrade-startup-to-hot=true|false:");
173 UsageError(" whether or not to upgrade startup methods to hot");
174 UsageError(" --special-package=pkg_name:percentage between 0 and 100");
175 UsageError(" what threshold to apply to the methods/classes that are used by the given");
176 UsageError(" package when deciding whether or not to include it in the final profile.");
Calin Juravle0f7f4fc2020-05-11 20:16:50 -0700177 UsageError(" --debug-append-uses=bool: whether or not to append package use as debug info.");
178 UsageError(" --out-profile-path=path: boot image profile output path");
179 UsageError(" --out-preloaded-classes-path=path: preloaded classes output path");
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800180 UsageError(" --copy-and-update-profile-key: if present, profman will copy the profile from");
181 UsageError(" the file passed with --profile-fd(file) to the profile passed with");
182 UsageError(" --reference-profile-fd(file) and update at the same time the profile-key");
183 UsageError(" of entries corresponding to the apks passed with --apk(-fd).");
Calin Juravle0e82e0f2019-11-11 18:34:10 -0800184 UsageError(" --boot-image-merge: indicates that this merge is for a boot image profile.");
185 UsageError(" In this case, the reference profile must have a boot profile version.");
186 UsageError(" --force-merge: performs a forced merge, without analyzing if there is a");
187 UsageError(" significant difference between the current profile and the reference profile.");
yawanngb209a042020-11-11 20:17:56 +0000188 UsageError(" --min-new-methods-percent-change=percentage between 0 and 100 (default 20)");
yawanng7c618802020-11-05 20:02:27 +0000189 UsageError(" the min percent of new methods to trigger a compilation.");
yawanngb209a042020-11-11 20:17:56 +0000190 UsageError(" --min-new-classes-percent-change=percentage between 0 and 100 (default 20)");
yawanng7c618802020-11-05 20:02:27 +0000191 UsageError(" the min percent of new classes to trigger a compilation.");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700192 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000193
194 exit(EXIT_FAILURE);
195}
196
Calin Juravle7bcdb532016-06-07 16:14:47 +0100197// Note: make sure you update the Usage if you change these values.
198static constexpr uint16_t kDefaultTestProfileNumDex = 20;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700199static constexpr uint16_t kDefaultTestProfileMethodPercentage = 5;
200static constexpr uint16_t kDefaultTestProfileClassPercentage = 5;
Calin Juravle7bcdb532016-06-07 16:14:47 +0100201
Calin Juravlee0ac1152017-02-13 19:03:47 -0800202// Separators used when parsing human friendly representation of profiles.
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800203static const std::string kMethodSep = "->"; // NOLINT [runtime/string] [4]
204static const std::string kMissingTypesMarker = "missing_types"; // NOLINT [runtime/string] [4]
Alex Lighta2f13192021-02-03 18:19:03 -0800205static const std::string kMegamorphicTypesMarker = "megamorphic_types"; // NOLINT [runtime/string] [4]
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800206static const std::string kInvalidClassDescriptor = "invalid_class"; // NOLINT [runtime/string] [4]
207static const std::string kInvalidMethod = "invalid_method"; // NOLINT [runtime/string] [4]
208static const std::string kClassAllMethods = "*"; // NOLINT [runtime/string] [4]
Calin Juravle0fee1fb2020-05-11 20:03:20 -0700209static constexpr char kAnnotationStart = '{';
210static constexpr char kAnnotationEnd = '}';
Calin Juravlee0ac1152017-02-13 19:03:47 -0800211static constexpr char kProfileParsingInlineChacheSep = '+';
Alex Light0b58ec52021-03-02 14:11:59 -0800212static constexpr char kProfileParsingInlineChacheTargetSep = ']';
Calin Juravlee0ac1152017-02-13 19:03:47 -0800213static constexpr char kProfileParsingTypeSep = ',';
214static constexpr char kProfileParsingFirstCharInSignature = '(';
Mathieu Chartierea650f32017-05-24 12:04:13 -0700215static constexpr char kMethodFlagStringHot = 'H';
216static constexpr char kMethodFlagStringStartup = 'S';
217static constexpr char kMethodFlagStringPostStartup = 'P';
Calin Juravlee0ac1152017-02-13 19:03:47 -0800218
David Sehr671af6c2018-05-17 11:00:35 -0700219NO_RETURN static void Abort(const char* msg) {
220 LOG(ERROR) << msg;
221 exit(1);
222}
Vladimir Markoe5125562019-02-06 17:38:26 +0000223template <typename T>
Calin Juravle0f7f4fc2020-05-11 20:16:50 -0700224static void ParseUintValue(const std::string& option_name,
225 const std::string& value,
226 T* out,
227 T min = std::numeric_limits<T>::min(),
228 T max = std::numeric_limits<T>::max()) {
Vladimir Markoe5125562019-02-06 17:38:26 +0000229 int64_t parsed_integer_value = 0;
Calin Juravle0f7f4fc2020-05-11 20:16:50 -0700230 if (!android::base::ParseInt(
231 value,
232 &parsed_integer_value,
233 static_cast<int64_t>(min),
234 static_cast<int64_t>(max))) {
235 Usage("Failed to parse %s '%s' as an integer", option_name.c_str(), value.c_str());
Vladimir Markoe5125562019-02-06 17:38:26 +0000236 }
237 if (parsed_integer_value < 0) {
Vladimir Markoe5125562019-02-06 17:38:26 +0000238 Usage("%s passed a negative value %" PRId64, option_name.c_str(), parsed_integer_value);
239 }
240 if (static_cast<uint64_t>(parsed_integer_value) >
241 static_cast<std::make_unsigned_t<T>>(std::numeric_limits<T>::max())) {
Vladimir Markoe5125562019-02-06 17:38:26 +0000242 Usage("%s passed a value %" PRIu64 " above max (%" PRIu64 ")",
243 option_name.c_str(),
244 static_cast<uint64_t>(parsed_integer_value),
245 static_cast<uint64_t>(std::numeric_limits<T>::max()));
246 }
247 *out = dchecked_integral_cast<T>(parsed_integer_value);
248}
249
Calin Juravle0f7f4fc2020-05-11 20:16:50 -0700250template <typename T>
251static void ParseUintOption(const char* raw_option,
252 std::string_view option_prefix,
253 T* out,
254 T min = std::numeric_limits<T>::min(),
255 T max = std::numeric_limits<T>::max()) {
256 DCHECK(EndsWith(option_prefix, "="));
257 DCHECK(StartsWith(raw_option, option_prefix)) << raw_option << " " << option_prefix;
258 std::string option_name(option_prefix.substr(option_prefix.size() - 1u));
259 const char* value_string = raw_option + option_prefix.size();
260
261 ParseUintValue(option_name, value_string, out, min, max);
262}
263
264static void ParseBoolOption(const char* raw_option,
265 std::string_view option_prefix,
266 bool* out) {
267 DCHECK(EndsWith(option_prefix, "="));
268 DCHECK(StartsWith(raw_option, option_prefix)) << raw_option << " " << option_prefix;
269 const char* value_string = raw_option + option_prefix.size();
270 android::base::ParseBoolResult result = android::base::ParseBool(value_string);
271 if (result == android::base::ParseBoolResult::kError) {
272 std::string option_name(option_prefix.substr(option_prefix.size() - 1u));
273 Usage("Failed to parse %s '%s' as an integer", option_name.c_str(), value_string);
274 }
275
276 *out = result == android::base::ParseBoolResult::kTrue;
277}
278
Calin Juravlee0ac1152017-02-13 19:03:47 -0800279// TODO(calin): This class has grown too much from its initial design. Split the functionality
280// into smaller, more contained pieces.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100281class ProfMan final {
Calin Juravle2e2db782016-02-23 12:00:03 +0000282 public:
283 ProfMan() :
Orion Hodson365f94f2021-01-13 16:27:57 +0000284 reference_profile_file_fd_(File::kInvalidFd),
David Sehr4fcdd6d2016-05-24 14:52:31 -0700285 dump_only_(false),
Mathieu Chartier34067262017-04-06 13:55:46 -0700286 dump_classes_and_methods_(false),
Mathieu Chartier2f794552017-06-19 10:58:08 -0700287 generate_boot_image_profile_(false),
Alex Lighta2f13192021-02-03 18:19:03 -0800288 generate_boot_android_profile_(false),
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +0100289 generate_boot_profile_(false),
Orion Hodson365f94f2021-01-13 16:27:57 +0000290 dump_output_to_fd_(File::kInvalidFd),
Calin Juravle7bcdb532016-06-07 16:14:47 +0100291 test_profile_num_dex_(kDefaultTestProfileNumDex),
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700292 test_profile_method_percerntage_(kDefaultTestProfileMethodPercentage),
293 test_profile_class_percentage_(kDefaultTestProfileClassPercentage),
Jeff Haof0a31f82017-03-27 15:50:37 -0700294 test_profile_seed_(NanoTime()),
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800295 start_ns_(NanoTime()),
Calin Juravle0e82e0f2019-11-11 18:34:10 -0800296 copy_and_update_profile_key_(false),
297 profile_assistant_options_(ProfileAssistant::Options()) {}
Calin Juravle2e2db782016-02-23 12:00:03 +0000298
299 ~ProfMan() {
300 LogCompletionTime();
301 }
302
303 void ParseArgs(int argc, char **argv) {
304 original_argc = argc;
305 original_argv = argv;
306
David Sehr671af6c2018-05-17 11:00:35 -0700307 MemMap::Init();
308 InitLogging(argv, Abort);
Calin Juravle2e2db782016-02-23 12:00:03 +0000309
310 // Skip over the command name.
311 argv++;
312 argc--;
313
314 if (argc == 0) {
315 Usage("No arguments specified");
316 }
317
318 for (int i = 0; i < argc; ++i) {
Vladimir Markoe5125562019-02-06 17:38:26 +0000319 const char* raw_option = argv[i];
320 const std::string_view option(raw_option);
Calin Juravle2e2db782016-02-23 12:00:03 +0000321 const bool log_options = false;
322 if (log_options) {
Calin Juravle876f3502016-03-24 16:16:34 +0000323 LOG(INFO) << "profman: option[" << i << "]=" << argv[i];
Calin Juravle2e2db782016-02-23 12:00:03 +0000324 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700325 if (option == "--dump-only") {
326 dump_only_ = true;
Mathieu Chartier34067262017-04-06 13:55:46 -0700327 } else if (option == "--dump-classes-and-methods") {
328 dump_classes_and_methods_ = true;
Vladimir Markoe5125562019-02-06 17:38:26 +0000329 } else if (StartsWith(option, "--create-profile-from=")) {
330 create_profile_from_file_ = std::string(option.substr(strlen("--create-profile-from=")));
331 } else if (StartsWith(option, "--dump-output-to-fd=")) {
332 ParseUintOption(raw_option, "--dump-output-to-fd=", &dump_output_to_fd_);
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +0100333 } else if (option == "--generate-boot-profile") {
334 generate_boot_profile_ = true;
Mathieu Chartier2f794552017-06-19 10:58:08 -0700335 } else if (option == "--generate-boot-image-profile") {
336 generate_boot_image_profile_ = true;
Alex Lighta2f13192021-02-03 18:19:03 -0800337 } else if (option == "--generate-boot-android-profile") {
338 generate_boot_android_profile_ = true;
Calin Juravle0f7f4fc2020-05-11 20:16:50 -0700339 } else if (StartsWith(option, "--method-threshold=")) {
Vladimir Markoe5125562019-02-06 17:38:26 +0000340 ParseUintOption(raw_option,
Calin Juravle0f7f4fc2020-05-11 20:16:50 -0700341 "--method-threshold=",
342 &boot_image_options_.method_threshold,
343 0u,
344 100u);
345 } else if (StartsWith(option, "--class-threshold=")) {
Vladimir Markoe5125562019-02-06 17:38:26 +0000346 ParseUintOption(raw_option,
Calin Juravle0f7f4fc2020-05-11 20:16:50 -0700347 "--class-threshold=",
348 &boot_image_options_.image_class_threshold,
349 0u,
350 100u);
351 } else if (StartsWith(option, "--clean-class-threshold=")) {
Vladimir Markoe5125562019-02-06 17:38:26 +0000352 ParseUintOption(raw_option,
Calin Juravle0f7f4fc2020-05-11 20:16:50 -0700353 "--clean-class-threshold=",
354 &boot_image_options_.image_class_clean_threshold,
355 0u,
356 100u);
357 } else if (StartsWith(option, "--preloaded-class-threshold=")) {
358 ParseUintOption(raw_option,
359 "--preloaded-class-threshold=",
360 &boot_image_options_.preloaded_class_threshold,
361 0u,
362 100u);
Orion Hodson3e8caeb2020-08-07 15:41:24 +0100363 } else if (StartsWith(option, "--preloaded-classes-denylist=")) {
364 std::string preloaded_classes_denylist =
365 std::string(option.substr(strlen("--preloaded-classes-denylist=")));
Calin Juravle48030c42020-06-17 19:16:01 -0700366 // Read the user-specified list of methods.
367 std::unique_ptr<std::set<std::string>>
Orion Hodson3e8caeb2020-08-07 15:41:24 +0100368 denylist(ReadCommentedInputFromFile<std::set<std::string>>(
369 preloaded_classes_denylist.c_str(), nullptr)); // No post-processing.
370 boot_image_options_.preloaded_classes_denylist.insert(
371 denylist->begin(), denylist->end());
Calin Juravle0f7f4fc2020-05-11 20:16:50 -0700372 } else if (StartsWith(option, "--upgrade-startup-to-hot=")) {
373 ParseBoolOption(raw_option,
374 "--upgrade-startup-to-hot=",
375 &boot_image_options_.upgrade_startup_to_hot);
376 } else if (StartsWith(option, "--special-package=")) {
377 std::vector<std::string> values;
378 Split(std::string(option.substr(strlen("--special-package="))), ':', &values);
379 if (values.size() != 2) {
380 Usage("--special-package needs to be specified as pkg_name:threshold");
381 }
382 uint32_t threshold;
383 ParseUintValue("special-package", values[1], &threshold, 0u, 100u);
384 boot_image_options_.special_packages_thresholds.Overwrite(values[0], threshold);
385 } else if (StartsWith(option, "--debug-append-uses=")) {
386 ParseBoolOption(raw_option,
387 "--debug-append-uses=",
388 &boot_image_options_.append_package_use_list);
389 } else if (StartsWith(option, "--out-profile-path=")) {
390 boot_profile_out_path_ = std::string(option.substr(strlen("--out-profile-path=")));
391 } else if (StartsWith(option, "--out-preloaded-classes-path=")) {
392 preloaded_classes_out_path_ = std::string(
393 option.substr(strlen("--out-preloaded-classes-path=")));
Vladimir Markoe5125562019-02-06 17:38:26 +0000394 } else if (StartsWith(option, "--profile-file=")) {
395 profile_files_.push_back(std::string(option.substr(strlen("--profile-file="))));
396 } else if (StartsWith(option, "--profile-file-fd=")) {
397 ParseFdForCollection(raw_option, "--profile-file-fd=", &profile_files_fd_);
398 } else if (StartsWith(option, "--reference-profile-file=")) {
399 reference_profile_file_ = std::string(option.substr(strlen("--reference-profile-file=")));
400 } else if (StartsWith(option, "--reference-profile-file-fd=")) {
401 ParseUintOption(raw_option, "--reference-profile-file-fd=", &reference_profile_file_fd_);
402 } else if (StartsWith(option, "--dex-location=")) {
403 dex_locations_.push_back(std::string(option.substr(strlen("--dex-location="))));
404 } else if (StartsWith(option, "--apk-fd=")) {
405 ParseFdForCollection(raw_option, "--apk-fd=", &apks_fd_);
406 } else if (StartsWith(option, "--apk=")) {
407 apk_files_.push_back(std::string(option.substr(strlen("--apk="))));
408 } else if (StartsWith(option, "--generate-test-profile=")) {
409 test_profile_ = std::string(option.substr(strlen("--generate-test-profile=")));
410 } else if (StartsWith(option, "--generate-test-profile-num-dex=")) {
411 ParseUintOption(raw_option,
412 "--generate-test-profile-num-dex=",
413 &test_profile_num_dex_);
414 } else if (StartsWith(option, "--generate-test-profile-method-percentage=")) {
415 ParseUintOption(raw_option,
416 "--generate-test-profile-method-percentage=",
417 &test_profile_method_percerntage_);
418 } else if (StartsWith(option, "--generate-test-profile-class-percentage=")) {
419 ParseUintOption(raw_option,
420 "--generate-test-profile-class-percentage=",
421 &test_profile_class_percentage_);
422 } else if (StartsWith(option, "--generate-test-profile-seed=")) {
423 ParseUintOption(raw_option, "--generate-test-profile-seed=", &test_profile_seed_);
yawanng7c618802020-11-05 20:02:27 +0000424 } else if (StartsWith(option, "--min-new-methods-percent-change=")) {
425 uint32_t min_new_methods_percent_change;
426 ParseUintOption(raw_option,
427 "--min-new-methods-percent-change=",
428 &min_new_methods_percent_change,
429 0u,
430 100u);
431 profile_assistant_options_.SetMinNewMethodsPercentChangeForCompilation(
432 min_new_methods_percent_change);
433 } else if (StartsWith(option, "--min-new-classes-percent-change=")) {
434 uint32_t min_new_classes_percent_change;
435 ParseUintOption(raw_option,
436 "--min-new-classes-percent-change=",
437 &min_new_classes_percent_change,
438 0u,
439 100u);
440 profile_assistant_options_.SetMinNewClassesPercentChangeForCompilation(
441 min_new_classes_percent_change);
Vladimir Markoe5125562019-02-06 17:38:26 +0000442 } else if (option == "--copy-and-update-profile-key") {
Calin Juravle02c08792018-02-15 19:40:48 -0800443 copy_and_update_profile_key_ = true;
Calin Juravle0e82e0f2019-11-11 18:34:10 -0800444 } else if (option == "--boot-image-merge") {
445 profile_assistant_options_.SetBootImageMerge(true);
446 } else if (option == "--force-merge") {
447 profile_assistant_options_.SetForceMerge(true);
Calin Juravle2e2db782016-02-23 12:00:03 +0000448 } else {
Vladimir Markoe5125562019-02-06 17:38:26 +0000449 Usage("Unknown argument '%s'", raw_option);
Calin Juravle2e2db782016-02-23 12:00:03 +0000450 }
451 }
452
David Sehr153da0e2017-02-15 08:54:51 -0800453 // Validate global consistency between file/fd options.
Calin Juravle2e2db782016-02-23 12:00:03 +0000454 if (!profile_files_.empty() && !profile_files_fd_.empty()) {
455 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
456 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700457 if (!reference_profile_file_.empty() && FdIsValid(reference_profile_file_fd_)) {
458 Usage("Reference profile should not be specified with both "
459 "--reference-profile-file-fd and --reference-profile-file");
460 }
David Sehr153da0e2017-02-15 08:54:51 -0800461 if (!apk_files_.empty() && !apks_fd_.empty()) {
462 Usage("APK files should not be specified with both --apk-fd and --apk");
Calin Juravle2e2db782016-02-23 12:00:03 +0000463 }
464 }
465
Calin Juravlee10c1e22018-01-26 20:10:15 -0800466 struct ProfileFilterKey {
467 ProfileFilterKey(const std::string& dex_location, uint32_t checksum)
468 : dex_location_(dex_location), checksum_(checksum) {}
469 const std::string dex_location_;
470 uint32_t checksum_;
471
472 bool operator==(const ProfileFilterKey& other) const {
473 return checksum_ == other.checksum_ && dex_location_ == other.dex_location_;
474 }
475 bool operator<(const ProfileFilterKey& other) const {
476 return checksum_ == other.checksum_
477 ? dex_location_ < other.dex_location_
478 : checksum_ < other.checksum_;
479 }
480 };
481
Calin Juravle2e2db782016-02-23 12:00:03 +0000482 ProfileAssistant::ProcessingResult ProcessProfiles() {
David Sehr153da0e2017-02-15 08:54:51 -0800483 // Validate that at least one profile file was passed, as well as a reference profile.
484 if (profile_files_.empty() && profile_files_fd_.empty()) {
485 Usage("No profile files specified.");
486 }
487 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
488 Usage("No reference profile file specified.");
489 }
490 if ((!profile_files_.empty() && FdIsValid(reference_profile_file_fd_)) ||
491 (!profile_files_fd_.empty() && !FdIsValid(reference_profile_file_fd_))) {
492 Usage("Options --profile-file-fd and --reference-profile-file-fd "
493 "should only be used together");
494 }
Calin Juravlee10c1e22018-01-26 20:10:15 -0800495
496 // Check if we have any apks which we should use to filter the profile data.
497 std::set<ProfileFilterKey> profile_filter_keys;
498 if (!GetProfileFilterKeyFromApks(&profile_filter_keys)) {
499 return ProfileAssistant::kErrorIO;
500 }
501
502 // Build the profile filter function. If the set of keys is empty it means we
503 // don't have any apks; as such we do not filter anything.
504 const ProfileCompilationInfo::ProfileLoadFilterFn& filter_fn =
Calin Juravlead88cbe2019-11-11 18:43:15 -0800505 [profile_filter_keys](const std::string& profile_key, uint32_t checksum) {
Calin Juravlee10c1e22018-01-26 20:10:15 -0800506 if (profile_filter_keys.empty()) {
507 // No --apk was specified. Accept all dex files.
508 return true;
509 } else {
Calin Juravlead88cbe2019-11-11 18:43:15 -0800510 // Remove any annotations from the profile key before comparing with the keys we get from apks.
511 std::string base_key = ProfileCompilationInfo::GetBaseKeyFromAugmentedKey(profile_key);
512 return profile_filter_keys.find(ProfileFilterKey(base_key, checksum)) !=
513 profile_filter_keys.end();
Calin Juravlee10c1e22018-01-26 20:10:15 -0800514 }
515 };
516
Calin Juravle2e2db782016-02-23 12:00:03 +0000517 ProfileAssistant::ProcessingResult result;
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800518
Calin Juravle2e2db782016-02-23 12:00:03 +0000519 if (profile_files_.empty()) {
520 // The file doesn't need to be flushed here (ProcessProfiles will do it)
521 // so don't check the usage.
522 File file(reference_profile_file_fd_, false);
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800523 result = ProfileAssistant::ProcessProfiles(profile_files_fd_,
Calin Juravlee10c1e22018-01-26 20:10:15 -0800524 reference_profile_file_fd_,
Calin Juravle0e82e0f2019-11-11 18:34:10 -0800525 filter_fn,
526 profile_assistant_options_);
Calin Juravle2e2db782016-02-23 12:00:03 +0000527 CloseAllFds(profile_files_fd_, "profile_files_fd_");
528 } else {
Calin Juravlee10c1e22018-01-26 20:10:15 -0800529 result = ProfileAssistant::ProcessProfiles(profile_files_,
530 reference_profile_file_,
Calin Juravle0e82e0f2019-11-11 18:34:10 -0800531 filter_fn,
532 profile_assistant_options_);
Calin Juravle2e2db782016-02-23 12:00:03 +0000533 }
534 return result;
535 }
536
Calin Juravlee10c1e22018-01-26 20:10:15 -0800537 bool GetProfileFilterKeyFromApks(std::set<ProfileFilterKey>* profile_filter_keys) {
538 auto process_fn = [profile_filter_keys](std::unique_ptr<const DexFile>&& dex_file) {
539 // Store the profile key of the location instead of the location itself.
540 // This will make the matching in the profile filter method much easier.
Calin Juravle849439a2019-09-16 15:09:16 -0700541 profile_filter_keys->emplace(ProfileCompilationInfo::GetProfileDexFileBaseKey(
Calin Juravlee10c1e22018-01-26 20:10:15 -0800542 dex_file->GetLocation()), dex_file->GetLocationChecksum());
543 };
544 return OpenApkFilesFromLocations(process_fn);
545 }
546
547 bool OpenApkFilesFromLocations(std::vector<std::unique_ptr<const DexFile>>* dex_files) {
548 auto process_fn = [dex_files](std::unique_ptr<const DexFile>&& dex_file) {
549 dex_files->emplace_back(std::move(dex_file));
550 };
551 return OpenApkFilesFromLocations(process_fn);
552 }
553
554 bool OpenApkFilesFromLocations(
Andreas Gampebc802de2018-06-20 17:24:11 -0700555 const std::function<void(std::unique_ptr<const DexFile>&&)>& process_fn) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800556 bool use_apk_fd_list = !apks_fd_.empty();
557 if (use_apk_fd_list) {
David Sehr153da0e2017-02-15 08:54:51 -0800558 // Get the APKs from the collection of FDs.
Calin Juravlee10c1e22018-01-26 20:10:15 -0800559 if (dex_locations_.empty()) {
560 // Try to compute the dex locations from the file paths of the descriptions.
561 // This will make it easier to invoke profman with --apk-fd and without
562 // being force to pass --dex-location when the location would be the apk path.
563 if (!ComputeDexLocationsFromApkFds()) {
564 return false;
565 }
566 } else {
567 if (dex_locations_.size() != apks_fd_.size()) {
568 Usage("The number of apk-fds must match the number of dex-locations.");
569 }
570 }
David Sehr153da0e2017-02-15 08:54:51 -0800571 } else if (!apk_files_.empty()) {
Calin Juravle02c08792018-02-15 19:40:48 -0800572 if (dex_locations_.empty()) {
573 // If no dex locations are specified use the apk names as locations.
574 dex_locations_ = apk_files_;
575 } else if (dex_locations_.size() != apk_files_.size()) {
576 Usage("The number of apk-fds must match the number of dex-locations.");
577 }
David Sehr153da0e2017-02-15 08:54:51 -0800578 } else {
579 // No APKs were specified.
580 CHECK(dex_locations_.empty());
Calin Juravlee10c1e22018-01-26 20:10:15 -0800581 return true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800582 }
583 static constexpr bool kVerifyChecksum = true;
584 for (size_t i = 0; i < dex_locations_.size(); ++i) {
Mathieu Chartier818cb802018-05-11 05:30:16 +0000585 std::string error_msg;
586 const ArtDexFileLoader dex_file_loader;
587 std::vector<std::unique_ptr<const DexFile>> dex_files_for_location;
Calin Juravle1bfe4bd2018-04-26 16:00:11 -0700588 // We do not need to verify the apk for processing profiles.
David Sehr7c80f2d2017-02-07 16:47:58 -0800589 if (use_apk_fd_list) {
Mathieu Chartier818cb802018-05-11 05:30:16 +0000590 if (dex_file_loader.OpenZip(apks_fd_[i],
591 dex_locations_[i],
Andreas Gampe9b031f72018-10-04 11:03:34 -0700592 /* verify= */ false,
Mathieu Chartier818cb802018-05-11 05:30:16 +0000593 kVerifyChecksum,
594 &error_msg,
595 &dex_files_for_location)) {
596 } else {
597 LOG(ERROR) << "OpenZip failed for '" << dex_locations_[i] << "' " << error_msg;
Calin Juravlee10c1e22018-01-26 20:10:15 -0800598 return false;
David Sehr7c80f2d2017-02-07 16:47:58 -0800599 }
Mathieu Chartier818cb802018-05-11 05:30:16 +0000600 } else {
601 if (dex_file_loader.Open(apk_files_[i].c_str(),
602 dex_locations_[i],
Andreas Gampe9b031f72018-10-04 11:03:34 -0700603 /* verify= */ false,
Mathieu Chartier818cb802018-05-11 05:30:16 +0000604 kVerifyChecksum,
605 &error_msg,
606 &dex_files_for_location)) {
607 } else {
608 LOG(ERROR) << "Open failed for '" << dex_locations_[i] << "' " << error_msg;
609 return false;
610 }
David Sehr2b80ed42018-05-08 08:58:15 -0700611 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800612 for (std::unique_ptr<const DexFile>& dex_file : dex_files_for_location) {
Calin Juravlee10c1e22018-01-26 20:10:15 -0800613 process_fn(std::move(dex_file));
David Sehr7c80f2d2017-02-07 16:47:58 -0800614 }
615 }
Calin Juravlee10c1e22018-01-26 20:10:15 -0800616 return true;
617 }
618
619 // Get the dex locations from the apk fds.
620 // The methods reads the links from /proc/self/fd/ to find the original apk paths
621 // and puts them in the dex_locations_ vector.
622 bool ComputeDexLocationsFromApkFds() {
David Sehr9d9227a2018-12-19 12:32:50 -0800623#ifdef _WIN32
624 PLOG(ERROR) << "ComputeDexLocationsFromApkFds is unsupported on Windows.";
625 return false;
626#else
Calin Juravlee10c1e22018-01-26 20:10:15 -0800627 // We can't use a char array of PATH_MAX size without exceeding the frame size.
628 // So we use a vector as the buffer for the path.
629 std::vector<char> buffer(PATH_MAX, 0);
630 for (size_t i = 0; i < apks_fd_.size(); ++i) {
631 std::string fd_path = "/proc/self/fd/" + std::to_string(apks_fd_[i]);
632 ssize_t len = readlink(fd_path.c_str(), buffer.data(), buffer.size() - 1);
633 if (len == -1) {
634 PLOG(ERROR) << "Could not open path from fd";
635 return false;
636 }
637
638 buffer[len] = '\0';
639 dex_locations_.push_back(buffer.data());
640 }
641 return true;
David Sehr9d9227a2018-12-19 12:32:50 -0800642#endif
David Sehr7c80f2d2017-02-07 16:47:58 -0800643 }
644
Mathieu Chartier2f794552017-06-19 10:58:08 -0700645 std::unique_ptr<const ProfileCompilationInfo> LoadProfile(const std::string& filename, int fd) {
646 if (!filename.empty()) {
David Sehr9d9227a2018-12-19 12:32:50 -0800647#ifdef _WIN32
648 int flags = O_RDWR;
649#else
650 int flags = O_RDWR | O_CLOEXEC;
651#endif
652 fd = open(filename.c_str(), flags);
Mathieu Chartier2f794552017-06-19 10:58:08 -0700653 if (fd < 0) {
Elliott Hughes23a8eb62019-03-08 12:37:33 -0800654 PLOG(ERROR) << "Cannot open " << filename;
Mathieu Chartier2f794552017-06-19 10:58:08 -0700655 return nullptr;
656 }
657 }
658 std::unique_ptr<ProfileCompilationInfo> info(new ProfileCompilationInfo);
659 if (!info->Load(fd)) {
660 LOG(ERROR) << "Cannot load profile info from fd=" << fd << "\n";
661 return nullptr;
662 }
663 return info;
664 }
665
David Sehrb18991b2017-02-08 20:58:10 -0800666 int DumpOneProfile(const std::string& banner,
667 const std::string& filename,
668 int fd,
669 const std::vector<std::unique_ptr<const DexFile>>* dex_files,
670 std::string* dump) {
Mathieu Chartier2f794552017-06-19 10:58:08 -0700671 std::unique_ptr<const ProfileCompilationInfo> info(LoadProfile(filename, fd));
672 if (info == nullptr) {
673 LOG(ERROR) << "Cannot load profile info from filename=" << filename << " fd=" << fd;
Calin Juravle876f3502016-03-24 16:16:34 +0000674 return -1;
675 }
Mathieu Chartier0573f852018-10-01 13:52:12 -0700676 *dump += banner + "\n" + info->DumpInfo(MakeNonOwningPointerVector(*dex_files)) + "\n";
David Sehr4fcdd6d2016-05-24 14:52:31 -0700677 return 0;
678 }
679
680 int DumpProfileInfo() {
David Sehr153da0e2017-02-15 08:54:51 -0800681 // Validate that at least one profile file or reference was specified.
682 if (profile_files_.empty() && profile_files_fd_.empty() &&
683 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
684 Usage("No profile files or reference profile specified.");
685 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700686 static const char* kEmptyString = "";
David Sehr546d24f2016-06-02 10:46:19 -0700687 static const char* kOrdinaryProfile = "=== profile ===";
688 static const char* kReferenceProfile = "=== reference profile ===";
Mathieu Chartier0573f852018-10-01 13:52:12 -0700689 static const char* kDexFiles = "=== Dex files ===";
David Sehr546d24f2016-06-02 10:46:19 -0700690
David Sehrb18991b2017-02-08 20:58:10 -0800691 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7c80f2d2017-02-07 16:47:58 -0800692 OpenApkFilesFromLocations(&dex_files);
Mathieu Chartier0573f852018-10-01 13:52:12 -0700693
David Sehr4fcdd6d2016-05-24 14:52:31 -0700694 std::string dump;
Mathieu Chartier0573f852018-10-01 13:52:12 -0700695
696 // Dump checkfiles and corresponding checksums.
697 dump += kDexFiles;
698 dump += "\n";
699 for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
700 std::ostringstream oss;
701 oss << dex_file->GetLocation()
702 << " [checksum=" << std::hex << dex_file->GetLocationChecksum() << "]\n";
703 dump += oss.str();
704 }
705
David Sehr4fcdd6d2016-05-24 14:52:31 -0700706 // Dump individual profile files.
707 if (!profile_files_fd_.empty()) {
708 for (int profile_file_fd : profile_files_fd_) {
David Sehr546d24f2016-06-02 10:46:19 -0700709 int ret = DumpOneProfile(kOrdinaryProfile,
710 kEmptyString,
711 profile_file_fd,
712 &dex_files,
713 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700714 if (ret != 0) {
715 return ret;
716 }
717 }
718 }
Mathieu Chartier0573f852018-10-01 13:52:12 -0700719 for (const std::string& profile_file : profile_files_) {
Orion Hodson365f94f2021-01-13 16:27:57 +0000720 int ret = DumpOneProfile(kOrdinaryProfile, profile_file, File::kInvalidFd, &dex_files, &dump);
Mathieu Chartier0573f852018-10-01 13:52:12 -0700721 if (ret != 0) {
722 return ret;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700723 }
724 }
725 // Dump reference profile file.
726 if (FdIsValid(reference_profile_file_fd_)) {
David Sehr546d24f2016-06-02 10:46:19 -0700727 int ret = DumpOneProfile(kReferenceProfile,
728 kEmptyString,
729 reference_profile_file_fd_,
730 &dex_files,
731 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700732 if (ret != 0) {
733 return ret;
734 }
735 }
736 if (!reference_profile_file_.empty()) {
David Sehr546d24f2016-06-02 10:46:19 -0700737 int ret = DumpOneProfile(kReferenceProfile,
738 reference_profile_file_,
Orion Hodson365f94f2021-01-13 16:27:57 +0000739 File::kInvalidFd,
David Sehr546d24f2016-06-02 10:46:19 -0700740 &dex_files,
David Sehr4fcdd6d2016-05-24 14:52:31 -0700741 &dump);
742 if (ret != 0) {
743 return ret;
744 }
745 }
746 if (!FdIsValid(dump_output_to_fd_)) {
747 std::cout << dump;
748 } else {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700749 unix_file::FdFile out_fd(dump_output_to_fd_, /*check_usage=*/ false);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700750 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
751 return -1;
752 }
753 }
Calin Juravle876f3502016-03-24 16:16:34 +0000754 return 0;
755 }
756
757 bool ShouldOnlyDumpProfile() {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700758 return dump_only_;
Calin Juravle876f3502016-03-24 16:16:34 +0000759 }
760
Alex Lighta2f13192021-02-03 18:19:03 -0800761 // Creates the inline-cache portion of a text-profile line. If there is no
762 // inline-caches this will be and empty string. Otherwise it will be '@'
763 // followed by an IC description matching the format described by ProcessLine
764 // below. Note that this will collapse all ICs with the same receiver type.
765 std::string GetInlineCacheLine(const ProfileCompilationInfo& profile_info,
766 std::vector<std::unique_ptr<const DexFile>>* dex_files,
767 const dex::MethodId& id,
768 const DexFile* dex_file,
769 uint16_t dex_method_idx) {
770 auto method_info = profile_info.GetHotMethodInfo(MethodReference(dex_file, dex_method_idx));
771 if (method_info == nullptr || method_info->inline_caches->empty()) {
772 return "";
773 }
774 const ProfileCompilationInfo::InlineCacheMap* inline_caches = method_info->inline_caches;
775 struct IcLineInfo {
776 bool is_megamorphic_ = false;
777 bool is_missing_types_ = false;
778 std::set<TypeReference> classes_;
779 };
780 std::unordered_map<dex::TypeIndex, IcLineInfo> ics;
781 CodeItemInstructionAccessor accessor(
782 *dex_file,
783 dex_file->GetCodeItem(dex_file->FindCodeItemOffset(*dex_file->FindClassDef(id.class_idx_),
784 dex_method_idx)));
785 for (const auto& [pc, ic_data] : *inline_caches) {
786 const Instruction& inst = accessor.InstructionAt(pc);
787 const dex::MethodId& target = dex_file->GetMethodId(inst.VRegB());
788 if (ic_data.classes.empty() && !ic_data.is_megamorphic && !ic_data.is_missing_types) {
789 continue;
790 }
791 auto val = ics.find(target.class_idx_);
792 if (val == ics.end()) {
793 val = ics.insert({ target.class_idx_, {} }).first;
794 }
795 if (ic_data.is_megamorphic) {
796 val->second.is_megamorphic_ = true;
797 }
798 if (ic_data.is_missing_types) {
799 val->second.is_missing_types_ = true;
800 }
801 for (auto cls : ic_data.classes) {
802 auto it = std::find_if(dex_files->begin(), dex_files->end(), [&](const auto& d) {
803 return method_info->dex_references[cls.dex_profile_index].MatchesDex(&*d);
804 });
805 if (it == dex_files->end()) {
806 val->second.is_missing_types_ = true;
807 continue;
808 }
809 val->second.classes_.insert({ it->get(), cls.type_index });
810 }
811 }
812 if (ics.empty()) {
813 return "";
814 }
815 std::ostringstream dump_ic;
816 dump_ic << kProfileParsingInlineChacheSep;
817 for (const auto& [target, dex_data] : ics) {
818 dump_ic << kProfileParsingInlineChacheTargetSep;
819 dump_ic << dex_file->GetTypeDescriptor(dex_file->GetTypeId(target));
820 if (dex_data.is_missing_types_) {
821 dump_ic << kMissingTypesMarker;
822 } else if (dex_data.is_megamorphic_) {
823 dump_ic << kMegamorphicTypesMarker;
824 } else {
825 bool first = true;
826 for (const auto& klass : dex_data.classes_) {
827 if (!first) {
828 dump_ic << kProfileParsingTypeSep;
829 }
830 first = false;
831 dump_ic << klass.dex_file->GetTypeDescriptor(
832 klass.dex_file->GetTypeId(klass.TypeIndex()));
833 }
834 }
835 }
836 return dump_ic.str();
837 }
838
Mathieu Chartier34067262017-04-06 13:55:46 -0700839 bool GetClassNamesAndMethods(int fd,
840 std::vector<std::unique_ptr<const DexFile>>* dex_files,
841 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800842 ProfileCompilationInfo profile_info;
843 if (!profile_info.Load(fd)) {
844 LOG(ERROR) << "Cannot load profile info";
845 return false;
846 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700847 for (const std::unique_ptr<const DexFile>& dex_file : *dex_files) {
848 std::set<dex::TypeIndex> class_types;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700849 std::set<uint16_t> hot_methods;
850 std::set<uint16_t> startup_methods;
851 std::set<uint16_t> post_startup_methods;
852 std::set<uint16_t> combined_methods;
853 if (profile_info.GetClassesAndMethods(*dex_file.get(),
854 &class_types,
855 &hot_methods,
856 &startup_methods,
857 &post_startup_methods)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700858 for (const dex::TypeIndex& type_index : class_types) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800859 const dex::TypeId& type_id = dex_file->GetTypeId(type_index);
Mathieu Chartier34067262017-04-06 13:55:46 -0700860 out_lines->insert(std::string(dex_file->GetTypeDescriptor(type_id)));
861 }
Mathieu Chartierea650f32017-05-24 12:04:13 -0700862 combined_methods = hot_methods;
863 combined_methods.insert(startup_methods.begin(), startup_methods.end());
864 combined_methods.insert(post_startup_methods.begin(), post_startup_methods.end());
865 for (uint16_t dex_method_idx : combined_methods) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800866 const dex::MethodId& id = dex_file->GetMethodId(dex_method_idx);
Mathieu Chartier34067262017-04-06 13:55:46 -0700867 std::string signature_string(dex_file->GetMethodSignature(id).ToString());
868 std::string type_string(dex_file->GetTypeDescriptor(dex_file->GetTypeId(id.class_idx_)));
869 std::string method_name(dex_file->GetMethodName(id));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700870 std::string flags_string;
871 if (hot_methods.find(dex_method_idx) != hot_methods.end()) {
872 flags_string += kMethodFlagStringHot;
873 }
874 if (startup_methods.find(dex_method_idx) != startup_methods.end()) {
875 flags_string += kMethodFlagStringStartup;
876 }
877 if (post_startup_methods.find(dex_method_idx) != post_startup_methods.end()) {
878 flags_string += kMethodFlagStringPostStartup;
879 }
Alex Lighta2f13192021-02-03 18:19:03 -0800880 std::string inline_cache_string =
881 GetInlineCacheLine(profile_info, dex_files, id, dex_file.get(), dex_method_idx);
882 out_lines->insert(flags_string + type_string + kMethodSep + method_name +
883 signature_string + inline_cache_string);
Mathieu Chartier34067262017-04-06 13:55:46 -0700884 }
885 }
886 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800887 return true;
888 }
889
Mathieu Chartier34067262017-04-06 13:55:46 -0700890 bool GetClassNamesAndMethods(const std::string& profile_file,
891 std::vector<std::unique_ptr<const DexFile>>* dex_files,
892 std::set<std::string>* out_lines) {
David Sehr9d9227a2018-12-19 12:32:50 -0800893#ifdef _WIN32
894 int flags = O_RDONLY;
895#else
896 int flags = O_RDONLY | O_CLOEXEC;
897#endif
898 int fd = open(profile_file.c_str(), flags);
David Sehr7c80f2d2017-02-07 16:47:58 -0800899 if (!FdIsValid(fd)) {
Elliott Hughes23a8eb62019-03-08 12:37:33 -0800900 PLOG(ERROR) << "Cannot open " << profile_file;
David Sehr7c80f2d2017-02-07 16:47:58 -0800901 return false;
902 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700903 if (!GetClassNamesAndMethods(fd, dex_files, out_lines)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800904 return false;
905 }
906 if (close(fd) < 0) {
907 PLOG(WARNING) << "Failed to close descriptor";
908 }
909 return true;
910 }
911
Mathieu Chartierea650f32017-05-24 12:04:13 -0700912 int DumpClassesAndMethods() {
David Sehr153da0e2017-02-15 08:54:51 -0800913 // Validate that at least one profile file or reference was specified.
914 if (profile_files_.empty() && profile_files_fd_.empty() &&
915 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
916 Usage("No profile files or reference profile specified.");
917 }
Calin Juravlee10c1e22018-01-26 20:10:15 -0800918
David Sehr7c80f2d2017-02-07 16:47:58 -0800919 // Open the dex files to get the names for classes.
920 std::vector<std::unique_ptr<const DexFile>> dex_files;
921 OpenApkFilesFromLocations(&dex_files);
922 // Build a vector of class names from individual profile files.
923 std::set<std::string> class_names;
924 if (!profile_files_fd_.empty()) {
925 for (int profile_file_fd : profile_files_fd_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700926 if (!GetClassNamesAndMethods(profile_file_fd, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800927 return -1;
928 }
929 }
930 }
931 if (!profile_files_.empty()) {
932 for (const std::string& profile_file : profile_files_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700933 if (!GetClassNamesAndMethods(profile_file, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800934 return -1;
935 }
936 }
937 }
938 // Concatenate class names from reference profile file.
939 if (FdIsValid(reference_profile_file_fd_)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700940 if (!GetClassNamesAndMethods(reference_profile_file_fd_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800941 return -1;
942 }
943 }
944 if (!reference_profile_file_.empty()) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700945 if (!GetClassNamesAndMethods(reference_profile_file_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800946 return -1;
947 }
948 }
949 // Dump the class names.
950 std::string dump;
951 for (const std::string& class_name : class_names) {
952 dump += class_name + std::string("\n");
953 }
954 if (!FdIsValid(dump_output_to_fd_)) {
955 std::cout << dump;
956 } else {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700957 unix_file::FdFile out_fd(dump_output_to_fd_, /*check_usage=*/ false);
David Sehr7c80f2d2017-02-07 16:47:58 -0800958 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
959 return -1;
960 }
961 }
962 return 0;
963 }
964
Mathieu Chartier34067262017-04-06 13:55:46 -0700965 bool ShouldOnlyDumpClassesAndMethods() {
966 return dump_classes_and_methods_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800967 }
968
969 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
970 // the given function.
971 template <typename T>
972 static T* ReadCommentedInputFromFile(
973 const char* input_filename, std::function<std::string(const char*)>* process) {
974 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
975 if (input_file.get() == nullptr) {
976 LOG(ERROR) << "Failed to open input file " << input_filename;
977 return nullptr;
978 }
979 std::unique_ptr<T> result(
980 ReadCommentedInputStream<T>(*input_file, process));
981 input_file->close();
982 return result.release();
983 }
984
985 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
986 // with the given function.
987 template <typename T>
988 static T* ReadCommentedInputStream(
989 std::istream& in_stream,
990 std::function<std::string(const char*)>* process) {
991 std::unique_ptr<T> output(new T());
992 while (in_stream.good()) {
993 std::string dot;
994 std::getline(in_stream, dot);
995 if (android::base::StartsWith(dot, "#") || dot.empty()) {
996 continue;
997 }
998 if (process != nullptr) {
999 std::string descriptor((*process)(dot.c_str()));
1000 output->insert(output->end(), descriptor);
1001 } else {
1002 output->insert(output->end(), dot);
1003 }
1004 }
1005 return output.release();
1006 }
1007
Calin Juravlee0ac1152017-02-13 19:03:47 -08001008 // Find class klass_descriptor in the given dex_files and store its reference
1009 // in the out parameter class_ref.
Nicolas Geoffrayf5e26f82019-08-13 15:21:05 +01001010 // Return true if the definition or a reference of the class was found in any
1011 // of the dex_files.
Calin Juravlee0ac1152017-02-13 19:03:47 -08001012 bool FindClass(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
Alex Lighta2f13192021-02-03 18:19:03 -08001013 const std::string_view& klass_descriptor,
1014 /*out*/ TypeReference* class_ref) {
1015 return FindClass(
1016 ArrayRef<const std::unique_ptr<const DexFile>>(dex_files), klass_descriptor, class_ref);
1017 }
1018
1019 bool FindClass(ArrayRef<const std::unique_ptr<const DexFile>> dex_files,
1020 const std::string_view& klass_descriptor,
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001021 /*out*/TypeReference* class_ref) {
Calin Juravle08556882017-05-26 16:40:45 -07001022 constexpr uint16_t kInvalidTypeIndex = std::numeric_limits<uint16_t>::max() - 1;
Calin Juravlee0ac1152017-02-13 19:03:47 -08001023 for (const std::unique_ptr<const DexFile>& dex_file_ptr : dex_files) {
1024 const DexFile* dex_file = dex_file_ptr.get();
Calin Juravle08556882017-05-26 16:40:45 -07001025 if (klass_descriptor == kInvalidClassDescriptor) {
1026 if (kInvalidTypeIndex >= dex_file->NumTypeIds()) {
1027 // The dex file does not contain all possible type ids which leaves us room
1028 // to add an "invalid" type id.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07001029 *class_ref = TypeReference(dex_file, dex::TypeIndex(kInvalidTypeIndex));
Calin Juravle08556882017-05-26 16:40:45 -07001030 return true;
1031 } else {
1032 // The dex file contains all possible type ids. We don't have any free type id
1033 // that we can use as invalid.
1034 continue;
1035 }
1036 }
1037
Alex Lighta2f13192021-02-03 18:19:03 -08001038 const dex::TypeId* type_id = dex_file->FindTypeId(klass_descriptor);
Calin Juravlee0ac1152017-02-13 19:03:47 -08001039 if (type_id == nullptr) {
1040 continue;
1041 }
1042 dex::TypeIndex type_index = dex_file->GetIndexForTypeId(*type_id);
Nicolas Geoffrayf5e26f82019-08-13 15:21:05 +01001043 *class_ref = TypeReference(dex_file, type_index);
1044
Calin Juravlee0ac1152017-02-13 19:03:47 -08001045 if (dex_file->FindClassDef(type_index) == nullptr) {
1046 // Class is only referenced in the current dex file but not defined in it.
Nicolas Geoffrayf5e26f82019-08-13 15:21:05 +01001047 // We use its current type reference, but keep looking for its
1048 // definition.
1049 // Note that array classes fall into that category, as they do not have
1050 // a class definition.
Calin Juravlee0ac1152017-02-13 19:03:47 -08001051 continue;
1052 }
Calin Juravlee0ac1152017-02-13 19:03:47 -08001053 return true;
1054 }
Nicolas Geoffrayf5e26f82019-08-13 15:21:05 +01001055 // If we arrive here, we haven't found a class definition. If the dex file
1056 // of the class reference is not null, then we have found a type reference,
1057 // and we return that to the caller.
1058 return (class_ref->dex_file != nullptr);
Calin Juravlee0ac1152017-02-13 19:03:47 -08001059 }
1060
Mathieu Chartier34067262017-04-06 13:55:46 -07001061 // Find the method specified by method_spec in the class class_ref.
Calin Juravle08556882017-05-26 16:40:45 -07001062 uint32_t FindMethodIndex(const TypeReference& class_ref,
1063 const std::string& method_spec) {
1064 const DexFile* dex_file = class_ref.dex_file;
1065 if (method_spec == kInvalidMethod) {
1066 constexpr uint16_t kInvalidMethodIndex = std::numeric_limits<uint16_t>::max() - 1;
1067 return kInvalidMethodIndex >= dex_file->NumMethodIds()
1068 ? kInvalidMethodIndex
Andreas Gampee2abbc62017-09-15 11:59:26 -07001069 : dex::kDexNoIndex;
Calin Juravle08556882017-05-26 16:40:45 -07001070 }
1071
Calin Juravlee0ac1152017-02-13 19:03:47 -08001072 std::vector<std::string> name_and_signature;
1073 Split(method_spec, kProfileParsingFirstCharInSignature, &name_and_signature);
1074 if (name_and_signature.size() != 2) {
1075 LOG(ERROR) << "Invalid method name and signature " << method_spec;
Andreas Gampee2abbc62017-09-15 11:59:26 -07001076 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -08001077 }
Calin Juravle08556882017-05-26 16:40:45 -07001078
Calin Juravlee0ac1152017-02-13 19:03:47 -08001079 const std::string& name = name_and_signature[0];
1080 const std::string& signature = kProfileParsingFirstCharInSignature + name_and_signature[1];
Calin Juravlee0ac1152017-02-13 19:03:47 -08001081
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001082 const dex::StringId* name_id = dex_file->FindStringId(name.c_str());
Calin Juravlee0ac1152017-02-13 19:03:47 -08001083 if (name_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -07001084 LOG(WARNING) << "Could not find name: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -07001085 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -08001086 }
1087 dex::TypeIndex return_type_idx;
1088 std::vector<dex::TypeIndex> param_type_idxs;
1089 if (!dex_file->CreateTypeList(signature, &return_type_idx, &param_type_idxs)) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -07001090 LOG(WARNING) << "Could not create type list" << signature;
Andreas Gampee2abbc62017-09-15 11:59:26 -07001091 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -08001092 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001093 const dex::ProtoId* proto_id = dex_file->FindProtoId(return_type_idx, param_type_idxs);
Calin Juravlee0ac1152017-02-13 19:03:47 -08001094 if (proto_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -07001095 LOG(WARNING) << "Could not find proto_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -07001096 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -08001097 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001098 const dex::MethodId* method_id = dex_file->FindMethodId(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07001099 dex_file->GetTypeId(class_ref.TypeIndex()), *name_id, *proto_id);
Calin Juravlee0ac1152017-02-13 19:03:47 -08001100 if (method_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -07001101 LOG(WARNING) << "Could not find method_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -07001102 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -08001103 }
1104
Mathieu Chartier34067262017-04-06 13:55:46 -07001105 return dex_file->GetIndexForMethodId(*method_id);
1106 }
Calin Juravlee0ac1152017-02-13 19:03:47 -08001107
Alex Lighta2f13192021-02-03 18:19:03 -08001108 template <typename Visitor>
1109 void VisitAllInstructions(const TypeReference& class_ref, uint16_t method_idx, Visitor visitor) {
1110 const DexFile* dex_file = class_ref.dex_file;
1111 uint32_t offset =
1112 dex_file->FindCodeItemOffset(*dex_file->FindClassDef(class_ref.TypeIndex()), method_idx);
1113 for (const DexInstructionPcPair& inst :
1114 CodeItemInstructionAccessor(*dex_file, dex_file->GetCodeItem(offset))) {
1115 if (!visitor(inst)) {
1116 break;
1117 }
1118 }
1119 }
1120
1121 // Get dex-pcs of any virtual + interface invokes referencing a method of the
1122 // 'target' type in the given method.
1123 void GetAllInvokes(const TypeReference& class_ref,
1124 uint16_t method_idx,
1125 dex::TypeIndex target,
1126 /*out*/ std::vector<uint32_t>* dex_pcs) {
1127 const DexFile* dex_file = class_ref.dex_file;
1128 VisitAllInstructions(class_ref, method_idx, [&](const DexInstructionPcPair& inst) -> bool {
1129 switch (inst->Opcode()) {
1130 case Instruction::INVOKE_INTERFACE:
1131 case Instruction::INVOKE_INTERFACE_RANGE:
1132 case Instruction::INVOKE_VIRTUAL:
1133 case Instruction::INVOKE_VIRTUAL_RANGE: {
1134 const dex::MethodId& meth = dex_file->GetMethodId(inst->VRegB());
1135 if (meth.class_idx_ == target) {
1136 dex_pcs->push_back(inst.DexPc());
1137 }
1138 break;
1139 }
1140 default:
1141 break;
1142 }
1143 return true;
1144 });
1145 }
1146
Mathieu Chartier34067262017-04-06 13:55:46 -07001147 // Given a method, return true if the method has a single INVOKE_VIRTUAL in its byte code.
1148 // Upon success it returns true and stores the method index and the invoke dex pc
1149 // in the output parameters.
1150 // The format of the method spec is "inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001151 bool HasSingleInvoke(const TypeReference& class_ref,
Mathieu Chartier34067262017-04-06 13:55:46 -07001152 uint16_t method_index,
Alex Lighta2f13192021-02-03 18:19:03 -08001153 /*out*/ uint32_t* dex_pc) {
Calin Juravlee0ac1152017-02-13 19:03:47 -08001154 bool found_invoke = false;
Alex Lighta2f13192021-02-03 18:19:03 -08001155 bool found_multiple_invokes = false;
1156 VisitAllInstructions(class_ref, method_index, [&](const DexInstructionPcPair& inst) -> bool {
Rico Windc24fa5d2018-04-25 12:44:58 +02001157 if (inst->Opcode() == Instruction::INVOKE_VIRTUAL ||
Alex Lighta2f13192021-02-03 18:19:03 -08001158 inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE ||
1159 inst->Opcode() == Instruction::INVOKE_INTERFACE ||
1160 inst->Opcode() == Instruction::INVOKE_INTERFACE_RANGE) {
Calin Juravlee0ac1152017-02-13 19:03:47 -08001161 if (found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -07001162 LOG(ERROR) << "Multiple invoke INVOKE_VIRTUAL found: "
Alex Lighta2f13192021-02-03 18:19:03 -08001163 << class_ref.dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -08001164 return false;
1165 }
1166 found_invoke = true;
Mathieu Chartier0021feb2017-11-07 00:08:52 -08001167 *dex_pc = inst.DexPc();
Calin Juravlee0ac1152017-02-13 19:03:47 -08001168 }
Alex Lighta2f13192021-02-03 18:19:03 -08001169 return true;
1170 });
Calin Juravlee0ac1152017-02-13 19:03:47 -08001171 if (!found_invoke) {
Alex Lighta2f13192021-02-03 18:19:03 -08001172 LOG(ERROR) << "Could not find any INVOKE_VIRTUAL/INTERFACE: "
1173 << class_ref.dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -08001174 }
Alex Lighta2f13192021-02-03 18:19:03 -08001175 return found_invoke && !found_multiple_invokes;
Calin Juravlee0ac1152017-02-13 19:03:47 -08001176 }
1177
Alex Lighta2f13192021-02-03 18:19:03 -08001178 struct InlineCacheSegment {
1179 public:
1180 using IcArray =
1181 std::array<std::string_view, ProfileCompilationInfo::kIndividualInlineCacheSize + 1>;
1182 static void SplitInlineCacheSegment(std::string_view ic_line,
1183 /*out*/ std::vector<InlineCacheSegment>* res) {
1184 if (ic_line[0] != kProfileParsingInlineChacheTargetSep) {
1185 // single target
1186 InlineCacheSegment out;
1187 Split(ic_line, kProfileParsingTypeSep, &out.inline_caches_);
1188 res->push_back(out);
1189 return;
1190 }
1191 std::vector<std::string_view> targets_and_resolutions;
1192 // Avoid a zero-length entry.
1193 for (std::string_view t :
1194 SplitString(ic_line.substr(1), kProfileParsingInlineChacheTargetSep)) {
1195 InlineCacheSegment out;
1196 DCHECK_EQ(t[0], 'L') << "Target is not a class? " << t;
1197 size_t recv_end = t.find_first_of(';');
1198 out.receiver_ = t.substr(0, recv_end + 1);
1199 Split(t.substr(recv_end + 1), kProfileParsingTypeSep, &out.inline_caches_);
1200 res->push_back(out);
1201 }
1202 }
1203
1204 bool IsSingleReceiver() const {
1205 return !receiver_.has_value();
1206 }
1207
1208 const std::string_view& GetReceiverType() const {
1209 DCHECK(!IsSingleReceiver());
1210 return *receiver_;
1211 }
1212
1213 const IcArray& GetIcTargets() const {
1214 return inline_caches_;
1215 }
1216
1217 size_t NumIcTargets() const {
1218 return std::count_if(
1219 inline_caches_.begin(), inline_caches_.end(), [](const auto& x) { return !x.empty(); });
1220 }
1221
1222 std::ostream& Dump(std::ostream& os) const {
1223 if (!IsSingleReceiver()) {
1224 os << "[" << GetReceiverType();
1225 }
1226 bool first = true;
1227 for (std::string_view target : inline_caches_) {
1228 if (target.empty()) {
1229 break;
1230 } else if (!first) {
1231 os << ",";
1232 }
1233 first = false;
1234 os << target;
1235 }
1236 return os;
1237 }
1238
1239 private:
1240 std::optional<std::string_view> receiver_;
1241 // Max number of ics in the profile file. Don't need to store more than this
1242 // (although internally we can have as many as we want). If we fill this up
1243 // we are megamorphic.
1244 IcArray inline_caches_;
1245
1246 friend std::ostream& operator<<(std::ostream& os, const InlineCacheSegment& ics);
1247 };
1248
Calin Juravlee0ac1152017-02-13 19:03:47 -08001249 // Process a line defining a class or a method and its inline caches.
1250 // Upon success return true and add the class or the method info to profile.
Alex Lighta2f13192021-02-03 18:19:03 -08001251 // Inline caches are identified by the type of the declared receiver type.
Calin Juravle589e71e2017-03-03 16:05:05 -08001252 // The possible line formats are:
Calin Juravle0fee1fb2020-05-11 20:03:20 -07001253 // "LJustTheClass;".
Calin Juravlee0ac1152017-02-13 19:03:47 -08001254 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
Calin Juravle08556882017-05-26 16:40:45 -07001255 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,invalid_class".
Calin Juravle589e71e2017-03-03 16:05:05 -08001256 // "LTestInline;->inlineMissingTypes(LSuper;)I+missing_types".
Alex Lighta2f13192021-02-03 18:19:03 -08001257 // // Note no ',' after [LTarget;
Alex Light0b58ec52021-03-02 14:11:59 -08001258 // "LTestInline;->multiInlinePolymorphic(LSuper;)I+]LTarget1;LResA;,LResB;]LTarget2;LResC;,LResD;".
1259 // "LTestInline;->multiInlinePolymorphic(LSuper;)I+]LTarget1;LResA;,invalid_class]LTarget2;LResC;,LResD;".
1260 // "LTestInline;->multiInlinePolymorphic(LSuper;)I+]LTarget1;missing_types]LTarget2;LResC;,LResD;".
Calin Juravle0fee1fb2020-05-11 20:03:20 -07001261 // "{annotation}LTestInline;->inlineNoInlineCaches(LSuper;)I".
Mathieu Chartierd808e8b2017-03-21 13:37:41 -07001262 // "LTestInline;->*".
Calin Juravle08556882017-05-26 16:40:45 -07001263 // "invalid_class".
1264 // "LTestInline;->invalid_method".
Calin Juravlee0ac1152017-02-13 19:03:47 -08001265 // The method and classes are searched only in the given dex files.
1266 bool ProcessLine(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
Calin Juravle0fee1fb2020-05-11 20:03:20 -07001267 const std::string& maybe_annotated_line,
Calin Juravlee0ac1152017-02-13 19:03:47 -08001268 /*out*/ProfileCompilationInfo* profile) {
Calin Juravle0fee1fb2020-05-11 20:03:20 -07001269 // First, process the annotation.
1270 if (maybe_annotated_line.empty()) {
1271 return true;
1272 }
1273 // Working line variable which will contain the user input without the annotations.
1274 std::string line = maybe_annotated_line;
1275
1276 std::string annotation_string;
1277 if (maybe_annotated_line[0] == kAnnotationStart) {
1278 size_t end_pos = maybe_annotated_line.find(kAnnotationEnd, 0);
1279 if (end_pos == std::string::npos || end_pos == 0) {
1280 LOG(ERROR) << "Invalid line: " << maybe_annotated_line;
1281 return false;
1282 }
1283 annotation_string = maybe_annotated_line.substr(1, end_pos - 1);
1284 // Update the working line.
1285 line = maybe_annotated_line.substr(end_pos + 1);
1286 }
1287
1288 ProfileSampleAnnotation annotation = annotation_string.empty()
1289 ? ProfileSampleAnnotation::kNone
1290 : ProfileSampleAnnotation(annotation_string);
1291
1292 // Now process the rest of the lines.
Calin Juravlee0ac1152017-02-13 19:03:47 -08001293 std::string klass;
1294 std::string method_str;
Mathieu Chartierea650f32017-05-24 12:04:13 -07001295 bool is_hot = false;
1296 bool is_startup = false;
1297 bool is_post_startup = false;
1298 const size_t method_sep_index = line.find(kMethodSep, 0);
Calin Juravlee0ac1152017-02-13 19:03:47 -08001299 if (method_sep_index == std::string::npos) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001300 klass = line.substr(0);
Calin Juravlee0ac1152017-02-13 19:03:47 -08001301 } else {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001302 // The method prefix flags are only valid for method strings.
1303 size_t start_index = 0;
1304 while (start_index < line.size() && line[start_index] != 'L') {
1305 const char c = line[start_index];
1306 if (c == kMethodFlagStringHot) {
1307 is_hot = true;
1308 } else if (c == kMethodFlagStringStartup) {
1309 is_startup = true;
1310 } else if (c == kMethodFlagStringPostStartup) {
1311 is_post_startup = true;
1312 } else {
1313 LOG(WARNING) << "Invalid flag " << c;
1314 return false;
1315 }
1316 ++start_index;
1317 }
1318 klass = line.substr(start_index, method_sep_index - start_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -08001319 method_str = line.substr(method_sep_index + kMethodSep.size());
1320 }
1321
Calin Juravleee9cb412018-02-13 20:32:35 -08001322 uint32_t flags = 0;
1323 if (is_hot) {
1324 flags |= ProfileCompilationInfo::MethodHotness::kFlagHot;
1325 }
1326 if (is_startup) {
1327 flags |= ProfileCompilationInfo::MethodHotness::kFlagStartup;
1328 }
1329 if (is_post_startup) {
1330 flags |= ProfileCompilationInfo::MethodHotness::kFlagPostStartup;
1331 }
1332
Andreas Gampe9b031f72018-10-04 11:03:34 -07001333 TypeReference class_ref(/* dex_file= */ nullptr, dex::TypeIndex());
Calin Juravlee0ac1152017-02-13 19:03:47 -08001334 if (!FindClass(dex_files, klass, &class_ref)) {
Mathieu Chartier3f121342017-03-06 11:16:20 -08001335 LOG(WARNING) << "Could not find class: " << klass;
Calin Juravlee0ac1152017-02-13 19:03:47 -08001336 return false;
1337 }
1338
Mathieu Chartierd808e8b2017-03-21 13:37:41 -07001339 if (method_str.empty() || method_str == kClassAllMethods) {
1340 // Start by adding the class.
Calin Juravlee0ac1152017-02-13 19:03:47 -08001341 const DexFile* dex_file = class_ref.dex_file;
Mathieu Chartierd808e8b2017-03-21 13:37:41 -07001342 std::vector<ProfileMethodInfo> methods;
1343 if (method_str == kClassAllMethods) {
Mathieu Chartier18e26872018-06-04 17:19:02 -07001344 ClassAccessor accessor(
1345 *dex_file,
1346 dex_file->GetIndexForClassDef(*dex_file->FindClassDef(class_ref.TypeIndex())));
Mathieu Chartier0d896bd2018-05-25 00:20:27 -07001347 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
Mathieu Chartier20f49922018-05-24 16:04:17 -07001348 if (method.GetCodeItemOffset() != 0) {
1349 // Add all of the methods that have code to the profile.
1350 methods.push_back(ProfileMethodInfo(method.GetReference()));
Mathieu Chartierd808e8b2017-03-21 13:37:41 -07001351 }
Mathieu Chartier0d896bd2018-05-25 00:20:27 -07001352 }
Mathieu Chartierd808e8b2017-03-21 13:37:41 -07001353 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001354 // TODO: Check return values?
Calin Juravle0fee1fb2020-05-11 20:03:20 -07001355 profile->AddMethods(
1356 methods, static_cast<ProfileCompilationInfo::MethodHotness::Flag>(flags), annotation);
Calin Juravlea6c9b782019-09-16 18:57:26 -07001357 std::set<dex::TypeIndex> classes;
1358 classes.insert(class_ref.TypeIndex());
Calin Juravle0fee1fb2020-05-11 20:03:20 -07001359 profile->AddClassesForDex(dex_file, classes.begin(), classes.end(), annotation);
Calin Juravlee0ac1152017-02-13 19:03:47 -08001360 return true;
1361 }
1362
1363 // Process the method.
1364 std::string method_spec;
Calin Juravlee0ac1152017-02-13 19:03:47 -08001365
Mathieu Chartierea650f32017-05-24 12:04:13 -07001366 // If none of the flags are set, default to hot.
1367 is_hot = is_hot || (!is_hot && !is_startup && !is_post_startup);
1368
Calin Juravlee0ac1152017-02-13 19:03:47 -08001369 std::vector<std::string> method_elems;
Alex Lighta2f13192021-02-03 18:19:03 -08001370 // Lifetime of segments is same as method_elems since it contains pointers into the string-data
1371 std::vector<InlineCacheSegment> segments;
Calin Juravlee0ac1152017-02-13 19:03:47 -08001372 Split(method_str, kProfileParsingInlineChacheSep, &method_elems);
1373 if (method_elems.size() == 2) {
1374 method_spec = method_elems[0];
Alex Lighta2f13192021-02-03 18:19:03 -08001375 InlineCacheSegment::SplitInlineCacheSegment(method_elems[1], &segments);
Calin Juravlee0ac1152017-02-13 19:03:47 -08001376 } else if (method_elems.size() == 1) {
1377 method_spec = method_elems[0];
1378 } else {
1379 LOG(ERROR) << "Invalid method line: " << line;
1380 return false;
1381 }
1382
Mathieu Chartier34067262017-04-06 13:55:46 -07001383 const uint32_t method_index = FindMethodIndex(class_ref, method_spec);
Andreas Gampee2abbc62017-09-15 11:59:26 -07001384 if (method_index == dex::kDexNoIndex) {
Calin Juravlee0ac1152017-02-13 19:03:47 -08001385 return false;
1386 }
Mathieu Chartier34067262017-04-06 13:55:46 -07001387
Mathieu Chartier34067262017-04-06 13:55:46 -07001388 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Alex Lighta2f13192021-02-03 18:19:03 -08001389 for (const InlineCacheSegment& segment : segments) {
1390 std::vector<uint32_t> dex_pcs;
1391 if (segment.IsSingleReceiver()) {
1392 DCHECK_EQ(segments.size(), 1u);
1393 dex_pcs.resize(1, -1);
1394 // TODO This single invoke format should really be phased out and removed.
1395 if (!HasSingleInvoke(class_ref, method_index, &dex_pcs[0])) {
Mathieu Chartier34067262017-04-06 13:55:46 -07001396 return false;
1397 }
Alex Lighta2f13192021-02-03 18:19:03 -08001398 } else {
1399 // Get the type-ref the method code will use.
1400 std::string receiver_str(segment.GetReceiverType());
1401 const dex::TypeId* type_id = class_ref.dex_file->FindTypeId(receiver_str.c_str());
1402 if (type_id == nullptr) {
1403 LOG(WARNING) << "Could not find class: " << segment.GetReceiverType() << " in dex-file "
1404 << class_ref.dex_file << ". Ignoring IC group: '" << segment << "'";
1405 continue;
1406 }
1407 dex::TypeIndex target_index = class_ref.dex_file->GetIndexForTypeId(*type_id);
1408
1409 GetAllInvokes(class_ref, method_index, target_index, &dex_pcs);
Mathieu Chartier34067262017-04-06 13:55:46 -07001410 }
Alex Lighta2f13192021-02-03 18:19:03 -08001411 bool missing_types = segment.GetIcTargets()[0] == kMissingTypesMarker;
1412 bool megamorphic_types = segment.GetIcTargets()[0] == kMegamorphicTypesMarker;
1413 std::vector<TypeReference> classes(
1414 missing_types || megamorphic_types ? 0u : segment.NumIcTargets(),
1415 TypeReference(/* dex_file= */ nullptr, dex::TypeIndex()));
1416 if (!missing_types && !megamorphic_types) {
1417 size_t class_it = 0;
1418 for (const std::string_view& ic_class : segment.GetIcTargets()) {
1419 if (ic_class.empty()) {
1420 break;
1421 }
1422 if (!FindClass(dex_files, ic_class, &(classes[class_it++]))) {
1423 LOG(segment.IsSingleReceiver() ? ERROR : WARNING)
1424 << "Could not find class: " << ic_class << " in " << segment;
1425 if (segment.IsSingleReceiver()) {
1426 return false;
1427 } else {
1428 // Be a bit more forgiving with profiles from servers.
1429 missing_types = true;
1430 classes.clear();
1431 break;
1432 }
1433 }
1434 }
1435 // Make sure we are actually the correct size
1436 classes.resize(class_it, TypeReference(nullptr, dex::TypeIndex()));
1437 }
1438 for (size_t dex_pc : dex_pcs) {
1439 inline_caches.emplace_back(dex_pc, missing_types, classes, megamorphic_types);
1440 }
Calin Juravlee0ac1152017-02-13 19:03:47 -08001441 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001442 MethodReference ref(class_ref.dex_file, method_index);
Mathieu Chartierea650f32017-05-24 12:04:13 -07001443 if (is_hot) {
Calin Juravleee9cb412018-02-13 20:32:35 -08001444 profile->AddMethod(ProfileMethodInfo(ref, inline_caches),
Calin Juravle0fee1fb2020-05-11 20:03:20 -07001445 static_cast<ProfileCompilationInfo::MethodHotness::Flag>(flags),
1446 annotation);
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001447 }
1448 if (flags != 0) {
Calin Juravlea6c9b782019-09-16 18:57:26 -07001449 if (!profile->AddMethod(ProfileMethodInfo(ref),
Calin Juravle0fee1fb2020-05-11 20:03:20 -07001450 static_cast<ProfileCompilationInfo::MethodHotness::Flag>(flags),
1451 annotation)) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001452 return false;
1453 }
Calin Juravle0fee1fb2020-05-11 20:03:20 -07001454 DCHECK(profile->GetMethodHotness(ref, annotation).IsInProfile()) << method_spec;
Mathieu Chartierea650f32017-05-24 12:04:13 -07001455 }
Calin Juravlee0ac1152017-02-13 19:03:47 -08001456 return true;
1457 }
1458
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +01001459 bool ProcessBootLine(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
1460 const std::string& line,
1461 ProfileBootInfo* boot_profiling_info) {
1462 const size_t method_sep_index = line.find(kMethodSep, 0);
1463 std::string klass_str = line.substr(0, method_sep_index);
1464 std::string method_str = line.substr(method_sep_index + kMethodSep.size());
1465
1466 TypeReference class_ref(/* dex_file= */ nullptr, dex::TypeIndex());
1467 if (!FindClass(dex_files, klass_str, &class_ref)) {
1468 LOG(WARNING) << "Could not find class: " << klass_str;
1469 return false;
1470 }
1471
1472 const uint32_t method_index = FindMethodIndex(class_ref, method_str);
1473 if (method_index == dex::kDexNoIndex) {
1474 LOG(WARNING) << "Could not find method: " << line;
1475 return false;
1476 }
1477 boot_profiling_info->Add(class_ref.dex_file, method_index);
1478 return true;
1479 }
1480
Mathieu Chartier2f794552017-06-19 10:58:08 -07001481 int OpenReferenceProfile() const {
1482 int fd = reference_profile_file_fd_;
1483 if (!FdIsValid(fd)) {
1484 CHECK(!reference_profile_file_.empty());
David Sehr9d9227a2018-12-19 12:32:50 -08001485#ifdef _WIN32
1486 int flags = O_CREAT | O_TRUNC | O_WRONLY;
1487#else
1488 int flags = O_CREAT | O_TRUNC | O_WRONLY | O_CLOEXEC;
1489#endif
1490 fd = open(reference_profile_file_.c_str(), flags, 0644);
Mathieu Chartier2f794552017-06-19 10:58:08 -07001491 if (fd < 0) {
Elliott Hughes23a8eb62019-03-08 12:37:33 -08001492 PLOG(ERROR) << "Cannot open " << reference_profile_file_;
Orion Hodson365f94f2021-01-13 16:27:57 +00001493 return File::kInvalidFd;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001494 }
1495 }
1496 return fd;
1497 }
1498
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +01001499 // Create and store a ProfileBootInfo.
1500 int CreateBootProfile() {
1501 // Validate parameters for this command.
1502 if (apk_files_.empty() && apks_fd_.empty()) {
1503 Usage("APK files must be specified");
1504 }
1505 if (dex_locations_.empty()) {
1506 Usage("DEX locations must be specified");
1507 }
1508 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
1509 Usage("Reference profile must be specified with --reference-profile-file or "
1510 "--reference-profile-file-fd");
1511 }
1512 if (!profile_files_.empty() || !profile_files_fd_.empty()) {
1513 Usage("Profile must be specified with --reference-profile-file or "
1514 "--reference-profile-file-fd");
1515 }
1516 // Open the profile output file if needed.
1517 int fd = OpenReferenceProfile();
1518 if (!FdIsValid(fd)) {
1519 return -1;
1520 }
1521 // Read the user-specified list of methods.
1522 std::unique_ptr<std::vector<std::string>>
1523 user_lines(ReadCommentedInputFromFile<std::vector<std::string>>(
1524 create_profile_from_file_.c_str(), nullptr)); // No post-processing.
1525
1526 // Open the dex files to look up classes and methods.
1527 std::vector<std::unique_ptr<const DexFile>> dex_files;
1528 OpenApkFilesFromLocations(&dex_files);
1529
1530 // Process the lines one by one and add the successful ones to the profile.
1531 ProfileBootInfo info;
1532
1533 for (const auto& line : *user_lines) {
1534 ProcessBootLine(dex_files, line, &info);
1535 }
1536
1537 // Write the profile file.
1538 CHECK(info.Save(fd));
1539
1540 if (close(fd) < 0) {
1541 PLOG(WARNING) << "Failed to close descriptor";
1542 }
1543
1544 return 0;
1545 }
1546
Calin Juravlee0ac1152017-02-13 19:03:47 -08001547 // Creates a profile from a human friendly textual representation.
1548 // The expected input format is:
1549 // # Classes
1550 // Ljava/lang/Comparable;
1551 // Ljava/lang/Math;
1552 // # Methods with inline caches
1553 // LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;
1554 // LTestInline;->noInlineCache(LSuper;)I
David Sehr7c80f2d2017-02-07 16:47:58 -08001555 int CreateProfile() {
David Sehr153da0e2017-02-15 08:54:51 -08001556 // Validate parameters for this command.
1557 if (apk_files_.empty() && apks_fd_.empty()) {
1558 Usage("APK files must be specified");
1559 }
1560 if (dex_locations_.empty()) {
1561 Usage("DEX locations must be specified");
1562 }
1563 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
1564 Usage("Reference profile must be specified with --reference-profile-file or "
1565 "--reference-profile-file-fd");
1566 }
1567 if (!profile_files_.empty() || !profile_files_fd_.empty()) {
1568 Usage("Profile must be specified with --reference-profile-file or "
1569 "--reference-profile-file-fd");
1570 }
David Sehr7c80f2d2017-02-07 16:47:58 -08001571 // Open the profile output file if needed.
Mathieu Chartier2f794552017-06-19 10:58:08 -07001572 int fd = OpenReferenceProfile();
David Sehr7c80f2d2017-02-07 16:47:58 -08001573 if (!FdIsValid(fd)) {
David Sehr7c80f2d2017-02-07 16:47:58 -08001574 return -1;
David Sehr7c80f2d2017-02-07 16:47:58 -08001575 }
Calin Juravlee0ac1152017-02-13 19:03:47 -08001576 // Read the user-specified list of classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -08001577 std::unique_ptr<std::unordered_set<std::string>>
Calin Juravlee0ac1152017-02-13 19:03:47 -08001578 user_lines(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
David Sehr7c80f2d2017-02-07 16:47:58 -08001579 create_profile_from_file_.c_str(), nullptr)); // No post-processing.
Calin Juravlee0ac1152017-02-13 19:03:47 -08001580
1581 // Open the dex files to look up classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -08001582 std::vector<std::unique_ptr<const DexFile>> dex_files;
1583 OpenApkFilesFromLocations(&dex_files);
Calin Juravlee0ac1152017-02-13 19:03:47 -08001584
1585 // Process the lines one by one and add the successful ones to the profile.
Alex Lighta2f13192021-02-03 18:19:03 -08001586 ProfileCompilationInfo info(/*for_boot_image=*/ ShouldCreateBootAndroidProfile());
Calin Juravlee0ac1152017-02-13 19:03:47 -08001587
1588 for (const auto& line : *user_lines) {
1589 ProcessLine(dex_files, line, &info);
1590 }
1591
David Sehr7c80f2d2017-02-07 16:47:58 -08001592 // Write the profile file.
1593 CHECK(info.Save(fd));
1594 if (close(fd) < 0) {
1595 PLOG(WARNING) << "Failed to close descriptor";
1596 }
1597 return 0;
1598 }
1599
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +01001600 bool ShouldCreateBootImageProfile() const {
Mathieu Chartier2f794552017-06-19 10:58:08 -07001601 return generate_boot_image_profile_;
1602 }
1603
Alex Lighta2f13192021-02-03 18:19:03 -08001604 bool ShouldCreateBootAndroidProfile() const {
1605 return generate_boot_android_profile_;
1606 }
1607
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +01001608 bool ShouldCreateBootProfile() const {
1609 return generate_boot_profile_;
1610 }
1611
1612 // Create and store a ProfileCompilationInfo for the boot image.
1613 int CreateBootImageProfile() {
Calin Juravle0f7f4fc2020-05-11 20:16:50 -07001614 // Open the input profile file.
Calin Juravle0e02d612020-06-18 18:05:29 -07001615 if (profile_files_.size() < 1) {
1616 LOG(ERROR) << "At least one --profile-file must be specified.";
Mathieu Chartier2f794552017-06-19 10:58:08 -07001617 return -1;
1618 }
1619 // Open the dex files.
1620 std::vector<std::unique_ptr<const DexFile>> dex_files;
1621 OpenApkFilesFromLocations(&dex_files);
1622 if (dex_files.empty()) {
1623 PLOG(ERROR) << "Expected dex files for creating boot profile";
1624 return -2;
1625 }
Calin Juravle0f7f4fc2020-05-11 20:16:50 -07001626
Calin Juravle0f7f4fc2020-05-11 20:16:50 -07001627 if (!GenerateBootImageProfile(dex_files,
Calin Juravle0e02d612020-06-18 18:05:29 -07001628 profile_files_,
Calin Juravle0f7f4fc2020-05-11 20:16:50 -07001629 boot_image_options_,
1630 boot_profile_out_path_,
1631 preloaded_classes_out_path_)) {
1632 LOG(ERROR) << "There was an error when generating the boot image profiles";
1633 return -4;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001634 }
Mathieu Chartier2f794552017-06-19 10:58:08 -07001635 return 0;
1636 }
1637
David Sehr7c80f2d2017-02-07 16:47:58 -08001638 bool ShouldCreateProfile() {
1639 return !create_profile_from_file_.empty();
1640 }
1641
Calin Juravle7bcdb532016-06-07 16:14:47 +01001642 int GenerateTestProfile() {
David Sehr153da0e2017-02-15 08:54:51 -08001643 // Validate parameters for this command.
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001644 if (test_profile_method_percerntage_ > 100) {
1645 Usage("Invalid percentage for --generate-test-profile-method-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001646 }
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001647 if (test_profile_class_percentage_ > 100) {
1648 Usage("Invalid percentage for --generate-test-profile-class-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001649 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001650 // If given APK files or DEX locations, check that they're ok.
1651 if (!apk_files_.empty() || !apks_fd_.empty() || !dex_locations_.empty()) {
1652 if (apk_files_.empty() && apks_fd_.empty()) {
1653 Usage("APK files must be specified when passing DEX locations to --generate-test-profile");
1654 }
1655 if (dex_locations_.empty()) {
1656 Usage("DEX locations must be specified when passing APK files to --generate-test-profile");
1657 }
1658 }
David Sehr153da0e2017-02-15 08:54:51 -08001659 // ShouldGenerateTestProfile confirms !test_profile_.empty().
David Sehr9d9227a2018-12-19 12:32:50 -08001660#ifdef _WIN32
1661 int flags = O_CREAT | O_TRUNC | O_WRONLY;
1662#else
1663 int flags = O_CREAT | O_TRUNC | O_WRONLY | O_CLOEXEC;
1664#endif
1665 int profile_test_fd = open(test_profile_.c_str(), flags, 0644);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001666 if (profile_test_fd < 0) {
Elliott Hughes23a8eb62019-03-08 12:37:33 -08001667 PLOG(ERROR) << "Cannot open " << test_profile_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001668 return -1;
1669 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001670 bool result;
1671 if (apk_files_.empty() && apks_fd_.empty() && dex_locations_.empty()) {
1672 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1673 test_profile_num_dex_,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001674 test_profile_method_percerntage_,
1675 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001676 test_profile_seed_);
1677 } else {
Jeff Haof0a31f82017-03-27 15:50:37 -07001678 // Open the dex files to look up classes and methods.
1679 std::vector<std::unique_ptr<const DexFile>> dex_files;
1680 OpenApkFilesFromLocations(&dex_files);
1681 // Create a random profile file based on the set of dex files.
1682 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1683 dex_files,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001684 test_profile_method_percerntage_,
1685 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001686 test_profile_seed_);
1687 }
Calin Juravle7bcdb532016-06-07 16:14:47 +01001688 close(profile_test_fd); // ignore close result.
1689 return result ? 0 : -1;
1690 }
1691
1692 bool ShouldGenerateTestProfile() {
1693 return !test_profile_.empty();
1694 }
1695
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001696 bool ShouldCopyAndUpdateProfileKey() const {
1697 return copy_and_update_profile_key_;
1698 }
1699
Calin Juravle02c08792018-02-15 19:40:48 -08001700 int32_t CopyAndUpdateProfileKey() {
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001701 // Validate that at least one profile file was passed, as well as a reference profile.
1702 if (!(profile_files_.size() == 1 ^ profile_files_fd_.size() == 1)) {
1703 Usage("Only one profile file should be specified.");
1704 }
1705 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
1706 Usage("No reference profile file specified.");
1707 }
1708
1709 if (apk_files_.empty() && apks_fd_.empty()) {
1710 Usage("No apk files specified");
1711 }
1712
Calin Juravle02c08792018-02-15 19:40:48 -08001713 static constexpr int32_t kErrorFailedToUpdateProfile = -1;
1714 static constexpr int32_t kErrorFailedToSaveProfile = -2;
1715 static constexpr int32_t kErrorFailedToLoadProfile = -3;
1716
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001717 bool use_fds = profile_files_fd_.size() == 1;
1718
1719 ProfileCompilationInfo profile;
1720 // Do not clear if invalid. The input might be an archive.
Calin Juravle02c08792018-02-15 19:40:48 -08001721 bool load_ok = use_fds
1722 ? profile.Load(profile_files_fd_[0])
Andreas Gampe9b031f72018-10-04 11:03:34 -07001723 : profile.Load(profile_files_[0], /*clear_if_invalid=*/ false);
Calin Juravle02c08792018-02-15 19:40:48 -08001724 if (load_ok) {
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001725 // Open the dex files to look up classes and methods.
1726 std::vector<std::unique_ptr<const DexFile>> dex_files;
1727 OpenApkFilesFromLocations(&dex_files);
1728 if (!profile.UpdateProfileKeys(dex_files)) {
Calin Juravle02c08792018-02-15 19:40:48 -08001729 return kErrorFailedToUpdateProfile;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001730 }
Calin Juravle02c08792018-02-15 19:40:48 -08001731 bool result = use_fds
1732 ? profile.Save(reference_profile_file_fd_)
Andreas Gampe9b031f72018-10-04 11:03:34 -07001733 : profile.Save(reference_profile_file_, /*bytes_written=*/ nullptr);
Calin Juravle02c08792018-02-15 19:40:48 -08001734 return result ? 0 : kErrorFailedToSaveProfile;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001735 } else {
Calin Juravle02c08792018-02-15 19:40:48 -08001736 return kErrorFailedToLoadProfile;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001737 }
1738 }
1739
Calin Juravle2e2db782016-02-23 12:00:03 +00001740 private:
Vladimir Markoe5125562019-02-06 17:38:26 +00001741 static void ParseFdForCollection(const char* raw_option,
1742 std::string_view option_prefix,
Calin Juravle2e2db782016-02-23 12:00:03 +00001743 std::vector<int>* fds) {
1744 int fd;
Vladimir Markoe5125562019-02-06 17:38:26 +00001745 ParseUintOption(raw_option, option_prefix, &fd);
Calin Juravle2e2db782016-02-23 12:00:03 +00001746 fds->push_back(fd);
1747 }
1748
1749 static void CloseAllFds(const std::vector<int>& fds, const char* descriptor) {
1750 for (size_t i = 0; i < fds.size(); i++) {
1751 if (close(fds[i]) < 0) {
Calin Juravlee10c1e22018-01-26 20:10:15 -08001752 PLOG(WARNING) << "Failed to close descriptor for "
1753 << descriptor << " at index " << i << ": " << fds[i];
Calin Juravle2e2db782016-02-23 12:00:03 +00001754 }
1755 }
1756 }
1757
1758 void LogCompletionTime() {
David Sehr52683cf2016-05-05 09:02:38 -07001759 static constexpr uint64_t kLogThresholdTime = MsToNs(100); // 100ms
1760 uint64_t time_taken = NanoTime() - start_ns_;
David Sehred793012016-05-05 13:39:43 -07001761 if (time_taken > kLogThresholdTime) {
David Sehrd8557182016-05-06 12:29:35 -07001762 LOG(WARNING) << "profman took " << PrettyDuration(time_taken);
David Sehred793012016-05-05 13:39:43 -07001763 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001764 }
1765
1766 std::vector<std::string> profile_files_;
1767 std::vector<int> profile_files_fd_;
David Sehr546d24f2016-06-02 10:46:19 -07001768 std::vector<std::string> dex_locations_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001769 std::vector<std::string> apk_files_;
David Sehr546d24f2016-06-02 10:46:19 -07001770 std::vector<int> apks_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001771 std::string reference_profile_file_;
1772 int reference_profile_file_fd_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001773 bool dump_only_;
Mathieu Chartier34067262017-04-06 13:55:46 -07001774 bool dump_classes_and_methods_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001775 bool generate_boot_image_profile_;
Alex Lighta2f13192021-02-03 18:19:03 -08001776 bool generate_boot_android_profile_;
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +01001777 bool generate_boot_profile_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001778 int dump_output_to_fd_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001779 BootImageOptions boot_image_options_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001780 std::string test_profile_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001781 std::string create_profile_from_file_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001782 uint16_t test_profile_num_dex_;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001783 uint16_t test_profile_method_percerntage_;
1784 uint16_t test_profile_class_percentage_;
Jeff Haof0a31f82017-03-27 15:50:37 -07001785 uint32_t test_profile_seed_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001786 uint64_t start_ns_;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001787 bool copy_and_update_profile_key_;
Calin Juravle0e82e0f2019-11-11 18:34:10 -08001788 ProfileAssistant::Options profile_assistant_options_;
Calin Juravle0f7f4fc2020-05-11 20:16:50 -07001789 std::string boot_profile_out_path_;
1790 std::string preloaded_classes_out_path_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001791};
1792
Alex Lighta2f13192021-02-03 18:19:03 -08001793std::ostream& operator<<(std::ostream& os, const ProfMan::InlineCacheSegment& ics) {
1794 return ics.Dump(os);
1795}
1796
Calin Juravle2e2db782016-02-23 12:00:03 +00001797// See ProfileAssistant::ProcessingResult for return codes.
1798static int profman(int argc, char** argv) {
1799 ProfMan profman;
1800
1801 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1802 profman.ParseArgs(argc, argv);
1803
Calin Juravlee10c1e22018-01-26 20:10:15 -08001804 // Initialize MemMap for ZipArchive::OpenFromFd.
1805 MemMap::Init();
1806
Calin Juravle7bcdb532016-06-07 16:14:47 +01001807 if (profman.ShouldGenerateTestProfile()) {
1808 return profman.GenerateTestProfile();
1809 }
Calin Juravle876f3502016-03-24 16:16:34 +00001810 if (profman.ShouldOnlyDumpProfile()) {
1811 return profman.DumpProfileInfo();
1812 }
Mathieu Chartier34067262017-04-06 13:55:46 -07001813 if (profman.ShouldOnlyDumpClassesAndMethods()) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001814 return profman.DumpClassesAndMethods();
David Sehr7c80f2d2017-02-07 16:47:58 -08001815 }
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +01001816 if (profman.ShouldCreateBootProfile()) {
1817 return profman.CreateBootProfile();
1818 }
David Sehr7c80f2d2017-02-07 16:47:58 -08001819 if (profman.ShouldCreateProfile()) {
1820 return profman.CreateProfile();
1821 }
Mathieu Chartier2f794552017-06-19 10:58:08 -07001822
Nicolas Geoffraya0fc13a2019-07-23 15:48:39 +01001823 if (profman.ShouldCreateBootImageProfile()) {
1824 return profman.CreateBootImageProfile();
Mathieu Chartier2f794552017-06-19 10:58:08 -07001825 }
Calin Juravle02c08792018-02-15 19:40:48 -08001826
1827 if (profman.ShouldCopyAndUpdateProfileKey()) {
1828 return profman.CopyAndUpdateProfileKey();
1829 }
1830
Calin Juravle2e2db782016-02-23 12:00:03 +00001831 // Process profile information and assess if we need to do a profile guided compilation.
1832 // This operation involves I/O.
1833 return profman.ProcessProfiles();
1834}
1835
1836} // namespace art
1837
1838int main(int argc, char **argv) {
1839 return art::profman(argc, argv);
1840}