blob: 14b026277f586db517635ba686b5a76488b3dddf [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
Calin Juravle876f3502016-03-24 16:16:34 +000017#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"
35#include "base/scoped_flock.h"
36#include "base/stringpiece.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000037#include "base/time_utils.h"
38#include "base/unix_file/fd_file.h"
Mathieu Chartier2f794552017-06-19 10:58:08 -070039#include "boot_image_profile.h"
Calin Juravlee0ac1152017-02-13 19:03:47 -080040#include "bytecode_utils.h"
David Sehr4fcdd6d2016-05-24 14:52:31 -070041#include "dex_file.h"
Calin Juravle33083d62017-01-18 15:29:12 -080042#include "jit/profile_compilation_info.h"
Mathieu Chartierdbddc222017-05-24 12:04:13 -070043#include "profile_assistant.h"
David Sehrf57589f2016-10-17 10:09:33 -070044#include "runtime.h"
Mathieu Chartierdbddc222017-05-24 12:04:13 -070045#include "type_reference.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000046#include "utils.h"
Mathieu Chartierea650f32017-05-24 12:04:13 -070047#include "type_reference.h"
David Sehr546d24f2016-06-02 10:46:19 -070048#include "zip_archive.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000049
50namespace art {
51
52static int original_argc;
53static char** original_argv;
54
55static std::string CommandLine() {
56 std::vector<std::string> command;
57 for (int i = 0; i < original_argc; ++i) {
58 command.push_back(original_argv[i]);
59 }
Andreas Gampe9186ced2016-12-12 14:28:21 -080060 return android::base::Join(command, ' ');
Calin Juravle2e2db782016-02-23 12:00:03 +000061}
62
David Sehr4fcdd6d2016-05-24 14:52:31 -070063static constexpr int kInvalidFd = -1;
64
65static bool FdIsValid(int fd) {
66 return fd != kInvalidFd;
67}
68
Calin Juravle2e2db782016-02-23 12:00:03 +000069static void UsageErrorV(const char* fmt, va_list ap) {
70 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080071 android::base::StringAppendV(&error, fmt, ap);
Calin Juravle2e2db782016-02-23 12:00:03 +000072 LOG(ERROR) << error;
73}
74
75static void UsageError(const char* fmt, ...) {
76 va_list ap;
77 va_start(ap, fmt);
78 UsageErrorV(fmt, ap);
79 va_end(ap);
80}
81
82NO_RETURN static void Usage(const char *fmt, ...) {
83 va_list ap;
84 va_start(ap, fmt);
85 UsageErrorV(fmt, ap);
86 va_end(ap);
87
88 UsageError("Command: %s", CommandLine().c_str());
89 UsageError("Usage: profman [options]...");
90 UsageError("");
David Sehr4fcdd6d2016-05-24 14:52:31 -070091 UsageError(" --dump-only: dumps the content of the specified profile files");
92 UsageError(" to standard output (default) in a human readable form.");
93 UsageError("");
David Sehr7c80f2d2017-02-07 16:47:58 -080094 UsageError(" --dump-output-to-fd=<number>: redirects --dump-only output to a file descriptor.");
95 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -070096 UsageError(" --dump-classes-and-methods: dumps a sorted list of classes and methods that are");
97 UsageError(" in the specified profile file to standard output (default) in a human");
98 UsageError(" readable form. The output is valid input for --create-profile-from");
Calin Juravle876f3502016-03-24 16:16:34 +000099 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000100 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
101 UsageError(" Can be specified multiple time, in which case the data from the different");
102 UsageError(" profiles will be aggregated.");
103 UsageError("");
104 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
105 UsageError(" Cannot be used together with --profile-file.");
106 UsageError("");
107 UsageError(" --reference-profile-file=<filename>: specify a reference profile.");
108 UsageError(" The data in this file will be compared with the data obtained by merging");
109 UsageError(" all the files specified with --profile-file or --profile-file-fd.");
110 UsageError(" If the exit code is EXIT_COMPILE then all --profile-file will be merged into");
111 UsageError(" --reference-profile-file. ");
112 UsageError("");
113 UsageError(" --reference-profile-file-fd=<number>: same as --reference-profile-file but");
114 UsageError(" accepts a file descriptor. Cannot be used together with");
115 UsageError(" --reference-profile-file.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800116 UsageError("");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100117 UsageError(" --generate-test-profile=<filename>: generates a random profile file for testing.");
118 UsageError(" --generate-test-profile-num-dex=<number>: number of dex files that should be");
119 UsageError(" included in the generated profile. Defaults to 20.");
120 UsageError(" --generate-test-profile-method-ratio=<number>: the percentage from the maximum");
121 UsageError(" number of methods that should be generated. Defaults to 5.");
122 UsageError(" --generate-test-profile-class-ratio=<number>: the percentage from the maximum");
123 UsageError(" number of classes that should be generated. Defaults to 5.");
Jeff Haof0a31f82017-03-27 15:50:37 -0700124 UsageError(" --generate-test-profile-seed=<number>: seed for random number generator used when");
125 UsageError(" generating random test profiles. Defaults to using NanoTime.");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100126 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -0700127 UsageError(" --create-profile-from=<filename>: creates a profile from a list of classes and");
128 UsageError(" methods.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800129 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700130 UsageError(" --dex-location=<string>: location string to use with corresponding");
131 UsageError(" apk-fd to find dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700132 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700133 UsageError(" --apk-fd=<number>: file descriptor containing an open APK to");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700134 UsageError(" search for dex files");
David Sehr7c80f2d2017-02-07 16:47:58 -0800135 UsageError(" --apk-=<filename>: an APK to search for dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700136 UsageError("");
Mathieu Chartier2f794552017-06-19 10:58:08 -0700137 UsageError(" --generate-boot-image-profile: Generate a boot image profile based on input");
138 UsageError(" profiles. Requires passing in dex files to inspect properties of classes.");
139 UsageError(" --boot-image-class-threshold=<value>: specify minimum number of class occurrences");
140 UsageError(" to include a class in the boot image profile. Default is 10.");
141 UsageError(" --boot-image-clean-class-threshold=<value>: specify minimum number of clean class");
142 UsageError(" occurrences to include a class in the boot image profile. A clean class is a");
143 UsageError(" class that doesn't have any static fields or native methods and is likely to");
144 UsageError(" remain clean in the image. Default is 3.");
145 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000146
147 exit(EXIT_FAILURE);
148}
149
Calin Juravle7bcdb532016-06-07 16:14:47 +0100150// Note: make sure you update the Usage if you change these values.
151static constexpr uint16_t kDefaultTestProfileNumDex = 20;
152static constexpr uint16_t kDefaultTestProfileMethodRatio = 5;
153static constexpr uint16_t kDefaultTestProfileClassRatio = 5;
154
Calin Juravlee0ac1152017-02-13 19:03:47 -0800155// Separators used when parsing human friendly representation of profiles.
156static const std::string kMethodSep = "->";
Calin Juravle589e71e2017-03-03 16:05:05 -0800157static const std::string kMissingTypesMarker = "missing_types";
Calin Juravle08556882017-05-26 16:40:45 -0700158static const std::string kInvalidClassDescriptor = "invalid_class";
159static const std::string kInvalidMethod = "invalid_method";
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700160static const std::string kClassAllMethods = "*";
Calin Juravlee0ac1152017-02-13 19:03:47 -0800161static constexpr char kProfileParsingInlineChacheSep = '+';
162static constexpr char kProfileParsingTypeSep = ',';
163static constexpr char kProfileParsingFirstCharInSignature = '(';
Mathieu Chartierea650f32017-05-24 12:04:13 -0700164static constexpr char kMethodFlagStringHot = 'H';
165static constexpr char kMethodFlagStringStartup = 'S';
166static constexpr char kMethodFlagStringPostStartup = 'P';
Calin Juravlee0ac1152017-02-13 19:03:47 -0800167
168// TODO(calin): This class has grown too much from its initial design. Split the functionality
169// into smaller, more contained pieces.
Calin Juravle2e2db782016-02-23 12:00:03 +0000170class ProfMan FINAL {
171 public:
172 ProfMan() :
David Sehr4fcdd6d2016-05-24 14:52:31 -0700173 reference_profile_file_fd_(kInvalidFd),
174 dump_only_(false),
Mathieu Chartier34067262017-04-06 13:55:46 -0700175 dump_classes_and_methods_(false),
Mathieu Chartier2f794552017-06-19 10:58:08 -0700176 generate_boot_image_profile_(false),
David Sehr4fcdd6d2016-05-24 14:52:31 -0700177 dump_output_to_fd_(kInvalidFd),
Calin Juravle7bcdb532016-06-07 16:14:47 +0100178 test_profile_num_dex_(kDefaultTestProfileNumDex),
179 test_profile_method_ratio_(kDefaultTestProfileMethodRatio),
180 test_profile_class_ratio_(kDefaultTestProfileClassRatio),
Jeff Haof0a31f82017-03-27 15:50:37 -0700181 test_profile_seed_(NanoTime()),
Calin Juravle2e2db782016-02-23 12:00:03 +0000182 start_ns_(NanoTime()) {}
183
184 ~ProfMan() {
185 LogCompletionTime();
186 }
187
188 void ParseArgs(int argc, char **argv) {
189 original_argc = argc;
190 original_argv = argv;
191
David Sehrf57589f2016-10-17 10:09:33 -0700192 InitLogging(argv, Runtime::Aborter);
Calin Juravle2e2db782016-02-23 12:00:03 +0000193
194 // Skip over the command name.
195 argv++;
196 argc--;
197
198 if (argc == 0) {
199 Usage("No arguments specified");
200 }
201
202 for (int i = 0; i < argc; ++i) {
203 const StringPiece option(argv[i]);
204 const bool log_options = false;
205 if (log_options) {
Calin Juravle876f3502016-03-24 16:16:34 +0000206 LOG(INFO) << "profman: option[" << i << "]=" << argv[i];
Calin Juravle2e2db782016-02-23 12:00:03 +0000207 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700208 if (option == "--dump-only") {
209 dump_only_ = true;
Mathieu Chartier34067262017-04-06 13:55:46 -0700210 } else if (option == "--dump-classes-and-methods") {
211 dump_classes_and_methods_ = true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800212 } else if (option.starts_with("--create-profile-from=")) {
213 create_profile_from_file_ = option.substr(strlen("--create-profile-from=")).ToString();
David Sehr4fcdd6d2016-05-24 14:52:31 -0700214 } else if (option.starts_with("--dump-output-to-fd=")) {
215 ParseUintOption(option, "--dump-output-to-fd", &dump_output_to_fd_, Usage);
Mathieu Chartier2f794552017-06-19 10:58:08 -0700216 } else if (option == "--generate-boot-image-profile") {
217 generate_boot_image_profile_ = true;
218 } else if (option.starts_with("--boot-image-class-threshold=")) {
219 ParseUintOption(option,
220 "--boot-image-class-threshold",
221 &boot_image_options_.image_class_theshold,
222 Usage);
223 } else if (option.starts_with("--boot-image-clean-class-threshold=")) {
224 ParseUintOption(option,
225 "--boot-image-clean-class-threshold",
226 &boot_image_options_.image_class_clean_theshold,
227 Usage);
Calin Juravle876f3502016-03-24 16:16:34 +0000228 } else if (option.starts_with("--profile-file=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000229 profile_files_.push_back(option.substr(strlen("--profile-file=")).ToString());
230 } else if (option.starts_with("--profile-file-fd=")) {
231 ParseFdForCollection(option, "--profile-file-fd", &profile_files_fd_);
232 } else if (option.starts_with("--reference-profile-file=")) {
233 reference_profile_file_ = option.substr(strlen("--reference-profile-file=")).ToString();
234 } else if (option.starts_with("--reference-profile-file-fd=")) {
235 ParseUintOption(option, "--reference-profile-file-fd", &reference_profile_file_fd_, Usage);
David Sehr546d24f2016-06-02 10:46:19 -0700236 } else if (option.starts_with("--dex-location=")) {
237 dex_locations_.push_back(option.substr(strlen("--dex-location=")).ToString());
238 } else if (option.starts_with("--apk-fd=")) {
239 ParseFdForCollection(option, "--apk-fd", &apks_fd_);
David Sehr7c80f2d2017-02-07 16:47:58 -0800240 } else if (option.starts_with("--apk=")) {
241 apk_files_.push_back(option.substr(strlen("--apk=")).ToString());
Calin Juravle7bcdb532016-06-07 16:14:47 +0100242 } else if (option.starts_with("--generate-test-profile=")) {
243 test_profile_ = option.substr(strlen("--generate-test-profile=")).ToString();
244 } else if (option.starts_with("--generate-test-profile-num-dex=")) {
245 ParseUintOption(option,
246 "--generate-test-profile-num-dex",
247 &test_profile_num_dex_,
248 Usage);
249 } else if (option.starts_with("--generate-test-profile-method-ratio")) {
250 ParseUintOption(option,
251 "--generate-test-profile-method-ratio",
252 &test_profile_method_ratio_,
253 Usage);
254 } else if (option.starts_with("--generate-test-profile-class-ratio")) {
255 ParseUintOption(option,
256 "--generate-test-profile-class-ratio",
257 &test_profile_class_ratio_,
258 Usage);
Jeff Haof0a31f82017-03-27 15:50:37 -0700259 } else if (option.starts_with("--generate-test-profile-seed=")) {
260 ParseUintOption(option, "--generate-test-profile-seed", &test_profile_seed_, Usage);
Calin Juravle2e2db782016-02-23 12:00:03 +0000261 } else {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700262 Usage("Unknown argument '%s'", option.data());
Calin Juravle2e2db782016-02-23 12:00:03 +0000263 }
264 }
265
David Sehr153da0e2017-02-15 08:54:51 -0800266 // Validate global consistency between file/fd options.
Calin Juravle2e2db782016-02-23 12:00:03 +0000267 if (!profile_files_.empty() && !profile_files_fd_.empty()) {
268 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
269 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700270 if (!reference_profile_file_.empty() && FdIsValid(reference_profile_file_fd_)) {
271 Usage("Reference profile should not be specified with both "
272 "--reference-profile-file-fd and --reference-profile-file");
273 }
David Sehr153da0e2017-02-15 08:54:51 -0800274 if (!apk_files_.empty() && !apks_fd_.empty()) {
275 Usage("APK files should not be specified with both --apk-fd and --apk");
Calin Juravle2e2db782016-02-23 12:00:03 +0000276 }
277 }
278
279 ProfileAssistant::ProcessingResult ProcessProfiles() {
David Sehr153da0e2017-02-15 08:54:51 -0800280 // Validate that at least one profile file was passed, as well as a reference profile.
281 if (profile_files_.empty() && profile_files_fd_.empty()) {
282 Usage("No profile files specified.");
283 }
284 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
285 Usage("No reference profile file specified.");
286 }
287 if ((!profile_files_.empty() && FdIsValid(reference_profile_file_fd_)) ||
288 (!profile_files_fd_.empty() && !FdIsValid(reference_profile_file_fd_))) {
289 Usage("Options --profile-file-fd and --reference-profile-file-fd "
290 "should only be used together");
291 }
Calin Juravle2e2db782016-02-23 12:00:03 +0000292 ProfileAssistant::ProcessingResult result;
293 if (profile_files_.empty()) {
294 // The file doesn't need to be flushed here (ProcessProfiles will do it)
295 // so don't check the usage.
296 File file(reference_profile_file_fd_, false);
297 result = ProfileAssistant::ProcessProfiles(profile_files_fd_, reference_profile_file_fd_);
298 CloseAllFds(profile_files_fd_, "profile_files_fd_");
299 } else {
300 result = ProfileAssistant::ProcessProfiles(profile_files_, reference_profile_file_);
301 }
302 return result;
303 }
304
David Sehr7c80f2d2017-02-07 16:47:58 -0800305 void OpenApkFilesFromLocations(std::vector<std::unique_ptr<const DexFile>>* dex_files) {
306 bool use_apk_fd_list = !apks_fd_.empty();
307 if (use_apk_fd_list) {
David Sehr153da0e2017-02-15 08:54:51 -0800308 // Get the APKs from the collection of FDs.
David Sehr7c80f2d2017-02-07 16:47:58 -0800309 CHECK_EQ(dex_locations_.size(), apks_fd_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800310 } else if (!apk_files_.empty()) {
311 // Get the APKs from the collection of filenames.
David Sehr7c80f2d2017-02-07 16:47:58 -0800312 CHECK_EQ(dex_locations_.size(), apk_files_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800313 } else {
314 // No APKs were specified.
315 CHECK(dex_locations_.empty());
316 return;
David Sehr7c80f2d2017-02-07 16:47:58 -0800317 }
318 static constexpr bool kVerifyChecksum = true;
319 for (size_t i = 0; i < dex_locations_.size(); ++i) {
320 std::string error_msg;
321 std::vector<std::unique_ptr<const DexFile>> dex_files_for_location;
322 if (use_apk_fd_list) {
323 if (DexFile::OpenZip(apks_fd_[i],
324 dex_locations_[i],
325 kVerifyChecksum,
326 &error_msg,
327 &dex_files_for_location)) {
328 } else {
329 LOG(WARNING) << "OpenZip failed for '" << dex_locations_[i] << "' " << error_msg;
330 continue;
331 }
332 } else {
333 if (DexFile::Open(apk_files_[i].c_str(),
334 dex_locations_[i],
335 kVerifyChecksum,
336 &error_msg,
337 &dex_files_for_location)) {
338 } else {
339 LOG(WARNING) << "Open failed for '" << dex_locations_[i] << "' " << error_msg;
340 continue;
341 }
342 }
343 for (std::unique_ptr<const DexFile>& dex_file : dex_files_for_location) {
344 dex_files->emplace_back(std::move(dex_file));
345 }
346 }
347 }
348
Mathieu Chartier2f794552017-06-19 10:58:08 -0700349 std::unique_ptr<const ProfileCompilationInfo> LoadProfile(const std::string& filename, int fd) {
350 if (!filename.empty()) {
351 fd = open(filename.c_str(), O_RDWR);
352 if (fd < 0) {
353 LOG(ERROR) << "Cannot open " << filename << strerror(errno);
354 return nullptr;
355 }
356 }
357 std::unique_ptr<ProfileCompilationInfo> info(new ProfileCompilationInfo);
358 if (!info->Load(fd)) {
359 LOG(ERROR) << "Cannot load profile info from fd=" << fd << "\n";
360 return nullptr;
361 }
362 return info;
363 }
364
David Sehrb18991b2017-02-08 20:58:10 -0800365 int DumpOneProfile(const std::string& banner,
366 const std::string& filename,
367 int fd,
368 const std::vector<std::unique_ptr<const DexFile>>* dex_files,
369 std::string* dump) {
Mathieu Chartier2f794552017-06-19 10:58:08 -0700370 std::unique_ptr<const ProfileCompilationInfo> info(LoadProfile(filename, fd));
371 if (info == nullptr) {
372 LOG(ERROR) << "Cannot load profile info from filename=" << filename << " fd=" << fd;
Calin Juravle876f3502016-03-24 16:16:34 +0000373 return -1;
374 }
Mathieu Chartier2f794552017-06-19 10:58:08 -0700375 *dump += banner + "\n" + info->DumpInfo(dex_files) + "\n";
David Sehr4fcdd6d2016-05-24 14:52:31 -0700376 return 0;
377 }
378
379 int DumpProfileInfo() {
David Sehr153da0e2017-02-15 08:54:51 -0800380 // Validate that at least one profile file or reference was specified.
381 if (profile_files_.empty() && profile_files_fd_.empty() &&
382 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
383 Usage("No profile files or reference profile specified.");
384 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700385 static const char* kEmptyString = "";
David Sehr546d24f2016-06-02 10:46:19 -0700386 static const char* kOrdinaryProfile = "=== profile ===";
387 static const char* kReferenceProfile = "=== reference profile ===";
388
389 // Open apk/zip files and and read dex files.
390 MemMap::Init(); // for ZipArchive::OpenFromFd
David Sehrb18991b2017-02-08 20:58:10 -0800391 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7c80f2d2017-02-07 16:47:58 -0800392 OpenApkFilesFromLocations(&dex_files);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700393 std::string dump;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700394 // Dump individual profile files.
395 if (!profile_files_fd_.empty()) {
396 for (int profile_file_fd : profile_files_fd_) {
David Sehr546d24f2016-06-02 10:46:19 -0700397 int ret = DumpOneProfile(kOrdinaryProfile,
398 kEmptyString,
399 profile_file_fd,
400 &dex_files,
401 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700402 if (ret != 0) {
403 return ret;
404 }
405 }
406 }
407 if (!profile_files_.empty()) {
408 for (const std::string& profile_file : profile_files_) {
David Sehr546d24f2016-06-02 10:46:19 -0700409 int ret = DumpOneProfile(kOrdinaryProfile, profile_file, kInvalidFd, &dex_files, &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700410 if (ret != 0) {
411 return ret;
412 }
413 }
414 }
415 // Dump reference profile file.
416 if (FdIsValid(reference_profile_file_fd_)) {
David Sehr546d24f2016-06-02 10:46:19 -0700417 int ret = DumpOneProfile(kReferenceProfile,
418 kEmptyString,
419 reference_profile_file_fd_,
420 &dex_files,
421 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700422 if (ret != 0) {
423 return ret;
424 }
425 }
426 if (!reference_profile_file_.empty()) {
David Sehr546d24f2016-06-02 10:46:19 -0700427 int ret = DumpOneProfile(kReferenceProfile,
428 reference_profile_file_,
429 kInvalidFd,
430 &dex_files,
David Sehr4fcdd6d2016-05-24 14:52:31 -0700431 &dump);
432 if (ret != 0) {
433 return ret;
434 }
435 }
436 if (!FdIsValid(dump_output_to_fd_)) {
437 std::cout << dump;
438 } else {
439 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
440 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
441 return -1;
442 }
443 }
Calin Juravle876f3502016-03-24 16:16:34 +0000444 return 0;
445 }
446
447 bool ShouldOnlyDumpProfile() {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700448 return dump_only_;
Calin Juravle876f3502016-03-24 16:16:34 +0000449 }
450
Mathieu Chartier34067262017-04-06 13:55:46 -0700451 bool GetClassNamesAndMethods(int fd,
452 std::vector<std::unique_ptr<const DexFile>>* dex_files,
453 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800454 ProfileCompilationInfo profile_info;
455 if (!profile_info.Load(fd)) {
456 LOG(ERROR) << "Cannot load profile info";
457 return false;
458 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700459 for (const std::unique_ptr<const DexFile>& dex_file : *dex_files) {
460 std::set<dex::TypeIndex> class_types;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700461 std::set<uint16_t> hot_methods;
462 std::set<uint16_t> startup_methods;
463 std::set<uint16_t> post_startup_methods;
464 std::set<uint16_t> combined_methods;
465 if (profile_info.GetClassesAndMethods(*dex_file.get(),
466 &class_types,
467 &hot_methods,
468 &startup_methods,
469 &post_startup_methods)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700470 for (const dex::TypeIndex& type_index : class_types) {
471 const DexFile::TypeId& type_id = dex_file->GetTypeId(type_index);
472 out_lines->insert(std::string(dex_file->GetTypeDescriptor(type_id)));
473 }
Mathieu Chartierea650f32017-05-24 12:04:13 -0700474 combined_methods = hot_methods;
475 combined_methods.insert(startup_methods.begin(), startup_methods.end());
476 combined_methods.insert(post_startup_methods.begin(), post_startup_methods.end());
477 for (uint16_t dex_method_idx : combined_methods) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700478 const DexFile::MethodId& id = dex_file->GetMethodId(dex_method_idx);
479 std::string signature_string(dex_file->GetMethodSignature(id).ToString());
480 std::string type_string(dex_file->GetTypeDescriptor(dex_file->GetTypeId(id.class_idx_)));
481 std::string method_name(dex_file->GetMethodName(id));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700482 std::string flags_string;
483 if (hot_methods.find(dex_method_idx) != hot_methods.end()) {
484 flags_string += kMethodFlagStringHot;
485 }
486 if (startup_methods.find(dex_method_idx) != startup_methods.end()) {
487 flags_string += kMethodFlagStringStartup;
488 }
489 if (post_startup_methods.find(dex_method_idx) != post_startup_methods.end()) {
490 flags_string += kMethodFlagStringPostStartup;
491 }
492 out_lines->insert(flags_string +
493 type_string +
494 kMethodSep +
495 method_name +
496 signature_string);
Mathieu Chartier34067262017-04-06 13:55:46 -0700497 }
498 }
499 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800500 return true;
501 }
502
Mathieu Chartier34067262017-04-06 13:55:46 -0700503 bool GetClassNamesAndMethods(const std::string& profile_file,
504 std::vector<std::unique_ptr<const DexFile>>* dex_files,
505 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800506 int fd = open(profile_file.c_str(), O_RDONLY);
507 if (!FdIsValid(fd)) {
508 LOG(ERROR) << "Cannot open " << profile_file << strerror(errno);
509 return false;
510 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700511 if (!GetClassNamesAndMethods(fd, dex_files, out_lines)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800512 return false;
513 }
514 if (close(fd) < 0) {
515 PLOG(WARNING) << "Failed to close descriptor";
516 }
517 return true;
518 }
519
Mathieu Chartierea650f32017-05-24 12:04:13 -0700520 int DumpClassesAndMethods() {
David Sehr153da0e2017-02-15 08:54:51 -0800521 // Validate that at least one profile file or reference was specified.
522 if (profile_files_.empty() && profile_files_fd_.empty() &&
523 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
524 Usage("No profile files or reference profile specified.");
525 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800526 // Open apk/zip files and and read dex files.
527 MemMap::Init(); // for ZipArchive::OpenFromFd
528 // Open the dex files to get the names for classes.
529 std::vector<std::unique_ptr<const DexFile>> dex_files;
530 OpenApkFilesFromLocations(&dex_files);
531 // Build a vector of class names from individual profile files.
532 std::set<std::string> class_names;
533 if (!profile_files_fd_.empty()) {
534 for (int profile_file_fd : profile_files_fd_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700535 if (!GetClassNamesAndMethods(profile_file_fd, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800536 return -1;
537 }
538 }
539 }
540 if (!profile_files_.empty()) {
541 for (const std::string& profile_file : profile_files_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700542 if (!GetClassNamesAndMethods(profile_file, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800543 return -1;
544 }
545 }
546 }
547 // Concatenate class names from reference profile file.
548 if (FdIsValid(reference_profile_file_fd_)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700549 if (!GetClassNamesAndMethods(reference_profile_file_fd_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800550 return -1;
551 }
552 }
553 if (!reference_profile_file_.empty()) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700554 if (!GetClassNamesAndMethods(reference_profile_file_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800555 return -1;
556 }
557 }
558 // Dump the class names.
559 std::string dump;
560 for (const std::string& class_name : class_names) {
561 dump += class_name + std::string("\n");
562 }
563 if (!FdIsValid(dump_output_to_fd_)) {
564 std::cout << dump;
565 } else {
566 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
567 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
568 return -1;
569 }
570 }
571 return 0;
572 }
573
Mathieu Chartier34067262017-04-06 13:55:46 -0700574 bool ShouldOnlyDumpClassesAndMethods() {
575 return dump_classes_and_methods_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800576 }
577
578 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
579 // the given function.
580 template <typename T>
581 static T* ReadCommentedInputFromFile(
582 const char* input_filename, std::function<std::string(const char*)>* process) {
583 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
584 if (input_file.get() == nullptr) {
585 LOG(ERROR) << "Failed to open input file " << input_filename;
586 return nullptr;
587 }
588 std::unique_ptr<T> result(
589 ReadCommentedInputStream<T>(*input_file, process));
590 input_file->close();
591 return result.release();
592 }
593
594 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
595 // with the given function.
596 template <typename T>
597 static T* ReadCommentedInputStream(
598 std::istream& in_stream,
599 std::function<std::string(const char*)>* process) {
600 std::unique_ptr<T> output(new T());
601 while (in_stream.good()) {
602 std::string dot;
603 std::getline(in_stream, dot);
604 if (android::base::StartsWith(dot, "#") || dot.empty()) {
605 continue;
606 }
607 if (process != nullptr) {
608 std::string descriptor((*process)(dot.c_str()));
609 output->insert(output->end(), descriptor);
610 } else {
611 output->insert(output->end(), dot);
612 }
613 }
614 return output.release();
615 }
616
Calin Juravlee0ac1152017-02-13 19:03:47 -0800617 // Find class klass_descriptor in the given dex_files and store its reference
618 // in the out parameter class_ref.
619 // Return true if the definition of the class was found in any of the dex_files.
620 bool FindClass(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
621 const std::string& klass_descriptor,
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700622 /*out*/TypeReference* class_ref) {
Calin Juravle08556882017-05-26 16:40:45 -0700623 constexpr uint16_t kInvalidTypeIndex = std::numeric_limits<uint16_t>::max() - 1;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800624 for (const std::unique_ptr<const DexFile>& dex_file_ptr : dex_files) {
625 const DexFile* dex_file = dex_file_ptr.get();
Calin Juravle08556882017-05-26 16:40:45 -0700626 if (klass_descriptor == kInvalidClassDescriptor) {
627 if (kInvalidTypeIndex >= dex_file->NumTypeIds()) {
628 // The dex file does not contain all possible type ids which leaves us room
629 // to add an "invalid" type id.
630 class_ref->dex_file = dex_file;
631 class_ref->type_index = dex::TypeIndex(kInvalidTypeIndex);
632 return true;
633 } else {
634 // The dex file contains all possible type ids. We don't have any free type id
635 // that we can use as invalid.
636 continue;
637 }
638 }
639
Calin Juravlee0ac1152017-02-13 19:03:47 -0800640 const DexFile::TypeId* type_id = dex_file->FindTypeId(klass_descriptor.c_str());
641 if (type_id == nullptr) {
642 continue;
643 }
644 dex::TypeIndex type_index = dex_file->GetIndexForTypeId(*type_id);
645 if (dex_file->FindClassDef(type_index) == nullptr) {
646 // Class is only referenced in the current dex file but not defined in it.
647 continue;
648 }
649 class_ref->dex_file = dex_file;
650 class_ref->type_index = type_index;
651 return true;
652 }
653 return false;
654 }
655
Mathieu Chartier34067262017-04-06 13:55:46 -0700656 // Find the method specified by method_spec in the class class_ref.
Calin Juravle08556882017-05-26 16:40:45 -0700657 uint32_t FindMethodIndex(const TypeReference& class_ref,
658 const std::string& method_spec) {
659 const DexFile* dex_file = class_ref.dex_file;
660 if (method_spec == kInvalidMethod) {
661 constexpr uint16_t kInvalidMethodIndex = std::numeric_limits<uint16_t>::max() - 1;
662 return kInvalidMethodIndex >= dex_file->NumMethodIds()
663 ? kInvalidMethodIndex
664 : DexFile::kDexNoIndex;
665 }
666
Calin Juravlee0ac1152017-02-13 19:03:47 -0800667 std::vector<std::string> name_and_signature;
668 Split(method_spec, kProfileParsingFirstCharInSignature, &name_and_signature);
669 if (name_and_signature.size() != 2) {
670 LOG(ERROR) << "Invalid method name and signature " << method_spec;
Calin Juravle08556882017-05-26 16:40:45 -0700671 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800672 }
Calin Juravle08556882017-05-26 16:40:45 -0700673
Calin Juravlee0ac1152017-02-13 19:03:47 -0800674 const std::string& name = name_and_signature[0];
675 const std::string& signature = kProfileParsingFirstCharInSignature + name_and_signature[1];
Calin Juravlee0ac1152017-02-13 19:03:47 -0800676
677 const DexFile::StringId* name_id = dex_file->FindStringId(name.c_str());
678 if (name_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700679 LOG(WARNING) << "Could not find name: " << name;
Mathieu Chartier34067262017-04-06 13:55:46 -0700680 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800681 }
682 dex::TypeIndex return_type_idx;
683 std::vector<dex::TypeIndex> param_type_idxs;
684 if (!dex_file->CreateTypeList(signature, &return_type_idx, &param_type_idxs)) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700685 LOG(WARNING) << "Could not create type list" << signature;
Mathieu Chartier34067262017-04-06 13:55:46 -0700686 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800687 }
688 const DexFile::ProtoId* proto_id = dex_file->FindProtoId(return_type_idx, param_type_idxs);
689 if (proto_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700690 LOG(WARNING) << "Could not find proto_id: " << name;
Mathieu Chartier34067262017-04-06 13:55:46 -0700691 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800692 }
693 const DexFile::MethodId* method_id = dex_file->FindMethodId(
694 dex_file->GetTypeId(class_ref.type_index), *name_id, *proto_id);
695 if (method_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700696 LOG(WARNING) << "Could not find method_id: " << name;
Mathieu Chartier34067262017-04-06 13:55:46 -0700697 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800698 }
699
Mathieu Chartier34067262017-04-06 13:55:46 -0700700 return dex_file->GetIndexForMethodId(*method_id);
701 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800702
Mathieu Chartier34067262017-04-06 13:55:46 -0700703 // Given a method, return true if the method has a single INVOKE_VIRTUAL in its byte code.
704 // Upon success it returns true and stores the method index and the invoke dex pc
705 // in the output parameters.
706 // The format of the method spec is "inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
707 //
708 // TODO(calin): support INVOKE_INTERFACE and the range variants.
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700709 bool HasSingleInvoke(const TypeReference& class_ref,
Mathieu Chartier34067262017-04-06 13:55:46 -0700710 uint16_t method_index,
711 /*out*/uint32_t* dex_pc) {
712 const DexFile* dex_file = class_ref.dex_file;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800713 uint32_t offset = dex_file->FindCodeItemOffset(
714 *dex_file->FindClassDef(class_ref.type_index),
Mathieu Chartier34067262017-04-06 13:55:46 -0700715 method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800716 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(offset);
717
718 bool found_invoke = false;
719 for (CodeItemIterator it(*code_item); !it.Done(); it.Advance()) {
720 if (it.CurrentInstruction().Opcode() == Instruction::INVOKE_VIRTUAL) {
721 if (found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700722 LOG(ERROR) << "Multiple invoke INVOKE_VIRTUAL found: "
723 << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800724 return false;
725 }
726 found_invoke = true;
727 *dex_pc = it.CurrentDexPc();
728 }
729 }
730 if (!found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700731 LOG(ERROR) << "Could not find any INVOKE_VIRTUAL: " << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800732 }
733 return found_invoke;
734 }
735
736 // Process a line defining a class or a method and its inline caches.
737 // Upon success return true and add the class or the method info to profile.
Calin Juravle589e71e2017-03-03 16:05:05 -0800738 // The possible line formats are:
739 // "LJustTheCass;".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800740 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
Calin Juravle08556882017-05-26 16:40:45 -0700741 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,invalid_class".
Calin Juravle589e71e2017-03-03 16:05:05 -0800742 // "LTestInline;->inlineMissingTypes(LSuper;)I+missing_types".
743 // "LTestInline;->inlineNoInlineCaches(LSuper;)I".
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700744 // "LTestInline;->*".
Calin Juravle08556882017-05-26 16:40:45 -0700745 // "invalid_class".
746 // "LTestInline;->invalid_method".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800747 // The method and classes are searched only in the given dex files.
748 bool ProcessLine(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
749 const std::string& line,
750 /*out*/ProfileCompilationInfo* profile) {
751 std::string klass;
752 std::string method_str;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700753 bool is_hot = false;
754 bool is_startup = false;
755 bool is_post_startup = false;
756 const size_t method_sep_index = line.find(kMethodSep, 0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800757 if (method_sep_index == std::string::npos) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700758 klass = line.substr(0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800759 } else {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700760 // The method prefix flags are only valid for method strings.
761 size_t start_index = 0;
762 while (start_index < line.size() && line[start_index] != 'L') {
763 const char c = line[start_index];
764 if (c == kMethodFlagStringHot) {
765 is_hot = true;
766 } else if (c == kMethodFlagStringStartup) {
767 is_startup = true;
768 } else if (c == kMethodFlagStringPostStartup) {
769 is_post_startup = true;
770 } else {
771 LOG(WARNING) << "Invalid flag " << c;
772 return false;
773 }
774 ++start_index;
775 }
776 klass = line.substr(start_index, method_sep_index - start_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800777 method_str = line.substr(method_sep_index + kMethodSep.size());
778 }
779
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700780 TypeReference class_ref;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800781 if (!FindClass(dex_files, klass, &class_ref)) {
Mathieu Chartier3f121342017-03-06 11:16:20 -0800782 LOG(WARNING) << "Could not find class: " << klass;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800783 return false;
784 }
785
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700786 if (method_str.empty() || method_str == kClassAllMethods) {
787 // Start by adding the class.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800788 std::set<DexCacheResolvedClasses> resolved_class_set;
789 const DexFile* dex_file = class_ref.dex_file;
790 const auto& dex_resolved_classes = resolved_class_set.emplace(
791 dex_file->GetLocation(),
792 dex_file->GetBaseLocation(),
Mathieu Chartierea650f32017-05-24 12:04:13 -0700793 dex_file->GetLocationChecksum(),
794 dex_file->NumMethodIds());
Calin Juravlee0ac1152017-02-13 19:03:47 -0800795 dex_resolved_classes.first->AddClass(class_ref.type_index);
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700796 std::vector<ProfileMethodInfo> methods;
797 if (method_str == kClassAllMethods) {
798 // Add all of the methods.
799 const DexFile::ClassDef* class_def = dex_file->FindClassDef(class_ref.type_index);
800 const uint8_t* class_data = dex_file->GetClassData(*class_def);
801 if (class_data != nullptr) {
802 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700803 it.SkipAllFields();
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700804 while (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
805 if (it.GetMethodCodeItemOffset() != 0) {
806 // Add all of the methods that have code to the profile.
807 const uint32_t method_idx = it.GetMemberIndex();
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700808 methods.push_back(ProfileMethodInfo(MethodReference(dex_file, method_idx)));
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700809 }
810 it.Next();
811 }
812 }
813 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700814 // TODO: Check return values?
815 profile->AddMethods(methods);
816 profile->AddClasses(resolved_class_set);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800817 return true;
818 }
819
820 // Process the method.
821 std::string method_spec;
822 std::vector<std::string> inline_cache_elems;
823
Mathieu Chartierea650f32017-05-24 12:04:13 -0700824 // If none of the flags are set, default to hot.
825 is_hot = is_hot || (!is_hot && !is_startup && !is_post_startup);
826
Calin Juravlee0ac1152017-02-13 19:03:47 -0800827 std::vector<std::string> method_elems;
Calin Juravle589e71e2017-03-03 16:05:05 -0800828 bool is_missing_types = false;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800829 Split(method_str, kProfileParsingInlineChacheSep, &method_elems);
830 if (method_elems.size() == 2) {
831 method_spec = method_elems[0];
Calin Juravle589e71e2017-03-03 16:05:05 -0800832 is_missing_types = method_elems[1] == kMissingTypesMarker;
833 if (!is_missing_types) {
834 Split(method_elems[1], kProfileParsingTypeSep, &inline_cache_elems);
835 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800836 } else if (method_elems.size() == 1) {
837 method_spec = method_elems[0];
838 } else {
839 LOG(ERROR) << "Invalid method line: " << line;
840 return false;
841 }
842
Mathieu Chartier34067262017-04-06 13:55:46 -0700843 const uint32_t method_index = FindMethodIndex(class_ref, method_spec);
844 if (method_index == DexFile::kDexNoIndex) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800845 return false;
846 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700847
Mathieu Chartier34067262017-04-06 13:55:46 -0700848 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
849 if (is_missing_types || !inline_cache_elems.empty()) {
850 uint32_t dex_pc;
851 if (!HasSingleInvoke(class_ref, method_index, &dex_pc)) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800852 return false;
853 }
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700854 std::vector<TypeReference> classes(inline_cache_elems.size());
Mathieu Chartier34067262017-04-06 13:55:46 -0700855 size_t class_it = 0;
856 for (const std::string& ic_class : inline_cache_elems) {
857 if (!FindClass(dex_files, ic_class, &(classes[class_it++]))) {
858 LOG(ERROR) << "Could not find class: " << ic_class;
859 return false;
860 }
861 }
862 inline_caches.emplace_back(dex_pc, is_missing_types, classes);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800863 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700864 MethodReference ref(class_ref.dex_file, method_index);
Mathieu Chartierea650f32017-05-24 12:04:13 -0700865 if (is_hot) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700866 profile->AddMethod(ProfileMethodInfo(ref, inline_caches));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700867 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700868 uint32_t flags = 0;
869 using Hotness = ProfileCompilationInfo::MethodHotness;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700870 if (is_startup) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700871 flags |= Hotness::kFlagStartup;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700872 }
873 if (is_post_startup) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700874 flags |= Hotness::kFlagPostStartup;
875 }
876 if (flags != 0) {
877 if (!profile->AddMethodIndex(static_cast<Hotness::Flag>(flags), ref)) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700878 return false;
879 }
Mathieu Chartiere46f3a82017-06-19 19:54:12 -0700880 DCHECK(profile->GetMethodHotness(ref).IsInProfile());
Mathieu Chartierea650f32017-05-24 12:04:13 -0700881 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800882 return true;
883 }
884
Mathieu Chartier2f794552017-06-19 10:58:08 -0700885 int OpenReferenceProfile() const {
886 int fd = reference_profile_file_fd_;
887 if (!FdIsValid(fd)) {
888 CHECK(!reference_profile_file_.empty());
889 fd = open(reference_profile_file_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
890 if (fd < 0) {
891 LOG(ERROR) << "Cannot open " << reference_profile_file_ << strerror(errno);
892 return kInvalidFd;
893 }
894 }
895 return fd;
896 }
897
Calin Juravlee0ac1152017-02-13 19:03:47 -0800898 // Creates a profile from a human friendly textual representation.
899 // The expected input format is:
900 // # Classes
901 // Ljava/lang/Comparable;
902 // Ljava/lang/Math;
903 // # Methods with inline caches
904 // LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;
905 // LTestInline;->noInlineCache(LSuper;)I
David Sehr7c80f2d2017-02-07 16:47:58 -0800906 int CreateProfile() {
David Sehr153da0e2017-02-15 08:54:51 -0800907 // Validate parameters for this command.
908 if (apk_files_.empty() && apks_fd_.empty()) {
909 Usage("APK files must be specified");
910 }
911 if (dex_locations_.empty()) {
912 Usage("DEX locations must be specified");
913 }
914 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
915 Usage("Reference profile must be specified with --reference-profile-file or "
916 "--reference-profile-file-fd");
917 }
918 if (!profile_files_.empty() || !profile_files_fd_.empty()) {
919 Usage("Profile must be specified with --reference-profile-file or "
920 "--reference-profile-file-fd");
921 }
922 // for ZipArchive::OpenFromFd
923 MemMap::Init();
David Sehr7c80f2d2017-02-07 16:47:58 -0800924 // Open the profile output file if needed.
Mathieu Chartier2f794552017-06-19 10:58:08 -0700925 int fd = OpenReferenceProfile();
David Sehr7c80f2d2017-02-07 16:47:58 -0800926 if (!FdIsValid(fd)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800927 return -1;
David Sehr7c80f2d2017-02-07 16:47:58 -0800928 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800929 // Read the user-specified list of classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800930 std::unique_ptr<std::unordered_set<std::string>>
Calin Juravlee0ac1152017-02-13 19:03:47 -0800931 user_lines(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
David Sehr7c80f2d2017-02-07 16:47:58 -0800932 create_profile_from_file_.c_str(), nullptr)); // No post-processing.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800933
934 // Open the dex files to look up classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800935 std::vector<std::unique_ptr<const DexFile>> dex_files;
936 OpenApkFilesFromLocations(&dex_files);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800937
938 // Process the lines one by one and add the successful ones to the profile.
David Sehr7c80f2d2017-02-07 16:47:58 -0800939 ProfileCompilationInfo info;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800940
941 for (const auto& line : *user_lines) {
942 ProcessLine(dex_files, line, &info);
943 }
944
David Sehr7c80f2d2017-02-07 16:47:58 -0800945 // Write the profile file.
946 CHECK(info.Save(fd));
947 if (close(fd) < 0) {
948 PLOG(WARNING) << "Failed to close descriptor";
949 }
950 return 0;
951 }
952
Mathieu Chartier2f794552017-06-19 10:58:08 -0700953 bool ShouldCreateBootProfile() const {
954 return generate_boot_image_profile_;
955 }
956
957 int CreateBootProfile() {
958 // Initialize memmap since it's required to open dex files.
959 MemMap::Init();
960 // Open the profile output file.
961 const int reference_fd = OpenReferenceProfile();
962 if (!FdIsValid(reference_fd)) {
963 PLOG(ERROR) << "Error opening reference profile";
964 return -1;
965 }
966 // Open the dex files.
967 std::vector<std::unique_ptr<const DexFile>> dex_files;
968 OpenApkFilesFromLocations(&dex_files);
969 if (dex_files.empty()) {
970 PLOG(ERROR) << "Expected dex files for creating boot profile";
971 return -2;
972 }
973 // Open the input profiles.
974 std::vector<std::unique_ptr<const ProfileCompilationInfo>> profiles;
975 if (!profile_files_fd_.empty()) {
976 for (int profile_file_fd : profile_files_fd_) {
977 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile("", profile_file_fd));
978 if (profile == nullptr) {
979 return -3;
980 }
981 profiles.emplace_back(std::move(profile));
982 }
983 }
984 if (!profile_files_.empty()) {
985 for (const std::string& profile_file : profile_files_) {
986 std::unique_ptr<const ProfileCompilationInfo> profile(LoadProfile(profile_file, kInvalidFd));
987 if (profile == nullptr) {
988 return -4;
989 }
990 profiles.emplace_back(std::move(profile));
991 }
992 }
993 ProfileCompilationInfo out_profile;
994 GenerateBootImageProfile(dex_files,
995 profiles,
996 boot_image_options_,
997 VLOG_IS_ON(profiler),
998 &out_profile);
999 out_profile.Save(reference_fd);
1000 close(reference_fd);
1001 return 0;
1002 }
1003
David Sehr7c80f2d2017-02-07 16:47:58 -08001004 bool ShouldCreateProfile() {
1005 return !create_profile_from_file_.empty();
1006 }
1007
Calin Juravle7bcdb532016-06-07 16:14:47 +01001008 int GenerateTestProfile() {
David Sehr153da0e2017-02-15 08:54:51 -08001009 // Validate parameters for this command.
1010 if (test_profile_method_ratio_ > 100) {
1011 Usage("Invalid ratio for --generate-test-profile-method-ratio");
1012 }
1013 if (test_profile_class_ratio_ > 100) {
1014 Usage("Invalid ratio for --generate-test-profile-class-ratio");
1015 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001016 // If given APK files or DEX locations, check that they're ok.
1017 if (!apk_files_.empty() || !apks_fd_.empty() || !dex_locations_.empty()) {
1018 if (apk_files_.empty() && apks_fd_.empty()) {
1019 Usage("APK files must be specified when passing DEX locations to --generate-test-profile");
1020 }
1021 if (dex_locations_.empty()) {
1022 Usage("DEX locations must be specified when passing APK files to --generate-test-profile");
1023 }
1024 }
David Sehr153da0e2017-02-15 08:54:51 -08001025 // ShouldGenerateTestProfile confirms !test_profile_.empty().
George Burgess IV71f77262016-10-25 13:08:17 -07001026 int profile_test_fd = open(test_profile_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001027 if (profile_test_fd < 0) {
David Sehr7c80f2d2017-02-07 16:47:58 -08001028 LOG(ERROR) << "Cannot open " << test_profile_ << strerror(errno);
Calin Juravle7bcdb532016-06-07 16:14:47 +01001029 return -1;
1030 }
Jeff Haof0a31f82017-03-27 15:50:37 -07001031 bool result;
1032 if (apk_files_.empty() && apks_fd_.empty() && dex_locations_.empty()) {
1033 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1034 test_profile_num_dex_,
1035 test_profile_method_ratio_,
1036 test_profile_class_ratio_,
1037 test_profile_seed_);
1038 } else {
1039 // Initialize MemMap for ZipArchive::OpenFromFd.
1040 MemMap::Init();
1041 // Open the dex files to look up classes and methods.
1042 std::vector<std::unique_ptr<const DexFile>> dex_files;
1043 OpenApkFilesFromLocations(&dex_files);
1044 // Create a random profile file based on the set of dex files.
1045 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
1046 dex_files,
1047 test_profile_seed_);
1048 }
Calin Juravle7bcdb532016-06-07 16:14:47 +01001049 close(profile_test_fd); // ignore close result.
1050 return result ? 0 : -1;
1051 }
1052
1053 bool ShouldGenerateTestProfile() {
1054 return !test_profile_.empty();
1055 }
1056
Calin Juravle2e2db782016-02-23 12:00:03 +00001057 private:
1058 static void ParseFdForCollection(const StringPiece& option,
1059 const char* arg_name,
1060 std::vector<int>* fds) {
1061 int fd;
1062 ParseUintOption(option, arg_name, &fd, Usage);
1063 fds->push_back(fd);
1064 }
1065
1066 static void CloseAllFds(const std::vector<int>& fds, const char* descriptor) {
1067 for (size_t i = 0; i < fds.size(); i++) {
1068 if (close(fds[i]) < 0) {
1069 PLOG(WARNING) << "Failed to close descriptor for " << descriptor << " at index " << i;
1070 }
1071 }
1072 }
1073
1074 void LogCompletionTime() {
David Sehr52683cf2016-05-05 09:02:38 -07001075 static constexpr uint64_t kLogThresholdTime = MsToNs(100); // 100ms
1076 uint64_t time_taken = NanoTime() - start_ns_;
David Sehred793012016-05-05 13:39:43 -07001077 if (time_taken > kLogThresholdTime) {
David Sehrd8557182016-05-06 12:29:35 -07001078 LOG(WARNING) << "profman took " << PrettyDuration(time_taken);
David Sehred793012016-05-05 13:39:43 -07001079 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001080 }
1081
1082 std::vector<std::string> profile_files_;
1083 std::vector<int> profile_files_fd_;
David Sehr546d24f2016-06-02 10:46:19 -07001084 std::vector<std::string> dex_locations_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001085 std::vector<std::string> apk_files_;
David Sehr546d24f2016-06-02 10:46:19 -07001086 std::vector<int> apks_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001087 std::string reference_profile_file_;
1088 int reference_profile_file_fd_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001089 bool dump_only_;
Mathieu Chartier34067262017-04-06 13:55:46 -07001090 bool dump_classes_and_methods_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001091 bool generate_boot_image_profile_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001092 int dump_output_to_fd_;
Mathieu Chartier2f794552017-06-19 10:58:08 -07001093 BootImageOptions boot_image_options_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001094 std::string test_profile_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001095 std::string create_profile_from_file_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001096 uint16_t test_profile_num_dex_;
1097 uint16_t test_profile_method_ratio_;
1098 uint16_t test_profile_class_ratio_;
Jeff Haof0a31f82017-03-27 15:50:37 -07001099 uint32_t test_profile_seed_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001100 uint64_t start_ns_;
1101};
1102
1103// See ProfileAssistant::ProcessingResult for return codes.
1104static int profman(int argc, char** argv) {
1105 ProfMan profman;
1106
1107 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1108 profman.ParseArgs(argc, argv);
1109
Calin Juravle7bcdb532016-06-07 16:14:47 +01001110 if (profman.ShouldGenerateTestProfile()) {
1111 return profman.GenerateTestProfile();
1112 }
Calin Juravle876f3502016-03-24 16:16:34 +00001113 if (profman.ShouldOnlyDumpProfile()) {
1114 return profman.DumpProfileInfo();
1115 }
Mathieu Chartier34067262017-04-06 13:55:46 -07001116 if (profman.ShouldOnlyDumpClassesAndMethods()) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001117 return profman.DumpClassesAndMethods();
David Sehr7c80f2d2017-02-07 16:47:58 -08001118 }
1119 if (profman.ShouldCreateProfile()) {
1120 return profman.CreateProfile();
1121 }
Mathieu Chartier2f794552017-06-19 10:58:08 -07001122
1123 if (profman.ShouldCreateBootProfile()) {
1124 return profman.CreateBootProfile();
1125 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001126 // Process profile information and assess if we need to do a profile guided compilation.
1127 // This operation involves I/O.
1128 return profman.ProcessProfiles();
1129}
1130
1131} // namespace art
1132
1133int main(int argc, char **argv) {
1134 return art::profman(argc, argv);
1135}
1136