blob: 5504695a967148620e2a366053432bf9b05e3eca [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"
David Sehrf57589f2016-10-17 10:09:33 -070042#include "runtime.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000043#include "utils.h"
David Sehr546d24f2016-06-02 10:46:19 -070044#include "zip_archive.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000045#include "profile_assistant.h"
46
47namespace art {
48
49static int original_argc;
50static char** original_argv;
51
52static std::string CommandLine() {
53 std::vector<std::string> command;
54 for (int i = 0; i < original_argc; ++i) {
55 command.push_back(original_argv[i]);
56 }
Andreas Gampe9186ced2016-12-12 14:28:21 -080057 return android::base::Join(command, ' ');
Calin Juravle2e2db782016-02-23 12:00:03 +000058}
59
David Sehr4fcdd6d2016-05-24 14:52:31 -070060static constexpr int kInvalidFd = -1;
61
62static bool FdIsValid(int fd) {
63 return fd != kInvalidFd;
64}
65
Calin Juravle2e2db782016-02-23 12:00:03 +000066static void UsageErrorV(const char* fmt, va_list ap) {
67 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080068 android::base::StringAppendV(&error, fmt, ap);
Calin Juravle2e2db782016-02-23 12:00:03 +000069 LOG(ERROR) << error;
70}
71
72static void UsageError(const char* fmt, ...) {
73 va_list ap;
74 va_start(ap, fmt);
75 UsageErrorV(fmt, ap);
76 va_end(ap);
77}
78
79NO_RETURN static void Usage(const char *fmt, ...) {
80 va_list ap;
81 va_start(ap, fmt);
82 UsageErrorV(fmt, ap);
83 va_end(ap);
84
85 UsageError("Command: %s", CommandLine().c_str());
86 UsageError("Usage: profman [options]...");
87 UsageError("");
David Sehr4fcdd6d2016-05-24 14:52:31 -070088 UsageError(" --dump-only: dumps the content of the specified profile files");
89 UsageError(" to standard output (default) in a human readable form.");
90 UsageError("");
David Sehr7c80f2d2017-02-07 16:47:58 -080091 UsageError(" --dump-output-to-fd=<number>: redirects --dump-only output to a file descriptor.");
92 UsageError("");
93 UsageError(" --dump-classes: dumps a sorted list of classes that are in the specified profile");
94 UsageError(" file to standard output (default) in a human readable form.");
Calin Juravle876f3502016-03-24 16:16:34 +000095 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +000096 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
97 UsageError(" Can be specified multiple time, in which case the data from the different");
98 UsageError(" profiles will be aggregated.");
99 UsageError("");
100 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
101 UsageError(" Cannot be used together with --profile-file.");
102 UsageError("");
103 UsageError(" --reference-profile-file=<filename>: specify a reference profile.");
104 UsageError(" The data in this file will be compared with the data obtained by merging");
105 UsageError(" all the files specified with --profile-file or --profile-file-fd.");
106 UsageError(" If the exit code is EXIT_COMPILE then all --profile-file will be merged into");
107 UsageError(" --reference-profile-file. ");
108 UsageError("");
109 UsageError(" --reference-profile-file-fd=<number>: same as --reference-profile-file but");
110 UsageError(" accepts a file descriptor. Cannot be used together with");
111 UsageError(" --reference-profile-file.");
David Sehr7c80f2d2017-02-07 16:47:58 -0800112 UsageError("");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100113 UsageError(" --generate-test-profile=<filename>: generates a random profile file for testing.");
114 UsageError(" --generate-test-profile-num-dex=<number>: number of dex files that should be");
115 UsageError(" included in the generated profile. Defaults to 20.");
116 UsageError(" --generate-test-profile-method-ratio=<number>: the percentage from the maximum");
117 UsageError(" number of methods that should be generated. Defaults to 5.");
118 UsageError(" --generate-test-profile-class-ratio=<number>: the percentage from the maximum");
119 UsageError(" number of classes that should be generated. Defaults to 5.");
Jeff Haof0a31f82017-03-27 15:50:37 -0700120 UsageError(" --generate-test-profile-seed=<number>: seed for random number generator used when");
121 UsageError(" generating random test profiles. Defaults to using NanoTime.");
Calin Juravle7bcdb532016-06-07 16:14:47 +0100122 UsageError("");
David Sehr7c80f2d2017-02-07 16:47:58 -0800123 UsageError(" --create-profile-from=<filename>: creates a profile from a list of classes.");
124 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700125 UsageError(" --dex-location=<string>: location string to use with corresponding");
126 UsageError(" apk-fd to find dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700127 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700128 UsageError(" --apk-fd=<number>: file descriptor containing an open APK to");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700129 UsageError(" search for dex files");
David Sehr7c80f2d2017-02-07 16:47:58 -0800130 UsageError(" --apk-=<filename>: an APK to search for dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700131 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000132
133 exit(EXIT_FAILURE);
134}
135
Calin Juravle7bcdb532016-06-07 16:14:47 +0100136// Note: make sure you update the Usage if you change these values.
137static constexpr uint16_t kDefaultTestProfileNumDex = 20;
138static constexpr uint16_t kDefaultTestProfileMethodRatio = 5;
139static constexpr uint16_t kDefaultTestProfileClassRatio = 5;
140
Calin Juravlee0ac1152017-02-13 19:03:47 -0800141// Separators used when parsing human friendly representation of profiles.
142static const std::string kMethodSep = "->";
Calin Juravle589e71e2017-03-03 16:05:05 -0800143static const std::string kMissingTypesMarker = "missing_types";
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700144static const std::string kClassAllMethods = "*";
Calin Juravlee0ac1152017-02-13 19:03:47 -0800145static constexpr char kProfileParsingInlineChacheSep = '+';
146static constexpr char kProfileParsingTypeSep = ',';
147static constexpr char kProfileParsingFirstCharInSignature = '(';
148
149// TODO(calin): This class has grown too much from its initial design. Split the functionality
150// into smaller, more contained pieces.
Calin Juravle2e2db782016-02-23 12:00:03 +0000151class ProfMan FINAL {
152 public:
153 ProfMan() :
David Sehr4fcdd6d2016-05-24 14:52:31 -0700154 reference_profile_file_fd_(kInvalidFd),
155 dump_only_(false),
David Sehr7c80f2d2017-02-07 16:47:58 -0800156 dump_classes_(false),
David Sehr4fcdd6d2016-05-24 14:52:31 -0700157 dump_output_to_fd_(kInvalidFd),
Calin Juravle7bcdb532016-06-07 16:14:47 +0100158 test_profile_num_dex_(kDefaultTestProfileNumDex),
159 test_profile_method_ratio_(kDefaultTestProfileMethodRatio),
160 test_profile_class_ratio_(kDefaultTestProfileClassRatio),
Jeff Haof0a31f82017-03-27 15:50:37 -0700161 test_profile_seed_(NanoTime()),
Calin Juravle2e2db782016-02-23 12:00:03 +0000162 start_ns_(NanoTime()) {}
163
164 ~ProfMan() {
165 LogCompletionTime();
166 }
167
168 void ParseArgs(int argc, char **argv) {
169 original_argc = argc;
170 original_argv = argv;
171
David Sehrf57589f2016-10-17 10:09:33 -0700172 InitLogging(argv, Runtime::Aborter);
Calin Juravle2e2db782016-02-23 12:00:03 +0000173
174 // Skip over the command name.
175 argv++;
176 argc--;
177
178 if (argc == 0) {
179 Usage("No arguments specified");
180 }
181
182 for (int i = 0; i < argc; ++i) {
183 const StringPiece option(argv[i]);
184 const bool log_options = false;
185 if (log_options) {
Calin Juravle876f3502016-03-24 16:16:34 +0000186 LOG(INFO) << "profman: option[" << i << "]=" << argv[i];
Calin Juravle2e2db782016-02-23 12:00:03 +0000187 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700188 if (option == "--dump-only") {
189 dump_only_ = true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800190 } else if (option == "--dump-classes") {
191 dump_classes_ = true;
192 } else if (option.starts_with("--create-profile-from=")) {
193 create_profile_from_file_ = option.substr(strlen("--create-profile-from=")).ToString();
David Sehr4fcdd6d2016-05-24 14:52:31 -0700194 } else if (option.starts_with("--dump-output-to-fd=")) {
195 ParseUintOption(option, "--dump-output-to-fd", &dump_output_to_fd_, Usage);
Calin Juravle876f3502016-03-24 16:16:34 +0000196 } else if (option.starts_with("--profile-file=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000197 profile_files_.push_back(option.substr(strlen("--profile-file=")).ToString());
198 } else if (option.starts_with("--profile-file-fd=")) {
199 ParseFdForCollection(option, "--profile-file-fd", &profile_files_fd_);
200 } else if (option.starts_with("--reference-profile-file=")) {
201 reference_profile_file_ = option.substr(strlen("--reference-profile-file=")).ToString();
202 } else if (option.starts_with("--reference-profile-file-fd=")) {
203 ParseUintOption(option, "--reference-profile-file-fd", &reference_profile_file_fd_, Usage);
David Sehr546d24f2016-06-02 10:46:19 -0700204 } else if (option.starts_with("--dex-location=")) {
205 dex_locations_.push_back(option.substr(strlen("--dex-location=")).ToString());
206 } else if (option.starts_with("--apk-fd=")) {
207 ParseFdForCollection(option, "--apk-fd", &apks_fd_);
David Sehr7c80f2d2017-02-07 16:47:58 -0800208 } else if (option.starts_with("--apk=")) {
209 apk_files_.push_back(option.substr(strlen("--apk=")).ToString());
Calin Juravle7bcdb532016-06-07 16:14:47 +0100210 } else if (option.starts_with("--generate-test-profile=")) {
211 test_profile_ = option.substr(strlen("--generate-test-profile=")).ToString();
212 } else if (option.starts_with("--generate-test-profile-num-dex=")) {
213 ParseUintOption(option,
214 "--generate-test-profile-num-dex",
215 &test_profile_num_dex_,
216 Usage);
217 } else if (option.starts_with("--generate-test-profile-method-ratio")) {
218 ParseUintOption(option,
219 "--generate-test-profile-method-ratio",
220 &test_profile_method_ratio_,
221 Usage);
222 } else if (option.starts_with("--generate-test-profile-class-ratio")) {
223 ParseUintOption(option,
224 "--generate-test-profile-class-ratio",
225 &test_profile_class_ratio_,
226 Usage);
Jeff Haof0a31f82017-03-27 15:50:37 -0700227 } else if (option.starts_with("--generate-test-profile-seed=")) {
228 ParseUintOption(option, "--generate-test-profile-seed", &test_profile_seed_, Usage);
Calin Juravle2e2db782016-02-23 12:00:03 +0000229 } else {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700230 Usage("Unknown argument '%s'", option.data());
Calin Juravle2e2db782016-02-23 12:00:03 +0000231 }
232 }
233
David Sehr153da0e2017-02-15 08:54:51 -0800234 // Validate global consistency between file/fd options.
Calin Juravle2e2db782016-02-23 12:00:03 +0000235 if (!profile_files_.empty() && !profile_files_fd_.empty()) {
236 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
237 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700238 if (!reference_profile_file_.empty() && FdIsValid(reference_profile_file_fd_)) {
239 Usage("Reference profile should not be specified with both "
240 "--reference-profile-file-fd and --reference-profile-file");
241 }
David Sehr153da0e2017-02-15 08:54:51 -0800242 if (!apk_files_.empty() && !apks_fd_.empty()) {
243 Usage("APK files should not be specified with both --apk-fd and --apk");
Calin Juravle2e2db782016-02-23 12:00:03 +0000244 }
245 }
246
247 ProfileAssistant::ProcessingResult ProcessProfiles() {
David Sehr153da0e2017-02-15 08:54:51 -0800248 // Validate that at least one profile file was passed, as well as a reference profile.
249 if (profile_files_.empty() && profile_files_fd_.empty()) {
250 Usage("No profile files specified.");
251 }
252 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
253 Usage("No reference profile file specified.");
254 }
255 if ((!profile_files_.empty() && FdIsValid(reference_profile_file_fd_)) ||
256 (!profile_files_fd_.empty() && !FdIsValid(reference_profile_file_fd_))) {
257 Usage("Options --profile-file-fd and --reference-profile-file-fd "
258 "should only be used together");
259 }
Calin Juravle2e2db782016-02-23 12:00:03 +0000260 ProfileAssistant::ProcessingResult result;
261 if (profile_files_.empty()) {
262 // The file doesn't need to be flushed here (ProcessProfiles will do it)
263 // so don't check the usage.
264 File file(reference_profile_file_fd_, false);
265 result = ProfileAssistant::ProcessProfiles(profile_files_fd_, reference_profile_file_fd_);
266 CloseAllFds(profile_files_fd_, "profile_files_fd_");
267 } else {
268 result = ProfileAssistant::ProcessProfiles(profile_files_, reference_profile_file_);
269 }
270 return result;
271 }
272
David Sehr7c80f2d2017-02-07 16:47:58 -0800273 void OpenApkFilesFromLocations(std::vector<std::unique_ptr<const DexFile>>* dex_files) {
274 bool use_apk_fd_list = !apks_fd_.empty();
275 if (use_apk_fd_list) {
David Sehr153da0e2017-02-15 08:54:51 -0800276 // Get the APKs from the collection of FDs.
David Sehr7c80f2d2017-02-07 16:47:58 -0800277 CHECK_EQ(dex_locations_.size(), apks_fd_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800278 } else if (!apk_files_.empty()) {
279 // Get the APKs from the collection of filenames.
David Sehr7c80f2d2017-02-07 16:47:58 -0800280 CHECK_EQ(dex_locations_.size(), apk_files_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800281 } else {
282 // No APKs were specified.
283 CHECK(dex_locations_.empty());
284 return;
David Sehr7c80f2d2017-02-07 16:47:58 -0800285 }
286 static constexpr bool kVerifyChecksum = true;
287 for (size_t i = 0; i < dex_locations_.size(); ++i) {
288 std::string error_msg;
289 std::vector<std::unique_ptr<const DexFile>> dex_files_for_location;
290 if (use_apk_fd_list) {
291 if (DexFile::OpenZip(apks_fd_[i],
292 dex_locations_[i],
293 kVerifyChecksum,
294 &error_msg,
295 &dex_files_for_location)) {
296 } else {
297 LOG(WARNING) << "OpenZip failed for '" << dex_locations_[i] << "' " << error_msg;
298 continue;
299 }
300 } else {
301 if (DexFile::Open(apk_files_[i].c_str(),
302 dex_locations_[i],
303 kVerifyChecksum,
304 &error_msg,
305 &dex_files_for_location)) {
306 } else {
307 LOG(WARNING) << "Open failed for '" << dex_locations_[i] << "' " << error_msg;
308 continue;
309 }
310 }
311 for (std::unique_ptr<const DexFile>& dex_file : dex_files_for_location) {
312 dex_files->emplace_back(std::move(dex_file));
313 }
314 }
315 }
316
David Sehrb18991b2017-02-08 20:58:10 -0800317 int DumpOneProfile(const std::string& banner,
318 const std::string& filename,
319 int fd,
320 const std::vector<std::unique_ptr<const DexFile>>* dex_files,
321 std::string* dump) {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700322 if (!filename.empty()) {
323 fd = open(filename.c_str(), O_RDWR);
324 if (fd < 0) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800325 LOG(ERROR) << "Cannot open " << filename << strerror(errno);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700326 return -1;
327 }
Calin Juravle876f3502016-03-24 16:16:34 +0000328 }
329 ProfileCompilationInfo info;
330 if (!info.Load(fd)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800331 LOG(ERROR) << "Cannot load profile info from fd=" << fd << "\n";
Calin Juravle876f3502016-03-24 16:16:34 +0000332 return -1;
333 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700334 std::string this_dump = banner + "\n" + info.DumpInfo(dex_files) + "\n";
335 *dump += this_dump;
336 if (close(fd) < 0) {
337 PLOG(WARNING) << "Failed to close descriptor";
338 }
339 return 0;
340 }
341
342 int DumpProfileInfo() {
David Sehr153da0e2017-02-15 08:54:51 -0800343 // Validate that at least one profile file or reference was specified.
344 if (profile_files_.empty() && profile_files_fd_.empty() &&
345 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
346 Usage("No profile files or reference profile specified.");
347 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700348 static const char* kEmptyString = "";
David Sehr546d24f2016-06-02 10:46:19 -0700349 static const char* kOrdinaryProfile = "=== profile ===";
350 static const char* kReferenceProfile = "=== reference profile ===";
351
352 // Open apk/zip files and and read dex files.
353 MemMap::Init(); // for ZipArchive::OpenFromFd
David Sehrb18991b2017-02-08 20:58:10 -0800354 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7c80f2d2017-02-07 16:47:58 -0800355 OpenApkFilesFromLocations(&dex_files);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700356 std::string dump;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700357 // Dump individual profile files.
358 if (!profile_files_fd_.empty()) {
359 for (int profile_file_fd : profile_files_fd_) {
David Sehr546d24f2016-06-02 10:46:19 -0700360 int ret = DumpOneProfile(kOrdinaryProfile,
361 kEmptyString,
362 profile_file_fd,
363 &dex_files,
364 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700365 if (ret != 0) {
366 return ret;
367 }
368 }
369 }
370 if (!profile_files_.empty()) {
371 for (const std::string& profile_file : profile_files_) {
David Sehr546d24f2016-06-02 10:46:19 -0700372 int ret = DumpOneProfile(kOrdinaryProfile, profile_file, kInvalidFd, &dex_files, &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700373 if (ret != 0) {
374 return ret;
375 }
376 }
377 }
378 // Dump reference profile file.
379 if (FdIsValid(reference_profile_file_fd_)) {
David Sehr546d24f2016-06-02 10:46:19 -0700380 int ret = DumpOneProfile(kReferenceProfile,
381 kEmptyString,
382 reference_profile_file_fd_,
383 &dex_files,
384 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700385 if (ret != 0) {
386 return ret;
387 }
388 }
389 if (!reference_profile_file_.empty()) {
David Sehr546d24f2016-06-02 10:46:19 -0700390 int ret = DumpOneProfile(kReferenceProfile,
391 reference_profile_file_,
392 kInvalidFd,
393 &dex_files,
David Sehr4fcdd6d2016-05-24 14:52:31 -0700394 &dump);
395 if (ret != 0) {
396 return ret;
397 }
398 }
399 if (!FdIsValid(dump_output_to_fd_)) {
400 std::cout << dump;
401 } else {
402 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
403 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
404 return -1;
405 }
406 }
Calin Juravle876f3502016-03-24 16:16:34 +0000407 return 0;
408 }
409
410 bool ShouldOnlyDumpProfile() {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700411 return dump_only_;
Calin Juravle876f3502016-03-24 16:16:34 +0000412 }
413
David Sehr7c80f2d2017-02-07 16:47:58 -0800414 bool GetClassNames(int fd,
415 std::vector<std::unique_ptr<const DexFile>>* dex_files,
416 std::set<std::string>* class_names) {
417 ProfileCompilationInfo profile_info;
418 if (!profile_info.Load(fd)) {
419 LOG(ERROR) << "Cannot load profile info";
420 return false;
421 }
422 profile_info.GetClassNames(dex_files, class_names);
423 return true;
424 }
425
Andreas Gampe37c58462017-03-27 15:14:27 -0700426 bool GetClassNames(const std::string& profile_file,
David Sehr7c80f2d2017-02-07 16:47:58 -0800427 std::vector<std::unique_ptr<const DexFile>>* dex_files,
428 std::set<std::string>* class_names) {
429 int fd = open(profile_file.c_str(), O_RDONLY);
430 if (!FdIsValid(fd)) {
431 LOG(ERROR) << "Cannot open " << profile_file << strerror(errno);
432 return false;
433 }
434 if (!GetClassNames(fd, dex_files, class_names)) {
435 return false;
436 }
437 if (close(fd) < 0) {
438 PLOG(WARNING) << "Failed to close descriptor";
439 }
440 return true;
441 }
442
443 int DumpClasses() {
David Sehr153da0e2017-02-15 08:54:51 -0800444 // Validate that at least one profile file or reference was specified.
445 if (profile_files_.empty() && profile_files_fd_.empty() &&
446 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
447 Usage("No profile files or reference profile specified.");
448 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800449 // Open apk/zip files and and read dex files.
450 MemMap::Init(); // for ZipArchive::OpenFromFd
451 // Open the dex files to get the names for classes.
452 std::vector<std::unique_ptr<const DexFile>> dex_files;
453 OpenApkFilesFromLocations(&dex_files);
454 // Build a vector of class names from individual profile files.
455 std::set<std::string> class_names;
456 if (!profile_files_fd_.empty()) {
457 for (int profile_file_fd : profile_files_fd_) {
458 if (!GetClassNames(profile_file_fd, &dex_files, &class_names)) {
459 return -1;
460 }
461 }
462 }
463 if (!profile_files_.empty()) {
464 for (const std::string& profile_file : profile_files_) {
465 if (!GetClassNames(profile_file, &dex_files, &class_names)) {
466 return -1;
467 }
468 }
469 }
470 // Concatenate class names from reference profile file.
471 if (FdIsValid(reference_profile_file_fd_)) {
472 if (!GetClassNames(reference_profile_file_fd_, &dex_files, &class_names)) {
473 return -1;
474 }
475 }
476 if (!reference_profile_file_.empty()) {
477 if (!GetClassNames(reference_profile_file_, &dex_files, &class_names)) {
478 return -1;
479 }
480 }
481 // Dump the class names.
482 std::string dump;
483 for (const std::string& class_name : class_names) {
484 dump += class_name + std::string("\n");
485 }
486 if (!FdIsValid(dump_output_to_fd_)) {
487 std::cout << dump;
488 } else {
489 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
490 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
491 return -1;
492 }
493 }
494 return 0;
495 }
496
497 bool ShouldOnlyDumpClasses() {
498 return dump_classes_;
499 }
500
501 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
502 // the given function.
503 template <typename T>
504 static T* ReadCommentedInputFromFile(
505 const char* input_filename, std::function<std::string(const char*)>* process) {
506 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
507 if (input_file.get() == nullptr) {
508 LOG(ERROR) << "Failed to open input file " << input_filename;
509 return nullptr;
510 }
511 std::unique_ptr<T> result(
512 ReadCommentedInputStream<T>(*input_file, process));
513 input_file->close();
514 return result.release();
515 }
516
517 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
518 // with the given function.
519 template <typename T>
520 static T* ReadCommentedInputStream(
521 std::istream& in_stream,
522 std::function<std::string(const char*)>* process) {
523 std::unique_ptr<T> output(new T());
524 while (in_stream.good()) {
525 std::string dot;
526 std::getline(in_stream, dot);
527 if (android::base::StartsWith(dot, "#") || dot.empty()) {
528 continue;
529 }
530 if (process != nullptr) {
531 std::string descriptor((*process)(dot.c_str()));
532 output->insert(output->end(), descriptor);
533 } else {
534 output->insert(output->end(), dot);
535 }
536 }
537 return output.release();
538 }
539
Calin Juravlee0ac1152017-02-13 19:03:47 -0800540 // Find class klass_descriptor in the given dex_files and store its reference
541 // in the out parameter class_ref.
542 // Return true if the definition of the class was found in any of the dex_files.
543 bool FindClass(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
544 const std::string& klass_descriptor,
545 /*out*/ProfileMethodInfo::ProfileClassReference* class_ref) {
546 for (const std::unique_ptr<const DexFile>& dex_file_ptr : dex_files) {
547 const DexFile* dex_file = dex_file_ptr.get();
548 const DexFile::TypeId* type_id = dex_file->FindTypeId(klass_descriptor.c_str());
549 if (type_id == nullptr) {
550 continue;
551 }
552 dex::TypeIndex type_index = dex_file->GetIndexForTypeId(*type_id);
553 if (dex_file->FindClassDef(type_index) == nullptr) {
554 // Class is only referenced in the current dex file but not defined in it.
555 continue;
556 }
557 class_ref->dex_file = dex_file;
558 class_ref->type_index = type_index;
559 return true;
560 }
561 return false;
562 }
563
564 // Find the method specified by method_spec in the class class_ref. The method
565 // must have a single INVOKE_VIRTUAL in its byte code.
566 // Upon success it returns true and stores the method index and the invoke dex pc
567 // in the output parameters.
568 // The format of the method spec is "inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
569 //
570 // TODO(calin): support INVOKE_INTERFACE and the range variants.
571 bool FindMethodWithSingleInvoke(const ProfileMethodInfo::ProfileClassReference& class_ref,
572 const std::string& method_spec,
573 /*out*/uint16_t* method_index,
574 /*out*/uint32_t* dex_pc) {
575 std::vector<std::string> name_and_signature;
576 Split(method_spec, kProfileParsingFirstCharInSignature, &name_and_signature);
577 if (name_and_signature.size() != 2) {
578 LOG(ERROR) << "Invalid method name and signature " << method_spec;
579 }
580 const std::string& name = name_and_signature[0];
581 const std::string& signature = kProfileParsingFirstCharInSignature + name_and_signature[1];
582 const DexFile* dex_file = class_ref.dex_file;
583
584 const DexFile::StringId* name_id = dex_file->FindStringId(name.c_str());
585 if (name_id == nullptr) {
586 LOG(ERROR) << "Could not find name: " << name;
587 return false;
588 }
589 dex::TypeIndex return_type_idx;
590 std::vector<dex::TypeIndex> param_type_idxs;
591 if (!dex_file->CreateTypeList(signature, &return_type_idx, &param_type_idxs)) {
592 LOG(ERROR) << "Could not create type list" << signature;
593 return false;
594 }
595 const DexFile::ProtoId* proto_id = dex_file->FindProtoId(return_type_idx, param_type_idxs);
596 if (proto_id == nullptr) {
597 LOG(ERROR) << "Could not find proto_id: " << name;
598 return false;
599 }
600 const DexFile::MethodId* method_id = dex_file->FindMethodId(
601 dex_file->GetTypeId(class_ref.type_index), *name_id, *proto_id);
602 if (method_id == nullptr) {
603 LOG(ERROR) << "Could not find method_id: " << name;
604 return false;
605 }
606
607 *method_index = dex_file->GetIndexForMethodId(*method_id);
608
609 uint32_t offset = dex_file->FindCodeItemOffset(
610 *dex_file->FindClassDef(class_ref.type_index),
611 *method_index);
612 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(offset);
613
614 bool found_invoke = false;
615 for (CodeItemIterator it(*code_item); !it.Done(); it.Advance()) {
616 if (it.CurrentInstruction().Opcode() == Instruction::INVOKE_VIRTUAL) {
617 if (found_invoke) {
618 LOG(ERROR) << "Multiple invoke INVOKE_VIRTUAL found: " << name;
619 return false;
620 }
621 found_invoke = true;
622 *dex_pc = it.CurrentDexPc();
623 }
624 }
625 if (!found_invoke) {
626 LOG(ERROR) << "Could not find any INVOKE_VIRTUAL: " << name;
627 }
628 return found_invoke;
629 }
630
631 // Process a line defining a class or a method and its inline caches.
632 // Upon success return true and add the class or the method info to profile.
Calin Juravle589e71e2017-03-03 16:05:05 -0800633 // The possible line formats are:
634 // "LJustTheCass;".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800635 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
Calin Juravle589e71e2017-03-03 16:05:05 -0800636 // "LTestInline;->inlineMissingTypes(LSuper;)I+missing_types".
637 // "LTestInline;->inlineNoInlineCaches(LSuper;)I".
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700638 // "LTestInline;->*".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800639 // The method and classes are searched only in the given dex files.
640 bool ProcessLine(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
641 const std::string& line,
642 /*out*/ProfileCompilationInfo* profile) {
643 std::string klass;
644 std::string method_str;
645 size_t method_sep_index = line.find(kMethodSep);
646 if (method_sep_index == std::string::npos) {
647 klass = line;
648 } else {
649 klass = line.substr(0, method_sep_index);
650 method_str = line.substr(method_sep_index + kMethodSep.size());
651 }
652
653 ProfileMethodInfo::ProfileClassReference class_ref;
654 if (!FindClass(dex_files, klass, &class_ref)) {
Mathieu Chartier3f121342017-03-06 11:16:20 -0800655 LOG(WARNING) << "Could not find class: " << klass;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800656 return false;
657 }
658
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700659 if (method_str.empty() || method_str == kClassAllMethods) {
660 // Start by adding the class.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800661 std::set<DexCacheResolvedClasses> resolved_class_set;
662 const DexFile* dex_file = class_ref.dex_file;
663 const auto& dex_resolved_classes = resolved_class_set.emplace(
664 dex_file->GetLocation(),
665 dex_file->GetBaseLocation(),
666 dex_file->GetLocationChecksum());
667 dex_resolved_classes.first->AddClass(class_ref.type_index);
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700668 std::vector<ProfileMethodInfo> methods;
669 if (method_str == kClassAllMethods) {
670 // Add all of the methods.
671 const DexFile::ClassDef* class_def = dex_file->FindClassDef(class_ref.type_index);
672 const uint8_t* class_data = dex_file->GetClassData(*class_def);
673 if (class_data != nullptr) {
674 ClassDataItemIterator it(*dex_file, class_data);
675 while (it.HasNextStaticField() || it.HasNextInstanceField()) {
676 it.Next();
677 }
678 while (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
679 if (it.GetMethodCodeItemOffset() != 0) {
680 // Add all of the methods that have code to the profile.
681 const uint32_t method_idx = it.GetMemberIndex();
682 methods.push_back(ProfileMethodInfo(dex_file, method_idx));
683 }
684 it.Next();
685 }
686 }
687 }
688 profile->AddMethodsAndClasses(methods, resolved_class_set);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800689 return true;
690 }
691
692 // Process the method.
693 std::string method_spec;
694 std::vector<std::string> inline_cache_elems;
695
696 std::vector<std::string> method_elems;
Calin Juravle589e71e2017-03-03 16:05:05 -0800697 bool is_missing_types = false;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800698 Split(method_str, kProfileParsingInlineChacheSep, &method_elems);
699 if (method_elems.size() == 2) {
700 method_spec = method_elems[0];
Calin Juravle589e71e2017-03-03 16:05:05 -0800701 is_missing_types = method_elems[1] == kMissingTypesMarker;
702 if (!is_missing_types) {
703 Split(method_elems[1], kProfileParsingTypeSep, &inline_cache_elems);
704 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800705 } else if (method_elems.size() == 1) {
706 method_spec = method_elems[0];
707 } else {
708 LOG(ERROR) << "Invalid method line: " << line;
709 return false;
710 }
711
712 uint16_t method_index;
713 uint32_t dex_pc;
714 if (!FindMethodWithSingleInvoke(class_ref, method_spec, &method_index, &dex_pc)) {
715 return false;
716 }
717 std::vector<ProfileMethodInfo::ProfileClassReference> classes(inline_cache_elems.size());
718 size_t class_it = 0;
Andreas Gampe37c58462017-03-27 15:14:27 -0700719 for (const std::string& ic_class : inline_cache_elems) {
Calin Juravlee0ac1152017-02-13 19:03:47 -0800720 if (!FindClass(dex_files, ic_class, &(classes[class_it++]))) {
721 LOG(ERROR) << "Could not find class: " << ic_class;
722 return false;
723 }
724 }
725 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravle589e71e2017-03-03 16:05:05 -0800726 inline_caches.emplace_back(dex_pc, is_missing_types, classes);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800727 std::vector<ProfileMethodInfo> pmi;
728 pmi.emplace_back(class_ref.dex_file, method_index, inline_caches);
729
730 profile->AddMethodsAndClasses(pmi, std::set<DexCacheResolvedClasses>());
731 return true;
732 }
733
734 // Creates a profile from a human friendly textual representation.
735 // The expected input format is:
736 // # Classes
737 // Ljava/lang/Comparable;
738 // Ljava/lang/Math;
739 // # Methods with inline caches
740 // LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;
741 // LTestInline;->noInlineCache(LSuper;)I
David Sehr7c80f2d2017-02-07 16:47:58 -0800742 int CreateProfile() {
David Sehr153da0e2017-02-15 08:54:51 -0800743 // Validate parameters for this command.
744 if (apk_files_.empty() && apks_fd_.empty()) {
745 Usage("APK files must be specified");
746 }
747 if (dex_locations_.empty()) {
748 Usage("DEX locations must be specified");
749 }
750 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
751 Usage("Reference profile must be specified with --reference-profile-file or "
752 "--reference-profile-file-fd");
753 }
754 if (!profile_files_.empty() || !profile_files_fd_.empty()) {
755 Usage("Profile must be specified with --reference-profile-file or "
756 "--reference-profile-file-fd");
757 }
758 // for ZipArchive::OpenFromFd
759 MemMap::Init();
David Sehr7c80f2d2017-02-07 16:47:58 -0800760 // Open the profile output file if needed.
761 int fd = reference_profile_file_fd_;
762 if (!FdIsValid(fd)) {
763 CHECK(!reference_profile_file_.empty());
764 fd = open(reference_profile_file_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
765 if (fd < 0) {
766 LOG(ERROR) << "Cannot open " << reference_profile_file_ << strerror(errno);
767 return -1;
768 }
769 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800770 // Read the user-specified list of classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800771 std::unique_ptr<std::unordered_set<std::string>>
Calin Juravlee0ac1152017-02-13 19:03:47 -0800772 user_lines(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
David Sehr7c80f2d2017-02-07 16:47:58 -0800773 create_profile_from_file_.c_str(), nullptr)); // No post-processing.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800774
775 // Open the dex files to look up classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800776 std::vector<std::unique_ptr<const DexFile>> dex_files;
777 OpenApkFilesFromLocations(&dex_files);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800778
779 // Process the lines one by one and add the successful ones to the profile.
David Sehr7c80f2d2017-02-07 16:47:58 -0800780 ProfileCompilationInfo info;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800781
782 for (const auto& line : *user_lines) {
783 ProcessLine(dex_files, line, &info);
784 }
785
David Sehr7c80f2d2017-02-07 16:47:58 -0800786 // Write the profile file.
787 CHECK(info.Save(fd));
788 if (close(fd) < 0) {
789 PLOG(WARNING) << "Failed to close descriptor";
790 }
791 return 0;
792 }
793
794 bool ShouldCreateProfile() {
795 return !create_profile_from_file_.empty();
796 }
797
Calin Juravle7bcdb532016-06-07 16:14:47 +0100798 int GenerateTestProfile() {
David Sehr153da0e2017-02-15 08:54:51 -0800799 // Validate parameters for this command.
800 if (test_profile_method_ratio_ > 100) {
801 Usage("Invalid ratio for --generate-test-profile-method-ratio");
802 }
803 if (test_profile_class_ratio_ > 100) {
804 Usage("Invalid ratio for --generate-test-profile-class-ratio");
805 }
Jeff Haof0a31f82017-03-27 15:50:37 -0700806 // If given APK files or DEX locations, check that they're ok.
807 if (!apk_files_.empty() || !apks_fd_.empty() || !dex_locations_.empty()) {
808 if (apk_files_.empty() && apks_fd_.empty()) {
809 Usage("APK files must be specified when passing DEX locations to --generate-test-profile");
810 }
811 if (dex_locations_.empty()) {
812 Usage("DEX locations must be specified when passing APK files to --generate-test-profile");
813 }
814 }
David Sehr153da0e2017-02-15 08:54:51 -0800815 // ShouldGenerateTestProfile confirms !test_profile_.empty().
George Burgess IV71f77262016-10-25 13:08:17 -0700816 int profile_test_fd = open(test_profile_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
Calin Juravle7bcdb532016-06-07 16:14:47 +0100817 if (profile_test_fd < 0) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800818 LOG(ERROR) << "Cannot open " << test_profile_ << strerror(errno);
Calin Juravle7bcdb532016-06-07 16:14:47 +0100819 return -1;
820 }
Jeff Haof0a31f82017-03-27 15:50:37 -0700821 bool result;
822 if (apk_files_.empty() && apks_fd_.empty() && dex_locations_.empty()) {
823 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
824 test_profile_num_dex_,
825 test_profile_method_ratio_,
826 test_profile_class_ratio_,
827 test_profile_seed_);
828 } else {
829 // Initialize MemMap for ZipArchive::OpenFromFd.
830 MemMap::Init();
831 // Open the dex files to look up classes and methods.
832 std::vector<std::unique_ptr<const DexFile>> dex_files;
833 OpenApkFilesFromLocations(&dex_files);
834 // Create a random profile file based on the set of dex files.
835 result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
836 dex_files,
837 test_profile_seed_);
838 }
Calin Juravle7bcdb532016-06-07 16:14:47 +0100839 close(profile_test_fd); // ignore close result.
840 return result ? 0 : -1;
841 }
842
843 bool ShouldGenerateTestProfile() {
844 return !test_profile_.empty();
845 }
846
Calin Juravle2e2db782016-02-23 12:00:03 +0000847 private:
848 static void ParseFdForCollection(const StringPiece& option,
849 const char* arg_name,
850 std::vector<int>* fds) {
851 int fd;
852 ParseUintOption(option, arg_name, &fd, Usage);
853 fds->push_back(fd);
854 }
855
856 static void CloseAllFds(const std::vector<int>& fds, const char* descriptor) {
857 for (size_t i = 0; i < fds.size(); i++) {
858 if (close(fds[i]) < 0) {
859 PLOG(WARNING) << "Failed to close descriptor for " << descriptor << " at index " << i;
860 }
861 }
862 }
863
864 void LogCompletionTime() {
David Sehr52683cf2016-05-05 09:02:38 -0700865 static constexpr uint64_t kLogThresholdTime = MsToNs(100); // 100ms
866 uint64_t time_taken = NanoTime() - start_ns_;
David Sehred793012016-05-05 13:39:43 -0700867 if (time_taken > kLogThresholdTime) {
David Sehrd8557182016-05-06 12:29:35 -0700868 LOG(WARNING) << "profman took " << PrettyDuration(time_taken);
David Sehred793012016-05-05 13:39:43 -0700869 }
Calin Juravle2e2db782016-02-23 12:00:03 +0000870 }
871
872 std::vector<std::string> profile_files_;
873 std::vector<int> profile_files_fd_;
David Sehr546d24f2016-06-02 10:46:19 -0700874 std::vector<std::string> dex_locations_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800875 std::vector<std::string> apk_files_;
David Sehr546d24f2016-06-02 10:46:19 -0700876 std::vector<int> apks_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +0000877 std::string reference_profile_file_;
878 int reference_profile_file_fd_;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700879 bool dump_only_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800880 bool dump_classes_;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700881 int dump_output_to_fd_;
Calin Juravle7bcdb532016-06-07 16:14:47 +0100882 std::string test_profile_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800883 std::string create_profile_from_file_;
Calin Juravle7bcdb532016-06-07 16:14:47 +0100884 uint16_t test_profile_num_dex_;
885 uint16_t test_profile_method_ratio_;
886 uint16_t test_profile_class_ratio_;
Jeff Haof0a31f82017-03-27 15:50:37 -0700887 uint32_t test_profile_seed_;
Calin Juravle2e2db782016-02-23 12:00:03 +0000888 uint64_t start_ns_;
889};
890
891// See ProfileAssistant::ProcessingResult for return codes.
892static int profman(int argc, char** argv) {
893 ProfMan profman;
894
895 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
896 profman.ParseArgs(argc, argv);
897
Calin Juravle7bcdb532016-06-07 16:14:47 +0100898 if (profman.ShouldGenerateTestProfile()) {
899 return profman.GenerateTestProfile();
900 }
Calin Juravle876f3502016-03-24 16:16:34 +0000901 if (profman.ShouldOnlyDumpProfile()) {
902 return profman.DumpProfileInfo();
903 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800904 if (profman.ShouldOnlyDumpClasses()) {
905 return profman.DumpClasses();
906 }
907 if (profman.ShouldCreateProfile()) {
908 return profman.CreateProfile();
909 }
Calin Juravle2e2db782016-02-23 12:00:03 +0000910 // Process profile information and assess if we need to do a profile guided compilation.
911 // This operation involves I/O.
912 return profman.ProcessProfiles();
913}
914
915} // namespace art
916
917int main(int argc, char **argv) {
918 return art::profman(argc, argv);
919}
920