blob: c4216fab998d22fbec7b687a2af53afa8e4a32c2 [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 Sehr9e734c72018-01-04 17:56:19 -080042#include "dex/code_item_accessors-inl.h"
43#include "dex/dex_file.h"
44#include "dex/dex_file_loader.h"
45#include "dex/dex_file_types.h"
Calin Juravle33083d62017-01-18 15:29:12 -080046#include "jit/profile_compilation_info.h"
Mathieu Chartierdbddc222017-05-24 12:04:13 -070047#include "profile_assistant.h"
David Sehrf57589f2016-10-17 10:09:33 -070048#include "runtime.h"
Mathieu Chartierdbddc222017-05-24 12:04:13 -070049#include "type_reference.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000050#include "utils.h"
David Sehr546d24f2016-06-02 10:46:19 -070051#include "zip_archive.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000052
53namespace art {
54
55static int original_argc;
56static char** original_argv;
57
58static std::string CommandLine() {
59 std::vector<std::string> command;
60 for (int i = 0; i < original_argc; ++i) {
61 command.push_back(original_argv[i]);
62 }
Andreas Gampe9186ced2016-12-12 14:28:21 -080063 return android::base::Join(command, ' ');
Calin Juravle2e2db782016-02-23 12:00:03 +000064}
65
David Sehr4fcdd6d2016-05-24 14:52:31 -070066static constexpr int kInvalidFd = -1;
67
68static bool FdIsValid(int fd) {
69 return fd != kInvalidFd;
70}
71
Calin Juravle2e2db782016-02-23 12:00:03 +000072static void UsageErrorV(const char* fmt, va_list ap) {
73 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080074 android::base::StringAppendV(&error, fmt, ap);
Calin Juravle2e2db782016-02-23 12:00:03 +000075 LOG(ERROR) << error;
76}
77
78static void UsageError(const char* fmt, ...) {
79 va_list ap;
80 va_start(ap, fmt);
81 UsageErrorV(fmt, ap);
82 va_end(ap);
83}
84
85NO_RETURN static void Usage(const char *fmt, ...) {
86 va_list ap;
87 va_start(ap, fmt);
88 UsageErrorV(fmt, ap);
89 va_end(ap);
90
91 UsageError("Command: %s", CommandLine().c_str());
92 UsageError("Usage: profman [options]...");
93 UsageError("");
David Sehr4fcdd6d2016-05-24 14:52:31 -070094 UsageError(" --dump-only: dumps the content of the specified profile files");
95 UsageError(" to standard output (default) in a human readable form.");
96 UsageError("");
David Sehr7c80f2d2017-02-07 16:47:58 -080097 UsageError(" --dump-output-to-fd=<number>: redirects --dump-only output to a file descriptor.");
98 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -070099 UsageError(" --dump-classes-and-methods: dumps a sorted list of classes and methods that are");
100 UsageError(" in the specified profile file to standard output (default) in a human");
101 UsageError(" readable form. The output is valid input for --create-profile-from");
Calin Juravle876f3502016-03-24 16:16:34 +0000102 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000103 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
104 UsageError(" Can be specified multiple time, in which case the data from the different");
105 UsageError(" profiles will be aggregated.");
106 UsageError("");
107 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
108 UsageError(" Cannot be used together with --profile-file.");
109 UsageError("");
110 UsageError(" --reference-profile-file=<filename>: specify a reference profile.");
111 UsageError(" The data in this file will be compared with the data obtained by merging");
112 UsageError(" all the files specified with --profile-file or --profile-file-fd.");
113 UsageError(" If the exit code is EXIT_COMPILE then all --profile-file will be merged into");
114 UsageError(" --reference-profile-file. ");
115 UsageError("");
116 UsageError(" --reference-profile-file-fd=<number>: same as --reference-profile-file but");
117 UsageError(" accepts a file descriptor. Cannot be used together with");
118 UsageError(" --reference-profile-file.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800119 UsageError("");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100120 UsageError(" --generate-test-profile=<filename>: generates a random profile file for testing.");
121 UsageError(" --generate-test-profile-num-dex=<number>: number of dex files that should be");
122 UsageError(" included in the generated profile. Defaults to 20.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700123 UsageError(" --generate-test-profile-method-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100124 UsageError(" number of methods that should be generated. Defaults to 5.");
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700125 UsageError(" --generate-test-profile-class-percentage=<number>: the percentage from the maximum");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100126 UsageError(" number of classes that should be generated. Defaults to 5.");
Jeff Haof0a31f82017-03-27 15:50:37 -0700127 UsageError(" --generate-test-profile-seed=<number>: seed for random number generator used when");
128 UsageError(" generating random test profiles. Defaults to using NanoTime.");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100129 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -0700130 UsageError(" --create-profile-from=<filename>: creates a profile from a list of classes and");
131 UsageError(" methods.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800132 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700133 UsageError(" --dex-location=<string>: location string to use with corresponding");
134 UsageError(" apk-fd to find dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700135 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700136 UsageError(" --apk-fd=<number>: file descriptor containing an open APK to");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700137 UsageError(" search for dex files");
David Sehr7c80f2d2017-02-07 16:47:58 -0800138 UsageError(" --apk-=<filename>: an APK to search for dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700139 UsageError("");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700140 UsageError(" --generate-boot-image-profile: Generate a boot image profile based on input");
141 UsageError(" profiles. Requires passing in dex files to inspect properties of classes.");
142 UsageError(" --boot-image-class-threshold=<value>: specify minimum number of class occurrences");
143 UsageError(" to include a class in the boot image profile. Default is 10.");
144 UsageError(" --boot-image-clean-class-threshold=<value>: specify minimum number of clean class");
145 UsageError(" occurrences to include a class in the boot image profile. A clean class is a");
146 UsageError(" class that doesn't have any static fields or native methods and is likely to");
147 UsageError(" remain clean in the image. Default is 3.");
Mathieu Chartier8eecddf2017-07-12 16:05:54 -0700148 UsageError(" --boot-image-sampled-method-threshold=<value>: minimum number of profiles a");
149 UsageError(" non-hot method needs to be in order to be hot in the output profile. The");
150 UsageError(" default is max int.");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700151 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000152
153 exit(EXIT_FAILURE);
154}
155
Calin Juravle7bcdb532016-06-07 16:14:47 +0100156// Note: make sure you update the Usage if you change these values.
157static constexpr uint16_t kDefaultTestProfileNumDex = 20;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700158static constexpr uint16_t kDefaultTestProfileMethodPercentage = 5;
159static constexpr uint16_t kDefaultTestProfileClassPercentage = 5;
Calin Juravle7bcdb532016-06-07 16:14:47 +0100160
Calin Juravlee0ac1152017-02-13 19:03:47 -0800161// Separators used when parsing human friendly representation of profiles.
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800162static const std::string kMethodSep = "->"; // NOLINT [runtime/string] [4]
163static const std::string kMissingTypesMarker = "missing_types"; // NOLINT [runtime/string] [4]
164static const std::string kInvalidClassDescriptor = "invalid_class"; // NOLINT [runtime/string] [4]
165static const std::string kInvalidMethod = "invalid_method"; // NOLINT [runtime/string] [4]
166static const std::string kClassAllMethods = "*"; // NOLINT [runtime/string] [4]
Calin Juravlee0ac1152017-02-13 19:03:47 -0800167static constexpr char kProfileParsingInlineChacheSep = '+';
168static constexpr char kProfileParsingTypeSep = ',';
169static constexpr char kProfileParsingFirstCharInSignature = '(';
Mathieu Chartierea650f32017-05-24 12:04:13 -0700170static constexpr char kMethodFlagStringHot = 'H';
171static constexpr char kMethodFlagStringStartup = 'S';
172static constexpr char kMethodFlagStringPostStartup = 'P';
Calin Juravlee0ac1152017-02-13 19:03:47 -0800173
174// TODO(calin): This class has grown too much from its initial design. Split the functionality
175// into smaller, more contained pieces.
Calin Juravle2e2db782016-02-23 12:00:03 +0000176class ProfMan FINAL {
177 public:
178 ProfMan() :
David Sehr4fcdd6d2016-05-24 14:52:31 -0700179 reference_profile_file_fd_(kInvalidFd),
180 dump_only_(false),
Mathieu Chartier34067262017-04-06 13:55:46 -0700181 dump_classes_and_methods_(false),
Mathieu Chartier2f794552017-06-19 10:58:08 -0700182 generate_boot_image_profile_(false),
David Sehr4fcdd6d2016-05-24 14:52:31 -0700183 dump_output_to_fd_(kInvalidFd),
Calin Juravle7bcdb532016-06-07 16:14:47 +0100184 test_profile_num_dex_(kDefaultTestProfileNumDex),
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700185 test_profile_method_percerntage_(kDefaultTestProfileMethodPercentage),
186 test_profile_class_percentage_(kDefaultTestProfileClassPercentage),
Jeff Haof0a31f82017-03-27 15:50:37 -0700187 test_profile_seed_(NanoTime()),
Calin Juravle2e2db782016-02-23 12:00:03 +0000188 start_ns_(NanoTime()) {}
189
190 ~ProfMan() {
191 LogCompletionTime();
192 }
193
194 void ParseArgs(int argc, char **argv) {
195 original_argc = argc;
196 original_argv = argv;
197
Andreas Gampe51d80cc2017-06-21 21:05:13 -0700198 InitLogging(argv, Runtime::Abort);
Calin Juravle2e2db782016-02-23 12:00:03 +0000199
200 // Skip over the command name.
201 argv++;
202 argc--;
203
204 if (argc == 0) {
205 Usage("No arguments specified");
206 }
207
208 for (int i = 0; i < argc; ++i) {
209 const StringPiece option(argv[i]);
210 const bool log_options = false;
211 if (log_options) {
Calin Juravle876f3502016-03-24 16:16:34 +0000212 LOG(INFO) << "profman: option[" << i << "]=" << argv[i];
Calin Juravle2e2db782016-02-23 12:00:03 +0000213 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700214 if (option == "--dump-only") {
215 dump_only_ = true;
Mathieu Chartier34067262017-04-06 13:55:46 -0700216 } else if (option == "--dump-classes-and-methods") {
217 dump_classes_and_methods_ = true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800218 } else if (option.starts_with("--create-profile-from=")) {
219 create_profile_from_file_ = option.substr(strlen("--create-profile-from=")).ToString();
David Sehr4fcdd6d2016-05-24 14:52:31 -0700220 } else if (option.starts_with("--dump-output-to-fd=")) {
221 ParseUintOption(option, "--dump-output-to-fd", &dump_output_to_fd_, Usage);
Mathieu Chartier2f794552017-06-19 10:58:08 -0700222 } else if (option == "--generate-boot-image-profile") {
223 generate_boot_image_profile_ = true;
224 } else if (option.starts_with("--boot-image-class-threshold=")) {
225 ParseUintOption(option,
226 "--boot-image-class-threshold",
227 &boot_image_options_.image_class_theshold,
228 Usage);
229 } else if (option.starts_with("--boot-image-clean-class-threshold=")) {
230 ParseUintOption(option,
231 "--boot-image-clean-class-threshold",
232 &boot_image_options_.image_class_clean_theshold,
233 Usage);
Mathieu Chartier8eecddf2017-07-12 16:05:54 -0700234 } else if (option.starts_with("--boot-image-sampled-method-threshold=")) {
235 ParseUintOption(option,
236 "--boot-image-sampled-method-threshold",
237 &boot_image_options_.compiled_method_threshold,
238 Usage);
Calin Juravle876f3502016-03-24 16:16:34 +0000239 } else if (option.starts_with("--profile-file=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000240 profile_files_.push_back(option.substr(strlen("--profile-file=")).ToString());
241 } else if (option.starts_with("--profile-file-fd=")) {
242 ParseFdForCollection(option, "--profile-file-fd", &profile_files_fd_);
243 } else if (option.starts_with("--reference-profile-file=")) {
244 reference_profile_file_ = option.substr(strlen("--reference-profile-file=")).ToString();
245 } else if (option.starts_with("--reference-profile-file-fd=")) {
246 ParseUintOption(option, "--reference-profile-file-fd", &reference_profile_file_fd_, Usage);
David Sehr546d24f2016-06-02 10:46:19 -0700247 } else if (option.starts_with("--dex-location=")) {
248 dex_locations_.push_back(option.substr(strlen("--dex-location=")).ToString());
249 } else if (option.starts_with("--apk-fd=")) {
250 ParseFdForCollection(option, "--apk-fd", &apks_fd_);
David Sehr7c80f2d2017-02-07 16:47:58 -0800251 } else if (option.starts_with("--apk=")) {
252 apk_files_.push_back(option.substr(strlen("--apk=")).ToString());
Calin Juravle7bcdb532016-06-07 16:14:47 +0100253 } else if (option.starts_with("--generate-test-profile=")) {
254 test_profile_ = option.substr(strlen("--generate-test-profile=")).ToString();
255 } else if (option.starts_with("--generate-test-profile-num-dex=")) {
256 ParseUintOption(option,
257 "--generate-test-profile-num-dex",
258 &test_profile_num_dex_,
259 Usage);
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700260 } else if (option.starts_with("--generate-test-profile-method-percentage")) {
Calin Juravle7bcdb532016-06-07 16:14:47 +0100261 ParseUintOption(option,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700262 "--generate-test-profile-method-percentage",
263 &test_profile_method_percerntage_,
Calin Juravle7bcdb532016-06-07 16:14:47 +0100264 Usage);
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700265 } else if (option.starts_with("--generate-test-profile-class-percentage")) {
Calin Juravle7bcdb532016-06-07 16:14:47 +0100266 ParseUintOption(option,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -0700267 "--generate-test-profile-class-percentage",
268 &test_profile_class_percentage_,
Calin Juravle7bcdb532016-06-07 16:14:47 +0100269 Usage);
Jeff Haof0a31f82017-03-27 15:50:37 -0700270 } else if (option.starts_with("--generate-test-profile-seed=")) {
271 ParseUintOption(option, "--generate-test-profile-seed", &test_profile_seed_, Usage);
Calin Juravle2e2db782016-02-23 12:00:03 +0000272 } else {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700273 Usage("Unknown argument '%s'", option.data());
Calin Juravle2e2db782016-02-23 12:00:03 +0000274 }
275 }
276
David Sehr153da0e2017-02-15 08:54:51 -0800277 // Validate global consistency between file/fd options.
Calin Juravle2e2db782016-02-23 12:00:03 +0000278 if (!profile_files_.empty() && !profile_files_fd_.empty()) {
279 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
280 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700281 if (!reference_profile_file_.empty() && FdIsValid(reference_profile_file_fd_)) {
282 Usage("Reference profile should not be specified with both "
283 "--reference-profile-file-fd and --reference-profile-file");
284 }
David Sehr153da0e2017-02-15 08:54:51 -0800285 if (!apk_files_.empty() && !apks_fd_.empty()) {
286 Usage("APK files should not be specified with both --apk-fd and --apk");
Calin Juravle2e2db782016-02-23 12:00:03 +0000287 }
288 }
289
290 ProfileAssistant::ProcessingResult ProcessProfiles() {
David Sehr153da0e2017-02-15 08:54:51 -0800291 // Validate that at least one profile file was passed, as well as a reference profile.
292 if (profile_files_.empty() && profile_files_fd_.empty()) {
293 Usage("No profile files specified.");
294 }
295 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
296 Usage("No reference profile file specified.");
297 }
298 if ((!profile_files_.empty() && FdIsValid(reference_profile_file_fd_)) ||
299 (!profile_files_fd_.empty() && !FdIsValid(reference_profile_file_fd_))) {
300 Usage("Options --profile-file-fd and --reference-profile-file-fd "
301 "should only be used together");
302 }
Calin Juravle2e2db782016-02-23 12:00:03 +0000303 ProfileAssistant::ProcessingResult result;
304 if (profile_files_.empty()) {
305 // The file doesn't need to be flushed here (ProcessProfiles will do it)
306 // so don't check the usage.
307 File file(reference_profile_file_fd_, false);
308 result = ProfileAssistant::ProcessProfiles(profile_files_fd_, reference_profile_file_fd_);
309 CloseAllFds(profile_files_fd_, "profile_files_fd_");
310 } else {
311 result = ProfileAssistant::ProcessProfiles(profile_files_, reference_profile_file_);
312 }
313 return result;
314 }
315
David Sehr7c80f2d2017-02-07 16:47:58 -0800316 void OpenApkFilesFromLocations(std::vector<std::unique_ptr<const DexFile>>* dex_files) {
317 bool use_apk_fd_list = !apks_fd_.empty();
318 if (use_apk_fd_list) {
David Sehr153da0e2017-02-15 08:54:51 -0800319 // Get the APKs from the collection of FDs.
David Sehr7c80f2d2017-02-07 16:47:58 -0800320 CHECK_EQ(dex_locations_.size(), apks_fd_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800321 } else if (!apk_files_.empty()) {
322 // Get the APKs from the collection of filenames.
David Sehr7c80f2d2017-02-07 16:47:58 -0800323 CHECK_EQ(dex_locations_.size(), apk_files_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800324 } else {
325 // No APKs were specified.
326 CHECK(dex_locations_.empty());
327 return;
David Sehr7c80f2d2017-02-07 16:47:58 -0800328 }
329 static constexpr bool kVerifyChecksum = true;
330 for (size_t i = 0; i < dex_locations_.size(); ++i) {
331 std::string error_msg;
332 std::vector<std::unique_ptr<const DexFile>> dex_files_for_location;
333 if (use_apk_fd_list) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700334 if (DexFileLoader::OpenZip(apks_fd_[i],
335 dex_locations_[i],
Nicolas Geoffray095c6c92017-10-19 13:59:55 +0100336 /* verify */ true,
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700337 kVerifyChecksum,
338 &error_msg,
339 &dex_files_for_location)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800340 } else {
341 LOG(WARNING) << "OpenZip failed for '" << dex_locations_[i] << "' " << error_msg;
342 continue;
343 }
344 } else {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700345 if (DexFileLoader::Open(apk_files_[i].c_str(),
346 dex_locations_[i],
Nicolas Geoffray095c6c92017-10-19 13:59:55 +0100347 /* verify */ true,
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700348 kVerifyChecksum,
349 &error_msg,
350 &dex_files_for_location)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800351 } else {
352 LOG(WARNING) << "Open failed for '" << dex_locations_[i] << "' " << error_msg;
353 continue;
354 }
355 }
356 for (std::unique_ptr<const DexFile>& dex_file : dex_files_for_location) {
357 dex_files->emplace_back(std::move(dex_file));
358 }
359 }
360 }
361
Mathieu Chartier2f794552017-06-19 10:58:08 -0700362 std::unique_ptr<const ProfileCompilationInfo> LoadProfile(const std::string& filename, int fd) {
363 if (!filename.empty()) {
364 fd = open(filename.c_str(), O_RDWR);
365 if (fd < 0) {
366 LOG(ERROR) << "Cannot open " << filename << strerror(errno);
367 return nullptr;
368 }
369 }
370 std::unique_ptr<ProfileCompilationInfo> info(new ProfileCompilationInfo);
371 if (!info->Load(fd)) {
372 LOG(ERROR) << "Cannot load profile info from fd=" << fd << "\n";
373 return nullptr;
374 }
375 return info;
376 }
377
David Sehrb18991b2017-02-08 20:58:10 -0800378 int DumpOneProfile(const std::string& banner,
379 const std::string& filename,
380 int fd,
381 const std::vector<std::unique_ptr<const DexFile>>* dex_files,
382 std::string* dump) {
Mathieu Chartier2f794552017-06-19 10:58:08 -0700383 std::unique_ptr<const ProfileCompilationInfo> info(LoadProfile(filename, fd));
384 if (info == nullptr) {
385 LOG(ERROR) << "Cannot load profile info from filename=" << filename << " fd=" << fd;
Calin Juravle876f3502016-03-24 16:16:34 +0000386 return -1;
387 }
Mathieu Chartier2f794552017-06-19 10:58:08 -0700388 *dump += banner + "\n" + info->DumpInfo(dex_files) + "\n";
David Sehr4fcdd6d2016-05-24 14:52:31 -0700389 return 0;
390 }
391
392 int DumpProfileInfo() {
David Sehr153da0e2017-02-15 08:54:51 -0800393 // Validate that at least one profile file or reference was specified.
394 if (profile_files_.empty() && profile_files_fd_.empty() &&
395 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
396 Usage("No profile files or reference profile specified.");
397 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700398 static const char* kEmptyString = "";
David Sehr546d24f2016-06-02 10:46:19 -0700399 static const char* kOrdinaryProfile = "=== profile ===";
400 static const char* kReferenceProfile = "=== reference profile ===";
401
402 // Open apk/zip files and and read dex files.
403 MemMap::Init(); // for ZipArchive::OpenFromFd
David Sehrb18991b2017-02-08 20:58:10 -0800404 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7c80f2d2017-02-07 16:47:58 -0800405 OpenApkFilesFromLocations(&dex_files);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700406 std::string dump;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700407 // Dump individual profile files.
408 if (!profile_files_fd_.empty()) {
409 for (int profile_file_fd : profile_files_fd_) {
David Sehr546d24f2016-06-02 10:46:19 -0700410 int ret = DumpOneProfile(kOrdinaryProfile,
411 kEmptyString,
412 profile_file_fd,
413 &dex_files,
414 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700415 if (ret != 0) {
416 return ret;
417 }
418 }
419 }
420 if (!profile_files_.empty()) {
421 for (const std::string& profile_file : profile_files_) {
David Sehr546d24f2016-06-02 10:46:19 -0700422 int ret = DumpOneProfile(kOrdinaryProfile, profile_file, kInvalidFd, &dex_files, &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700423 if (ret != 0) {
424 return ret;
425 }
426 }
427 }
428 // Dump reference profile file.
429 if (FdIsValid(reference_profile_file_fd_)) {
David Sehr546d24f2016-06-02 10:46:19 -0700430 int ret = DumpOneProfile(kReferenceProfile,
431 kEmptyString,
432 reference_profile_file_fd_,
433 &dex_files,
434 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700435 if (ret != 0) {
436 return ret;
437 }
438 }
439 if (!reference_profile_file_.empty()) {
David Sehr546d24f2016-06-02 10:46:19 -0700440 int ret = DumpOneProfile(kReferenceProfile,
441 reference_profile_file_,
442 kInvalidFd,
443 &dex_files,
David Sehr4fcdd6d2016-05-24 14:52:31 -0700444 &dump);
445 if (ret != 0) {
446 return ret;
447 }
448 }
449 if (!FdIsValid(dump_output_to_fd_)) {
450 std::cout << dump;
451 } else {
452 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
453 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
454 return -1;
455 }
456 }
Calin Juravle876f3502016-03-24 16:16:34 +0000457 return 0;
458 }
459
460 bool ShouldOnlyDumpProfile() {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700461 return dump_only_;
Calin Juravle876f3502016-03-24 16:16:34 +0000462 }
463
Mathieu Chartier34067262017-04-06 13:55:46 -0700464 bool GetClassNamesAndMethods(int fd,
465 std::vector<std::unique_ptr<const DexFile>>* dex_files,
466 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800467 ProfileCompilationInfo profile_info;
468 if (!profile_info.Load(fd)) {
469 LOG(ERROR) << "Cannot load profile info";
470 return false;
471 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700472 for (const std::unique_ptr<const DexFile>& dex_file : *dex_files) {
473 std::set<dex::TypeIndex> class_types;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700474 std::set<uint16_t> hot_methods;
475 std::set<uint16_t> startup_methods;
476 std::set<uint16_t> post_startup_methods;
477 std::set<uint16_t> combined_methods;
478 if (profile_info.GetClassesAndMethods(*dex_file.get(),
479 &class_types,
480 &hot_methods,
481 &startup_methods,
482 &post_startup_methods)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700483 for (const dex::TypeIndex& type_index : class_types) {
484 const DexFile::TypeId& type_id = dex_file->GetTypeId(type_index);
485 out_lines->insert(std::string(dex_file->GetTypeDescriptor(type_id)));
486 }
Mathieu Chartierea650f32017-05-24 12:04:13 -0700487 combined_methods = hot_methods;
488 combined_methods.insert(startup_methods.begin(), startup_methods.end());
489 combined_methods.insert(post_startup_methods.begin(), post_startup_methods.end());
490 for (uint16_t dex_method_idx : combined_methods) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700491 const DexFile::MethodId& id = dex_file->GetMethodId(dex_method_idx);
492 std::string signature_string(dex_file->GetMethodSignature(id).ToString());
493 std::string type_string(dex_file->GetTypeDescriptor(dex_file->GetTypeId(id.class_idx_)));
494 std::string method_name(dex_file->GetMethodName(id));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700495 std::string flags_string;
496 if (hot_methods.find(dex_method_idx) != hot_methods.end()) {
497 flags_string += kMethodFlagStringHot;
498 }
499 if (startup_methods.find(dex_method_idx) != startup_methods.end()) {
500 flags_string += kMethodFlagStringStartup;
501 }
502 if (post_startup_methods.find(dex_method_idx) != post_startup_methods.end()) {
503 flags_string += kMethodFlagStringPostStartup;
504 }
505 out_lines->insert(flags_string +
506 type_string +
507 kMethodSep +
508 method_name +
509 signature_string);
Mathieu Chartier34067262017-04-06 13:55:46 -0700510 }
511 }
512 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800513 return true;
514 }
515
Mathieu Chartier34067262017-04-06 13:55:46 -0700516 bool GetClassNamesAndMethods(const std::string& profile_file,
517 std::vector<std::unique_ptr<const DexFile>>* dex_files,
518 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800519 int fd = open(profile_file.c_str(), O_RDONLY);
520 if (!FdIsValid(fd)) {
521 LOG(ERROR) << "Cannot open " << profile_file << strerror(errno);
522 return false;
523 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700524 if (!GetClassNamesAndMethods(fd, dex_files, out_lines)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800525 return false;
526 }
527 if (close(fd) < 0) {
528 PLOG(WARNING) << "Failed to close descriptor";
529 }
530 return true;
531 }
532
Mathieu Chartierea650f32017-05-24 12:04:13 -0700533 int DumpClassesAndMethods() {
David Sehr153da0e2017-02-15 08:54:51 -0800534 // Validate that at least one profile file or reference was specified.
535 if (profile_files_.empty() && profile_files_fd_.empty() &&
536 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
537 Usage("No profile files or reference profile specified.");
538 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800539 // Open apk/zip files and and read dex files.
540 MemMap::Init(); // for ZipArchive::OpenFromFd
541 // Open the dex files to get the names for classes.
542 std::vector<std::unique_ptr<const DexFile>> dex_files;
543 OpenApkFilesFromLocations(&dex_files);
544 // Build a vector of class names from individual profile files.
545 std::set<std::string> class_names;
546 if (!profile_files_fd_.empty()) {
547 for (int profile_file_fd : profile_files_fd_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700548 if (!GetClassNamesAndMethods(profile_file_fd, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800549 return -1;
550 }
551 }
552 }
553 if (!profile_files_.empty()) {
554 for (const std::string& profile_file : profile_files_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700555 if (!GetClassNamesAndMethods(profile_file, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800556 return -1;
557 }
558 }
559 }
560 // Concatenate class names from reference profile file.
561 if (FdIsValid(reference_profile_file_fd_)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700562 if (!GetClassNamesAndMethods(reference_profile_file_fd_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800563 return -1;
564 }
565 }
566 if (!reference_profile_file_.empty()) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700567 if (!GetClassNamesAndMethods(reference_profile_file_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800568 return -1;
569 }
570 }
571 // Dump the class names.
572 std::string dump;
573 for (const std::string& class_name : class_names) {
574 dump += class_name + std::string("\n");
575 }
576 if (!FdIsValid(dump_output_to_fd_)) {
577 std::cout << dump;
578 } else {
579 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
580 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
581 return -1;
582 }
583 }
584 return 0;
585 }
586
Mathieu Chartier34067262017-04-06 13:55:46 -0700587 bool ShouldOnlyDumpClassesAndMethods() {
588 return dump_classes_and_methods_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800589 }
590
591 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
592 // the given function.
593 template <typename T>
594 static T* ReadCommentedInputFromFile(
595 const char* input_filename, std::function<std::string(const char*)>* process) {
596 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
597 if (input_file.get() == nullptr) {
598 LOG(ERROR) << "Failed to open input file " << input_filename;
599 return nullptr;
600 }
601 std::unique_ptr<T> result(
602 ReadCommentedInputStream<T>(*input_file, process));
603 input_file->close();
604 return result.release();
605 }
606
607 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
608 // with the given function.
609 template <typename T>
610 static T* ReadCommentedInputStream(
611 std::istream& in_stream,
612 std::function<std::string(const char*)>* process) {
613 std::unique_ptr<T> output(new T());
614 while (in_stream.good()) {
615 std::string dot;
616 std::getline(in_stream, dot);
617 if (android::base::StartsWith(dot, "#") || dot.empty()) {
618 continue;
619 }
620 if (process != nullptr) {
621 std::string descriptor((*process)(dot.c_str()));
622 output->insert(output->end(), descriptor);
623 } else {
624 output->insert(output->end(), dot);
625 }
626 }
627 return output.release();
628 }
629
Calin Juravlee0ac1152017-02-13 19:03:47 -0800630 // Find class klass_descriptor in the given dex_files and store its reference
631 // in the out parameter class_ref.
632 // Return true if the definition of the class was found in any of the dex_files.
633 bool FindClass(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
634 const std::string& klass_descriptor,
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700635 /*out*/TypeReference* class_ref) {
Calin Juravle08556882017-05-26 16:40:45 -0700636 constexpr uint16_t kInvalidTypeIndex = std::numeric_limits<uint16_t>::max() - 1;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800637 for (const std::unique_ptr<const DexFile>& dex_file_ptr : dex_files) {
638 const DexFile* dex_file = dex_file_ptr.get();
Calin Juravle08556882017-05-26 16:40:45 -0700639 if (klass_descriptor == kInvalidClassDescriptor) {
640 if (kInvalidTypeIndex >= dex_file->NumTypeIds()) {
641 // The dex file does not contain all possible type ids which leaves us room
642 // to add an "invalid" type id.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700643 *class_ref = TypeReference(dex_file, dex::TypeIndex(kInvalidTypeIndex));
Calin Juravle08556882017-05-26 16:40:45 -0700644 return true;
645 } else {
646 // The dex file contains all possible type ids. We don't have any free type id
647 // that we can use as invalid.
648 continue;
649 }
650 }
651
Calin Juravlee0ac1152017-02-13 19:03:47 -0800652 const DexFile::TypeId* type_id = dex_file->FindTypeId(klass_descriptor.c_str());
653 if (type_id == nullptr) {
654 continue;
655 }
656 dex::TypeIndex type_index = dex_file->GetIndexForTypeId(*type_id);
657 if (dex_file->FindClassDef(type_index) == nullptr) {
658 // Class is only referenced in the current dex file but not defined in it.
659 continue;
660 }
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700661 *class_ref = TypeReference(dex_file, type_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800662 return true;
663 }
664 return false;
665 }
666
Mathieu Chartier34067262017-04-06 13:55:46 -0700667 // Find the method specified by method_spec in the class class_ref.
Calin Juravle08556882017-05-26 16:40:45 -0700668 uint32_t FindMethodIndex(const TypeReference& class_ref,
669 const std::string& method_spec) {
670 const DexFile* dex_file = class_ref.dex_file;
671 if (method_spec == kInvalidMethod) {
672 constexpr uint16_t kInvalidMethodIndex = std::numeric_limits<uint16_t>::max() - 1;
673 return kInvalidMethodIndex >= dex_file->NumMethodIds()
674 ? kInvalidMethodIndex
Andreas Gampee2abbc62017-09-15 11:59:26 -0700675 : dex::kDexNoIndex;
Calin Juravle08556882017-05-26 16:40:45 -0700676 }
677
Calin Juravlee0ac1152017-02-13 19:03:47 -0800678 std::vector<std::string> name_and_signature;
679 Split(method_spec, kProfileParsingFirstCharInSignature, &name_and_signature);
680 if (name_and_signature.size() != 2) {
681 LOG(ERROR) << "Invalid method name and signature " << method_spec;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700682 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800683 }
Calin Juravle08556882017-05-26 16:40:45 -0700684
Calin Juravlee0ac1152017-02-13 19:03:47 -0800685 const std::string& name = name_and_signature[0];
686 const std::string& signature = kProfileParsingFirstCharInSignature + name_and_signature[1];
Calin Juravlee0ac1152017-02-13 19:03:47 -0800687
688 const DexFile::StringId* name_id = dex_file->FindStringId(name.c_str());
689 if (name_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700690 LOG(WARNING) << "Could not find name: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700691 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800692 }
693 dex::TypeIndex return_type_idx;
694 std::vector<dex::TypeIndex> param_type_idxs;
695 if (!dex_file->CreateTypeList(signature, &return_type_idx, &param_type_idxs)) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700696 LOG(WARNING) << "Could not create type list" << signature;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700697 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800698 }
699 const DexFile::ProtoId* proto_id = dex_file->FindProtoId(return_type_idx, param_type_idxs);
700 if (proto_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700701 LOG(WARNING) << "Could not find proto_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700702 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800703 }
704 const DexFile::MethodId* method_id = dex_file->FindMethodId(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700705 dex_file->GetTypeId(class_ref.TypeIndex()), *name_id, *proto_id);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800706 if (method_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700707 LOG(WARNING) << "Could not find method_id: " << name;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700708 return dex::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800709 }
710
Mathieu Chartier34067262017-04-06 13:55:46 -0700711 return dex_file->GetIndexForMethodId(*method_id);
712 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800713
Mathieu Chartier34067262017-04-06 13:55:46 -0700714 // Given a method, return true if the method has a single INVOKE_VIRTUAL in its byte code.
715 // Upon success it returns true and stores the method index and the invoke dex pc
716 // in the output parameters.
717 // The format of the method spec is "inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
718 //
719 // TODO(calin): support INVOKE_INTERFACE and the range variants.
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700720 bool HasSingleInvoke(const TypeReference& class_ref,
Mathieu Chartier34067262017-04-06 13:55:46 -0700721 uint16_t method_index,
722 /*out*/uint32_t* dex_pc) {
723 const DexFile* dex_file = class_ref.dex_file;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800724 uint32_t offset = dex_file->FindCodeItemOffset(
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700725 *dex_file->FindClassDef(class_ref.TypeIndex()),
Mathieu Chartier34067262017-04-06 13:55:46 -0700726 method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800727 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(offset);
728
729 bool found_invoke = false;
Mathieu Chartier698ebbc2018-01-05 11:00:42 -0800730 for (const DexInstructionPcPair& inst : CodeItemInstructionAccessor(*dex_file, code_item)) {
Mathieu Chartier0021feb2017-11-07 00:08:52 -0800731 if (inst->Opcode() == Instruction::INVOKE_VIRTUAL) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800732 if (found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700733 LOG(ERROR) << "Multiple invoke INVOKE_VIRTUAL found: "
734 << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800735 return false;
736 }
737 found_invoke = true;
Mathieu Chartier0021feb2017-11-07 00:08:52 -0800738 *dex_pc = inst.DexPc();
Calin Juravlee0ac1152017-02-13 19:03:47 -0800739 }
740 }
741 if (!found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700742 LOG(ERROR) << "Could not find any INVOKE_VIRTUAL: " << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800743 }
744 return found_invoke;
745 }
746
747 // Process a line defining a class or a method and its inline caches.
748 // Upon success return true and add the class or the method info to profile.
Calin Juravle589e71e2017-03-03 16:05:05 -0800749 // The possible line formats are:
750 // "LJustTheCass;".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800751 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
Calin Juravle08556882017-05-26 16:40:45 -0700752 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,invalid_class".
Calin Juravle589e71e2017-03-03 16:05:05 -0800753 // "LTestInline;->inlineMissingTypes(LSuper;)I+missing_types".
754 // "LTestInline;->inlineNoInlineCaches(LSuper;)I".
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700755 // "LTestInline;->*".
Calin Juravle08556882017-05-26 16:40:45 -0700756 // "invalid_class".
757 // "LTestInline;->invalid_method".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800758 // The method and classes are searched only in the given dex files.
759 bool ProcessLine(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
760 const std::string& line,
761 /*out*/ProfileCompilationInfo* profile) {
762 std::string klass;
763 std::string method_str;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700764 bool is_hot = false;
765 bool is_startup = false;
766 bool is_post_startup = false;
767 const size_t method_sep_index = line.find(kMethodSep, 0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800768 if (method_sep_index == std::string::npos) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700769 klass = line.substr(0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800770 } else {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700771 // The method prefix flags are only valid for method strings.
772 size_t start_index = 0;
773 while (start_index < line.size() && line[start_index] != 'L') {
774 const char c = line[start_index];
775 if (c == kMethodFlagStringHot) {
776 is_hot = true;
777 } else if (c == kMethodFlagStringStartup) {
778 is_startup = true;
779 } else if (c == kMethodFlagStringPostStartup) {
780 is_post_startup = true;
781 } else {
782 LOG(WARNING) << "Invalid flag " << c;
783 return false;
784 }
785 ++start_index;
786 }
787 klass = line.substr(start_index, method_sep_index - start_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800788 method_str = line.substr(method_sep_index + kMethodSep.size());
789 }
790
Vladimir Markof3c52b42017-11-17 17:32:12 +0000791 TypeReference class_ref(/* dex_file */ nullptr, dex::TypeIndex());
Calin Juravlee0ac1152017-02-13 19:03:47 -0800792 if (!FindClass(dex_files, klass, &class_ref)) {
Mathieu Chartier3f121342017-03-06 11:16:20 -0800793 LOG(WARNING) << "Could not find class: " << klass;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800794 return false;
795 }
796
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700797 if (method_str.empty() || method_str == kClassAllMethods) {
798 // Start by adding the class.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800799 std::set<DexCacheResolvedClasses> resolved_class_set;
800 const DexFile* dex_file = class_ref.dex_file;
801 const auto& dex_resolved_classes = resolved_class_set.emplace(
802 dex_file->GetLocation(),
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700803 DexFileLoader::GetBaseLocation(dex_file->GetLocation()),
Mathieu Chartierea650f32017-05-24 12:04:13 -0700804 dex_file->GetLocationChecksum(),
805 dex_file->NumMethodIds());
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700806 dex_resolved_classes.first->AddClass(class_ref.TypeIndex());
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700807 std::vector<ProfileMethodInfo> methods;
808 if (method_str == kClassAllMethods) {
809 // Add all of the methods.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700810 const DexFile::ClassDef* class_def = dex_file->FindClassDef(class_ref.TypeIndex());
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700811 const uint8_t* class_data = dex_file->GetClassData(*class_def);
812 if (class_data != nullptr) {
813 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700814 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800815 while (it.HasNextMethod()) {
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700816 if (it.GetMethodCodeItemOffset() != 0) {
817 // Add all of the methods that have code to the profile.
818 const uint32_t method_idx = it.GetMemberIndex();
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700819 methods.push_back(ProfileMethodInfo(MethodReference(dex_file, method_idx)));
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700820 }
821 it.Next();
822 }
823 }
824 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700825 // TODO: Check return values?
826 profile->AddMethods(methods);
827 profile->AddClasses(resolved_class_set);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800828 return true;
829 }
830
831 // Process the method.
832 std::string method_spec;
833 std::vector<std::string> inline_cache_elems;
834
Mathieu Chartierea650f32017-05-24 12:04:13 -0700835 // If none of the flags are set, default to hot.
836 is_hot = is_hot || (!is_hot && !is_startup && !is_post_startup);
837
Calin Juravlee0ac1152017-02-13 19:03:47 -0800838 std::vector<std::string> method_elems;
Calin Juravle589e71e2017-03-03 16:05:05 -0800839 bool is_missing_types = false;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800840 Split(method_str, kProfileParsingInlineChacheSep, &method_elems);
841 if (method_elems.size() == 2) {
842 method_spec = method_elems[0];
Calin Juravle589e71e2017-03-03 16:05:05 -0800843 is_missing_types = method_elems[1] == kMissingTypesMarker;
844 if (!is_missing_types) {
845 Split(method_elems[1], kProfileParsingTypeSep, &inline_cache_elems);
846 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800847 } else if (method_elems.size() == 1) {
848 method_spec = method_elems[0];
849 } else {
850 LOG(ERROR) << "Invalid method line: " << line;
851 return false;
852 }
853
Mathieu Chartier34067262017-04-06 13:55:46 -0700854 const uint32_t method_index = FindMethodIndex(class_ref, method_spec);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700855 if (method_index == dex::kDexNoIndex) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800856 return false;
857 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700858
Mathieu Chartier34067262017-04-06 13:55:46 -0700859 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
860 if (is_missing_types || !inline_cache_elems.empty()) {
861 uint32_t dex_pc;
862 if (!HasSingleInvoke(class_ref, method_index, &dex_pc)) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800863 return false;
864 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000865 std::vector<TypeReference> classes(inline_cache_elems.size(),
866 TypeReference(/* dex_file */ nullptr, dex::TypeIndex()));
Mathieu Chartier34067262017-04-06 13:55:46 -0700867 size_t class_it = 0;
868 for (const std::string& ic_class : inline_cache_elems) {
869 if (!FindClass(dex_files, ic_class, &(classes[class_it++]))) {
870 LOG(ERROR) << "Could not find class: " << ic_class;
871 return false;
872 }
873 }
874 inline_caches.emplace_back(dex_pc, is_missing_types, classes);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800875 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700876 MethodReference ref(class_ref.dex_file, method_index);
Mathieu Chartierea650f32017-05-24 12:04:13 -0700877 if (is_hot) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700878 profile->AddMethod(ProfileMethodInfo(ref, inline_caches));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700879 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700880 uint32_t flags = 0;
881 using Hotness = ProfileCompilationInfo::MethodHotness;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700882 if (is_startup) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700883 flags |= Hotness::kFlagStartup;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700884 }
885 if (is_post_startup) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700886 flags |= Hotness::kFlagPostStartup;
887 }
888 if (flags != 0) {
889 if (!profile->AddMethodIndex(static_cast<Hotness::Flag>(flags), ref)) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700890 return false;
891 }
Mathieu Chartiere46f3a82017-06-19 19:54:12 -0700892 DCHECK(profile->GetMethodHotness(ref).IsInProfile());
Mathieu Chartierea650f32017-05-24 12:04:13 -0700893 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800894 return true;
895 }
896
Mathieu Chartier2f794552017-06-19 10:58:08 -0700897 int OpenReferenceProfile() const {
898 int fd = reference_profile_file_fd_;
899 if (!FdIsValid(fd)) {
900 CHECK(!reference_profile_file_.empty());
901 fd = open(reference_profile_file_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
902 if (fd < 0) {
903 LOG(ERROR) << "Cannot open " << reference_profile_file_ << strerror(errno);
904 return kInvalidFd;
905 }
906 }
907 return fd;
908 }
909
Calin Juravlee0ac1152017-02-13 19:03:47 -0800910 // Creates a profile from a human friendly textual representation.
911 // The expected input format is:
912 // # Classes
913 // Ljava/lang/Comparable;
914 // Ljava/lang/Math;
915 // # Methods with inline caches
916 // LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;
917 // LTestInline;->noInlineCache(LSuper;)I
David Sehr7c80f2d2017-02-07 16:47:58 -0800918 int CreateProfile() {
David Sehr153da0e2017-02-15 08:54:51 -0800919 // Validate parameters for this command.
920 if (apk_files_.empty() && apks_fd_.empty()) {
921 Usage("APK files must be specified");
922 }
923 if (dex_locations_.empty()) {
924 Usage("DEX locations must be specified");
925 }
926 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
927 Usage("Reference profile must be specified with --reference-profile-file or "
928 "--reference-profile-file-fd");
929 }
930 if (!profile_files_.empty() || !profile_files_fd_.empty()) {
931 Usage("Profile must be specified with --reference-profile-file or "
932 "--reference-profile-file-fd");
933 }
934 // for ZipArchive::OpenFromFd
935 MemMap::Init();
David Sehr7c80f2d2017-02-07 16:47:58 -0800936 // Open the profile output file if needed.
Mathieu Chartier2f794552017-06-19 10:58:08 -0700937 int fd = OpenReferenceProfile();
David Sehr7c80f2d2017-02-07 16:47:58 -0800938 if (!FdIsValid(fd)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800939 return -1;
David Sehr7c80f2d2017-02-07 16:47:58 -0800940 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800941 // Read the user-specified list of classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800942 std::unique_ptr<std::unordered_set<std::string>>
Calin Juravlee0ac1152017-02-13 19:03:47 -0800943 user_lines(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
David Sehr7c80f2d2017-02-07 16:47:58 -0800944 create_profile_from_file_.c_str(), nullptr)); // No post-processing.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800945
946 // Open the dex files to look up classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800947 std::vector<std::unique_ptr<const DexFile>> dex_files;
948 OpenApkFilesFromLocations(&dex_files);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800949
950 // Process the lines one by one and add the successful ones to the profile.
David Sehr7c80f2d2017-02-07 16:47:58 -0800951 ProfileCompilationInfo info;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800952
953 for (const auto& line : *user_lines) {
954 ProcessLine(dex_files, line, &info);
955 }
956
David Sehr7c80f2d2017-02-07 16:47:58 -0800957 // Write the profile file.
958 CHECK(info.Save(fd));
959 if (close(fd) < 0) {
960 PLOG(WARNING) << "Failed to close descriptor";
961 }
962 return 0;
963 }
964
Mathieu Chartier2f794552017-06-19 10:58:08 -0700965 bool ShouldCreateBootProfile() const {
966 return generate_boot_image_profile_;
967 }
968
969 int CreateBootProfile() {
970 // Initialize memmap since it's required to open dex files.
971 MemMap::Init();
972 // Open the profile output file.
973 const int reference_fd = OpenReferenceProfile();
974 if (!FdIsValid(reference_fd)) {
975 PLOG(ERROR) << "Error opening reference profile";
976 return -1;
977 }
978 // Open the dex files.
979 std::vector<std::unique_ptr<const DexFile>> dex_files;
980 OpenApkFilesFromLocations(&dex_files);
981 if (dex_files.empty()) {
982 PLOG(ERROR) << "Expected dex files for creating boot profile";
983 return -2;
984 }
985 // Open the input profiles.
986 std::vector<std::unique_ptr<const ProfileCompilationInfo>> profiles;
987 if (!profile_files_fd_.empty()) {
988 for (int profile_file_fd : profile_files_fd_) {
989 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile("", profile_file_fd));
990 if (profile == nullptr) {
991 return -3;
992 }
993 profiles.emplace_back(std::move(profile));
994 }
995 }
996 if (!profile_files_.empty()) {
997 for (const std::string& profile_file : profile_files_) {
998 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile(profile_file, kInvalidFd));
999 if (profile == nullptr) {
1000 return -4;
1001 }
1002 profiles.emplace_back(std::move(profile));
1003 }
1004 }
1005 ProfileCompilationInfo out_profile;
1006 GenerateBootImageProfile(dex_files,
1007 profiles,
1008 boot_image_options_,
1009 VLOG_IS_ON(profiler),
1010 &out_profile);
1011 out_profile.Save(reference_fd);
1012 close(reference_fd);
1013 return 0;
1014 }
1015
David Sehr7c80f2d2017-02-07 16:47:58 -08001016 bool ShouldCreateProfile() {
1017 return !create_profile_from_file_.empty();
1018 }
1019
Calin Juravle7bcdb532016-06-07 16:14:47 +01001020 int GenerateTestProfile() {
David Sehr153da0e2017-02-15 08:54:51 -08001021 // Validate parameters for this command.
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001022 if (test_profile_method_percerntage_ > 100) {
1023 Usage("Invalid percentage for --generate-test-profile-method-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001024 }
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001025 if (test_profile_class_percentage_ > 100) {
1026 Usage("Invalid percentage for --generate-test-profile-class-percentage");
David Sehr153da0e2017-02-15 08:54:51 -08001027 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001028 // If given APK files or DEX locations, check that they're ok.
1029 if (!apk_files_.empty() || !apks_fd_.empty() || !dex_locations_.empty()) {
1030 if (apk_files_.empty() && apks_fd_.empty()) {
1031 Usage("APK files must be specified when passing DEX locations to --generate-test-profile");
1032 }
1033 if (dex_locations_.empty()) {
1034 Usage("DEX locations must be specified when passing APK files to --generate-test-profile");
1035 }
1036 }
David Sehr153da0e2017-02-15 08:54:51 -08001037 // ShouldGenerateTestProfile confirms !test_profile_.empty().
George Burgess IV71f77262016-10-25 13:08:17 -07001038 int profile_test_fd = open(test_profile_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001039 if (profile_test_fd < 0) {
David Sehr7c80f2d2017-02-07 16:47:58 -08001040 LOG(ERROR) << "Cannot open " << test_profile_ << strerror(errno);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001041 return -1;
1042 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001043 bool result;
1044 if (apk_files_.empty() && apks_fd_.empty() && dex_locations_.empty()) {
1045 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1046 test_profile_num_dex_,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001047 test_profile_method_percerntage_,
1048 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001049 test_profile_seed_);
1050 } else {
1051 // Initialize MemMap for ZipArchive::OpenFromFd.
1052 MemMap::Init();
1053 // Open the dex files to look up classes and methods.
1054 std::vector<std::unique_ptr<const DexFile>> dex_files;
1055 OpenApkFilesFromLocations(&dex_files);
1056 // Create a random profile file based on the set of dex files.
1057 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1058 dex_files,
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001059 test_profile_method_percerntage_,
1060 test_profile_class_percentage_,
Jeff Haof0a31f82017-03-27 15:50:37 -07001061 test_profile_seed_);
1062 }
Calin Juravle7bcdb532016-06-07 16:14:47 +01001063 close(profile_test_fd); // ignore close result.
1064 return result ? 0 : -1;
1065 }
1066
1067 bool ShouldGenerateTestProfile() {
1068 return !test_profile_.empty();
1069 }
1070
Calin Juravle2e2db782016-02-23 12:00:03 +00001071 private:
1072 static void ParseFdForCollection(const StringPiece& option,
1073 const char* arg_name,
1074 std::vector<int>* fds) {
1075 int fd;
1076 ParseUintOption(option, arg_name, &fd, Usage);
1077 fds->push_back(fd);
1078 }
1079
1080 static void CloseAllFds(const std::vector<int>& fds, const char* descriptor) {
1081 for (size_t i = 0; i < fds.size(); i++) {
1082 if (close(fds[i]) < 0) {
1083 PLOG(WARNING) << "Failed to close descriptor for " << descriptor << " at index " << i;
1084 }
1085 }
1086 }
1087
1088 void LogCompletionTime() {
David Sehr52683cf2016-05-05 09:02:38 -07001089 static constexpr uint64_t kLogThresholdTime = MsToNs(100); // 100ms
1090 uint64_t time_taken = NanoTime() - start_ns_;
David Sehred793012016-05-05 13:39:43 -07001091 if (time_taken > kLogThresholdTime) {
David Sehrd8557182016-05-06 12:29:35 -07001092 LOG(WARNING) << "profman took " << PrettyDuration(time_taken);
David Sehred793012016-05-05 13:39:43 -07001093 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001094 }
1095
1096 std::vector<std::string> profile_files_;
1097 std::vector<int> profile_files_fd_;
David Sehr546d24f2016-06-02 10:46:19 -07001098 std::vector<std::string> dex_locations_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001099 std::vector<std::string> apk_files_;
David Sehr546d24f2016-06-02 10:46:19 -07001100 std::vector<int> apks_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001101 std::string reference_profile_file_;
1102 int reference_profile_file_fd_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001103 bool dump_only_;
Mathieu Chartier34067262017-04-06 13:55:46 -07001104 bool dump_classes_and_methods_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001105 bool generate_boot_image_profile_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001106 int dump_output_to_fd_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001107 BootImageOptions boot_image_options_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001108 std::string test_profile_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001109 std::string create_profile_from_file_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001110 uint16_t test_profile_num_dex_;
Shubham Ajmerad704f0b2017-07-26 16:33:35 -07001111 uint16_t test_profile_method_percerntage_;
1112 uint16_t test_profile_class_percentage_;
Jeff Haof0a31f82017-03-27 15:50:37 -07001113 uint32_t test_profile_seed_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001114 uint64_t start_ns_;
1115};
1116
1117// See ProfileAssistant::ProcessingResult for return codes.
1118static int profman(int argc, char** argv) {
1119 ProfMan profman;
1120
1121 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1122 profman.ParseArgs(argc, argv);
1123
Calin Juravle7bcdb532016-06-07 16:14:47 +01001124 if (profman.ShouldGenerateTestProfile()) {
1125 return profman.GenerateTestProfile();
1126 }
Calin Juravle876f3502016-03-24 16:16:34 +00001127 if (profman.ShouldOnlyDumpProfile()) {
1128 return profman.DumpProfileInfo();
1129 }
Mathieu Chartier34067262017-04-06 13:55:46 -07001130 if (profman.ShouldOnlyDumpClassesAndMethods()) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001131 return profman.DumpClassesAndMethods();
David Sehr7c80f2d2017-02-07 16:47:58 -08001132 }
1133 if (profman.ShouldCreateProfile()) {
1134 return profman.CreateProfile();
1135 }
Mathieu Chartier2f794552017-06-19 10:58:08 -07001136
1137 if (profman.ShouldCreateBootProfile()) {
1138 return profman.CreateBootProfile();
1139 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001140 // Process profile information and assess if we need to do a profile guided compilation.
1141 // This operation involves I/O.
1142 return profman.ProcessProfiles();
1143}
1144
1145} // namespace art
1146
1147int main(int argc, char **argv) {
1148 return art::profman(argc, argv);
1149}
1150