blob: afc21057b13a34de57797da8b660356fcc1e45c2 [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"
Calin Juravlee0ac1152017-02-13 19:03:47 -080039#include "bytecode_utils.h"
David Sehr4fcdd6d2016-05-24 14:52:31 -070040#include "dex_file.h"
Calin Juravle33083d62017-01-18 15:29:12 -080041#include "jit/profile_compilation_info.h"
Mathieu Chartierdbddc222017-05-24 12:04:13 -070042#include "profile_assistant.h"
David Sehrf57589f2016-10-17 10:09:33 -070043#include "runtime.h"
Mathieu Chartierdbddc222017-05-24 12:04:13 -070044#include "type_reference.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000045#include "utils.h"
David Sehr546d24f2016-06-02 10:46:19 -070046#include "zip_archive.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000047
48namespace art {
49
50static int original_argc;
51static char** original_argv;
52
53static std::string CommandLine() {
54 std::vector<std::string> command;
55 for (int i = 0; i < original_argc; ++i) {
56 command.push_back(original_argv[i]);
57 }
Andreas Gampe9186ced2016-12-12 14:28:21 -080058 return android::base::Join(command, ' ');
Calin Juravle2e2db782016-02-23 12:00:03 +000059}
60
David Sehr4fcdd6d2016-05-24 14:52:31 -070061static constexpr int kInvalidFd = -1;
62
63static bool FdIsValid(int fd) {
64 return fd != kInvalidFd;
65}
66
Calin Juravle2e2db782016-02-23 12:00:03 +000067static void UsageErrorV(const char* fmt, va_list ap) {
68 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080069 android::base::StringAppendV(&error, fmt, ap);
Calin Juravle2e2db782016-02-23 12:00:03 +000070 LOG(ERROR) << error;
71}
72
73static void UsageError(const char* fmt, ...) {
74 va_list ap;
75 va_start(ap, fmt);
76 UsageErrorV(fmt, ap);
77 va_end(ap);
78}
79
80NO_RETURN static void Usage(const char *fmt, ...) {
81 va_list ap;
82 va_start(ap, fmt);
83 UsageErrorV(fmt, ap);
84 va_end(ap);
85
86 UsageError("Command: %s", CommandLine().c_str());
87 UsageError("Usage: profman [options]...");
88 UsageError("");
David Sehr4fcdd6d2016-05-24 14:52:31 -070089 UsageError(" --dump-only: dumps the content of the specified profile files");
90 UsageError(" to standard output (default) in a human readable form.");
91 UsageError("");
David Sehr7c80f2d2017-02-07 16:47:58 -080092 UsageError(" --dump-output-to-fd=<number>: redirects --dump-only output to a file descriptor.");
93 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -070094 UsageError(" --dump-classes-and-methods: dumps a sorted list of classes and methods that are");
95 UsageError(" in the specified profile file to standard output (default) in a human");
96 UsageError(" readable form. The output is valid input for --create-profile-from");
Calin Juravle876f3502016-03-24 16:16:34 +000097 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +000098 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
99 UsageError(" Can be specified multiple time, in which case the data from the different");
100 UsageError(" profiles will be aggregated.");
101 UsageError("");
102 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
103 UsageError(" Cannot be used together with --profile-file.");
104 UsageError("");
105 UsageError(" --reference-profile-file=<filename>: specify a reference profile.");
106 UsageError(" The data in this file will be compared with the data obtained by merging");
107 UsageError(" all the files specified with --profile-file or --profile-file-fd.");
108 UsageError(" If the exit code is EXIT_COMPILE then all --profile-file will be merged into");
109 UsageError(" --reference-profile-file. ");
110 UsageError("");
111 UsageError(" --reference-profile-file-fd=<number>: same as --reference-profile-file but");
112 UsageError(" accepts a file descriptor. Cannot be used together with");
113 UsageError(" --reference-profile-file.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800114 UsageError("");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100115 UsageError(" --generate-test-profile=<filename>: generates a random profile file for testing.");
116 UsageError(" --generate-test-profile-num-dex=<number>: number of dex files that should be");
117 UsageError(" included in the generated profile. Defaults to 20.");
118 UsageError(" --generate-test-profile-method-ratio=<number>: the percentage from the maximum");
119 UsageError(" number of methods that should be generated. Defaults to 5.");
120 UsageError(" --generate-test-profile-class-ratio=<number>: the percentage from the maximum");
121 UsageError(" number of classes that should be generated. Defaults to 5.");
Jeff Haof0a31f82017-03-27 15:50:37 -0700122 UsageError(" --generate-test-profile-seed=<number>: seed for random number generator used when");
123 UsageError(" generating random test profiles. Defaults to using NanoTime.");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100124 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -0700125 UsageError(" --create-profile-from=<filename>: creates a profile from a list of classes and");
126 UsageError(" methods.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800127 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700128 UsageError(" --dex-location=<string>: location string to use with corresponding");
129 UsageError(" apk-fd to find dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700130 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700131 UsageError(" --apk-fd=<number>: file descriptor containing an open APK to");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700132 UsageError(" search for dex files");
David Sehr7c80f2d2017-02-07 16:47:58 -0800133 UsageError(" --apk-=<filename>: an APK to search for dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700134 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000135
136 exit(EXIT_FAILURE);
137}
138
Calin Juravle7bcdb532016-06-07 16:14:47 +0100139// Note: make sure you update the Usage if you change these values.
140static constexpr uint16_t kDefaultTestProfileNumDex = 20;
141static constexpr uint16_t kDefaultTestProfileMethodRatio = 5;
142static constexpr uint16_t kDefaultTestProfileClassRatio = 5;
143
Calin Juravlee0ac1152017-02-13 19:03:47 -0800144// Separators used when parsing human friendly representation of profiles.
145static const std::string kMethodSep = "->";
Calin Juravle589e71e2017-03-03 16:05:05 -0800146static const std::string kMissingTypesMarker = "missing_types";
Calin Juravle08556882017-05-26 16:40:45 -0700147static const std::string kInvalidClassDescriptor = "invalid_class";
148static const std::string kInvalidMethod = "invalid_method";
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700149static const std::string kClassAllMethods = "*";
Calin Juravlee0ac1152017-02-13 19:03:47 -0800150static constexpr char kProfileParsingInlineChacheSep = '+';
151static constexpr char kProfileParsingTypeSep = ',';
152static constexpr char kProfileParsingFirstCharInSignature = '(';
153
154// TODO(calin): This class has grown too much from its initial design. Split the functionality
155// into smaller, more contained pieces.
Calin Juravle2e2db782016-02-23 12:00:03 +0000156class ProfMan FINAL {
157 public:
158 ProfMan() :
David Sehr4fcdd6d2016-05-24 14:52:31 -0700159 reference_profile_file_fd_(kInvalidFd),
160 dump_only_(false),
Mathieu Chartier34067262017-04-06 13:55:46 -0700161 dump_classes_and_methods_(false),
David Sehr4fcdd6d2016-05-24 14:52:31 -0700162 dump_output_to_fd_(kInvalidFd),
Calin Juravle7bcdb532016-06-07 16:14:47 +0100163 test_profile_num_dex_(kDefaultTestProfileNumDex),
164 test_profile_method_ratio_(kDefaultTestProfileMethodRatio),
165 test_profile_class_ratio_(kDefaultTestProfileClassRatio),
Jeff Haof0a31f82017-03-27 15:50:37 -0700166 test_profile_seed_(NanoTime()),
Calin Juravle2e2db782016-02-23 12:00:03 +0000167 start_ns_(NanoTime()) {}
168
169 ~ProfMan() {
170 LogCompletionTime();
171 }
172
173 void ParseArgs(int argc, char **argv) {
174 original_argc = argc;
175 original_argv = argv;
176
David Sehrf57589f2016-10-17 10:09:33 -0700177 InitLogging(argv, Runtime::Aborter);
Calin Juravle2e2db782016-02-23 12:00:03 +0000178
179 // Skip over the command name.
180 argv++;
181 argc--;
182
183 if (argc == 0) {
184 Usage("No arguments specified");
185 }
186
187 for (int i = 0; i < argc; ++i) {
188 const StringPiece option(argv[i]);
189 const bool log_options = false;
190 if (log_options) {
Calin Juravle876f3502016-03-24 16:16:34 +0000191 LOG(INFO) << "profman: option[" << i << "]=" << argv[i];
Calin Juravle2e2db782016-02-23 12:00:03 +0000192 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700193 if (option == "--dump-only") {
194 dump_only_ = true;
Mathieu Chartier34067262017-04-06 13:55:46 -0700195 } else if (option == "--dump-classes-and-methods") {
196 dump_classes_and_methods_ = true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800197 } else if (option.starts_with("--create-profile-from=")) {
198 create_profile_from_file_ = option.substr(strlen("--create-profile-from=")).ToString();
David Sehr4fcdd6d2016-05-24 14:52:31 -0700199 } else if (option.starts_with("--dump-output-to-fd=")) {
200 ParseUintOption(option, "--dump-output-to-fd", &dump_output_to_fd_, Usage);
Calin Juravle876f3502016-03-24 16:16:34 +0000201 } else if (option.starts_with("--profile-file=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000202 profile_files_.push_back(option.substr(strlen("--profile-file=")).ToString());
203 } else if (option.starts_with("--profile-file-fd=")) {
204 ParseFdForCollection(option, "--profile-file-fd", &profile_files_fd_);
205 } else if (option.starts_with("--reference-profile-file=")) {
206 reference_profile_file_ = option.substr(strlen("--reference-profile-file=")).ToString();
207 } else if (option.starts_with("--reference-profile-file-fd=")) {
208 ParseUintOption(option, "--reference-profile-file-fd", &reference_profile_file_fd_, Usage);
David Sehr546d24f2016-06-02 10:46:19 -0700209 } else if (option.starts_with("--dex-location=")) {
210 dex_locations_.push_back(option.substr(strlen("--dex-location=")).ToString());
211 } else if (option.starts_with("--apk-fd=")) {
212 ParseFdForCollection(option, "--apk-fd", &apks_fd_);
David Sehr7c80f2d2017-02-07 16:47:58 -0800213 } else if (option.starts_with("--apk=")) {
214 apk_files_.push_back(option.substr(strlen("--apk=")).ToString());
Calin Juravle7bcdb532016-06-07 16:14:47 +0100215 } else if (option.starts_with("--generate-test-profile=")) {
216 test_profile_ = option.substr(strlen("--generate-test-profile=")).ToString();
217 } else if (option.starts_with("--generate-test-profile-num-dex=")) {
218 ParseUintOption(option,
219 "--generate-test-profile-num-dex",
220 &test_profile_num_dex_,
221 Usage);
222 } else if (option.starts_with("--generate-test-profile-method-ratio")) {
223 ParseUintOption(option,
224 "--generate-test-profile-method-ratio",
225 &test_profile_method_ratio_,
226 Usage);
227 } else if (option.starts_with("--generate-test-profile-class-ratio")) {
228 ParseUintOption(option,
229 "--generate-test-profile-class-ratio",
230 &test_profile_class_ratio_,
231 Usage);
Jeff Haof0a31f82017-03-27 15:50:37 -0700232 } else if (option.starts_with("--generate-test-profile-seed=")) {
233 ParseUintOption(option, "--generate-test-profile-seed", &test_profile_seed_, Usage);
Calin Juravle2e2db782016-02-23 12:00:03 +0000234 } else {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700235 Usage("Unknown argument '%s'", option.data());
Calin Juravle2e2db782016-02-23 12:00:03 +0000236 }
237 }
238
David Sehr153da0e2017-02-15 08:54:51 -0800239 // Validate global consistency between file/fd options.
Calin Juravle2e2db782016-02-23 12:00:03 +0000240 if (!profile_files_.empty() && !profile_files_fd_.empty()) {
241 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
242 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700243 if (!reference_profile_file_.empty() && FdIsValid(reference_profile_file_fd_)) {
244 Usage("Reference profile should not be specified with both "
245 "--reference-profile-file-fd and --reference-profile-file");
246 }
David Sehr153da0e2017-02-15 08:54:51 -0800247 if (!apk_files_.empty() && !apks_fd_.empty()) {
248 Usage("APK files should not be specified with both --apk-fd and --apk");
Calin Juravle2e2db782016-02-23 12:00:03 +0000249 }
250 }
251
252 ProfileAssistant::ProcessingResult ProcessProfiles() {
David Sehr153da0e2017-02-15 08:54:51 -0800253 // Validate that at least one profile file was passed, as well as a reference profile.
254 if (profile_files_.empty() && profile_files_fd_.empty()) {
255 Usage("No profile files specified.");
256 }
257 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
258 Usage("No reference profile file specified.");
259 }
260 if ((!profile_files_.empty() && FdIsValid(reference_profile_file_fd_)) ||
261 (!profile_files_fd_.empty() && !FdIsValid(reference_profile_file_fd_))) {
262 Usage("Options --profile-file-fd and --reference-profile-file-fd "
263 "should only be used together");
264 }
Calin Juravle2e2db782016-02-23 12:00:03 +0000265 ProfileAssistant::ProcessingResult result;
266 if (profile_files_.empty()) {
267 // The file doesn't need to be flushed here (ProcessProfiles will do it)
268 // so don't check the usage.
269 File file(reference_profile_file_fd_, false);
270 result = ProfileAssistant::ProcessProfiles(profile_files_fd_, reference_profile_file_fd_);
271 CloseAllFds(profile_files_fd_, "profile_files_fd_");
272 } else {
273 result = ProfileAssistant::ProcessProfiles(profile_files_, reference_profile_file_);
274 }
275 return result;
276 }
277
David Sehr7c80f2d2017-02-07 16:47:58 -0800278 void OpenApkFilesFromLocations(std::vector<std::unique_ptr<const DexFile>>* dex_files) {
279 bool use_apk_fd_list = !apks_fd_.empty();
280 if (use_apk_fd_list) {
David Sehr153da0e2017-02-15 08:54:51 -0800281 // Get the APKs from the collection of FDs.
David Sehr7c80f2d2017-02-07 16:47:58 -0800282 CHECK_EQ(dex_locations_.size(), apks_fd_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800283 } else if (!apk_files_.empty()) {
284 // Get the APKs from the collection of filenames.
David Sehr7c80f2d2017-02-07 16:47:58 -0800285 CHECK_EQ(dex_locations_.size(), apk_files_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800286 } else {
287 // No APKs were specified.
288 CHECK(dex_locations_.empty());
289 return;
David Sehr7c80f2d2017-02-07 16:47:58 -0800290 }
291 static constexpr bool kVerifyChecksum = true;
292 for (size_t i = 0; i < dex_locations_.size(); ++i) {
293 std::string error_msg;
294 std::vector<std::unique_ptr<const DexFile>> dex_files_for_location;
295 if (use_apk_fd_list) {
296 if (DexFile::OpenZip(apks_fd_[i],
297 dex_locations_[i],
298 kVerifyChecksum,
299 &error_msg,
300 &dex_files_for_location)) {
301 } else {
302 LOG(WARNING) << "OpenZip failed for '" << dex_locations_[i] << "' " << error_msg;
303 continue;
304 }
305 } else {
306 if (DexFile::Open(apk_files_[i].c_str(),
307 dex_locations_[i],
308 kVerifyChecksum,
309 &error_msg,
310 &dex_files_for_location)) {
311 } else {
312 LOG(WARNING) << "Open failed for '" << dex_locations_[i] << "' " << error_msg;
313 continue;
314 }
315 }
316 for (std::unique_ptr<const DexFile>& dex_file : dex_files_for_location) {
317 dex_files->emplace_back(std::move(dex_file));
318 }
319 }
320 }
321
David Sehrb18991b2017-02-08 20:58:10 -0800322 int DumpOneProfile(const std::string& banner,
323 const std::string& filename,
324 int fd,
325 const std::vector<std::unique_ptr<const DexFile>>* dex_files,
326 std::string* dump) {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700327 if (!filename.empty()) {
328 fd = open(filename.c_str(), O_RDWR);
329 if (fd < 0) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800330 LOG(ERROR) << "Cannot open " << filename << strerror(errno);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700331 return -1;
332 }
Calin Juravle876f3502016-03-24 16:16:34 +0000333 }
334 ProfileCompilationInfo info;
335 if (!info.Load(fd)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800336 LOG(ERROR) << "Cannot load profile info from fd=" << fd << "\n";
Calin Juravle876f3502016-03-24 16:16:34 +0000337 return -1;
338 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700339 std::string this_dump = banner + "\n" + info.DumpInfo(dex_files) + "\n";
340 *dump += this_dump;
341 if (close(fd) < 0) {
342 PLOG(WARNING) << "Failed to close descriptor";
343 }
344 return 0;
345 }
346
347 int DumpProfileInfo() {
David Sehr153da0e2017-02-15 08:54:51 -0800348 // Validate that at least one profile file or reference was specified.
349 if (profile_files_.empty() && profile_files_fd_.empty() &&
350 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
351 Usage("No profile files or reference profile specified.");
352 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700353 static const char* kEmptyString = "";
David Sehr546d24f2016-06-02 10:46:19 -0700354 static const char* kOrdinaryProfile = "=== profile ===";
355 static const char* kReferenceProfile = "=== reference profile ===";
356
357 // Open apk/zip files and and read dex files.
358 MemMap::Init(); // for ZipArchive::OpenFromFd
David Sehrb18991b2017-02-08 20:58:10 -0800359 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7c80f2d2017-02-07 16:47:58 -0800360 OpenApkFilesFromLocations(&dex_files);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700361 std::string dump;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700362 // Dump individual profile files.
363 if (!profile_files_fd_.empty()) {
364 for (int profile_file_fd : profile_files_fd_) {
David Sehr546d24f2016-06-02 10:46:19 -0700365 int ret = DumpOneProfile(kOrdinaryProfile,
366 kEmptyString,
367 profile_file_fd,
368 &dex_files,
369 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700370 if (ret != 0) {
371 return ret;
372 }
373 }
374 }
375 if (!profile_files_.empty()) {
376 for (const std::string& profile_file : profile_files_) {
David Sehr546d24f2016-06-02 10:46:19 -0700377 int ret = DumpOneProfile(kOrdinaryProfile, profile_file, kInvalidFd, &dex_files, &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700378 if (ret != 0) {
379 return ret;
380 }
381 }
382 }
383 // Dump reference profile file.
384 if (FdIsValid(reference_profile_file_fd_)) {
David Sehr546d24f2016-06-02 10:46:19 -0700385 int ret = DumpOneProfile(kReferenceProfile,
386 kEmptyString,
387 reference_profile_file_fd_,
388 &dex_files,
389 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700390 if (ret != 0) {
391 return ret;
392 }
393 }
394 if (!reference_profile_file_.empty()) {
David Sehr546d24f2016-06-02 10:46:19 -0700395 int ret = DumpOneProfile(kReferenceProfile,
396 reference_profile_file_,
397 kInvalidFd,
398 &dex_files,
David Sehr4fcdd6d2016-05-24 14:52:31 -0700399 &dump);
400 if (ret != 0) {
401 return ret;
402 }
403 }
404 if (!FdIsValid(dump_output_to_fd_)) {
405 std::cout << dump;
406 } else {
407 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
408 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
409 return -1;
410 }
411 }
Calin Juravle876f3502016-03-24 16:16:34 +0000412 return 0;
413 }
414
415 bool ShouldOnlyDumpProfile() {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700416 return dump_only_;
Calin Juravle876f3502016-03-24 16:16:34 +0000417 }
418
Mathieu Chartier34067262017-04-06 13:55:46 -0700419 bool GetClassNamesAndMethods(int fd,
420 std::vector<std::unique_ptr<const DexFile>>* dex_files,
421 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800422 ProfileCompilationInfo profile_info;
423 if (!profile_info.Load(fd)) {
424 LOG(ERROR) << "Cannot load profile info";
425 return false;
426 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700427 for (const std::unique_ptr<const DexFile>& dex_file : *dex_files) {
428 std::set<dex::TypeIndex> class_types;
Calin Juravlee6f87cc2017-05-24 17:41:05 -0700429 std::set<uint16_t> methods;
430 if (profile_info.GetClassesAndMethods(*dex_file.get(), &class_types, &methods)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700431 for (const dex::TypeIndex& type_index : class_types) {
432 const DexFile::TypeId& type_id = dex_file->GetTypeId(type_index);
433 out_lines->insert(std::string(dex_file->GetTypeDescriptor(type_id)));
434 }
Calin Juravlee6f87cc2017-05-24 17:41:05 -0700435 for (uint16_t dex_method_idx : methods) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700436 const DexFile::MethodId& id = dex_file->GetMethodId(dex_method_idx);
437 std::string signature_string(dex_file->GetMethodSignature(id).ToString());
438 std::string type_string(dex_file->GetTypeDescriptor(dex_file->GetTypeId(id.class_idx_)));
439 std::string method_name(dex_file->GetMethodName(id));
440 out_lines->insert(type_string + kMethodSep + method_name + signature_string);
441 }
442 }
443 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800444 return true;
445 }
446
Mathieu Chartier34067262017-04-06 13:55:46 -0700447 bool GetClassNamesAndMethods(const std::string& profile_file,
448 std::vector<std::unique_ptr<const DexFile>>* dex_files,
449 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800450 int fd = open(profile_file.c_str(), O_RDONLY);
451 if (!FdIsValid(fd)) {
452 LOG(ERROR) << "Cannot open " << profile_file << strerror(errno);
453 return false;
454 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700455 if (!GetClassNamesAndMethods(fd, dex_files, out_lines)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800456 return false;
457 }
458 if (close(fd) < 0) {
459 PLOG(WARNING) << "Failed to close descriptor";
460 }
461 return true;
462 }
463
464 int DumpClasses() {
David Sehr153da0e2017-02-15 08:54:51 -0800465 // Validate that at least one profile file or reference was specified.
466 if (profile_files_.empty() && profile_files_fd_.empty() &&
467 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
468 Usage("No profile files or reference profile specified.");
469 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800470 // Open apk/zip files and and read dex files.
471 MemMap::Init(); // for ZipArchive::OpenFromFd
472 // Open the dex files to get the names for classes.
473 std::vector<std::unique_ptr<const DexFile>> dex_files;
474 OpenApkFilesFromLocations(&dex_files);
475 // Build a vector of class names from individual profile files.
476 std::set<std::string> class_names;
477 if (!profile_files_fd_.empty()) {
478 for (int profile_file_fd : profile_files_fd_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700479 if (!GetClassNamesAndMethods(profile_file_fd, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800480 return -1;
481 }
482 }
483 }
484 if (!profile_files_.empty()) {
485 for (const std::string& profile_file : profile_files_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700486 if (!GetClassNamesAndMethods(profile_file, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800487 return -1;
488 }
489 }
490 }
491 // Concatenate class names from reference profile file.
492 if (FdIsValid(reference_profile_file_fd_)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700493 if (!GetClassNamesAndMethods(reference_profile_file_fd_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800494 return -1;
495 }
496 }
497 if (!reference_profile_file_.empty()) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700498 if (!GetClassNamesAndMethods(reference_profile_file_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800499 return -1;
500 }
501 }
502 // Dump the class names.
503 std::string dump;
504 for (const std::string& class_name : class_names) {
505 dump += class_name + std::string("\n");
506 }
507 if (!FdIsValid(dump_output_to_fd_)) {
508 std::cout << dump;
509 } else {
510 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
511 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
512 return -1;
513 }
514 }
515 return 0;
516 }
517
Mathieu Chartier34067262017-04-06 13:55:46 -0700518 bool ShouldOnlyDumpClassesAndMethods() {
519 return dump_classes_and_methods_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800520 }
521
522 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
523 // the given function.
524 template <typename T>
525 static T* ReadCommentedInputFromFile(
526 const char* input_filename, std::function<std::string(const char*)>* process) {
527 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
528 if (input_file.get() == nullptr) {
529 LOG(ERROR) << "Failed to open input file " << input_filename;
530 return nullptr;
531 }
532 std::unique_ptr<T> result(
533 ReadCommentedInputStream<T>(*input_file, process));
534 input_file->close();
535 return result.release();
536 }
537
538 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
539 // with the given function.
540 template <typename T>
541 static T* ReadCommentedInputStream(
542 std::istream& in_stream,
543 std::function<std::string(const char*)>* process) {
544 std::unique_ptr<T> output(new T());
545 while (in_stream.good()) {
546 std::string dot;
547 std::getline(in_stream, dot);
548 if (android::base::StartsWith(dot, "#") || dot.empty()) {
549 continue;
550 }
551 if (process != nullptr) {
552 std::string descriptor((*process)(dot.c_str()));
553 output->insert(output->end(), descriptor);
554 } else {
555 output->insert(output->end(), dot);
556 }
557 }
558 return output.release();
559 }
560
Calin Juravlee0ac1152017-02-13 19:03:47 -0800561 // Find class klass_descriptor in the given dex_files and store its reference
562 // in the out parameter class_ref.
563 // Return true if the definition of the class was found in any of the dex_files.
564 bool FindClass(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
565 const std::string& klass_descriptor,
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700566 /*out*/TypeReference* class_ref) {
Calin Juravle08556882017-05-26 16:40:45 -0700567 constexpr uint16_t kInvalidTypeIndex = std::numeric_limits<uint16_t>::max() - 1;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800568 for (const std::unique_ptr<const DexFile>& dex_file_ptr : dex_files) {
569 const DexFile* dex_file = dex_file_ptr.get();
Calin Juravle08556882017-05-26 16:40:45 -0700570 if (klass_descriptor == kInvalidClassDescriptor) {
571 if (kInvalidTypeIndex >= dex_file->NumTypeIds()) {
572 // The dex file does not contain all possible type ids which leaves us room
573 // to add an "invalid" type id.
574 class_ref->dex_file = dex_file;
575 class_ref->type_index = dex::TypeIndex(kInvalidTypeIndex);
576 return true;
577 } else {
578 // The dex file contains all possible type ids. We don't have any free type id
579 // that we can use as invalid.
580 continue;
581 }
582 }
583
Calin Juravlee0ac1152017-02-13 19:03:47 -0800584 const DexFile::TypeId* type_id = dex_file->FindTypeId(klass_descriptor.c_str());
585 if (type_id == nullptr) {
586 continue;
587 }
588 dex::TypeIndex type_index = dex_file->GetIndexForTypeId(*type_id);
589 if (dex_file->FindClassDef(type_index) == nullptr) {
590 // Class is only referenced in the current dex file but not defined in it.
591 continue;
592 }
593 class_ref->dex_file = dex_file;
594 class_ref->type_index = type_index;
595 return true;
596 }
597 return false;
598 }
599
Mathieu Chartier34067262017-04-06 13:55:46 -0700600 // Find the method specified by method_spec in the class class_ref.
Calin Juravle08556882017-05-26 16:40:45 -0700601 uint32_t FindMethodIndex(const TypeReference& class_ref,
602 const std::string& method_spec) {
603 const DexFile* dex_file = class_ref.dex_file;
604 if (method_spec == kInvalidMethod) {
605 constexpr uint16_t kInvalidMethodIndex = std::numeric_limits<uint16_t>::max() - 1;
606 return kInvalidMethodIndex >= dex_file->NumMethodIds()
607 ? kInvalidMethodIndex
608 : DexFile::kDexNoIndex;
609 }
610
Calin Juravlee0ac1152017-02-13 19:03:47 -0800611 std::vector<std::string> name_and_signature;
612 Split(method_spec, kProfileParsingFirstCharInSignature, &name_and_signature);
613 if (name_and_signature.size() != 2) {
614 LOG(ERROR) << "Invalid method name and signature " << method_spec;
Calin Juravle08556882017-05-26 16:40:45 -0700615 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800616 }
Calin Juravle08556882017-05-26 16:40:45 -0700617
Calin Juravlee0ac1152017-02-13 19:03:47 -0800618 const std::string& name = name_and_signature[0];
619 const std::string& signature = kProfileParsingFirstCharInSignature + name_and_signature[1];
Calin Juravlee0ac1152017-02-13 19:03:47 -0800620
621 const DexFile::StringId* name_id = dex_file->FindStringId(name.c_str());
622 if (name_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700623 LOG(WARNING) << "Could not find name: " << name;
Mathieu Chartier34067262017-04-06 13:55:46 -0700624 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800625 }
626 dex::TypeIndex return_type_idx;
627 std::vector<dex::TypeIndex> param_type_idxs;
628 if (!dex_file->CreateTypeList(signature, &return_type_idx, &param_type_idxs)) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700629 LOG(WARNING) << "Could not create type list" << signature;
Mathieu Chartier34067262017-04-06 13:55:46 -0700630 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800631 }
632 const DexFile::ProtoId* proto_id = dex_file->FindProtoId(return_type_idx, param_type_idxs);
633 if (proto_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700634 LOG(WARNING) << "Could not find proto_id: " << name;
Mathieu Chartier34067262017-04-06 13:55:46 -0700635 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800636 }
637 const DexFile::MethodId* method_id = dex_file->FindMethodId(
638 dex_file->GetTypeId(class_ref.type_index), *name_id, *proto_id);
639 if (method_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700640 LOG(WARNING) << "Could not find method_id: " << name;
Mathieu Chartier34067262017-04-06 13:55:46 -0700641 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800642 }
643
Mathieu Chartier34067262017-04-06 13:55:46 -0700644 return dex_file->GetIndexForMethodId(*method_id);
645 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800646
Mathieu Chartier34067262017-04-06 13:55:46 -0700647 // Given a method, return true if the method has a single INVOKE_VIRTUAL in its byte code.
648 // Upon success it returns true and stores the method index and the invoke dex pc
649 // in the output parameters.
650 // The format of the method spec is "inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
651 //
652 // TODO(calin): support INVOKE_INTERFACE and the range variants.
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700653 bool HasSingleInvoke(const TypeReference& class_ref,
Mathieu Chartier34067262017-04-06 13:55:46 -0700654 uint16_t method_index,
655 /*out*/uint32_t* dex_pc) {
656 const DexFile* dex_file = class_ref.dex_file;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800657 uint32_t offset = dex_file->FindCodeItemOffset(
658 *dex_file->FindClassDef(class_ref.type_index),
Mathieu Chartier34067262017-04-06 13:55:46 -0700659 method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800660 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(offset);
661
662 bool found_invoke = false;
663 for (CodeItemIterator it(*code_item); !it.Done(); it.Advance()) {
664 if (it.CurrentInstruction().Opcode() == Instruction::INVOKE_VIRTUAL) {
665 if (found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700666 LOG(ERROR) << "Multiple invoke INVOKE_VIRTUAL found: "
667 << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800668 return false;
669 }
670 found_invoke = true;
671 *dex_pc = it.CurrentDexPc();
672 }
673 }
674 if (!found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700675 LOG(ERROR) << "Could not find any INVOKE_VIRTUAL: " << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800676 }
677 return found_invoke;
678 }
679
680 // Process a line defining a class or a method and its inline caches.
681 // Upon success return true and add the class or the method info to profile.
Calin Juravle589e71e2017-03-03 16:05:05 -0800682 // The possible line formats are:
683 // "LJustTheCass;".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800684 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
Calin Juravle08556882017-05-26 16:40:45 -0700685 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,invalid_class".
Calin Juravle589e71e2017-03-03 16:05:05 -0800686 // "LTestInline;->inlineMissingTypes(LSuper;)I+missing_types".
687 // "LTestInline;->inlineNoInlineCaches(LSuper;)I".
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700688 // "LTestInline;->*".
Calin Juravle08556882017-05-26 16:40:45 -0700689 // "invalid_class".
690 // "LTestInline;->invalid_method".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800691 // The method and classes are searched only in the given dex files.
692 bool ProcessLine(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
693 const std::string& line,
694 /*out*/ProfileCompilationInfo* profile) {
695 std::string klass;
696 std::string method_str;
697 size_t method_sep_index = line.find(kMethodSep);
698 if (method_sep_index == std::string::npos) {
699 klass = line;
700 } else {
701 klass = line.substr(0, method_sep_index);
702 method_str = line.substr(method_sep_index + kMethodSep.size());
703 }
704
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700705 TypeReference class_ref;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800706 if (!FindClass(dex_files, klass, &class_ref)) {
Mathieu Chartier3f121342017-03-06 11:16:20 -0800707 LOG(WARNING) << "Could not find class: " << klass;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800708 return false;
709 }
710
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700711 if (method_str.empty() || method_str == kClassAllMethods) {
712 // Start by adding the class.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800713 std::set<DexCacheResolvedClasses> resolved_class_set;
714 const DexFile* dex_file = class_ref.dex_file;
715 const auto& dex_resolved_classes = resolved_class_set.emplace(
716 dex_file->GetLocation(),
717 dex_file->GetBaseLocation(),
718 dex_file->GetLocationChecksum());
719 dex_resolved_classes.first->AddClass(class_ref.type_index);
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700720 std::vector<ProfileMethodInfo> methods;
721 if (method_str == kClassAllMethods) {
722 // Add all of the methods.
723 const DexFile::ClassDef* class_def = dex_file->FindClassDef(class_ref.type_index);
724 const uint8_t* class_data = dex_file->GetClassData(*class_def);
725 if (class_data != nullptr) {
726 ClassDataItemIterator it(*dex_file, class_data);
727 while (it.HasNextStaticField() || it.HasNextInstanceField()) {
728 it.Next();
729 }
730 while (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
731 if (it.GetMethodCodeItemOffset() != 0) {
732 // Add all of the methods that have code to the profile.
733 const uint32_t method_idx = it.GetMemberIndex();
734 methods.push_back(ProfileMethodInfo(dex_file, method_idx));
735 }
736 it.Next();
737 }
738 }
739 }
740 profile->AddMethodsAndClasses(methods, resolved_class_set);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800741 return true;
742 }
743
744 // Process the method.
745 std::string method_spec;
746 std::vector<std::string> inline_cache_elems;
747
748 std::vector<std::string> method_elems;
Calin Juravle589e71e2017-03-03 16:05:05 -0800749 bool is_missing_types = false;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800750 Split(method_str, kProfileParsingInlineChacheSep, &method_elems);
751 if (method_elems.size() == 2) {
752 method_spec = method_elems[0];
Calin Juravle589e71e2017-03-03 16:05:05 -0800753 is_missing_types = method_elems[1] == kMissingTypesMarker;
754 if (!is_missing_types) {
755 Split(method_elems[1], kProfileParsingTypeSep, &inline_cache_elems);
756 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800757 } else if (method_elems.size() == 1) {
758 method_spec = method_elems[0];
759 } else {
760 LOG(ERROR) << "Invalid method line: " << line;
761 return false;
762 }
763
Mathieu Chartier34067262017-04-06 13:55:46 -0700764 const uint32_t method_index = FindMethodIndex(class_ref, method_spec);
765 if (method_index == DexFile::kDexNoIndex) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800766 return false;
767 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700768
769 std::vector<ProfileMethodInfo> pmi;
770 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
771 if (is_missing_types || !inline_cache_elems.empty()) {
772 uint32_t dex_pc;
773 if (!HasSingleInvoke(class_ref, method_index, &dex_pc)) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800774 return false;
775 }
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700776 std::vector<TypeReference> classes(inline_cache_elems.size());
Mathieu Chartier34067262017-04-06 13:55:46 -0700777 size_t class_it = 0;
778 for (const std::string& ic_class : inline_cache_elems) {
779 if (!FindClass(dex_files, ic_class, &(classes[class_it++]))) {
780 LOG(ERROR) << "Could not find class: " << ic_class;
781 return false;
782 }
783 }
784 inline_caches.emplace_back(dex_pc, is_missing_types, classes);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800785 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800786 pmi.emplace_back(class_ref.dex_file, method_index, inline_caches);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800787 profile->AddMethodsAndClasses(pmi, std::set<DexCacheResolvedClasses>());
788 return true;
789 }
790
791 // Creates a profile from a human friendly textual representation.
792 // The expected input format is:
793 // # Classes
794 // Ljava/lang/Comparable;
795 // Ljava/lang/Math;
796 // # Methods with inline caches
797 // LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;
798 // LTestInline;->noInlineCache(LSuper;)I
David Sehr7c80f2d2017-02-07 16:47:58 -0800799 int CreateProfile() {
David Sehr153da0e2017-02-15 08:54:51 -0800800 // Validate parameters for this command.
801 if (apk_files_.empty() && apks_fd_.empty()) {
802 Usage("APK files must be specified");
803 }
804 if (dex_locations_.empty()) {
805 Usage("DEX locations must be specified");
806 }
807 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
808 Usage("Reference profile must be specified with --reference-profile-file or "
809 "--reference-profile-file-fd");
810 }
811 if (!profile_files_.empty() || !profile_files_fd_.empty()) {
812 Usage("Profile must be specified with --reference-profile-file or "
813 "--reference-profile-file-fd");
814 }
815 // for ZipArchive::OpenFromFd
816 MemMap::Init();
David Sehr7c80f2d2017-02-07 16:47:58 -0800817 // Open the profile output file if needed.
818 int fd = reference_profile_file_fd_;
819 if (!FdIsValid(fd)) {
820 CHECK(!reference_profile_file_.empty());
821 fd = open(reference_profile_file_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
822 if (fd < 0) {
823 LOG(ERROR) << "Cannot open " << reference_profile_file_ << strerror(errno);
824 return -1;
825 }
826 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800827 // Read the user-specified list of classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800828 std::unique_ptr<std::unordered_set<std::string>>
Calin Juravlee0ac1152017-02-13 19:03:47 -0800829 user_lines(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
David Sehr7c80f2d2017-02-07 16:47:58 -0800830 create_profile_from_file_.c_str(), nullptr)); // No post-processing.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800831
832 // Open the dex files to look up classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800833 std::vector<std::unique_ptr<const DexFile>> dex_files;
834 OpenApkFilesFromLocations(&dex_files);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800835
836 // Process the lines one by one and add the successful ones to the profile.
David Sehr7c80f2d2017-02-07 16:47:58 -0800837 ProfileCompilationInfo info;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800838
839 for (const auto& line : *user_lines) {
840 ProcessLine(dex_files, line, &info);
841 }
842
David Sehr7c80f2d2017-02-07 16:47:58 -0800843 // Write the profile file.
844 CHECK(info.Save(fd));
845 if (close(fd) < 0) {
846 PLOG(WARNING) << "Failed to close descriptor";
847 }
848 return 0;
849 }
850
851 bool ShouldCreateProfile() {
852 return !create_profile_from_file_.empty();
853 }
854
Calin Juravle7bcdb532016-06-07 16:14:47 +0100855 int GenerateTestProfile() {
David Sehr153da0e2017-02-15 08:54:51 -0800856 // Validate parameters for this command.
857 if (test_profile_method_ratio_ > 100) {
858 Usage("Invalid ratio for --generate-test-profile-method-ratio");
859 }
860 if (test_profile_class_ratio_ > 100) {
861 Usage("Invalid ratio for --generate-test-profile-class-ratio");
862 }
Jeff Haof0a31f82017-03-27 15:50:37 -0700863 // If given APK files or DEX locations, check that they're ok.
864 if (!apk_files_.empty() || !apks_fd_.empty() || !dex_locations_.empty()) {
865 if (apk_files_.empty() && apks_fd_.empty()) {
866 Usage("APK files must be specified when passing DEX locations to --generate-test-profile");
867 }
868 if (dex_locations_.empty()) {
869 Usage("DEX locations must be specified when passing APK files to --generate-test-profile");
870 }
871 }
David Sehr153da0e2017-02-15 08:54:51 -0800872 // ShouldGenerateTestProfile confirms !test_profile_.empty().
George Burgess IV71f77262016-10-25 13:08:17 -0700873 int profile_test_fd = open(test_profile_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
Calin Juravle7bcdb532016-06-07 16:14:47 +0100874 if (profile_test_fd < 0) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800875 LOG(ERROR) << "Cannot open " << test_profile_ << strerror(errno);
Calin Juravle7bcdb532016-06-07 16:14:47 +0100876 return -1;
877 }
Jeff Haof0a31f82017-03-27 15:50:37 -0700878 bool result;
879 if (apk_files_.empty() && apks_fd_.empty() && dex_locations_.empty()) {
880 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
881 test_profile_num_dex_,
882 test_profile_method_ratio_,
883 test_profile_class_ratio_,
884 test_profile_seed_);
885 } else {
886 // Initialize MemMap for ZipArchive::OpenFromFd.
887 MemMap::Init();
888 // Open the dex files to look up classes and methods.
889 std::vector<std::unique_ptr<const DexFile>> dex_files;
890 OpenApkFilesFromLocations(&dex_files);
891 // Create a random profile file based on the set of dex files.
892 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
893 dex_files,
894 test_profile_seed_);
895 }
Calin Juravle7bcdb532016-06-07 16:14:47 +0100896 close(profile_test_fd); // ignore close result.
897 return result ? 0 : -1;
898 }
899
900 bool ShouldGenerateTestProfile() {
901 return !test_profile_.empty();
902 }
903
Calin Juravle2e2db782016-02-23 12:00:03 +0000904 private:
905 static void ParseFdForCollection(const StringPiece& option,
906 const char* arg_name,
907 std::vector<int>* fds) {
908 int fd;
909 ParseUintOption(option, arg_name, &fd, Usage);
910 fds->push_back(fd);
911 }
912
913 static void CloseAllFds(const std::vector<int>& fds, const char* descriptor) {
914 for (size_t i = 0; i < fds.size(); i++) {
915 if (close(fds[i]) < 0) {
916 PLOG(WARNING) << "Failed to close descriptor for " << descriptor << " at index " << i;
917 }
918 }
919 }
920
921 void LogCompletionTime() {
David Sehr52683cf2016-05-05 09:02:38 -0700922 static constexpr uint64_t kLogThresholdTime = MsToNs(100); // 100ms
923 uint64_t time_taken = NanoTime() - start_ns_;
David Sehred793012016-05-05 13:39:43 -0700924 if (time_taken > kLogThresholdTime) {
David Sehrd8557182016-05-06 12:29:35 -0700925 LOG(WARNING) << "profman took " << PrettyDuration(time_taken);
David Sehred793012016-05-05 13:39:43 -0700926 }
Calin Juravle2e2db782016-02-23 12:00:03 +0000927 }
928
929 std::vector<std::string> profile_files_;
930 std::vector<int> profile_files_fd_;
David Sehr546d24f2016-06-02 10:46:19 -0700931 std::vector<std::string> dex_locations_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800932 std::vector<std::string> apk_files_;
David Sehr546d24f2016-06-02 10:46:19 -0700933 std::vector<int> apks_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +0000934 std::string reference_profile_file_;
935 int reference_profile_file_fd_;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700936 bool dump_only_;
Mathieu Chartier34067262017-04-06 13:55:46 -0700937 bool dump_classes_and_methods_;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700938 int dump_output_to_fd_;
Calin Juravle7bcdb532016-06-07 16:14:47 +0100939 std::string test_profile_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800940 std::string create_profile_from_file_;
Calin Juravle7bcdb532016-06-07 16:14:47 +0100941 uint16_t test_profile_num_dex_;
942 uint16_t test_profile_method_ratio_;
943 uint16_t test_profile_class_ratio_;
Jeff Haof0a31f82017-03-27 15:50:37 -0700944 uint32_t test_profile_seed_;
Calin Juravle2e2db782016-02-23 12:00:03 +0000945 uint64_t start_ns_;
946};
947
948// See ProfileAssistant::ProcessingResult for return codes.
949static int profman(int argc, char** argv) {
950 ProfMan profman;
951
952 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
953 profman.ParseArgs(argc, argv);
954
Calin Juravle7bcdb532016-06-07 16:14:47 +0100955 if (profman.ShouldGenerateTestProfile()) {
956 return profman.GenerateTestProfile();
957 }
Calin Juravle876f3502016-03-24 16:16:34 +0000958 if (profman.ShouldOnlyDumpProfile()) {
959 return profman.DumpProfileInfo();
960 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700961 if (profman.ShouldOnlyDumpClassesAndMethods()) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800962 return profman.DumpClasses();
963 }
964 if (profman.ShouldCreateProfile()) {
965 return profman.CreateProfile();
966 }
Calin Juravle2e2db782016-02-23 12:00:03 +0000967 // Process profile information and assess if we need to do a profile guided compilation.
968 // This operation involves I/O.
969 return profman.ProcessProfiles();
970}
971
972} // namespace art
973
974int main(int argc, char **argv) {
975 return art::profman(argc, argv);
976}
977