blob: ffc3c0170fd8ca400ebcac56552351a3237b9ea6 [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>
21#include <sys/stat.h>
22#include <unistd.h>
23
David Sehr7c80f2d2017-02-07 16:47:58 -080024#include <fstream>
Calin Juravle876f3502016-03-24 16:16:34 +000025#include <iostream>
David Sehr7c80f2d2017-02-07 16:47:58 -080026#include <set>
Calin Juravle2e2db782016-02-23 12:00:03 +000027#include <string>
David Sehr7c80f2d2017-02-07 16:47:58 -080028#include <unordered_set>
Calin Juravle2e2db782016-02-23 12:00:03 +000029#include <vector>
30
Andreas Gampe46ee31b2016-12-14 10:11:49 -080031#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080032#include "android-base/strings.h"
33
Calin Juravle2e2db782016-02-23 12:00:03 +000034#include "base/dumpable.h"
Andreas Gampe57943812017-12-06 21:39:13 -080035#include "base/logging.h" // For InitLogging.
Calin Juravle2e2db782016-02-23 12:00:03 +000036#include "base/scoped_flock.h"
37#include "base/stringpiece.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000038#include "base/time_utils.h"
39#include "base/unix_file/fd_file.h"
Mathieu Chartier2f794552017-06-19 10:58:08 -070040#include "boot_image_profile.h"
Calin Juravlee0ac1152017-02-13 19:03:47 -080041#include "bytecode_utils.h"
David Sehr013fd802018-01-11 22:55:24 -080042#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080043#include "dex/code_item_accessors-inl.h"
44#include "dex/dex_file.h"
45#include "dex/dex_file_loader.h"
46#include "dex/dex_file_types.h"
Calin Juravle33083d62017-01-18 15:29:12 -080047#include "jit/profile_compilation_info.h"
Mathieu Chartierdbddc222017-05-24 12:04:13 -070048#include "profile_assistant.h"
David Sehrf57589f2016-10-17 10:09:33 -070049#include "runtime.h"
Mathieu Chartierdbddc222017-05-24 12:04:13 -070050#include "type_reference.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000051#include "utils.h"
David Sehr546d24f2016-06-02 10:46:19 -070052#include "zip_archive.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000053
54namespace art {
55
56static int original_argc;
57static char** original_argv;
58
59static std::string CommandLine() {
60 std::vector<std::string> command;
61 for (int i = 0; i < original_argc; ++i) {
62 command.push_back(original_argv[i]);
63 }
Andreas Gampe9186ced2016-12-12 14:28:21 -080064 return android::base::Join(command, ' ');
Calin Juravle2e2db782016-02-23 12:00:03 +000065}
66
David Sehr4fcdd6d2016-05-24 14:52:31 -070067static constexpr int kInvalidFd = -1;
68
69static bool FdIsValid(int fd) {
70 return fd != kInvalidFd;
71}
72
Calin Juravle2e2db782016-02-23 12:00:03 +000073static void UsageErrorV(const char* fmt, va_list ap) {
74 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080075 android::base::StringAppendV(&error, fmt, ap);
Calin Juravle2e2db782016-02-23 12:00:03 +000076 LOG(ERROR) << error;
77}
78
79static void UsageError(const char* fmt, ...) {
80 va_list ap;
81 va_start(ap, fmt);
82 UsageErrorV(fmt, ap);
83 va_end(ap);
84}
85
86NO_RETURN static void Usage(const char *fmt, ...) {
87 va_list ap;
88 va_start(ap, fmt);
89 UsageErrorV(fmt, ap);
90 va_end(ap);
91
92 UsageError("Command: %s", CommandLine().c_str());
93 UsageError("Usage: profman [options]...");
94 UsageError("");
David Sehr4fcdd6d2016-05-24 14:52:31 -070095 UsageError(" --dump-only: dumps the content of the specified profile files");
96 UsageError(" to standard output (default) in a human readable form.");
97 UsageError("");
David Sehr7c80f2d2017-02-07 16:47:58 -080098 UsageError(" --dump-output-to-fd=<number>: redirects --dump-only output to a file descriptor.");
99 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -0700100 UsageError(" --dump-classes-and-methods: dumps a sorted list of classes and methods that are");
101 UsageError(" in the specified profile file to standard output (default) in a human");
102 UsageError(" readable form. The output is valid input for --create-profile-from");
Calin Juravle876f3502016-03-24 16:16:34 +0000103 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000104 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
105 UsageError(" Can be specified multiple time, in which case the data from the different");
106 UsageError(" profiles will be aggregated.");
107 UsageError("");
108 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
109 UsageError(" Cannot be used together with --profile-file.");
110 UsageError("");
111 UsageError(" --reference-profile-file=<filename>: specify a reference profile.");
112 UsageError(" The data in this file will be compared with the data obtained by merging");
113 UsageError(" all the files specified with --profile-file or --profile-file-fd.");
114 UsageError(" If the exit code is EXIT_COMPILE then all --profile-file will be merged into");
115 UsageError(" --reference-profile-file. ");
116 UsageError("");
117 UsageError(" --reference-profile-file-fd=<number>: same as --reference-profile-file but");
118 UsageError(" accepts a file descriptor. Cannot be used together with");
119 UsageError(" --reference-profile-file.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800120 UsageError("");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100121 UsageError(" --generate-test-profile=<filename>: generates a random profile file for testing.");
122 UsageError(" --generate-test-profile-num-dex=<number>: number of dex files that should be");
123 UsageError(" included in the generated profile. Defaults to 20.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700124 UsageError(" --generate-test-profile-method-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100125 UsageError(" number of methods that should be generated. Defaults to 5.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700126 UsageError(" --generate-test-profile-class-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100127 UsageError(" number of classes that should be generated. Defaults to 5.");
Jeff Haof0a31f82017-03-27 15:50:37 -0700128 UsageError(" --generate-test-profile-seed=<number>: seed for random number generator used when");
129 UsageError(" generating random test profiles. Defaults to using NanoTime.");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100130 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -0700131 UsageError(" --create-profile-from=<filename>: creates a profile from a list of classes and");
132 UsageError(" methods.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800133 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700134 UsageError(" --dex-location=<string>: location string to use with corresponding");
135 UsageError(" apk-fd to find dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700136 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700137 UsageError(" --apk-fd=<number>: file descriptor containing an open APK to");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700138 UsageError(" search for dex files");
David Sehr7c80f2d2017-02-07 16:47:58 -0800139 UsageError(" --apk-=<filename>: an APK to search for dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700140 UsageError("");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700141 UsageError(" --generate-boot-image-profile: Generate a boot image profile based on input");
142 UsageError(" profiles. Requires passing in dex files to inspect properties of classes.");
143 UsageError(" --boot-image-class-threshold=<value>: specify minimum number of class occurrences");
144 UsageError(" to include a class in the boot image profile. Default is 10.");
145 UsageError(" --boot-image-clean-class-threshold=<value>: specify minimum number of clean class");
146 UsageError(" occurrences to include a class in the boot image profile. A clean class is a");
147 UsageError(" class that doesn't have any static fields or native methods and is likely to");
148 UsageError(" remain clean in the image. Default is 3.");
Mathieu Chartier8eecddf2017-07-12 16:05:54 -0700149 UsageError(" --boot-image-sampled-method-threshold=<value>: minimum number of profiles a");
150 UsageError(" non-hot method needs to be in order to be hot in the output profile. The");
151 UsageError(" default is max int.");
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800152 UsageError(" --copy-and-update-profile-key: if present, profman will copy the profile from");
153 UsageError(" the file passed with --profile-fd(file) to the profile passed with");
154 UsageError(" --reference-profile-fd(file) and update at the same time the profile-key");
155 UsageError(" of entries corresponding to the apks passed with --apk(-fd).");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700156 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000157
158 exit(EXIT_FAILURE);
159}
160
Calin Juravle7bcdb532016-06-07 16:14:47 +0100161// Note: make sure you update the Usage if you change these values.
162static constexpr uint16_t kDefaultTestProfileNumDex = 20;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700163static constexpr uint16_t kDefaultTestProfileMethodPercentage = 5;
164static constexpr uint16_t kDefaultTestProfileClassPercentage = 5;
Calin Juravle7bcdb532016-06-07 16:14:47 +0100165
Calin Juravlee0ac1152017-02-13 19:03:47 -0800166// Separators used when parsing human friendly representation of profiles.
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800167static const std::string kMethodSep = "->"; // NOLINT [runtime/string] [4]
168static const std::string kMissingTypesMarker = "missing_types"; // NOLINT [runtime/string] [4]
169static const std::string kInvalidClassDescriptor = "invalid_class"; // NOLINT [runtime/string] [4]
170static const std::string kInvalidMethod = "invalid_method"; // NOLINT [runtime/string] [4]
171static const std::string kClassAllMethods = "*"; // NOLINT [runtime/string] [4]
Calin Juravlee0ac1152017-02-13 19:03:47 -0800172static constexpr char kProfileParsingInlineChacheSep = '+';
173static constexpr char kProfileParsingTypeSep = ',';
174static constexpr char kProfileParsingFirstCharInSignature = '(';
Mathieu Chartierea650f32017-05-24 12:04:13 -0700175static constexpr char kMethodFlagStringHot = 'H';
176static constexpr char kMethodFlagStringStartup = 'S';
177static constexpr char kMethodFlagStringPostStartup = 'P';
Calin Juravlee0ac1152017-02-13 19:03:47 -0800178
179// TODO(calin): This class has grown too much from its initial design. Split the functionality
180// into smaller, more contained pieces.
Calin Juravle2e2db782016-02-23 12:00:03 +0000181class ProfMan FINAL {
182 public:
183 ProfMan() :
David Sehr4fcdd6d2016-05-24 14:52:31 -0700184 reference_profile_file_fd_(kInvalidFd),
185 dump_only_(false),
Mathieu Chartier34067262017-04-06 13:55:46 -0700186 dump_classes_and_methods_(false),
Mathieu Chartier2f794552017-06-19 10:58:08 -0700187 generate_boot_image_profile_(false),
David Sehr4fcdd6d2016-05-24 14:52:31 -0700188 dump_output_to_fd_(kInvalidFd),
Calin Juravle7bcdb532016-06-07 16:14:47 +0100189 test_profile_num_dex_(kDefaultTestProfileNumDex),
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700190 test_profile_method_percerntage_(kDefaultTestProfileMethodPercentage),
191 test_profile_class_percentage_(kDefaultTestProfileClassPercentage),
Jeff Haof0a31f82017-03-27 15:50:37 -0700192 test_profile_seed_(NanoTime()),
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800193 start_ns_(NanoTime()),
194 copy_and_update_profile_key_(false) {}
Calin Juravle2e2db782016-02-23 12:00:03 +0000195
196 ~ProfMan() {
197 LogCompletionTime();
198 }
199
200 void ParseArgs(int argc, char **argv) {
201 original_argc = argc;
202 original_argv = argv;
203
Andreas Gampe51d80cc2017-06-21 21:05:13 -0700204 InitLogging(argv, Runtime::Abort);
Calin Juravle2e2db782016-02-23 12:00:03 +0000205
206 // Skip over the command name.
207 argv++;
208 argc--;
209
210 if (argc == 0) {
211 Usage("No arguments specified");
212 }
213
214 for (int i = 0; i < argc; ++i) {
215 const StringPiece option(argv[i]);
216 const bool log_options = false;
217 if (log_options) {
Calin Juravle876f3502016-03-24 16:16:34 +0000218 LOG(INFO) << "profman: option[" << i << "]=" << argv[i];
Calin Juravle2e2db782016-02-23 12:00:03 +0000219 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700220 if (option == "--dump-only") {
221 dump_only_ = true;
Mathieu Chartier34067262017-04-06 13:55:46 -0700222 } else if (option == "--dump-classes-and-methods") {
223 dump_classes_and_methods_ = true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800224 } else if (option.starts_with("--create-profile-from=")) {
225 create_profile_from_file_ = option.substr(strlen("--create-profile-from=")).ToString();
David Sehr4fcdd6d2016-05-24 14:52:31 -0700226 } else if (option.starts_with("--dump-output-to-fd=")) {
227 ParseUintOption(option, "--dump-output-to-fd", &dump_output_to_fd_, Usage);
Mathieu Chartier2f794552017-06-19 10:58:08 -0700228 } else if (option == "--generate-boot-image-profile") {
229 generate_boot_image_profile_ = true;
230 } else if (option.starts_with("--boot-image-class-threshold=")) {
231 ParseUintOption(option,
232 "--boot-image-class-threshold",
233 &boot_image_options_.image_class_theshold,
234 Usage);
235 } else if (option.starts_with("--boot-image-clean-class-threshold=")) {
236 ParseUintOption(option,
237 "--boot-image-clean-class-threshold",
238 &boot_image_options_.image_class_clean_theshold,
239 Usage);
Mathieu Chartier8eecddf2017-07-12 16:05:54 -0700240 } else if (option.starts_with("--boot-image-sampled-method-threshold=")) {
241 ParseUintOption(option,
242 "--boot-image-sampled-method-threshold",
243 &boot_image_options_.compiled_method_threshold,
244 Usage);
Calin Juravle876f3502016-03-24 16:16:34 +0000245 } else if (option.starts_with("--profile-file=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000246 profile_files_.push_back(option.substr(strlen("--profile-file=")).ToString());
247 } else if (option.starts_with("--profile-file-fd=")) {
248 ParseFdForCollection(option, "--profile-file-fd", &profile_files_fd_);
249 } else if (option.starts_with("--reference-profile-file=")) {
250 reference_profile_file_ = option.substr(strlen("--reference-profile-file=")).ToString();
251 } else if (option.starts_with("--reference-profile-file-fd=")) {
252 ParseUintOption(option, "--reference-profile-file-fd", &reference_profile_file_fd_, Usage);
David Sehr546d24f2016-06-02 10:46:19 -0700253 } else if (option.starts_with("--dex-location=")) {
254 dex_locations_.push_back(option.substr(strlen("--dex-location=")).ToString());
255 } else if (option.starts_with("--apk-fd=")) {
256 ParseFdForCollection(option, "--apk-fd", &apks_fd_);
David Sehr7c80f2d2017-02-07 16:47:58 -0800257 } else if (option.starts_with("--apk=")) {
258 apk_files_.push_back(option.substr(strlen("--apk=")).ToString());
Calin Juravle7bcdb532016-06-07 16:14:47 +0100259 } else if (option.starts_with("--generate-test-profile=")) {
260 test_profile_ = option.substr(strlen("--generate-test-profile=")).ToString();
261 } else if (option.starts_with("--generate-test-profile-num-dex=")) {
262 ParseUintOption(option,
263 "--generate-test-profile-num-dex",
264 &test_profile_num_dex_,
265 Usage);
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700266 } else if (option.starts_with("--generate-test-profile-method-percentage")) {
Calin Juravle7bcdb532016-06-07 16:14:47 +0100267 ParseUintOption(option,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700268 "--generate-test-profile-method-percentage",
269 &test_profile_method_percerntage_,
Calin Juravle7bcdb532016-06-07 16:14:47 +0100270 Usage);
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700271 } else if (option.starts_with("--generate-test-profile-class-percentage")) {
Calin Juravle7bcdb532016-06-07 16:14:47 +0100272 ParseUintOption(option,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700273 "--generate-test-profile-class-percentage",
274 &test_profile_class_percentage_,
Calin Juravle7bcdb532016-06-07 16:14:47 +0100275 Usage);
Jeff Haof0a31f82017-03-27 15:50:37 -0700276 } else if (option.starts_with("--generate-test-profile-seed=")) {
277 ParseUintOption(option, "--generate-test-profile-seed", &test_profile_seed_, Usage);
Calin Juravle2e2db782016-02-23 12:00:03 +0000278 } else {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700279 Usage("Unknown argument '%s'", option.data());
Calin Juravle2e2db782016-02-23 12:00:03 +0000280 }
281 }
282
David Sehr153da0e2017-02-15 08:54:51 -0800283 // Validate global consistency between file/fd options.
Calin Juravle2e2db782016-02-23 12:00:03 +0000284 if (!profile_files_.empty() && !profile_files_fd_.empty()) {
285 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
286 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700287 if (!reference_profile_file_.empty() && FdIsValid(reference_profile_file_fd_)) {
288 Usage("Reference profile should not be specified with both "
289 "--reference-profile-file-fd and --reference-profile-file");
290 }
David Sehr153da0e2017-02-15 08:54:51 -0800291 if (!apk_files_.empty() && !apks_fd_.empty()) {
292 Usage("APK files should not be specified with both --apk-fd and --apk");
Calin Juravle2e2db782016-02-23 12:00:03 +0000293 }
294 }
295
296 ProfileAssistant::ProcessingResult ProcessProfiles() {
David Sehr153da0e2017-02-15 08:54:51 -0800297 // Validate that at least one profile file was passed, as well as a reference profile.
298 if (profile_files_.empty() && profile_files_fd_.empty()) {
299 Usage("No profile files specified.");
300 }
301 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
302 Usage("No reference profile file specified.");
303 }
304 if ((!profile_files_.empty() && FdIsValid(reference_profile_file_fd_)) ||
305 (!profile_files_fd_.empty() && !FdIsValid(reference_profile_file_fd_))) {
306 Usage("Options --profile-file-fd and --reference-profile-file-fd "
307 "should only be used together");
308 }
Calin Juravle2e2db782016-02-23 12:00:03 +0000309 ProfileAssistant::ProcessingResult result;
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800310
Calin Juravle2e2db782016-02-23 12:00:03 +0000311 if (profile_files_.empty()) {
312 // The file doesn't need to be flushed here (ProcessProfiles will do it)
313 // so don't check the usage.
314 File file(reference_profile_file_fd_, false);
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800315 result = ProfileAssistant::ProcessProfiles(profile_files_fd_,
316 reference_profile_file_fd_);
Calin Juravle2e2db782016-02-23 12:00:03 +0000317 CloseAllFds(profile_files_fd_, "profile_files_fd_");
318 } else {
319 result = ProfileAssistant::ProcessProfiles(profile_files_, reference_profile_file_);
320 }
321 return result;
322 }
323
Calin Juravle2dba0ab2018-01-22 19:22:24 -0800324 void OpenApkFilesFromLocations(std::vector<std::unique_ptr<const DexFile>>* dex_files) const {
David Sehr7c80f2d2017-02-07 16:47:58 -0800325 bool use_apk_fd_list = !apks_fd_.empty();
326 if (use_apk_fd_list) {
David Sehr153da0e2017-02-15 08:54:51 -0800327 // Get the APKs from the collection of FDs.
David Sehr7c80f2d2017-02-07 16:47:58 -0800328 CHECK_EQ(dex_locations_.size(), apks_fd_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800329 } else if (!apk_files_.empty()) {
330 // Get the APKs from the collection of filenames.
David Sehr7c80f2d2017-02-07 16:47:58 -0800331 CHECK_EQ(dex_locations_.size(), apk_files_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800332 } else {
333 // No APKs were specified.
334 CHECK(dex_locations_.empty());
335 return;
David Sehr7c80f2d2017-02-07 16:47:58 -0800336 }
337 static constexpr bool kVerifyChecksum = true;
338 for (size_t i = 0; i < dex_locations_.size(); ++i) {
339 std::string error_msg;
David Sehr013fd802018-01-11 22:55:24 -0800340 const ArtDexFileLoader dex_file_loader;
David Sehr7c80f2d2017-02-07 16:47:58 -0800341 std::vector<std::unique_ptr<const DexFile>> dex_files_for_location;
342 if (use_apk_fd_list) {
David Sehr013fd802018-01-11 22:55:24 -0800343 if (dex_file_loader.OpenZip(apks_fd_[i],
344 dex_locations_[i],
345 /* verify */ true,
346 kVerifyChecksum,
347 &error_msg,
348 &dex_files_for_location)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800349 } else {
350 LOG(WARNING) << "OpenZip failed for '" << dex_locations_[i] << "' " << error_msg;
351 continue;
352 }
353 } else {
David Sehr013fd802018-01-11 22:55:24 -0800354 if (dex_file_loader.Open(apk_files_[i].c_str(),
355 dex_locations_[i],
356 /* verify */ true,
357 kVerifyChecksum,
358 &error_msg,
359 &dex_files_for_location)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800360 } else {
361 LOG(WARNING) << "Open failed for '" << dex_locations_[i] << "' " << error_msg;
362 continue;
363 }
364 }
365 for (std::unique_ptr<const DexFile>& dex_file : dex_files_for_location) {
366 dex_files->emplace_back(std::move(dex_file));
367 }
368 }
369 }
370
Mathieu Chartier2f794552017-06-19 10:58:08 -0700371 std::unique_ptr<const ProfileCompilationInfo> LoadProfile(const std::string& filename, int fd) {
372 if (!filename.empty()) {
373 fd = open(filename.c_str(), O_RDWR);
374 if (fd < 0) {
375 LOG(ERROR) << "Cannot open " << filename << strerror(errno);
376 return nullptr;
377 }
378 }
379 std::unique_ptr<ProfileCompilationInfo> info(new ProfileCompilationInfo);
380 if (!info->Load(fd)) {
381 LOG(ERROR) << "Cannot load profile info from fd=" << fd << "\n";
382 return nullptr;
383 }
384 return info;
385 }
386
David Sehrb18991b2017-02-08 20:58:10 -0800387 int DumpOneProfile(const std::string& banner,
388 const std::string& filename,
389 int fd,
390 const std::vector<std::unique_ptr<const DexFile>>* dex_files,
391 std::string* dump) {
Mathieu Chartier2f794552017-06-19 10:58:08 -0700392 std::unique_ptr<const ProfileCompilationInfo> info(LoadProfile(filename, fd));
393 if (info == nullptr) {
394 LOG(ERROR) << "Cannot load profile info from filename=" << filename << " fd=" << fd;
Calin Juravle876f3502016-03-24 16:16:34 +0000395 return -1;
396 }
Mathieu Chartier2f794552017-06-19 10:58:08 -0700397 *dump += banner + "\n" + info->DumpInfo(dex_files) + "\n";
David Sehr4fcdd6d2016-05-24 14:52:31 -0700398 return 0;
399 }
400
401 int DumpProfileInfo() {
David Sehr153da0e2017-02-15 08:54:51 -0800402 // Validate that at least one profile file or reference was specified.
403 if (profile_files_.empty() && profile_files_fd_.empty() &&
404 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
405 Usage("No profile files or reference profile specified.");
406 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700407 static const char* kEmptyString = "";
David Sehr546d24f2016-06-02 10:46:19 -0700408 static const char* kOrdinaryProfile = "=== profile ===";
409 static const char* kReferenceProfile = "=== reference profile ===";
410
411 // Open apk/zip files and and read dex files.
412 MemMap::Init(); // for ZipArchive::OpenFromFd
David Sehrb18991b2017-02-08 20:58:10 -0800413 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7c80f2d2017-02-07 16:47:58 -0800414 OpenApkFilesFromLocations(&dex_files);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700415 std::string dump;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700416 // Dump individual profile files.
417 if (!profile_files_fd_.empty()) {
418 for (int profile_file_fd : profile_files_fd_) {
David Sehr546d24f2016-06-02 10:46:19 -0700419 int ret = DumpOneProfile(kOrdinaryProfile,
420 kEmptyString,
421 profile_file_fd,
422 &dex_files,
423 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700424 if (ret != 0) {
425 return ret;
426 }
427 }
428 }
429 if (!profile_files_.empty()) {
430 for (const std::string& profile_file : profile_files_) {
David Sehr546d24f2016-06-02 10:46:19 -0700431 int ret = DumpOneProfile(kOrdinaryProfile, profile_file, kInvalidFd, &dex_files, &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700432 if (ret != 0) {
433 return ret;
434 }
435 }
436 }
437 // Dump reference profile file.
438 if (FdIsValid(reference_profile_file_fd_)) {
David Sehr546d24f2016-06-02 10:46:19 -0700439 int ret = DumpOneProfile(kReferenceProfile,
440 kEmptyString,
441 reference_profile_file_fd_,
442 &dex_files,
443 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700444 if (ret != 0) {
445 return ret;
446 }
447 }
448 if (!reference_profile_file_.empty()) {
David Sehr546d24f2016-06-02 10:46:19 -0700449 int ret = DumpOneProfile(kReferenceProfile,
450 reference_profile_file_,
451 kInvalidFd,
452 &dex_files,
David Sehr4fcdd6d2016-05-24 14:52:31 -0700453 &dump);
454 if (ret != 0) {
455 return ret;
456 }
457 }
458 if (!FdIsValid(dump_output_to_fd_)) {
459 std::cout << dump;
460 } else {
461 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
462 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
463 return -1;
464 }
465 }
Calin Juravle876f3502016-03-24 16:16:34 +0000466 return 0;
467 }
468
469 bool ShouldOnlyDumpProfile() {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700470 return dump_only_;
Calin Juravle876f3502016-03-24 16:16:34 +0000471 }
472
Mathieu Chartier34067262017-04-06 13:55:46 -0700473 bool GetClassNamesAndMethods(int fd,
474 std::vector<std::unique_ptr<const DexFile>>* dex_files,
475 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800476 ProfileCompilationInfo profile_info;
477 if (!profile_info.Load(fd)) {
478 LOG(ERROR) << "Cannot load profile info";
479 return false;
480 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700481 for (const std::unique_ptr<const DexFile>& dex_file : *dex_files) {
482 std::set<dex::TypeIndex> class_types;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700483 std::set<uint16_t> hot_methods;
484 std::set<uint16_t> startup_methods;
485 std::set<uint16_t> post_startup_methods;
486 std::set<uint16_t> combined_methods;
487 if (profile_info.GetClassesAndMethods(*dex_file.get(),
488 &class_types,
489 &hot_methods,
490 &startup_methods,
491 &post_startup_methods)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700492 for (const dex::TypeIndex& type_index : class_types) {
493 const DexFile::TypeId& type_id = dex_file->GetTypeId(type_index);
494 out_lines->insert(std::string(dex_file->GetTypeDescriptor(type_id)));
495 }
Mathieu Chartierea650f32017-05-24 12:04:13 -0700496 combined_methods = hot_methods;
497 combined_methods.insert(startup_methods.begin(), startup_methods.end());
498 combined_methods.insert(post_startup_methods.begin(), post_startup_methods.end());
499 for (uint16_t dex_method_idx : combined_methods) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700500 const DexFile::MethodId& id = dex_file->GetMethodId(dex_method_idx);
501 std::string signature_string(dex_file->GetMethodSignature(id).ToString());
502 std::string type_string(dex_file->GetTypeDescriptor(dex_file->GetTypeId(id.class_idx_)));
503 std::string method_name(dex_file->GetMethodName(id));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700504 std::string flags_string;
505 if (hot_methods.find(dex_method_idx) != hot_methods.end()) {
506 flags_string += kMethodFlagStringHot;
507 }
508 if (startup_methods.find(dex_method_idx) != startup_methods.end()) {
509 flags_string += kMethodFlagStringStartup;
510 }
511 if (post_startup_methods.find(dex_method_idx) != post_startup_methods.end()) {
512 flags_string += kMethodFlagStringPostStartup;
513 }
514 out_lines->insert(flags_string +
515 type_string +
516 kMethodSep +
517 method_name +
518 signature_string);
Mathieu Chartier34067262017-04-06 13:55:46 -0700519 }
520 }
521 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800522 return true;
523 }
524
Mathieu Chartier34067262017-04-06 13:55:46 -0700525 bool GetClassNamesAndMethods(const std::string& profile_file,
526 std::vector<std::unique_ptr<const DexFile>>* dex_files,
527 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800528 int fd = open(profile_file.c_str(), O_RDONLY);
529 if (!FdIsValid(fd)) {
530 LOG(ERROR) << "Cannot open " << profile_file << strerror(errno);
531 return false;
532 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700533 if (!GetClassNamesAndMethods(fd, dex_files, out_lines)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800534 return false;
535 }
536 if (close(fd) < 0) {
537 PLOG(WARNING) << "Failed to close descriptor";
538 }
539 return true;
540 }
541
Mathieu Chartierea650f32017-05-24 12:04:13 -0700542 int DumpClassesAndMethods() {
David Sehr153da0e2017-02-15 08:54:51 -0800543 // Validate that at least one profile file or reference was specified.
544 if (profile_files_.empty() && profile_files_fd_.empty() &&
545 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
546 Usage("No profile files or reference profile specified.");
547 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800548 // Open apk/zip files and and read dex files.
549 MemMap::Init(); // for ZipArchive::OpenFromFd
550 // Open the dex files to get the names for classes.
551 std::vector<std::unique_ptr<const DexFile>> dex_files;
552 OpenApkFilesFromLocations(&dex_files);
553 // Build a vector of class names from individual profile files.
554 std::set<std::string> class_names;
555 if (!profile_files_fd_.empty()) {
556 for (int profile_file_fd : profile_files_fd_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700557 if (!GetClassNamesAndMethods(profile_file_fd, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800558 return -1;
559 }
560 }
561 }
562 if (!profile_files_.empty()) {
563 for (const std::string& profile_file : profile_files_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700564 if (!GetClassNamesAndMethods(profile_file, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800565 return -1;
566 }
567 }
568 }
569 // Concatenate class names from reference profile file.
570 if (FdIsValid(reference_profile_file_fd_)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700571 if (!GetClassNamesAndMethods(reference_profile_file_fd_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800572 return -1;
573 }
574 }
575 if (!reference_profile_file_.empty()) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700576 if (!GetClassNamesAndMethods(reference_profile_file_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800577 return -1;
578 }
579 }
580 // Dump the class names.
581 std::string dump;
582 for (const std::string& class_name : class_names) {
583 dump += class_name + std::string("\n");
584 }
585 if (!FdIsValid(dump_output_to_fd_)) {
586 std::cout << dump;
587 } else {
588 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
589 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
590 return -1;
591 }
592 }
593 return 0;
594 }
595
Mathieu Chartier34067262017-04-06 13:55:46 -0700596 bool ShouldOnlyDumpClassesAndMethods() {
597 return dump_classes_and_methods_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800598 }
599
600 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
601 // the given function.
602 template <typename T>
603 static T* ReadCommentedInputFromFile(
604 const char* input_filename, std::function<std::string(const char*)>* process) {
605 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
606 if (input_file.get() == nullptr) {
607 LOG(ERROR) << "Failed to open input file " << input_filename;
608 return nullptr;
609 }
610 std::unique_ptr<T> result(
611 ReadCommentedInputStream<T>(*input_file, process));
612 input_file->close();
613 return result.release();
614 }
615
616 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
617 // with the given function.
618 template <typename T>
619 static T* ReadCommentedInputStream(
620 std::istream& in_stream,
621 std::function<std::string(const char*)>* process) {
622 std::unique_ptr<T> output(new T());
623 while (in_stream.good()) {
624 std::string dot;
625 std::getline(in_stream, dot);
626 if (android::base::StartsWith(dot, "#") || dot.empty()) {
627 continue;
628 }
629 if (process != nullptr) {
630 std::string descriptor((*process)(dot.c_str()));
631 output->insert(output->end(), descriptor);
632 } else {
633 output->insert(output->end(), dot);
634 }
635 }
636 return output.release();
637 }
638
Calin Juravlee0ac1152017-02-13 19:03:47 -0800639 // Find class klass_descriptor in the given dex_files and store its reference
640 // in the out parameter class_ref.
641 // Return true if the definition of the class was found in any of the dex_files.
642 bool FindClass(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
643 const std::string& klass_descriptor,
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700644 /*out*/TypeReference* class_ref) {
Calin Juravle08556882017-05-26 16:40:45 -0700645 constexpr uint16_t kInvalidTypeIndex = std::numeric_limits<uint16_t>::max() - 1;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800646 for (const std::unique_ptr<const DexFile>& dex_file_ptr : dex_files) {
647 const DexFile* dex_file = dex_file_ptr.get();
Calin Juravle08556882017-05-26 16:40:45 -0700648 if (klass_descriptor == kInvalidClassDescriptor) {
649 if (kInvalidTypeIndex >= dex_file->NumTypeIds()) {
650 // The dex file does not contain all possible type ids which leaves us room
651 // to add an "invalid" type id.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700652 *class_ref = TypeReference(dex_file, dex::TypeIndex(kInvalidTypeIndex));
Calin Juravle08556882017-05-26 16:40:45 -0700653 return true;
654 } else {
655 // The dex file contains all possible type ids. We don't have any free type id
656 // that we can use as invalid.
657 continue;
658 }
659 }
660
Calin Juravlee0ac1152017-02-13 19:03:47 -0800661 const DexFile::TypeId* type_id = dex_file->FindTypeId(klass_descriptor.c_str());
662 if (type_id == nullptr) {
663 continue;
664 }
665 dex::TypeIndex type_index = dex_file->GetIndexForTypeId(*type_id);
666 if (dex_file->FindClassDef(type_index) == nullptr) {
667 // Class is only referenced in the current dex file but not defined in it.
668 continue;
669 }
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700670 *class_ref = TypeReference(dex_file, type_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800671 return true;
672 }
673 return false;
674 }
675
Mathieu Chartier34067262017-04-06 13:55:46 -0700676 // Find the method specified by method_spec in the class class_ref.
Calin Juravle08556882017-05-26 16:40:45 -0700677 uint32_t FindMethodIndex(const TypeReference& class_ref,
678 const std::string& method_spec) {
679 const DexFile* dex_file = class_ref.dex_file;
680 if (method_spec == kInvalidMethod) {
681 constexpr uint16_t kInvalidMethodIndex = std::numeric_limits<uint16_t>::max() - 1;
682 return kInvalidMethodIndex >= dex_file->NumMethodIds()
683 ? kInvalidMethodIndex
Andreas Gampee2abbc62017-09-15 11:59:26 -0700684 : dex::kDexNoIndex;
Calin Juravle08556882017-05-26 16:40:45 -0700685 }
686
Calin Juravlee0ac1152017-02-13 19:03:47 -0800687 std::vector<std::string> name_and_signature;
688 Split(method_spec, kProfileParsingFirstCharInSignature, &name_and_signature);
689 if (name_and_signature.size() != 2) {
690 LOG(ERROR) << "Invalid method name and signature " << method_spec;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700691 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800692 }
Calin Juravle08556882017-05-26 16:40:45 -0700693
Calin Juravlee0ac1152017-02-13 19:03:47 -0800694 const std::string& name = name_and_signature[0];
695 const std::string& signature = kProfileParsingFirstCharInSignature + name_and_signature[1];
Calin Juravlee0ac1152017-02-13 19:03:47 -0800696
697 const DexFile::StringId* name_id = dex_file->FindStringId(name.c_str());
698 if (name_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700699 LOG(WARNING) << "Could not find name: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700700 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800701 }
702 dex::TypeIndex return_type_idx;
703 std::vector<dex::TypeIndex> param_type_idxs;
704 if (!dex_file->CreateTypeList(signature, &return_type_idx, &param_type_idxs)) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700705 LOG(WARNING) << "Could not create type list" << signature;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700706 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800707 }
708 const DexFile::ProtoId* proto_id = dex_file->FindProtoId(return_type_idx, param_type_idxs);
709 if (proto_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700710 LOG(WARNING) << "Could not find proto_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700711 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800712 }
713 const DexFile::MethodId* method_id = dex_file->FindMethodId(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700714 dex_file->GetTypeId(class_ref.TypeIndex()), *name_id, *proto_id);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800715 if (method_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700716 LOG(WARNING) << "Could not find method_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700717 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800718 }
719
Mathieu Chartier34067262017-04-06 13:55:46 -0700720 return dex_file->GetIndexForMethodId(*method_id);
721 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800722
Mathieu Chartier34067262017-04-06 13:55:46 -0700723 // Given a method, return true if the method has a single INVOKE_VIRTUAL in its byte code.
724 // Upon success it returns true and stores the method index and the invoke dex pc
725 // in the output parameters.
726 // The format of the method spec is "inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
727 //
728 // TODO(calin): support INVOKE_INTERFACE and the range variants.
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700729 bool HasSingleInvoke(const TypeReference& class_ref,
Mathieu Chartier34067262017-04-06 13:55:46 -0700730 uint16_t method_index,
731 /*out*/uint32_t* dex_pc) {
732 const DexFile* dex_file = class_ref.dex_file;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800733 uint32_t offset = dex_file->FindCodeItemOffset(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700734 *dex_file->FindClassDef(class_ref.TypeIndex()),
Mathieu Chartier34067262017-04-06 13:55:46 -0700735 method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800736 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(offset);
737
738 bool found_invoke = false;
Mathieu Chartier698ebbc2018-01-05 11:00:42 -0800739 for (const DexInstructionPcPair& inst : CodeItemInstructionAccessor(*dex_file, code_item)) {
Mathieu Chartier0021feb2017-11-07 00:08:52 -0800740 if (inst->Opcode() == Instruction::INVOKE_VIRTUAL) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800741 if (found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700742 LOG(ERROR) << "Multiple invoke INVOKE_VIRTUAL found: "
743 << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800744 return false;
745 }
746 found_invoke = true;
Mathieu Chartier0021feb2017-11-07 00:08:52 -0800747 *dex_pc = inst.DexPc();
Calin Juravlee0ac1152017-02-13 19:03:47 -0800748 }
749 }
750 if (!found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700751 LOG(ERROR) << "Could not find any INVOKE_VIRTUAL: " << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800752 }
753 return found_invoke;
754 }
755
756 // Process a line defining a class or a method and its inline caches.
757 // Upon success return true and add the class or the method info to profile.
Calin Juravle589e71e2017-03-03 16:05:05 -0800758 // The possible line formats are:
759 // "LJustTheCass;".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800760 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
Calin Juravle08556882017-05-26 16:40:45 -0700761 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,invalid_class".
Calin Juravle589e71e2017-03-03 16:05:05 -0800762 // "LTestInline;->inlineMissingTypes(LSuper;)I+missing_types".
763 // "LTestInline;->inlineNoInlineCaches(LSuper;)I".
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700764 // "LTestInline;->*".
Calin Juravle08556882017-05-26 16:40:45 -0700765 // "invalid_class".
766 // "LTestInline;->invalid_method".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800767 // The method and classes are searched only in the given dex files.
768 bool ProcessLine(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
769 const std::string& line,
770 /*out*/ProfileCompilationInfo* profile) {
771 std::string klass;
772 std::string method_str;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700773 bool is_hot = false;
774 bool is_startup = false;
775 bool is_post_startup = false;
776 const size_t method_sep_index = line.find(kMethodSep, 0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800777 if (method_sep_index == std::string::npos) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700778 klass = line.substr(0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800779 } else {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700780 // The method prefix flags are only valid for method strings.
781 size_t start_index = 0;
782 while (start_index < line.size() && line[start_index] != 'L') {
783 const char c = line[start_index];
784 if (c == kMethodFlagStringHot) {
785 is_hot = true;
786 } else if (c == kMethodFlagStringStartup) {
787 is_startup = true;
788 } else if (c == kMethodFlagStringPostStartup) {
789 is_post_startup = true;
790 } else {
791 LOG(WARNING) << "Invalid flag " << c;
792 return false;
793 }
794 ++start_index;
795 }
796 klass = line.substr(start_index, method_sep_index - start_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800797 method_str = line.substr(method_sep_index + kMethodSep.size());
798 }
799
Vladimir Markof3c52b42017-11-17 17:32:12 +0000800 TypeReference class_ref(/* dex_file */ nullptr, dex::TypeIndex());
Calin Juravlee0ac1152017-02-13 19:03:47 -0800801 if (!FindClass(dex_files, klass, &class_ref)) {
Mathieu Chartier3f121342017-03-06 11:16:20 -0800802 LOG(WARNING) << "Could not find class: " << klass;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800803 return false;
804 }
805
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700806 if (method_str.empty() || method_str == kClassAllMethods) {
807 // Start by adding the class.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800808 std::set<DexCacheResolvedClasses> resolved_class_set;
809 const DexFile* dex_file = class_ref.dex_file;
810 const auto& dex_resolved_classes = resolved_class_set.emplace(
811 dex_file->GetLocation(),
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700812 DexFileLoader::GetBaseLocation(dex_file->GetLocation()),
Mathieu Chartierea650f32017-05-24 12:04:13 -0700813 dex_file->GetLocationChecksum(),
814 dex_file->NumMethodIds());
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700815 dex_resolved_classes.first->AddClass(class_ref.TypeIndex());
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700816 std::vector<ProfileMethodInfo> methods;
817 if (method_str == kClassAllMethods) {
818 // Add all of the methods.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700819 const DexFile::ClassDef* class_def = dex_file->FindClassDef(class_ref.TypeIndex());
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700820 const uint8_t* class_data = dex_file->GetClassData(*class_def);
821 if (class_data != nullptr) {
822 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700823 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800824 while (it.HasNextMethod()) {
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700825 if (it.GetMethodCodeItemOffset() != 0) {
826 // Add all of the methods that have code to the profile.
827 const uint32_t method_idx = it.GetMemberIndex();
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700828 methods.push_back(ProfileMethodInfo(MethodReference(dex_file, method_idx)));
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700829 }
830 it.Next();
831 }
832 }
833 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700834 // TODO: Check return values?
835 profile->AddMethods(methods);
836 profile->AddClasses(resolved_class_set);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800837 return true;
838 }
839
840 // Process the method.
841 std::string method_spec;
842 std::vector<std::string> inline_cache_elems;
843
Mathieu Chartierea650f32017-05-24 12:04:13 -0700844 // If none of the flags are set, default to hot.
845 is_hot = is_hot || (!is_hot && !is_startup && !is_post_startup);
846
Calin Juravlee0ac1152017-02-13 19:03:47 -0800847 std::vector<std::string> method_elems;
Calin Juravle589e71e2017-03-03 16:05:05 -0800848 bool is_missing_types = false;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800849 Split(method_str, kProfileParsingInlineChacheSep, &method_elems);
850 if (method_elems.size() == 2) {
851 method_spec = method_elems[0];
Calin Juravle589e71e2017-03-03 16:05:05 -0800852 is_missing_types = method_elems[1] == kMissingTypesMarker;
853 if (!is_missing_types) {
854 Split(method_elems[1], kProfileParsingTypeSep, &inline_cache_elems);
855 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800856 } else if (method_elems.size() == 1) {
857 method_spec = method_elems[0];
858 } else {
859 LOG(ERROR) << "Invalid method line: " << line;
860 return false;
861 }
862
Mathieu Chartier34067262017-04-06 13:55:46 -0700863 const uint32_t method_index = FindMethodIndex(class_ref, method_spec);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700864 if (method_index == dex::kDexNoIndex) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800865 return false;
866 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700867
Mathieu Chartier34067262017-04-06 13:55:46 -0700868 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
869 if (is_missing_types || !inline_cache_elems.empty()) {
870 uint32_t dex_pc;
871 if (!HasSingleInvoke(class_ref, method_index, &dex_pc)) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800872 return false;
873 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000874 std::vector<TypeReference> classes(inline_cache_elems.size(),
875 TypeReference(/* dex_file */ nullptr, dex::TypeIndex()));
Mathieu Chartier34067262017-04-06 13:55:46 -0700876 size_t class_it = 0;
877 for (const std::string& ic_class : inline_cache_elems) {
878 if (!FindClass(dex_files, ic_class, &(classes[class_it++]))) {
879 LOG(ERROR) << "Could not find class: " << ic_class;
880 return false;
881 }
882 }
883 inline_caches.emplace_back(dex_pc, is_missing_types, classes);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800884 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700885 MethodReference ref(class_ref.dex_file, method_index);
Mathieu Chartierea650f32017-05-24 12:04:13 -0700886 if (is_hot) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700887 profile->AddMethod(ProfileMethodInfo(ref, inline_caches));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700888 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700889 uint32_t flags = 0;
890 using Hotness = ProfileCompilationInfo::MethodHotness;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700891 if (is_startup) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700892 flags |= Hotness::kFlagStartup;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700893 }
894 if (is_post_startup) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700895 flags |= Hotness::kFlagPostStartup;
896 }
897 if (flags != 0) {
898 if (!profile->AddMethodIndex(static_cast<Hotness::Flag>(flags), ref)) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700899 return false;
900 }
Mathieu Chartiere46f3a82017-06-19 19:54:12 -0700901 DCHECK(profile->GetMethodHotness(ref).IsInProfile());
Mathieu Chartierea650f32017-05-24 12:04:13 -0700902 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800903 return true;
904 }
905
Mathieu Chartier2f794552017-06-19 10:58:08 -0700906 int OpenReferenceProfile() const {
907 int fd = reference_profile_file_fd_;
908 if (!FdIsValid(fd)) {
909 CHECK(!reference_profile_file_.empty());
910 fd = open(reference_profile_file_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
911 if (fd < 0) {
912 LOG(ERROR) << "Cannot open " << reference_profile_file_ << strerror(errno);
913 return kInvalidFd;
914 }
915 }
916 return fd;
917 }
918
Calin Juravlee0ac1152017-02-13 19:03:47 -0800919 // Creates a profile from a human friendly textual representation.
920 // The expected input format is:
921 // # Classes
922 // Ljava/lang/Comparable;
923 // Ljava/lang/Math;
924 // # Methods with inline caches
925 // LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;
926 // LTestInline;->noInlineCache(LSuper;)I
David Sehr7c80f2d2017-02-07 16:47:58 -0800927 int CreateProfile() {
David Sehr153da0e2017-02-15 08:54:51 -0800928 // Validate parameters for this command.
929 if (apk_files_.empty() && apks_fd_.empty()) {
930 Usage("APK files must be specified");
931 }
932 if (dex_locations_.empty()) {
933 Usage("DEX locations must be specified");
934 }
935 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
936 Usage("Reference profile must be specified with --reference-profile-file or "
937 "--reference-profile-file-fd");
938 }
939 if (!profile_files_.empty() || !profile_files_fd_.empty()) {
940 Usage("Profile must be specified with --reference-profile-file or "
941 "--reference-profile-file-fd");
942 }
943 // for ZipArchive::OpenFromFd
944 MemMap::Init();
David Sehr7c80f2d2017-02-07 16:47:58 -0800945 // Open the profile output file if needed.
Mathieu Chartier2f794552017-06-19 10:58:08 -0700946 int fd = OpenReferenceProfile();
David Sehr7c80f2d2017-02-07 16:47:58 -0800947 if (!FdIsValid(fd)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800948 return -1;
David Sehr7c80f2d2017-02-07 16:47:58 -0800949 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800950 // Read the user-specified list of classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800951 std::unique_ptr<std::unordered_set<std::string>>
Calin Juravlee0ac1152017-02-13 19:03:47 -0800952 user_lines(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
David Sehr7c80f2d2017-02-07 16:47:58 -0800953 create_profile_from_file_.c_str(), nullptr)); // No post-processing.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800954
955 // Open the dex files to look up classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800956 std::vector<std::unique_ptr<const DexFile>> dex_files;
957 OpenApkFilesFromLocations(&dex_files);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800958
959 // Process the lines one by one and add the successful ones to the profile.
David Sehr7c80f2d2017-02-07 16:47:58 -0800960 ProfileCompilationInfo info;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800961
962 for (const auto& line : *user_lines) {
963 ProcessLine(dex_files, line, &info);
964 }
965
David Sehr7c80f2d2017-02-07 16:47:58 -0800966 // Write the profile file.
967 CHECK(info.Save(fd));
968 if (close(fd) < 0) {
969 PLOG(WARNING) << "Failed to close descriptor";
970 }
971 return 0;
972 }
973
Mathieu Chartier2f794552017-06-19 10:58:08 -0700974 bool ShouldCreateBootProfile() const {
975 return generate_boot_image_profile_;
976 }
977
978 int CreateBootProfile() {
979 // Initialize memmap since it's required to open dex files.
980 MemMap::Init();
981 // Open the profile output file.
982 const int reference_fd = OpenReferenceProfile();
983 if (!FdIsValid(reference_fd)) {
984 PLOG(ERROR) << "Error opening reference profile";
985 return -1;
986 }
987 // Open the dex files.
988 std::vector<std::unique_ptr<const DexFile>> dex_files;
989 OpenApkFilesFromLocations(&dex_files);
990 if (dex_files.empty()) {
991 PLOG(ERROR) << "Expected dex files for creating boot profile";
992 return -2;
993 }
994 // Open the input profiles.
995 std::vector<std::unique_ptr<const ProfileCompilationInfo>> profiles;
996 if (!profile_files_fd_.empty()) {
997 for (int profile_file_fd : profile_files_fd_) {
998 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile("", profile_file_fd));
999 if (profile == nullptr) {
1000 return -3;
1001 }
1002 profiles.emplace_back(std::move(profile));
1003 }
1004 }
1005 if (!profile_files_.empty()) {
1006 for (const std::string& profile_file : profile_files_) {
1007 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile(profile_file, kInvalidFd));
1008 if (profile == nullptr) {
1009 return -4;
1010 }
1011 profiles.emplace_back(std::move(profile));
1012 }
1013 }
1014 ProfileCompilationInfo out_profile;
1015 GenerateBootImageProfile(dex_files,
1016 profiles,
1017 boot_image_options_,
1018 VLOG_IS_ON(profiler),
1019 &out_profile);
1020 out_profile.Save(reference_fd);
1021 close(reference_fd);
1022 return 0;
1023 }
1024
David Sehr7c80f2d2017-02-07 16:47:58 -08001025 bool ShouldCreateProfile() {
1026 return !create_profile_from_file_.empty();
1027 }
1028
Calin Juravle7bcdb532016-06-07 16:14:47 +01001029 int GenerateTestProfile() {
David Sehr153da0e2017-02-15 08:54:51 -08001030 // Validate parameters for this command.
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001031 if (test_profile_method_percerntage_ > 100) {
1032 Usage("Invalid percentage for --generate-test-profile-method-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001033 }
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001034 if (test_profile_class_percentage_ > 100) {
1035 Usage("Invalid percentage for --generate-test-profile-class-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001036 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001037 // If given APK files or DEX locations, check that they're ok.
1038 if (!apk_files_.empty() || !apks_fd_.empty() || !dex_locations_.empty()) {
1039 if (apk_files_.empty() && apks_fd_.empty()) {
1040 Usage("APK files must be specified when passing DEX locations to --generate-test-profile");
1041 }
1042 if (dex_locations_.empty()) {
1043 Usage("DEX locations must be specified when passing APK files to --generate-test-profile");
1044 }
1045 }
David Sehr153da0e2017-02-15 08:54:51 -08001046 // ShouldGenerateTestProfile confirms !test_profile_.empty().
George Burgess IV71f77262016-10-25 13:08:17 -07001047 int profile_test_fd = open(test_profile_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001048 if (profile_test_fd < 0) {
David Sehr7c80f2d2017-02-07 16:47:58 -08001049 LOG(ERROR) << "Cannot open " << test_profile_ << strerror(errno);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001050 return -1;
1051 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001052 bool result;
1053 if (apk_files_.empty() && apks_fd_.empty() && dex_locations_.empty()) {
1054 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1055 test_profile_num_dex_,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001056 test_profile_method_percerntage_,
1057 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001058 test_profile_seed_);
1059 } else {
1060 // Initialize MemMap for ZipArchive::OpenFromFd.
1061 MemMap::Init();
1062 // Open the dex files to look up classes and methods.
1063 std::vector<std::unique_ptr<const DexFile>> dex_files;
1064 OpenApkFilesFromLocations(&dex_files);
1065 // Create a random profile file based on the set of dex files.
1066 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1067 dex_files,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001068 test_profile_method_percerntage_,
1069 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001070 test_profile_seed_);
1071 }
Calin Juravle7bcdb532016-06-07 16:14:47 +01001072 close(profile_test_fd); // ignore close result.
1073 return result ? 0 : -1;
1074 }
1075
1076 bool ShouldGenerateTestProfile() {
1077 return !test_profile_.empty();
1078 }
1079
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001080 bool ShouldCopyAndUpdateProfileKey() const {
1081 return copy_and_update_profile_key_;
1082 }
1083
1084 bool CopyAndUpdateProfileKey() const {
1085 // Validate that at least one profile file was passed, as well as a reference profile.
1086 if (!(profile_files_.size() == 1 ^ profile_files_fd_.size() == 1)) {
1087 Usage("Only one profile file should be specified.");
1088 }
1089 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
1090 Usage("No reference profile file specified.");
1091 }
1092
1093 if (apk_files_.empty() && apks_fd_.empty()) {
1094 Usage("No apk files specified");
1095 }
1096
1097 bool use_fds = profile_files_fd_.size() == 1;
1098
1099 ProfileCompilationInfo profile;
1100 // Do not clear if invalid. The input might be an archive.
1101 if (profile.Load(profile_files_[0], /*clear_if_invalid*/ false)) {
1102 // Open the dex files to look up classes and methods.
1103 std::vector<std::unique_ptr<const DexFile>> dex_files;
1104 OpenApkFilesFromLocations(&dex_files);
1105 if (!profile.UpdateProfileKeys(dex_files)) {
1106 return false;
1107 }
1108 return use_fds
1109 ? profile.Save(reference_profile_file_fd_)
1110 : profile.Save(reference_profile_file_, /*bytes_written*/ nullptr);
1111 } else {
1112 return false;
1113 }
1114 }
1115
Calin Juravle2e2db782016-02-23 12:00:03 +00001116 private:
1117 static void ParseFdForCollection(const StringPiece& option,
1118 const char* arg_name,
1119 std::vector<int>* fds) {
1120 int fd;
1121 ParseUintOption(option, arg_name, &fd, Usage);
1122 fds->push_back(fd);
1123 }
1124
1125 static void CloseAllFds(const std::vector<int>& fds, const char* descriptor) {
1126 for (size_t i = 0; i < fds.size(); i++) {
1127 if (close(fds[i]) < 0) {
1128 PLOG(WARNING) << "Failed to close descriptor for " << descriptor << " at index " << i;
1129 }
1130 }
1131 }
1132
1133 void LogCompletionTime() {
David Sehr52683cf2016-05-05 09:02:38 -07001134 static constexpr uint64_t kLogThresholdTime = MsToNs(100); // 100ms
1135 uint64_t time_taken = NanoTime() - start_ns_;
David Sehred793012016-05-05 13:39:43 -07001136 if (time_taken > kLogThresholdTime) {
David Sehrd8557182016-05-06 12:29:35 -07001137 LOG(WARNING) << "profman took " << PrettyDuration(time_taken);
David Sehred793012016-05-05 13:39:43 -07001138 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001139 }
1140
1141 std::vector<std::string> profile_files_;
1142 std::vector<int> profile_files_fd_;
David Sehr546d24f2016-06-02 10:46:19 -07001143 std::vector<std::string> dex_locations_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001144 std::vector<std::string> apk_files_;
David Sehr546d24f2016-06-02 10:46:19 -07001145 std::vector<int> apks_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001146 std::string reference_profile_file_;
1147 int reference_profile_file_fd_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001148 bool dump_only_;
Mathieu Chartier34067262017-04-06 13:55:46 -07001149 bool dump_classes_and_methods_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001150 bool generate_boot_image_profile_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001151 int dump_output_to_fd_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001152 BootImageOptions boot_image_options_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001153 std::string test_profile_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001154 std::string create_profile_from_file_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001155 uint16_t test_profile_num_dex_;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001156 uint16_t test_profile_method_percerntage_;
1157 uint16_t test_profile_class_percentage_;
Jeff Haof0a31f82017-03-27 15:50:37 -07001158 uint32_t test_profile_seed_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001159 uint64_t start_ns_;
Calin Juravle2dba0ab2018-01-22 19:22:24 -08001160 bool copy_and_update_profile_key_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001161};
1162
1163// See ProfileAssistant::ProcessingResult for return codes.
1164static int profman(int argc, char** argv) {
1165 ProfMan profman;
1166
1167 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1168 profman.ParseArgs(argc, argv);
1169
Calin Juravle7bcdb532016-06-07 16:14:47 +01001170 if (profman.ShouldGenerateTestProfile()) {
1171 return profman.GenerateTestProfile();
1172 }
Calin Juravle876f3502016-03-24 16:16:34 +00001173 if (profman.ShouldOnlyDumpProfile()) {
1174 return profman.DumpProfileInfo();
1175 }
Mathieu Chartier34067262017-04-06 13:55:46 -07001176 if (profman.ShouldOnlyDumpClassesAndMethods()) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001177 return profman.DumpClassesAndMethods();
David Sehr7c80f2d2017-02-07 16:47:58 -08001178 }
1179 if (profman.ShouldCreateProfile()) {
1180 return profman.CreateProfile();
1181 }
Mathieu Chartier2f794552017-06-19 10:58:08 -07001182
1183 if (profman.ShouldCreateBootProfile()) {
1184 return profman.CreateBootProfile();
1185 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001186 // Process profile information and assess if we need to do a profile guided compilation.
1187 // This operation involves I/O.
1188 return profman.ProcessProfiles();
1189}
1190
1191} // namespace art
1192
1193int main(int argc, char **argv) {
1194 return art::profman(argc, argv);
1195}
1196