blob: b46378e354cc1e1a8ca35e4fa428a971c70fa498 [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"
Mathieu Chartierea650f32017-05-24 12:04:13 -070046#include "type_reference.h"
David Sehr546d24f2016-06-02 10:46:19 -070047#include "zip_archive.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000048
49namespace art {
50
51static int original_argc;
52static char** original_argv;
53
54static std::string CommandLine() {
55 std::vector<std::string> command;
56 for (int i = 0; i < original_argc; ++i) {
57 command.push_back(original_argv[i]);
58 }
Andreas Gampe9186ced2016-12-12 14:28:21 -080059 return android::base::Join(command, ' ');
Calin Juravle2e2db782016-02-23 12:00:03 +000060}
61
David Sehr4fcdd6d2016-05-24 14:52:31 -070062static constexpr int kInvalidFd = -1;
63
64static bool FdIsValid(int fd) {
65 return fd != kInvalidFd;
66}
67
Calin Juravle2e2db782016-02-23 12:00:03 +000068static void UsageErrorV(const char* fmt, va_list ap) {
69 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080070 android::base::StringAppendV(&error, fmt, ap);
Calin Juravle2e2db782016-02-23 12:00:03 +000071 LOG(ERROR) << error;
72}
73
74static void UsageError(const char* fmt, ...) {
75 va_list ap;
76 va_start(ap, fmt);
77 UsageErrorV(fmt, ap);
78 va_end(ap);
79}
80
81NO_RETURN static void Usage(const char *fmt, ...) {
82 va_list ap;
83 va_start(ap, fmt);
84 UsageErrorV(fmt, ap);
85 va_end(ap);
86
87 UsageError("Command: %s", CommandLine().c_str());
88 UsageError("Usage: profman [options]...");
89 UsageError("");
David Sehr4fcdd6d2016-05-24 14:52:31 -070090 UsageError(" --dump-only: dumps the content of the specified profile files");
91 UsageError(" to standard output (default) in a human readable form.");
92 UsageError("");
David Sehr7c80f2d2017-02-07 16:47:58 -080093 UsageError(" --dump-output-to-fd=<number>: redirects --dump-only output to a file descriptor.");
94 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -070095 UsageError(" --dump-classes-and-methods: dumps a sorted list of classes and methods that are");
96 UsageError(" in the specified profile file to standard output (default) in a human");
97 UsageError(" readable form. The output is valid input for --create-profile-from");
Calin Juravle876f3502016-03-24 16:16:34 +000098 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +000099 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
100 UsageError(" Can be specified multiple time, in which case the data from the different");
101 UsageError(" profiles will be aggregated.");
102 UsageError("");
103 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
104 UsageError(" Cannot be used together with --profile-file.");
105 UsageError("");
106 UsageError(" --reference-profile-file=<filename>: specify a reference profile.");
107 UsageError(" The data in this file will be compared with the data obtained by merging");
108 UsageError(" all the files specified with --profile-file or --profile-file-fd.");
109 UsageError(" If the exit code is EXIT_COMPILE then all --profile-file will be merged into");
110 UsageError(" --reference-profile-file. ");
111 UsageError("");
112 UsageError(" --reference-profile-file-fd=<number>: same as --reference-profile-file but");
113 UsageError(" accepts a file descriptor. Cannot be used together with");
114 UsageError(" --reference-profile-file.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800115 UsageError("");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100116 UsageError(" --generate-test-profile=<filename>: generates a random profile file for testing.");
117 UsageError(" --generate-test-profile-num-dex=<number>: number of dex files that should be");
118 UsageError(" included in the generated profile. Defaults to 20.");
119 UsageError(" --generate-test-profile-method-ratio=<number>: the percentage from the maximum");
120 UsageError(" number of methods that should be generated. Defaults to 5.");
121 UsageError(" --generate-test-profile-class-ratio=<number>: the percentage from the maximum");
122 UsageError(" number of classes that should be generated. Defaults to 5.");
Jeff Haof0a31f82017-03-27 15:50:37 -0700123 UsageError(" --generate-test-profile-seed=<number>: seed for random number generator used when");
124 UsageError(" generating random test profiles. Defaults to using NanoTime.");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100125 UsageError("");
Mathieu Chartier34067262017-04-06 13:55:46 -0700126 UsageError(" --create-profile-from=<filename>: creates a profile from a list of classes and");
127 UsageError(" methods.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800128 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700129 UsageError(" --dex-location=<string>: location string to use with corresponding");
130 UsageError(" apk-fd to find dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700131 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700132 UsageError(" --apk-fd=<number>: file descriptor containing an open APK to");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700133 UsageError(" search for dex files");
David Sehr7c80f2d2017-02-07 16:47:58 -0800134 UsageError(" --apk-=<filename>: an APK to search for dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700135 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000136
137 exit(EXIT_FAILURE);
138}
139
Calin Juravle7bcdb532016-06-07 16:14:47 +0100140// Note: make sure you update the Usage if you change these values.
141static constexpr uint16_t kDefaultTestProfileNumDex = 20;
142static constexpr uint16_t kDefaultTestProfileMethodRatio = 5;
143static constexpr uint16_t kDefaultTestProfileClassRatio = 5;
144
Calin Juravlee0ac1152017-02-13 19:03:47 -0800145// Separators used when parsing human friendly representation of profiles.
146static const std::string kMethodSep = "->";
Calin Juravle589e71e2017-03-03 16:05:05 -0800147static const std::string kMissingTypesMarker = "missing_types";
Calin Juravle08556882017-05-26 16:40:45 -0700148static const std::string kInvalidClassDescriptor = "invalid_class";
149static const std::string kInvalidMethod = "invalid_method";
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700150static const std::string kClassAllMethods = "*";
Calin Juravlee0ac1152017-02-13 19:03:47 -0800151static constexpr char kProfileParsingInlineChacheSep = '+';
152static constexpr char kProfileParsingTypeSep = ',';
153static constexpr char kProfileParsingFirstCharInSignature = '(';
Mathieu Chartierea650f32017-05-24 12:04:13 -0700154static constexpr char kMethodFlagStringHot = 'H';
155static constexpr char kMethodFlagStringStartup = 'S';
156static constexpr char kMethodFlagStringPostStartup = 'P';
Calin Juravlee0ac1152017-02-13 19:03:47 -0800157
158// TODO(calin): This class has grown too much from its initial design. Split the functionality
159// into smaller, more contained pieces.
Calin Juravle2e2db782016-02-23 12:00:03 +0000160class ProfMan FINAL {
161 public:
162 ProfMan() :
David Sehr4fcdd6d2016-05-24 14:52:31 -0700163 reference_profile_file_fd_(kInvalidFd),
164 dump_only_(false),
Mathieu Chartier34067262017-04-06 13:55:46 -0700165 dump_classes_and_methods_(false),
David Sehr4fcdd6d2016-05-24 14:52:31 -0700166 dump_output_to_fd_(kInvalidFd),
Calin Juravle7bcdb532016-06-07 16:14:47 +0100167 test_profile_num_dex_(kDefaultTestProfileNumDex),
168 test_profile_method_ratio_(kDefaultTestProfileMethodRatio),
169 test_profile_class_ratio_(kDefaultTestProfileClassRatio),
Jeff Haof0a31f82017-03-27 15:50:37 -0700170 test_profile_seed_(NanoTime()),
Calin Juravle2e2db782016-02-23 12:00:03 +0000171 start_ns_(NanoTime()) {}
172
173 ~ProfMan() {
174 LogCompletionTime();
175 }
176
177 void ParseArgs(int argc, char **argv) {
178 original_argc = argc;
179 original_argv = argv;
180
David Sehrf57589f2016-10-17 10:09:33 -0700181 InitLogging(argv, Runtime::Aborter);
Calin Juravle2e2db782016-02-23 12:00:03 +0000182
183 // Skip over the command name.
184 argv++;
185 argc--;
186
187 if (argc == 0) {
188 Usage("No arguments specified");
189 }
190
191 for (int i = 0; i < argc; ++i) {
192 const StringPiece option(argv[i]);
193 const bool log_options = false;
194 if (log_options) {
Calin Juravle876f3502016-03-24 16:16:34 +0000195 LOG(INFO) << "profman: option[" << i << "]=" << argv[i];
Calin Juravle2e2db782016-02-23 12:00:03 +0000196 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700197 if (option == "--dump-only") {
198 dump_only_ = true;
Mathieu Chartier34067262017-04-06 13:55:46 -0700199 } else if (option == "--dump-classes-and-methods") {
200 dump_classes_and_methods_ = true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800201 } else if (option.starts_with("--create-profile-from=")) {
202 create_profile_from_file_ = option.substr(strlen("--create-profile-from=")).ToString();
David Sehr4fcdd6d2016-05-24 14:52:31 -0700203 } else if (option.starts_with("--dump-output-to-fd=")) {
204 ParseUintOption(option, "--dump-output-to-fd", &dump_output_to_fd_, Usage);
Calin Juravle876f3502016-03-24 16:16:34 +0000205 } else if (option.starts_with("--profile-file=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000206 profile_files_.push_back(option.substr(strlen("--profile-file=")).ToString());
207 } else if (option.starts_with("--profile-file-fd=")) {
208 ParseFdForCollection(option, "--profile-file-fd", &profile_files_fd_);
209 } else if (option.starts_with("--reference-profile-file=")) {
210 reference_profile_file_ = option.substr(strlen("--reference-profile-file=")).ToString();
211 } else if (option.starts_with("--reference-profile-file-fd=")) {
212 ParseUintOption(option, "--reference-profile-file-fd", &reference_profile_file_fd_, Usage);
David Sehr546d24f2016-06-02 10:46:19 -0700213 } else if (option.starts_with("--dex-location=")) {
214 dex_locations_.push_back(option.substr(strlen("--dex-location=")).ToString());
215 } else if (option.starts_with("--apk-fd=")) {
216 ParseFdForCollection(option, "--apk-fd", &apks_fd_);
David Sehr7c80f2d2017-02-07 16:47:58 -0800217 } else if (option.starts_with("--apk=")) {
218 apk_files_.push_back(option.substr(strlen("--apk=")).ToString());
Calin Juravle7bcdb532016-06-07 16:14:47 +0100219 } else if (option.starts_with("--generate-test-profile=")) {
220 test_profile_ = option.substr(strlen("--generate-test-profile=")).ToString();
221 } else if (option.starts_with("--generate-test-profile-num-dex=")) {
222 ParseUintOption(option,
223 "--generate-test-profile-num-dex",
224 &test_profile_num_dex_,
225 Usage);
226 } else if (option.starts_with("--generate-test-profile-method-ratio")) {
227 ParseUintOption(option,
228 "--generate-test-profile-method-ratio",
229 &test_profile_method_ratio_,
230 Usage);
231 } else if (option.starts_with("--generate-test-profile-class-ratio")) {
232 ParseUintOption(option,
233 "--generate-test-profile-class-ratio",
234 &test_profile_class_ratio_,
235 Usage);
Jeff Haof0a31f82017-03-27 15:50:37 -0700236 } else if (option.starts_with("--generate-test-profile-seed=")) {
237 ParseUintOption(option, "--generate-test-profile-seed", &test_profile_seed_, Usage);
Calin Juravle2e2db782016-02-23 12:00:03 +0000238 } else {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700239 Usage("Unknown argument '%s'", option.data());
Calin Juravle2e2db782016-02-23 12:00:03 +0000240 }
241 }
242
David Sehr153da0e2017-02-15 08:54:51 -0800243 // Validate global consistency between file/fd options.
Calin Juravle2e2db782016-02-23 12:00:03 +0000244 if (!profile_files_.empty() && !profile_files_fd_.empty()) {
245 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
246 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700247 if (!reference_profile_file_.empty() && FdIsValid(reference_profile_file_fd_)) {
248 Usage("Reference profile should not be specified with both "
249 "--reference-profile-file-fd and --reference-profile-file");
250 }
David Sehr153da0e2017-02-15 08:54:51 -0800251 if (!apk_files_.empty() && !apks_fd_.empty()) {
252 Usage("APK files should not be specified with both --apk-fd and --apk");
Calin Juravle2e2db782016-02-23 12:00:03 +0000253 }
254 }
255
256 ProfileAssistant::ProcessingResult ProcessProfiles() {
David Sehr153da0e2017-02-15 08:54:51 -0800257 // Validate that at least one profile file was passed, as well as a reference profile.
258 if (profile_files_.empty() && profile_files_fd_.empty()) {
259 Usage("No profile files specified.");
260 }
261 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
262 Usage("No reference profile file specified.");
263 }
264 if ((!profile_files_.empty() && FdIsValid(reference_profile_file_fd_)) ||
265 (!profile_files_fd_.empty() && !FdIsValid(reference_profile_file_fd_))) {
266 Usage("Options --profile-file-fd and --reference-profile-file-fd "
267 "should only be used together");
268 }
Calin Juravle2e2db782016-02-23 12:00:03 +0000269 ProfileAssistant::ProcessingResult result;
270 if (profile_files_.empty()) {
271 // The file doesn't need to be flushed here (ProcessProfiles will do it)
272 // so don't check the usage.
273 File file(reference_profile_file_fd_, false);
274 result = ProfileAssistant::ProcessProfiles(profile_files_fd_, reference_profile_file_fd_);
275 CloseAllFds(profile_files_fd_, "profile_files_fd_");
276 } else {
277 result = ProfileAssistant::ProcessProfiles(profile_files_, reference_profile_file_);
278 }
279 return result;
280 }
281
David Sehr7c80f2d2017-02-07 16:47:58 -0800282 void OpenApkFilesFromLocations(std::vector<std::unique_ptr<const DexFile>>* dex_files) {
283 bool use_apk_fd_list = !apks_fd_.empty();
284 if (use_apk_fd_list) {
David Sehr153da0e2017-02-15 08:54:51 -0800285 // Get the APKs from the collection of FDs.
David Sehr7c80f2d2017-02-07 16:47:58 -0800286 CHECK_EQ(dex_locations_.size(), apks_fd_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800287 } else if (!apk_files_.empty()) {
288 // Get the APKs from the collection of filenames.
David Sehr7c80f2d2017-02-07 16:47:58 -0800289 CHECK_EQ(dex_locations_.size(), apk_files_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800290 } else {
291 // No APKs were specified.
292 CHECK(dex_locations_.empty());
293 return;
David Sehr7c80f2d2017-02-07 16:47:58 -0800294 }
295 static constexpr bool kVerifyChecksum = true;
296 for (size_t i = 0; i < dex_locations_.size(); ++i) {
297 std::string error_msg;
298 std::vector<std::unique_ptr<const DexFile>> dex_files_for_location;
299 if (use_apk_fd_list) {
300 if (DexFile::OpenZip(apks_fd_[i],
301 dex_locations_[i],
302 kVerifyChecksum,
303 &error_msg,
304 &dex_files_for_location)) {
305 } else {
306 LOG(WARNING) << "OpenZip failed for '" << dex_locations_[i] << "' " << error_msg;
307 continue;
308 }
309 } else {
310 if (DexFile::Open(apk_files_[i].c_str(),
311 dex_locations_[i],
312 kVerifyChecksum,
313 &error_msg,
314 &dex_files_for_location)) {
315 } else {
316 LOG(WARNING) << "Open failed for '" << dex_locations_[i] << "' " << error_msg;
317 continue;
318 }
319 }
320 for (std::unique_ptr<const DexFile>& dex_file : dex_files_for_location) {
321 dex_files->emplace_back(std::move(dex_file));
322 }
323 }
324 }
325
David Sehrb18991b2017-02-08 20:58:10 -0800326 int DumpOneProfile(const std::string& banner,
327 const std::string& filename,
328 int fd,
329 const std::vector<std::unique_ptr<const DexFile>>* dex_files,
330 std::string* dump) {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700331 if (!filename.empty()) {
332 fd = open(filename.c_str(), O_RDWR);
333 if (fd < 0) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800334 LOG(ERROR) << "Cannot open " << filename << strerror(errno);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700335 return -1;
336 }
Calin Juravle876f3502016-03-24 16:16:34 +0000337 }
338 ProfileCompilationInfo info;
339 if (!info.Load(fd)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800340 LOG(ERROR) << "Cannot load profile info from fd=" << fd << "\n";
Calin Juravle876f3502016-03-24 16:16:34 +0000341 return -1;
342 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700343 std::string this_dump = banner + "\n" + info.DumpInfo(dex_files) + "\n";
344 *dump += this_dump;
345 if (close(fd) < 0) {
346 PLOG(WARNING) << "Failed to close descriptor";
347 }
348 return 0;
349 }
350
351 int DumpProfileInfo() {
David Sehr153da0e2017-02-15 08:54:51 -0800352 // Validate that at least one profile file or reference was specified.
353 if (profile_files_.empty() && profile_files_fd_.empty() &&
354 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
355 Usage("No profile files or reference profile specified.");
356 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700357 static const char* kEmptyString = "";
David Sehr546d24f2016-06-02 10:46:19 -0700358 static const char* kOrdinaryProfile = "=== profile ===";
359 static const char* kReferenceProfile = "=== reference profile ===";
360
361 // Open apk/zip files and and read dex files.
362 MemMap::Init(); // for ZipArchive::OpenFromFd
David Sehrb18991b2017-02-08 20:58:10 -0800363 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7c80f2d2017-02-07 16:47:58 -0800364 OpenApkFilesFromLocations(&dex_files);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700365 std::string dump;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700366 // Dump individual profile files.
367 if (!profile_files_fd_.empty()) {
368 for (int profile_file_fd : profile_files_fd_) {
David Sehr546d24f2016-06-02 10:46:19 -0700369 int ret = DumpOneProfile(kOrdinaryProfile,
370 kEmptyString,
371 profile_file_fd,
372 &dex_files,
373 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700374 if (ret != 0) {
375 return ret;
376 }
377 }
378 }
379 if (!profile_files_.empty()) {
380 for (const std::string& profile_file : profile_files_) {
David Sehr546d24f2016-06-02 10:46:19 -0700381 int ret = DumpOneProfile(kOrdinaryProfile, profile_file, kInvalidFd, &dex_files, &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700382 if (ret != 0) {
383 return ret;
384 }
385 }
386 }
387 // Dump reference profile file.
388 if (FdIsValid(reference_profile_file_fd_)) {
David Sehr546d24f2016-06-02 10:46:19 -0700389 int ret = DumpOneProfile(kReferenceProfile,
390 kEmptyString,
391 reference_profile_file_fd_,
392 &dex_files,
393 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700394 if (ret != 0) {
395 return ret;
396 }
397 }
398 if (!reference_profile_file_.empty()) {
David Sehr546d24f2016-06-02 10:46:19 -0700399 int ret = DumpOneProfile(kReferenceProfile,
400 reference_profile_file_,
401 kInvalidFd,
402 &dex_files,
David Sehr4fcdd6d2016-05-24 14:52:31 -0700403 &dump);
404 if (ret != 0) {
405 return ret;
406 }
407 }
408 if (!FdIsValid(dump_output_to_fd_)) {
409 std::cout << dump;
410 } else {
411 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
412 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
413 return -1;
414 }
415 }
Calin Juravle876f3502016-03-24 16:16:34 +0000416 return 0;
417 }
418
419 bool ShouldOnlyDumpProfile() {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700420 return dump_only_;
Calin Juravle876f3502016-03-24 16:16:34 +0000421 }
422
Mathieu Chartier34067262017-04-06 13:55:46 -0700423 bool GetClassNamesAndMethods(int fd,
424 std::vector<std::unique_ptr<const DexFile>>* dex_files,
425 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800426 ProfileCompilationInfo profile_info;
427 if (!profile_info.Load(fd)) {
428 LOG(ERROR) << "Cannot load profile info";
429 return false;
430 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700431 for (const std::unique_ptr<const DexFile>& dex_file : *dex_files) {
432 std::set<dex::TypeIndex> class_types;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700433 std::set<uint16_t> hot_methods;
434 std::set<uint16_t> startup_methods;
435 std::set<uint16_t> post_startup_methods;
436 std::set<uint16_t> combined_methods;
437 if (profile_info.GetClassesAndMethods(*dex_file.get(),
438 &class_types,
439 &hot_methods,
440 &startup_methods,
441 &post_startup_methods)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700442 for (const dex::TypeIndex& type_index : class_types) {
443 const DexFile::TypeId& type_id = dex_file->GetTypeId(type_index);
444 out_lines->insert(std::string(dex_file->GetTypeDescriptor(type_id)));
445 }
Mathieu Chartierea650f32017-05-24 12:04:13 -0700446 combined_methods = hot_methods;
447 combined_methods.insert(startup_methods.begin(), startup_methods.end());
448 combined_methods.insert(post_startup_methods.begin(), post_startup_methods.end());
449 for (uint16_t dex_method_idx : combined_methods) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700450 const DexFile::MethodId& id = dex_file->GetMethodId(dex_method_idx);
451 std::string signature_string(dex_file->GetMethodSignature(id).ToString());
452 std::string type_string(dex_file->GetTypeDescriptor(dex_file->GetTypeId(id.class_idx_)));
453 std::string method_name(dex_file->GetMethodName(id));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700454 std::string flags_string;
455 if (hot_methods.find(dex_method_idx) != hot_methods.end()) {
456 flags_string += kMethodFlagStringHot;
457 }
458 if (startup_methods.find(dex_method_idx) != startup_methods.end()) {
459 flags_string += kMethodFlagStringStartup;
460 }
461 if (post_startup_methods.find(dex_method_idx) != post_startup_methods.end()) {
462 flags_string += kMethodFlagStringPostStartup;
463 }
464 out_lines->insert(flags_string +
465 type_string +
466 kMethodSep +
467 method_name +
468 signature_string);
Mathieu Chartier34067262017-04-06 13:55:46 -0700469 }
470 }
471 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800472 return true;
473 }
474
Mathieu Chartier34067262017-04-06 13:55:46 -0700475 bool GetClassNamesAndMethods(const std::string& profile_file,
476 std::vector<std::unique_ptr<const DexFile>>* dex_files,
477 std::set<std::string>* out_lines) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800478 int fd = open(profile_file.c_str(), O_RDONLY);
479 if (!FdIsValid(fd)) {
480 LOG(ERROR) << "Cannot open " << profile_file << strerror(errno);
481 return false;
482 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700483 if (!GetClassNamesAndMethods(fd, dex_files, out_lines)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800484 return false;
485 }
486 if (close(fd) < 0) {
487 PLOG(WARNING) << "Failed to close descriptor";
488 }
489 return true;
490 }
491
Mathieu Chartierea650f32017-05-24 12:04:13 -0700492 int DumpClassesAndMethods() {
David Sehr153da0e2017-02-15 08:54:51 -0800493 // Validate that at least one profile file or reference was specified.
494 if (profile_files_.empty() && profile_files_fd_.empty() &&
495 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
496 Usage("No profile files or reference profile specified.");
497 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800498 // Open apk/zip files and and read dex files.
499 MemMap::Init(); // for ZipArchive::OpenFromFd
500 // Open the dex files to get the names for classes.
501 std::vector<std::unique_ptr<const DexFile>> dex_files;
502 OpenApkFilesFromLocations(&dex_files);
503 // Build a vector of class names from individual profile files.
504 std::set<std::string> class_names;
505 if (!profile_files_fd_.empty()) {
506 for (int profile_file_fd : profile_files_fd_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700507 if (!GetClassNamesAndMethods(profile_file_fd, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800508 return -1;
509 }
510 }
511 }
512 if (!profile_files_.empty()) {
513 for (const std::string& profile_file : profile_files_) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700514 if (!GetClassNamesAndMethods(profile_file, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800515 return -1;
516 }
517 }
518 }
519 // Concatenate class names from reference profile file.
520 if (FdIsValid(reference_profile_file_fd_)) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700521 if (!GetClassNamesAndMethods(reference_profile_file_fd_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800522 return -1;
523 }
524 }
525 if (!reference_profile_file_.empty()) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700526 if (!GetClassNamesAndMethods(reference_profile_file_, &dex_files, &class_names)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800527 return -1;
528 }
529 }
530 // Dump the class names.
531 std::string dump;
532 for (const std::string& class_name : class_names) {
533 dump += class_name + std::string("\n");
534 }
535 if (!FdIsValid(dump_output_to_fd_)) {
536 std::cout << dump;
537 } else {
538 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
539 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
540 return -1;
541 }
542 }
543 return 0;
544 }
545
Mathieu Chartier34067262017-04-06 13:55:46 -0700546 bool ShouldOnlyDumpClassesAndMethods() {
547 return dump_classes_and_methods_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800548 }
549
550 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
551 // the given function.
552 template <typename T>
553 static T* ReadCommentedInputFromFile(
554 const char* input_filename, std::function<std::string(const char*)>* process) {
555 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
556 if (input_file.get() == nullptr) {
557 LOG(ERROR) << "Failed to open input file " << input_filename;
558 return nullptr;
559 }
560 std::unique_ptr<T> result(
561 ReadCommentedInputStream<T>(*input_file, process));
562 input_file->close();
563 return result.release();
564 }
565
566 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
567 // with the given function.
568 template <typename T>
569 static T* ReadCommentedInputStream(
570 std::istream& in_stream,
571 std::function<std::string(const char*)>* process) {
572 std::unique_ptr<T> output(new T());
573 while (in_stream.good()) {
574 std::string dot;
575 std::getline(in_stream, dot);
576 if (android::base::StartsWith(dot, "#") || dot.empty()) {
577 continue;
578 }
579 if (process != nullptr) {
580 std::string descriptor((*process)(dot.c_str()));
581 output->insert(output->end(), descriptor);
582 } else {
583 output->insert(output->end(), dot);
584 }
585 }
586 return output.release();
587 }
588
Calin Juravlee0ac1152017-02-13 19:03:47 -0800589 // Find class klass_descriptor in the given dex_files and store its reference
590 // in the out parameter class_ref.
591 // Return true if the definition of the class was found in any of the dex_files.
592 bool FindClass(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
593 const std::string& klass_descriptor,
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700594 /*out*/TypeReference* class_ref) {
Calin Juravle08556882017-05-26 16:40:45 -0700595 constexpr uint16_t kInvalidTypeIndex = std::numeric_limits<uint16_t>::max() - 1;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800596 for (const std::unique_ptr<const DexFile>& dex_file_ptr : dex_files) {
597 const DexFile* dex_file = dex_file_ptr.get();
Calin Juravle08556882017-05-26 16:40:45 -0700598 if (klass_descriptor == kInvalidClassDescriptor) {
599 if (kInvalidTypeIndex >= dex_file->NumTypeIds()) {
600 // The dex file does not contain all possible type ids which leaves us room
601 // to add an "invalid" type id.
602 class_ref->dex_file = dex_file;
603 class_ref->type_index = dex::TypeIndex(kInvalidTypeIndex);
604 return true;
605 } else {
606 // The dex file contains all possible type ids. We don't have any free type id
607 // that we can use as invalid.
608 continue;
609 }
610 }
611
Calin Juravlee0ac1152017-02-13 19:03:47 -0800612 const DexFile::TypeId* type_id = dex_file->FindTypeId(klass_descriptor.c_str());
613 if (type_id == nullptr) {
614 continue;
615 }
616 dex::TypeIndex type_index = dex_file->GetIndexForTypeId(*type_id);
617 if (dex_file->FindClassDef(type_index) == nullptr) {
618 // Class is only referenced in the current dex file but not defined in it.
619 continue;
620 }
621 class_ref->dex_file = dex_file;
622 class_ref->type_index = type_index;
623 return true;
624 }
625 return false;
626 }
627
Mathieu Chartier34067262017-04-06 13:55:46 -0700628 // Find the method specified by method_spec in the class class_ref.
Calin Juravle08556882017-05-26 16:40:45 -0700629 uint32_t FindMethodIndex(const TypeReference& class_ref,
630 const std::string& method_spec) {
631 const DexFile* dex_file = class_ref.dex_file;
632 if (method_spec == kInvalidMethod) {
633 constexpr uint16_t kInvalidMethodIndex = std::numeric_limits<uint16_t>::max() - 1;
634 return kInvalidMethodIndex >= dex_file->NumMethodIds()
635 ? kInvalidMethodIndex
636 : DexFile::kDexNoIndex;
637 }
638
Calin Juravlee0ac1152017-02-13 19:03:47 -0800639 std::vector<std::string> name_and_signature;
640 Split(method_spec, kProfileParsingFirstCharInSignature, &name_and_signature);
641 if (name_and_signature.size() != 2) {
642 LOG(ERROR) << "Invalid method name and signature " << method_spec;
Calin Juravle08556882017-05-26 16:40:45 -0700643 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800644 }
Calin Juravle08556882017-05-26 16:40:45 -0700645
Calin Juravlee0ac1152017-02-13 19:03:47 -0800646 const std::string& name = name_and_signature[0];
647 const std::string& signature = kProfileParsingFirstCharInSignature + name_and_signature[1];
Calin Juravlee0ac1152017-02-13 19:03:47 -0800648
649 const DexFile::StringId* name_id = dex_file->FindStringId(name.c_str());
650 if (name_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700651 LOG(WARNING) << "Could not find name: " << name;
Mathieu Chartier34067262017-04-06 13:55:46 -0700652 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800653 }
654 dex::TypeIndex return_type_idx;
655 std::vector<dex::TypeIndex> param_type_idxs;
656 if (!dex_file->CreateTypeList(signature, &return_type_idx, &param_type_idxs)) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700657 LOG(WARNING) << "Could not create type list" << signature;
Mathieu Chartier34067262017-04-06 13:55:46 -0700658 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800659 }
660 const DexFile::ProtoId* proto_id = dex_file->FindProtoId(return_type_idx, param_type_idxs);
661 if (proto_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700662 LOG(WARNING) << "Could not find proto_id: " << name;
Mathieu Chartier34067262017-04-06 13:55:46 -0700663 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800664 }
665 const DexFile::MethodId* method_id = dex_file->FindMethodId(
666 dex_file->GetTypeId(class_ref.type_index), *name_id, *proto_id);
667 if (method_id == nullptr) {
Mathieu Chartier66aae3b2017-05-18 10:38:28 -0700668 LOG(WARNING) << "Could not find method_id: " << name;
Mathieu Chartier34067262017-04-06 13:55:46 -0700669 return DexFile::kDexNoIndex;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800670 }
671
Mathieu Chartier34067262017-04-06 13:55:46 -0700672 return dex_file->GetIndexForMethodId(*method_id);
673 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800674
Mathieu Chartier34067262017-04-06 13:55:46 -0700675 // Given a method, return true if the method has a single INVOKE_VIRTUAL in its byte code.
676 // Upon success it returns true and stores the method index and the invoke dex pc
677 // in the output parameters.
678 // The format of the method spec is "inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
679 //
680 // TODO(calin): support INVOKE_INTERFACE and the range variants.
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700681 bool HasSingleInvoke(const TypeReference& class_ref,
Mathieu Chartier34067262017-04-06 13:55:46 -0700682 uint16_t method_index,
683 /*out*/uint32_t* dex_pc) {
684 const DexFile* dex_file = class_ref.dex_file;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800685 uint32_t offset = dex_file->FindCodeItemOffset(
686 *dex_file->FindClassDef(class_ref.type_index),
Mathieu Chartier34067262017-04-06 13:55:46 -0700687 method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800688 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(offset);
689
690 bool found_invoke = false;
691 for (CodeItemIterator it(*code_item); !it.Done(); it.Advance()) {
692 if (it.CurrentInstruction().Opcode() == Instruction::INVOKE_VIRTUAL) {
693 if (found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700694 LOG(ERROR) << "Multiple invoke INVOKE_VIRTUAL found: "
695 << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800696 return false;
697 }
698 found_invoke = true;
699 *dex_pc = it.CurrentDexPc();
700 }
701 }
702 if (!found_invoke) {
Mathieu Chartier34067262017-04-06 13:55:46 -0700703 LOG(ERROR) << "Could not find any INVOKE_VIRTUAL: " << dex_file->PrettyMethod(method_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800704 }
705 return found_invoke;
706 }
707
708 // Process a line defining a class or a method and its inline caches.
709 // Upon success return true and add the class or the method info to profile.
Calin Juravle589e71e2017-03-03 16:05:05 -0800710 // The possible line formats are:
711 // "LJustTheCass;".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800712 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
Calin Juravle08556882017-05-26 16:40:45 -0700713 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,invalid_class".
Calin Juravle589e71e2017-03-03 16:05:05 -0800714 // "LTestInline;->inlineMissingTypes(LSuper;)I+missing_types".
715 // "LTestInline;->inlineNoInlineCaches(LSuper;)I".
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700716 // "LTestInline;->*".
Calin Juravle08556882017-05-26 16:40:45 -0700717 // "invalid_class".
718 // "LTestInline;->invalid_method".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800719 // The method and classes are searched only in the given dex files.
720 bool ProcessLine(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
721 const std::string& line,
722 /*out*/ProfileCompilationInfo* profile) {
723 std::string klass;
724 std::string method_str;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700725 bool is_hot = false;
726 bool is_startup = false;
727 bool is_post_startup = false;
728 const size_t method_sep_index = line.find(kMethodSep, 0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800729 if (method_sep_index == std::string::npos) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700730 klass = line.substr(0);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800731 } else {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700732 // The method prefix flags are only valid for method strings.
733 size_t start_index = 0;
734 while (start_index < line.size() && line[start_index] != 'L') {
735 const char c = line[start_index];
736 if (c == kMethodFlagStringHot) {
737 is_hot = true;
738 } else if (c == kMethodFlagStringStartup) {
739 is_startup = true;
740 } else if (c == kMethodFlagStringPostStartup) {
741 is_post_startup = true;
742 } else {
743 LOG(WARNING) << "Invalid flag " << c;
744 return false;
745 }
746 ++start_index;
747 }
748 klass = line.substr(start_index, method_sep_index - start_index);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800749 method_str = line.substr(method_sep_index + kMethodSep.size());
750 }
751
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700752 TypeReference class_ref;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800753 if (!FindClass(dex_files, klass, &class_ref)) {
Mathieu Chartier3f121342017-03-06 11:16:20 -0800754 LOG(WARNING) << "Could not find class: " << klass;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800755 return false;
756 }
757
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700758 if (method_str.empty() || method_str == kClassAllMethods) {
759 // Start by adding the class.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800760 std::set<DexCacheResolvedClasses> resolved_class_set;
761 const DexFile* dex_file = class_ref.dex_file;
762 const auto& dex_resolved_classes = resolved_class_set.emplace(
763 dex_file->GetLocation(),
764 dex_file->GetBaseLocation(),
Mathieu Chartierea650f32017-05-24 12:04:13 -0700765 dex_file->GetLocationChecksum(),
766 dex_file->NumMethodIds());
Calin Juravlee0ac1152017-02-13 19:03:47 -0800767 dex_resolved_classes.first->AddClass(class_ref.type_index);
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700768 std::vector<ProfileMethodInfo> methods;
769 if (method_str == kClassAllMethods) {
770 // Add all of the methods.
771 const DexFile::ClassDef* class_def = dex_file->FindClassDef(class_ref.type_index);
772 const uint8_t* class_data = dex_file->GetClassData(*class_def);
773 if (class_data != nullptr) {
774 ClassDataItemIterator it(*dex_file, class_data);
775 while (it.HasNextStaticField() || it.HasNextInstanceField()) {
776 it.Next();
777 }
778 while (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
779 if (it.GetMethodCodeItemOffset() != 0) {
780 // Add all of the methods that have code to the profile.
781 const uint32_t method_idx = it.GetMemberIndex();
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700782 methods.push_back(ProfileMethodInfo(MethodReference(dex_file, method_idx)));
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700783 }
784 it.Next();
785 }
786 }
787 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700788 // TODO: Check return values?
789 profile->AddMethods(methods);
790 profile->AddClasses(resolved_class_set);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800791 return true;
792 }
793
794 // Process the method.
795 std::string method_spec;
796 std::vector<std::string> inline_cache_elems;
797
Mathieu Chartierea650f32017-05-24 12:04:13 -0700798 // If none of the flags are set, default to hot.
799 is_hot = is_hot || (!is_hot && !is_startup && !is_post_startup);
800
Calin Juravlee0ac1152017-02-13 19:03:47 -0800801 std::vector<std::string> method_elems;
Calin Juravle589e71e2017-03-03 16:05:05 -0800802 bool is_missing_types = false;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800803 Split(method_str, kProfileParsingInlineChacheSep, &method_elems);
804 if (method_elems.size() == 2) {
805 method_spec = method_elems[0];
Calin Juravle589e71e2017-03-03 16:05:05 -0800806 is_missing_types = method_elems[1] == kMissingTypesMarker;
807 if (!is_missing_types) {
808 Split(method_elems[1], kProfileParsingTypeSep, &inline_cache_elems);
809 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800810 } else if (method_elems.size() == 1) {
811 method_spec = method_elems[0];
812 } else {
813 LOG(ERROR) << "Invalid method line: " << line;
814 return false;
815 }
816
Mathieu Chartier34067262017-04-06 13:55:46 -0700817 const uint32_t method_index = FindMethodIndex(class_ref, method_spec);
818 if (method_index == DexFile::kDexNoIndex) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800819 return false;
820 }
Mathieu Chartier34067262017-04-06 13:55:46 -0700821
Mathieu Chartier34067262017-04-06 13:55:46 -0700822 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
823 if (is_missing_types || !inline_cache_elems.empty()) {
824 uint32_t dex_pc;
825 if (!HasSingleInvoke(class_ref, method_index, &dex_pc)) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800826 return false;
827 }
Mathieu Chartierdbddc222017-05-24 12:04:13 -0700828 std::vector<TypeReference> classes(inline_cache_elems.size());
Mathieu Chartier34067262017-04-06 13:55:46 -0700829 size_t class_it = 0;
830 for (const std::string& ic_class : inline_cache_elems) {
831 if (!FindClass(dex_files, ic_class, &(classes[class_it++]))) {
832 LOG(ERROR) << "Could not find class: " << ic_class;
833 return false;
834 }
835 }
836 inline_caches.emplace_back(dex_pc, is_missing_types, classes);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800837 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700838 MethodReference ref(class_ref.dex_file, method_index);
Mathieu Chartierea650f32017-05-24 12:04:13 -0700839 if (is_hot) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700840 profile->AddMethod(ProfileMethodInfo(ref, inline_caches));
Mathieu Chartierea650f32017-05-24 12:04:13 -0700841 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700842 uint32_t flags = 0;
843 using Hotness = ProfileCompilationInfo::MethodHotness;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700844 if (is_startup) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700845 flags |= Hotness::kFlagStartup;
Mathieu Chartierea650f32017-05-24 12:04:13 -0700846 }
847 if (is_post_startup) {
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700848 flags |= Hotness::kFlagPostStartup;
849 }
850 if (flags != 0) {
851 if (!profile->AddMethodIndex(static_cast<Hotness::Flag>(flags), ref)) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700852 return false;
853 }
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700854 DCHECK(profile->GetMethodHotness(ref).HasAnyFlags());
Mathieu Chartierea650f32017-05-24 12:04:13 -0700855 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800856 return true;
857 }
858
859 // Creates a profile from a human friendly textual representation.
860 // The expected input format is:
861 // # Classes
862 // Ljava/lang/Comparable;
863 // Ljava/lang/Math;
864 // # Methods with inline caches
865 // LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;
866 // LTestInline;->noInlineCache(LSuper;)I
David Sehr7c80f2d2017-02-07 16:47:58 -0800867 int CreateProfile() {
David Sehr153da0e2017-02-15 08:54:51 -0800868 // Validate parameters for this command.
869 if (apk_files_.empty() && apks_fd_.empty()) {
870 Usage("APK files must be specified");
871 }
872 if (dex_locations_.empty()) {
873 Usage("DEX locations must be specified");
874 }
875 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
876 Usage("Reference profile must be specified with --reference-profile-file or "
877 "--reference-profile-file-fd");
878 }
879 if (!profile_files_.empty() || !profile_files_fd_.empty()) {
880 Usage("Profile must be specified with --reference-profile-file or "
881 "--reference-profile-file-fd");
882 }
883 // for ZipArchive::OpenFromFd
884 MemMap::Init();
David Sehr7c80f2d2017-02-07 16:47:58 -0800885 // Open the profile output file if needed.
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 -1;
893 }
894 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800895 // Read the user-specified list of classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800896 std::unique_ptr<std::unordered_set<std::string>>
Calin Juravlee0ac1152017-02-13 19:03:47 -0800897 user_lines(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
David Sehr7c80f2d2017-02-07 16:47:58 -0800898 create_profile_from_file_.c_str(), nullptr)); // No post-processing.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800899
900 // Open the dex files to look up classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800901 std::vector<std::unique_ptr<const DexFile>> dex_files;
902 OpenApkFilesFromLocations(&dex_files);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800903
904 // Process the lines one by one and add the successful ones to the profile.
David Sehr7c80f2d2017-02-07 16:47:58 -0800905 ProfileCompilationInfo info;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800906
907 for (const auto& line : *user_lines) {
908 ProcessLine(dex_files, line, &info);
909 }
910
David Sehr7c80f2d2017-02-07 16:47:58 -0800911 // Write the profile file.
912 CHECK(info.Save(fd));
913 if (close(fd) < 0) {
914 PLOG(WARNING) << "Failed to close descriptor";
915 }
916 return 0;
917 }
918
919 bool ShouldCreateProfile() {
920 return !create_profile_from_file_.empty();
921 }
922
Calin Juravle7bcdb532016-06-07 16:14:47 +0100923 int GenerateTestProfile() {
David Sehr153da0e2017-02-15 08:54:51 -0800924 // Validate parameters for this command.
925 if (test_profile_method_ratio_ > 100) {
926 Usage("Invalid ratio for --generate-test-profile-method-ratio");
927 }
928 if (test_profile_class_ratio_ > 100) {
929 Usage("Invalid ratio for --generate-test-profile-class-ratio");
930 }
Jeff Haof0a31f82017-03-27 15:50:37 -0700931 // If given APK files or DEX locations, check that they're ok.
932 if (!apk_files_.empty() || !apks_fd_.empty() || !dex_locations_.empty()) {
933 if (apk_files_.empty() && apks_fd_.empty()) {
934 Usage("APK files must be specified when passing DEX locations to --generate-test-profile");
935 }
936 if (dex_locations_.empty()) {
937 Usage("DEX locations must be specified when passing APK files to --generate-test-profile");
938 }
939 }
David Sehr153da0e2017-02-15 08:54:51 -0800940 // ShouldGenerateTestProfile confirms !test_profile_.empty().
George Burgess IV71f77262016-10-25 13:08:17 -0700941 int profile_test_fd = open(test_profile_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
Calin Juravle7bcdb532016-06-07 16:14:47 +0100942 if (profile_test_fd < 0) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800943 LOG(ERROR) << "Cannot open " << test_profile_ << strerror(errno);
Calin Juravle7bcdb532016-06-07 16:14:47 +0100944 return -1;
945 }
Jeff Haof0a31f82017-03-27 15:50:37 -0700946 bool result;
947 if (apk_files_.empty() && apks_fd_.empty() && dex_locations_.empty()) {
948 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
949 test_profile_num_dex_,
950 test_profile_method_ratio_,
951 test_profile_class_ratio_,
952 test_profile_seed_);
953 } else {
954 // Initialize MemMap for ZipArchive::OpenFromFd.
955 MemMap::Init();
956 // Open the dex files to look up classes and methods.
957 std::vector<std::unique_ptr<const DexFile>> dex_files;
958 OpenApkFilesFromLocations(&dex_files);
959 // Create a random profile file based on the set of dex files.
960 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
961 dex_files,
962 test_profile_seed_);
963 }
Calin Juravle7bcdb532016-06-07 16:14:47 +0100964 close(profile_test_fd); // ignore close result.
965 return result ? 0 : -1;
966 }
967
968 bool ShouldGenerateTestProfile() {
969 return !test_profile_.empty();
970 }
971
Calin Juravle2e2db782016-02-23 12:00:03 +0000972 private:
973 static void ParseFdForCollection(const StringPiece& option,
974 const char* arg_name,
975 std::vector<int>* fds) {
976 int fd;
977 ParseUintOption(option, arg_name, &fd, Usage);
978 fds->push_back(fd);
979 }
980
981 static void CloseAllFds(const std::vector<int>& fds, const char* descriptor) {
982 for (size_t i = 0; i < fds.size(); i++) {
983 if (close(fds[i]) < 0) {
984 PLOG(WARNING) << "Failed to close descriptor for " << descriptor << " at index " << i;
985 }
986 }
987 }
988
989 void LogCompletionTime() {
David Sehr52683cf2016-05-05 09:02:38 -0700990 static constexpr uint64_t kLogThresholdTime = MsToNs(100); // 100ms
991 uint64_t time_taken = NanoTime() - start_ns_;
David Sehred793012016-05-05 13:39:43 -0700992 if (time_taken > kLogThresholdTime) {
David Sehrd8557182016-05-06 12:29:35 -0700993 LOG(WARNING) << "profman took " << PrettyDuration(time_taken);
David Sehred793012016-05-05 13:39:43 -0700994 }
Calin Juravle2e2db782016-02-23 12:00:03 +0000995 }
996
997 std::vector<std::string> profile_files_;
998 std::vector<int> profile_files_fd_;
David Sehr546d24f2016-06-02 10:46:19 -0700999 std::vector<std::string> dex_locations_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001000 std::vector<std::string> apk_files_;
David Sehr546d24f2016-06-02 10:46:19 -07001001 std::vector<int> apks_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001002 std::string reference_profile_file_;
1003 int reference_profile_file_fd_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001004 bool dump_only_;
Mathieu Chartier34067262017-04-06 13:55:46 -07001005 bool dump_classes_and_methods_;
David Sehr4fcdd6d2016-05-24 14:52:31 -07001006 int dump_output_to_fd_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001007 std::string test_profile_;
David Sehr7c80f2d2017-02-07 16:47:58 -08001008 std::string create_profile_from_file_;
Calin Juravle7bcdb532016-06-07 16:14:47 +01001009 uint16_t test_profile_num_dex_;
1010 uint16_t test_profile_method_ratio_;
1011 uint16_t test_profile_class_ratio_;
Jeff Haof0a31f82017-03-27 15:50:37 -07001012 uint32_t test_profile_seed_;
Calin Juravle2e2db782016-02-23 12:00:03 +00001013 uint64_t start_ns_;
1014};
1015
1016// See ProfileAssistant::ProcessingResult for return codes.
1017static int profman(int argc, char** argv) {
1018 ProfMan profman;
1019
1020 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1021 profman.ParseArgs(argc, argv);
1022
Calin Juravle7bcdb532016-06-07 16:14:47 +01001023 if (profman.ShouldGenerateTestProfile()) {
1024 return profman.GenerateTestProfile();
1025 }
Calin Juravle876f3502016-03-24 16:16:34 +00001026 if (profman.ShouldOnlyDumpProfile()) {
1027 return profman.DumpProfileInfo();
1028 }
Mathieu Chartier34067262017-04-06 13:55:46 -07001029 if (profman.ShouldOnlyDumpClassesAndMethods()) {
Mathieu Chartierea650f32017-05-24 12:04:13 -07001030 return profman.DumpClassesAndMethods();
David Sehr7c80f2d2017-02-07 16:47:58 -08001031 }
1032 if (profman.ShouldCreateProfile()) {
1033 return profman.CreateProfile();
1034 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001035 // Process profile information and assess if we need to do a profile guided compilation.
1036 // This operation involves I/O.
1037 return profman.ProcessProfiles();
1038}
1039
1040} // namespace art
1041
1042int main(int argc, char **argv) {
1043 return art::profman(argc, argv);
1044}
1045