blob: fdb9a75a6f88bcfa59175179d4171c2a5fdb68ed [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.");
120 UsageError("");
David Sehr7c80f2d2017-02-07 16:47:58 -0800121 UsageError(" --create-profile-from=<filename>: creates a profile from a list of classes.");
122 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700123 UsageError(" --dex-location=<string>: location string to use with corresponding");
124 UsageError(" apk-fd to find dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700125 UsageError("");
David Sehr546d24f2016-06-02 10:46:19 -0700126 UsageError(" --apk-fd=<number>: file descriptor containing an open APK to");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700127 UsageError(" search for dex files");
David Sehr7c80f2d2017-02-07 16:47:58 -0800128 UsageError(" --apk-=<filename>: an APK to search for dex files");
David Sehr4fcdd6d2016-05-24 14:52:31 -0700129 UsageError("");
Calin Juravle2e2db782016-02-23 12:00:03 +0000130
131 exit(EXIT_FAILURE);
132}
133
Calin Juravle7bcdb532016-06-07 16:14:47 +0100134// Note: make sure you update the Usage if you change these values.
135static constexpr uint16_t kDefaultTestProfileNumDex = 20;
136static constexpr uint16_t kDefaultTestProfileMethodRatio = 5;
137static constexpr uint16_t kDefaultTestProfileClassRatio = 5;
138
Calin Juravlee0ac1152017-02-13 19:03:47 -0800139// Separators used when parsing human friendly representation of profiles.
140static const std::string kMethodSep = "->";
Calin Juravle589e71e2017-03-03 16:05:05 -0800141static const std::string kMissingTypesMarker = "missing_types";
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700142static const std::string kClassAllMethods = "*";
Calin Juravlee0ac1152017-02-13 19:03:47 -0800143static constexpr char kProfileParsingInlineChacheSep = '+';
144static constexpr char kProfileParsingTypeSep = ',';
145static constexpr char kProfileParsingFirstCharInSignature = '(';
146
147// TODO(calin): This class has grown too much from its initial design. Split the functionality
148// into smaller, more contained pieces.
Calin Juravle2e2db782016-02-23 12:00:03 +0000149class ProfMan FINAL {
150 public:
151 ProfMan() :
David Sehr4fcdd6d2016-05-24 14:52:31 -0700152 reference_profile_file_fd_(kInvalidFd),
153 dump_only_(false),
David Sehr7c80f2d2017-02-07 16:47:58 -0800154 dump_classes_(false),
David Sehr4fcdd6d2016-05-24 14:52:31 -0700155 dump_output_to_fd_(kInvalidFd),
Calin Juravle7bcdb532016-06-07 16:14:47 +0100156 test_profile_num_dex_(kDefaultTestProfileNumDex),
157 test_profile_method_ratio_(kDefaultTestProfileMethodRatio),
158 test_profile_class_ratio_(kDefaultTestProfileClassRatio),
Calin Juravle2e2db782016-02-23 12:00:03 +0000159 start_ns_(NanoTime()) {}
160
161 ~ProfMan() {
162 LogCompletionTime();
163 }
164
165 void ParseArgs(int argc, char **argv) {
166 original_argc = argc;
167 original_argv = argv;
168
David Sehrf57589f2016-10-17 10:09:33 -0700169 InitLogging(argv, Runtime::Aborter);
Calin Juravle2e2db782016-02-23 12:00:03 +0000170
171 // Skip over the command name.
172 argv++;
173 argc--;
174
175 if (argc == 0) {
176 Usage("No arguments specified");
177 }
178
179 for (int i = 0; i < argc; ++i) {
180 const StringPiece option(argv[i]);
181 const bool log_options = false;
182 if (log_options) {
Calin Juravle876f3502016-03-24 16:16:34 +0000183 LOG(INFO) << "profman: option[" << i << "]=" << argv[i];
Calin Juravle2e2db782016-02-23 12:00:03 +0000184 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700185 if (option == "--dump-only") {
186 dump_only_ = true;
David Sehr7c80f2d2017-02-07 16:47:58 -0800187 } else if (option == "--dump-classes") {
188 dump_classes_ = true;
189 } else if (option.starts_with("--create-profile-from=")) {
190 create_profile_from_file_ = option.substr(strlen("--create-profile-from=")).ToString();
David Sehr4fcdd6d2016-05-24 14:52:31 -0700191 } else if (option.starts_with("--dump-output-to-fd=")) {
192 ParseUintOption(option, "--dump-output-to-fd", &dump_output_to_fd_, Usage);
Calin Juravle876f3502016-03-24 16:16:34 +0000193 } else if (option.starts_with("--profile-file=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000194 profile_files_.push_back(option.substr(strlen("--profile-file=")).ToString());
195 } else if (option.starts_with("--profile-file-fd=")) {
196 ParseFdForCollection(option, "--profile-file-fd", &profile_files_fd_);
197 } else if (option.starts_with("--reference-profile-file=")) {
198 reference_profile_file_ = option.substr(strlen("--reference-profile-file=")).ToString();
199 } else if (option.starts_with("--reference-profile-file-fd=")) {
200 ParseUintOption(option, "--reference-profile-file-fd", &reference_profile_file_fd_, Usage);
David Sehr546d24f2016-06-02 10:46:19 -0700201 } else if (option.starts_with("--dex-location=")) {
202 dex_locations_.push_back(option.substr(strlen("--dex-location=")).ToString());
203 } else if (option.starts_with("--apk-fd=")) {
204 ParseFdForCollection(option, "--apk-fd", &apks_fd_);
David Sehr7c80f2d2017-02-07 16:47:58 -0800205 } else if (option.starts_with("--apk=")) {
206 apk_files_.push_back(option.substr(strlen("--apk=")).ToString());
Calin Juravle7bcdb532016-06-07 16:14:47 +0100207 } else if (option.starts_with("--generate-test-profile=")) {
208 test_profile_ = option.substr(strlen("--generate-test-profile=")).ToString();
209 } else if (option.starts_with("--generate-test-profile-num-dex=")) {
210 ParseUintOption(option,
211 "--generate-test-profile-num-dex",
212 &test_profile_num_dex_,
213 Usage);
214 } else if (option.starts_with("--generate-test-profile-method-ratio")) {
215 ParseUintOption(option,
216 "--generate-test-profile-method-ratio",
217 &test_profile_method_ratio_,
218 Usage);
219 } else if (option.starts_with("--generate-test-profile-class-ratio")) {
220 ParseUintOption(option,
221 "--generate-test-profile-class-ratio",
222 &test_profile_class_ratio_,
223 Usage);
Calin Juravle2e2db782016-02-23 12:00:03 +0000224 } else {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700225 Usage("Unknown argument '%s'", option.data());
Calin Juravle2e2db782016-02-23 12:00:03 +0000226 }
227 }
228
David Sehr153da0e2017-02-15 08:54:51 -0800229 // Validate global consistency between file/fd options.
Calin Juravle2e2db782016-02-23 12:00:03 +0000230 if (!profile_files_.empty() && !profile_files_fd_.empty()) {
231 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
232 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700233 if (!reference_profile_file_.empty() && FdIsValid(reference_profile_file_fd_)) {
234 Usage("Reference profile should not be specified with both "
235 "--reference-profile-file-fd and --reference-profile-file");
236 }
David Sehr153da0e2017-02-15 08:54:51 -0800237 if (!apk_files_.empty() && !apks_fd_.empty()) {
238 Usage("APK files should not be specified with both --apk-fd and --apk");
Calin Juravle2e2db782016-02-23 12:00:03 +0000239 }
240 }
241
242 ProfileAssistant::ProcessingResult ProcessProfiles() {
David Sehr153da0e2017-02-15 08:54:51 -0800243 // Validate that at least one profile file was passed, as well as a reference profile.
244 if (profile_files_.empty() && profile_files_fd_.empty()) {
245 Usage("No profile files specified.");
246 }
247 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
248 Usage("No reference profile file specified.");
249 }
250 if ((!profile_files_.empty() && FdIsValid(reference_profile_file_fd_)) ||
251 (!profile_files_fd_.empty() && !FdIsValid(reference_profile_file_fd_))) {
252 Usage("Options --profile-file-fd and --reference-profile-file-fd "
253 "should only be used together");
254 }
Calin Juravle2e2db782016-02-23 12:00:03 +0000255 ProfileAssistant::ProcessingResult result;
256 if (profile_files_.empty()) {
257 // The file doesn't need to be flushed here (ProcessProfiles will do it)
258 // so don't check the usage.
259 File file(reference_profile_file_fd_, false);
260 result = ProfileAssistant::ProcessProfiles(profile_files_fd_, reference_profile_file_fd_);
261 CloseAllFds(profile_files_fd_, "profile_files_fd_");
262 } else {
263 result = ProfileAssistant::ProcessProfiles(profile_files_, reference_profile_file_);
264 }
265 return result;
266 }
267
David Sehr7c80f2d2017-02-07 16:47:58 -0800268 void OpenApkFilesFromLocations(std::vector<std::unique_ptr<const DexFile>>* dex_files) {
269 bool use_apk_fd_list = !apks_fd_.empty();
270 if (use_apk_fd_list) {
David Sehr153da0e2017-02-15 08:54:51 -0800271 // Get the APKs from the collection of FDs.
David Sehr7c80f2d2017-02-07 16:47:58 -0800272 CHECK_EQ(dex_locations_.size(), apks_fd_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800273 } else if (!apk_files_.empty()) {
274 // Get the APKs from the collection of filenames.
David Sehr7c80f2d2017-02-07 16:47:58 -0800275 CHECK_EQ(dex_locations_.size(), apk_files_.size());
David Sehr153da0e2017-02-15 08:54:51 -0800276 } else {
277 // No APKs were specified.
278 CHECK(dex_locations_.empty());
279 return;
David Sehr7c80f2d2017-02-07 16:47:58 -0800280 }
281 static constexpr bool kVerifyChecksum = true;
282 for (size_t i = 0; i < dex_locations_.size(); ++i) {
283 std::string error_msg;
284 std::vector<std::unique_ptr<const DexFile>> dex_files_for_location;
285 if (use_apk_fd_list) {
286 if (DexFile::OpenZip(apks_fd_[i],
287 dex_locations_[i],
288 kVerifyChecksum,
289 &error_msg,
290 &dex_files_for_location)) {
291 } else {
292 LOG(WARNING) << "OpenZip failed for '" << dex_locations_[i] << "' " << error_msg;
293 continue;
294 }
295 } else {
296 if (DexFile::Open(apk_files_[i].c_str(),
297 dex_locations_[i],
298 kVerifyChecksum,
299 &error_msg,
300 &dex_files_for_location)) {
301 } else {
302 LOG(WARNING) << "Open failed for '" << dex_locations_[i] << "' " << error_msg;
303 continue;
304 }
305 }
306 for (std::unique_ptr<const DexFile>& dex_file : dex_files_for_location) {
307 dex_files->emplace_back(std::move(dex_file));
308 }
309 }
310 }
311
David Sehrb18991b2017-02-08 20:58:10 -0800312 int DumpOneProfile(const std::string& banner,
313 const std::string& filename,
314 int fd,
315 const std::vector<std::unique_ptr<const DexFile>>* dex_files,
316 std::string* dump) {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700317 if (!filename.empty()) {
318 fd = open(filename.c_str(), O_RDWR);
319 if (fd < 0) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800320 LOG(ERROR) << "Cannot open " << filename << strerror(errno);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700321 return -1;
322 }
Calin Juravle876f3502016-03-24 16:16:34 +0000323 }
324 ProfileCompilationInfo info;
325 if (!info.Load(fd)) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800326 LOG(ERROR) << "Cannot load profile info from fd=" << fd << "\n";
Calin Juravle876f3502016-03-24 16:16:34 +0000327 return -1;
328 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700329 std::string this_dump = banner + "\n" + info.DumpInfo(dex_files) + "\n";
330 *dump += this_dump;
331 if (close(fd) < 0) {
332 PLOG(WARNING) << "Failed to close descriptor";
333 }
334 return 0;
335 }
336
337 int DumpProfileInfo() {
David Sehr153da0e2017-02-15 08:54:51 -0800338 // Validate that at least one profile file or reference was specified.
339 if (profile_files_.empty() && profile_files_fd_.empty() &&
340 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
341 Usage("No profile files or reference profile specified.");
342 }
David Sehr4fcdd6d2016-05-24 14:52:31 -0700343 static const char* kEmptyString = "";
David Sehr546d24f2016-06-02 10:46:19 -0700344 static const char* kOrdinaryProfile = "=== profile ===";
345 static const char* kReferenceProfile = "=== reference profile ===";
346
347 // Open apk/zip files and and read dex files.
348 MemMap::Init(); // for ZipArchive::OpenFromFd
David Sehrb18991b2017-02-08 20:58:10 -0800349 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7c80f2d2017-02-07 16:47:58 -0800350 OpenApkFilesFromLocations(&dex_files);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700351 std::string dump;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700352 // Dump individual profile files.
353 if (!profile_files_fd_.empty()) {
354 for (int profile_file_fd : profile_files_fd_) {
David Sehr546d24f2016-06-02 10:46:19 -0700355 int ret = DumpOneProfile(kOrdinaryProfile,
356 kEmptyString,
357 profile_file_fd,
358 &dex_files,
359 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700360 if (ret != 0) {
361 return ret;
362 }
363 }
364 }
365 if (!profile_files_.empty()) {
366 for (const std::string& profile_file : profile_files_) {
David Sehr546d24f2016-06-02 10:46:19 -0700367 int ret = DumpOneProfile(kOrdinaryProfile, profile_file, kInvalidFd, &dex_files, &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700368 if (ret != 0) {
369 return ret;
370 }
371 }
372 }
373 // Dump reference profile file.
374 if (FdIsValid(reference_profile_file_fd_)) {
David Sehr546d24f2016-06-02 10:46:19 -0700375 int ret = DumpOneProfile(kReferenceProfile,
376 kEmptyString,
377 reference_profile_file_fd_,
378 &dex_files,
379 &dump);
David Sehr4fcdd6d2016-05-24 14:52:31 -0700380 if (ret != 0) {
381 return ret;
382 }
383 }
384 if (!reference_profile_file_.empty()) {
David Sehr546d24f2016-06-02 10:46:19 -0700385 int ret = DumpOneProfile(kReferenceProfile,
386 reference_profile_file_,
387 kInvalidFd,
388 &dex_files,
David Sehr4fcdd6d2016-05-24 14:52:31 -0700389 &dump);
390 if (ret != 0) {
391 return ret;
392 }
393 }
394 if (!FdIsValid(dump_output_to_fd_)) {
395 std::cout << dump;
396 } else {
397 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
398 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
399 return -1;
400 }
401 }
Calin Juravle876f3502016-03-24 16:16:34 +0000402 return 0;
403 }
404
405 bool ShouldOnlyDumpProfile() {
David Sehr4fcdd6d2016-05-24 14:52:31 -0700406 return dump_only_;
Calin Juravle876f3502016-03-24 16:16:34 +0000407 }
408
David Sehr7c80f2d2017-02-07 16:47:58 -0800409 bool GetClassNames(int fd,
410 std::vector<std::unique_ptr<const DexFile>>* dex_files,
411 std::set<std::string>* class_names) {
412 ProfileCompilationInfo profile_info;
413 if (!profile_info.Load(fd)) {
414 LOG(ERROR) << "Cannot load profile info";
415 return false;
416 }
417 profile_info.GetClassNames(dex_files, class_names);
418 return true;
419 }
420
421 bool GetClassNames(std::string profile_file,
422 std::vector<std::unique_ptr<const DexFile>>* dex_files,
423 std::set<std::string>* class_names) {
424 int fd = open(profile_file.c_str(), O_RDONLY);
425 if (!FdIsValid(fd)) {
426 LOG(ERROR) << "Cannot open " << profile_file << strerror(errno);
427 return false;
428 }
429 if (!GetClassNames(fd, dex_files, class_names)) {
430 return false;
431 }
432 if (close(fd) < 0) {
433 PLOG(WARNING) << "Failed to close descriptor";
434 }
435 return true;
436 }
437
438 int DumpClasses() {
David Sehr153da0e2017-02-15 08:54:51 -0800439 // Validate that at least one profile file or reference was specified.
440 if (profile_files_.empty() && profile_files_fd_.empty() &&
441 reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
442 Usage("No profile files or reference profile specified.");
443 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800444 // Open apk/zip files and and read dex files.
445 MemMap::Init(); // for ZipArchive::OpenFromFd
446 // Open the dex files to get the names for classes.
447 std::vector<std::unique_ptr<const DexFile>> dex_files;
448 OpenApkFilesFromLocations(&dex_files);
449 // Build a vector of class names from individual profile files.
450 std::set<std::string> class_names;
451 if (!profile_files_fd_.empty()) {
452 for (int profile_file_fd : profile_files_fd_) {
453 if (!GetClassNames(profile_file_fd, &dex_files, &class_names)) {
454 return -1;
455 }
456 }
457 }
458 if (!profile_files_.empty()) {
459 for (const std::string& profile_file : profile_files_) {
460 if (!GetClassNames(profile_file, &dex_files, &class_names)) {
461 return -1;
462 }
463 }
464 }
465 // Concatenate class names from reference profile file.
466 if (FdIsValid(reference_profile_file_fd_)) {
467 if (!GetClassNames(reference_profile_file_fd_, &dex_files, &class_names)) {
468 return -1;
469 }
470 }
471 if (!reference_profile_file_.empty()) {
472 if (!GetClassNames(reference_profile_file_, &dex_files, &class_names)) {
473 return -1;
474 }
475 }
476 // Dump the class names.
477 std::string dump;
478 for (const std::string& class_name : class_names) {
479 dump += class_name + std::string("\n");
480 }
481 if (!FdIsValid(dump_output_to_fd_)) {
482 std::cout << dump;
483 } else {
484 unix_file::FdFile out_fd(dump_output_to_fd_, false /*check_usage*/);
485 if (!out_fd.WriteFully(dump.c_str(), dump.length())) {
486 return -1;
487 }
488 }
489 return 0;
490 }
491
492 bool ShouldOnlyDumpClasses() {
493 return dump_classes_;
494 }
495
496 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
497 // the given function.
498 template <typename T>
499 static T* ReadCommentedInputFromFile(
500 const char* input_filename, std::function<std::string(const char*)>* process) {
501 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
502 if (input_file.get() == nullptr) {
503 LOG(ERROR) << "Failed to open input file " << input_filename;
504 return nullptr;
505 }
506 std::unique_ptr<T> result(
507 ReadCommentedInputStream<T>(*input_file, process));
508 input_file->close();
509 return result.release();
510 }
511
512 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
513 // with the given function.
514 template <typename T>
515 static T* ReadCommentedInputStream(
516 std::istream& in_stream,
517 std::function<std::string(const char*)>* process) {
518 std::unique_ptr<T> output(new T());
519 while (in_stream.good()) {
520 std::string dot;
521 std::getline(in_stream, dot);
522 if (android::base::StartsWith(dot, "#") || dot.empty()) {
523 continue;
524 }
525 if (process != nullptr) {
526 std::string descriptor((*process)(dot.c_str()));
527 output->insert(output->end(), descriptor);
528 } else {
529 output->insert(output->end(), dot);
530 }
531 }
532 return output.release();
533 }
534
Calin Juravlee0ac1152017-02-13 19:03:47 -0800535 // Find class klass_descriptor in the given dex_files and store its reference
536 // in the out parameter class_ref.
537 // Return true if the definition of the class was found in any of the dex_files.
538 bool FindClass(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
539 const std::string& klass_descriptor,
540 /*out*/ProfileMethodInfo::ProfileClassReference* class_ref) {
541 for (const std::unique_ptr<const DexFile>& dex_file_ptr : dex_files) {
542 const DexFile* dex_file = dex_file_ptr.get();
543 const DexFile::TypeId* type_id = dex_file->FindTypeId(klass_descriptor.c_str());
544 if (type_id == nullptr) {
545 continue;
546 }
547 dex::TypeIndex type_index = dex_file->GetIndexForTypeId(*type_id);
548 if (dex_file->FindClassDef(type_index) == nullptr) {
549 // Class is only referenced in the current dex file but not defined in it.
550 continue;
551 }
552 class_ref->dex_file = dex_file;
553 class_ref->type_index = type_index;
554 return true;
555 }
556 return false;
557 }
558
559 // Find the method specified by method_spec in the class class_ref. The method
560 // must have a single INVOKE_VIRTUAL in its byte code.
561 // Upon success it returns true and stores the method index and the invoke dex pc
562 // in the output parameters.
563 // The format of the method spec is "inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
564 //
565 // TODO(calin): support INVOKE_INTERFACE and the range variants.
566 bool FindMethodWithSingleInvoke(const ProfileMethodInfo::ProfileClassReference& class_ref,
567 const std::string& method_spec,
568 /*out*/uint16_t* method_index,
569 /*out*/uint32_t* dex_pc) {
570 std::vector<std::string> name_and_signature;
571 Split(method_spec, kProfileParsingFirstCharInSignature, &name_and_signature);
572 if (name_and_signature.size() != 2) {
573 LOG(ERROR) << "Invalid method name and signature " << method_spec;
574 }
575 const std::string& name = name_and_signature[0];
576 const std::string& signature = kProfileParsingFirstCharInSignature + name_and_signature[1];
577 const DexFile* dex_file = class_ref.dex_file;
578
579 const DexFile::StringId* name_id = dex_file->FindStringId(name.c_str());
580 if (name_id == nullptr) {
581 LOG(ERROR) << "Could not find name: " << name;
582 return false;
583 }
584 dex::TypeIndex return_type_idx;
585 std::vector<dex::TypeIndex> param_type_idxs;
586 if (!dex_file->CreateTypeList(signature, &return_type_idx, &param_type_idxs)) {
587 LOG(ERROR) << "Could not create type list" << signature;
588 return false;
589 }
590 const DexFile::ProtoId* proto_id = dex_file->FindProtoId(return_type_idx, param_type_idxs);
591 if (proto_id == nullptr) {
592 LOG(ERROR) << "Could not find proto_id: " << name;
593 return false;
594 }
595 const DexFile::MethodId* method_id = dex_file->FindMethodId(
596 dex_file->GetTypeId(class_ref.type_index), *name_id, *proto_id);
597 if (method_id == nullptr) {
598 LOG(ERROR) << "Could not find method_id: " << name;
599 return false;
600 }
601
602 *method_index = dex_file->GetIndexForMethodId(*method_id);
603
604 uint32_t offset = dex_file->FindCodeItemOffset(
605 *dex_file->FindClassDef(class_ref.type_index),
606 *method_index);
607 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(offset);
608
609 bool found_invoke = false;
610 for (CodeItemIterator it(*code_item); !it.Done(); it.Advance()) {
611 if (it.CurrentInstruction().Opcode() == Instruction::INVOKE_VIRTUAL) {
612 if (found_invoke) {
613 LOG(ERROR) << "Multiple invoke INVOKE_VIRTUAL found: " << name;
614 return false;
615 }
616 found_invoke = true;
617 *dex_pc = it.CurrentDexPc();
618 }
619 }
620 if (!found_invoke) {
621 LOG(ERROR) << "Could not find any INVOKE_VIRTUAL: " << name;
622 }
623 return found_invoke;
624 }
625
626 // Process a line defining a class or a method and its inline caches.
627 // Upon success return true and add the class or the method info to profile.
Calin Juravle589e71e2017-03-03 16:05:05 -0800628 // The possible line formats are:
629 // "LJustTheCass;".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800630 // "LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;".
Calin Juravle589e71e2017-03-03 16:05:05 -0800631 // "LTestInline;->inlineMissingTypes(LSuper;)I+missing_types".
632 // "LTestInline;->inlineNoInlineCaches(LSuper;)I".
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700633 // "LTestInline;->*".
Calin Juravlee0ac1152017-02-13 19:03:47 -0800634 // The method and classes are searched only in the given dex files.
635 bool ProcessLine(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
636 const std::string& line,
637 /*out*/ProfileCompilationInfo* profile) {
638 std::string klass;
639 std::string method_str;
640 size_t method_sep_index = line.find(kMethodSep);
641 if (method_sep_index == std::string::npos) {
642 klass = line;
643 } else {
644 klass = line.substr(0, method_sep_index);
645 method_str = line.substr(method_sep_index + kMethodSep.size());
646 }
647
648 ProfileMethodInfo::ProfileClassReference class_ref;
649 if (!FindClass(dex_files, klass, &class_ref)) {
Mathieu Chartier3f121342017-03-06 11:16:20 -0800650 LOG(WARNING) << "Could not find class: " << klass;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800651 return false;
652 }
653
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700654 if (method_str.empty() || method_str == kClassAllMethods) {
655 // Start by adding the class.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800656 std::set<DexCacheResolvedClasses> resolved_class_set;
657 const DexFile* dex_file = class_ref.dex_file;
658 const auto& dex_resolved_classes = resolved_class_set.emplace(
659 dex_file->GetLocation(),
660 dex_file->GetBaseLocation(),
661 dex_file->GetLocationChecksum());
662 dex_resolved_classes.first->AddClass(class_ref.type_index);
Mathieu Chartierd808e8b2017-03-21 13:37:41 -0700663 std::vector<ProfileMethodInfo> methods;
664 if (method_str == kClassAllMethods) {
665 // Add all of the methods.
666 const DexFile::ClassDef* class_def = dex_file->FindClassDef(class_ref.type_index);
667 const uint8_t* class_data = dex_file->GetClassData(*class_def);
668 if (class_data != nullptr) {
669 ClassDataItemIterator it(*dex_file, class_data);
670 while (it.HasNextStaticField() || it.HasNextInstanceField()) {
671 it.Next();
672 }
673 while (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
674 if (it.GetMethodCodeItemOffset() != 0) {
675 // Add all of the methods that have code to the profile.
676 const uint32_t method_idx = it.GetMemberIndex();
677 methods.push_back(ProfileMethodInfo(dex_file, method_idx));
678 }
679 it.Next();
680 }
681 }
682 }
683 profile->AddMethodsAndClasses(methods, resolved_class_set);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800684 return true;
685 }
686
687 // Process the method.
688 std::string method_spec;
689 std::vector<std::string> inline_cache_elems;
690
691 std::vector<std::string> method_elems;
Calin Juravle589e71e2017-03-03 16:05:05 -0800692 bool is_missing_types = false;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800693 Split(method_str, kProfileParsingInlineChacheSep, &method_elems);
694 if (method_elems.size() == 2) {
695 method_spec = method_elems[0];
Calin Juravle589e71e2017-03-03 16:05:05 -0800696 is_missing_types = method_elems[1] == kMissingTypesMarker;
697 if (!is_missing_types) {
698 Split(method_elems[1], kProfileParsingTypeSep, &inline_cache_elems);
699 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800700 } else if (method_elems.size() == 1) {
701 method_spec = method_elems[0];
702 } else {
703 LOG(ERROR) << "Invalid method line: " << line;
704 return false;
705 }
706
707 uint16_t method_index;
708 uint32_t dex_pc;
709 if (!FindMethodWithSingleInvoke(class_ref, method_spec, &method_index, &dex_pc)) {
710 return false;
711 }
712 std::vector<ProfileMethodInfo::ProfileClassReference> classes(inline_cache_elems.size());
713 size_t class_it = 0;
714 for (const std::string ic_class : inline_cache_elems) {
715 if (!FindClass(dex_files, ic_class, &(classes[class_it++]))) {
716 LOG(ERROR) << "Could not find class: " << ic_class;
717 return false;
718 }
719 }
720 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravle589e71e2017-03-03 16:05:05 -0800721 inline_caches.emplace_back(dex_pc, is_missing_types, classes);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800722 std::vector<ProfileMethodInfo> pmi;
723 pmi.emplace_back(class_ref.dex_file, method_index, inline_caches);
724
725 profile->AddMethodsAndClasses(pmi, std::set<DexCacheResolvedClasses>());
726 return true;
727 }
728
729 // Creates a profile from a human friendly textual representation.
730 // The expected input format is:
731 // # Classes
732 // Ljava/lang/Comparable;
733 // Ljava/lang/Math;
734 // # Methods with inline caches
735 // LTestInline;->inlinePolymorphic(LSuper;)I+LSubA;,LSubB;,LSubC;
736 // LTestInline;->noInlineCache(LSuper;)I
David Sehr7c80f2d2017-02-07 16:47:58 -0800737 int CreateProfile() {
David Sehr153da0e2017-02-15 08:54:51 -0800738 // Validate parameters for this command.
739 if (apk_files_.empty() && apks_fd_.empty()) {
740 Usage("APK files must be specified");
741 }
742 if (dex_locations_.empty()) {
743 Usage("DEX locations must be specified");
744 }
745 if (reference_profile_file_.empty() && !FdIsValid(reference_profile_file_fd_)) {
746 Usage("Reference profile must be specified with --reference-profile-file or "
747 "--reference-profile-file-fd");
748 }
749 if (!profile_files_.empty() || !profile_files_fd_.empty()) {
750 Usage("Profile must be specified with --reference-profile-file or "
751 "--reference-profile-file-fd");
752 }
753 // for ZipArchive::OpenFromFd
754 MemMap::Init();
David Sehr7c80f2d2017-02-07 16:47:58 -0800755 // Open the profile output file if needed.
756 int fd = reference_profile_file_fd_;
757 if (!FdIsValid(fd)) {
758 CHECK(!reference_profile_file_.empty());
759 fd = open(reference_profile_file_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
760 if (fd < 0) {
761 LOG(ERROR) << "Cannot open " << reference_profile_file_ << strerror(errno);
762 return -1;
763 }
764 }
Calin Juravlee0ac1152017-02-13 19:03:47 -0800765 // Read the user-specified list of classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800766 std::unique_ptr<std::unordered_set<std::string>>
Calin Juravlee0ac1152017-02-13 19:03:47 -0800767 user_lines(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
David Sehr7c80f2d2017-02-07 16:47:58 -0800768 create_profile_from_file_.c_str(), nullptr)); // No post-processing.
Calin Juravlee0ac1152017-02-13 19:03:47 -0800769
770 // Open the dex files to look up classes and methods.
David Sehr7c80f2d2017-02-07 16:47:58 -0800771 std::vector<std::unique_ptr<const DexFile>> dex_files;
772 OpenApkFilesFromLocations(&dex_files);
Calin Juravlee0ac1152017-02-13 19:03:47 -0800773
774 // Process the lines one by one and add the successful ones to the profile.
David Sehr7c80f2d2017-02-07 16:47:58 -0800775 ProfileCompilationInfo info;
Calin Juravlee0ac1152017-02-13 19:03:47 -0800776
777 for (const auto& line : *user_lines) {
778 ProcessLine(dex_files, line, &info);
779 }
780
David Sehr7c80f2d2017-02-07 16:47:58 -0800781 // Write the profile file.
782 CHECK(info.Save(fd));
783 if (close(fd) < 0) {
784 PLOG(WARNING) << "Failed to close descriptor";
785 }
786 return 0;
787 }
788
789 bool ShouldCreateProfile() {
790 return !create_profile_from_file_.empty();
791 }
792
Calin Juravle7bcdb532016-06-07 16:14:47 +0100793 int GenerateTestProfile() {
David Sehr153da0e2017-02-15 08:54:51 -0800794 // Validate parameters for this command.
795 if (test_profile_method_ratio_ > 100) {
796 Usage("Invalid ratio for --generate-test-profile-method-ratio");
797 }
798 if (test_profile_class_ratio_ > 100) {
799 Usage("Invalid ratio for --generate-test-profile-class-ratio");
800 }
801 // ShouldGenerateTestProfile confirms !test_profile_.empty().
George Burgess IV71f77262016-10-25 13:08:17 -0700802 int profile_test_fd = open(test_profile_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
Calin Juravle7bcdb532016-06-07 16:14:47 +0100803 if (profile_test_fd < 0) {
David Sehr7c80f2d2017-02-07 16:47:58 -0800804 LOG(ERROR) << "Cannot open " << test_profile_ << strerror(errno);
Calin Juravle7bcdb532016-06-07 16:14:47 +0100805 return -1;
806 }
807
808 bool result = ProfileCompilationInfo::GenerateTestProfile(profile_test_fd,
David Sehr7c80f2d2017-02-07 16:47:58 -0800809 test_profile_num_dex_,
810 test_profile_method_ratio_,
811 test_profile_class_ratio_);
Calin Juravle7bcdb532016-06-07 16:14:47 +0100812 close(profile_test_fd); // ignore close result.
813 return result ? 0 : -1;
814 }
815
816 bool ShouldGenerateTestProfile() {
817 return !test_profile_.empty();
818 }
819
Calin Juravle2e2db782016-02-23 12:00:03 +0000820 private:
821 static void ParseFdForCollection(const StringPiece& option,
822 const char* arg_name,
823 std::vector<int>* fds) {
824 int fd;
825 ParseUintOption(option, arg_name, &fd, Usage);
826 fds->push_back(fd);
827 }
828
829 static void CloseAllFds(const std::vector<int>& fds, const char* descriptor) {
830 for (size_t i = 0; i < fds.size(); i++) {
831 if (close(fds[i]) < 0) {
832 PLOG(WARNING) << "Failed to close descriptor for " << descriptor << " at index " << i;
833 }
834 }
835 }
836
837 void LogCompletionTime() {
David Sehr52683cf2016-05-05 09:02:38 -0700838 static constexpr uint64_t kLogThresholdTime = MsToNs(100); // 100ms
839 uint64_t time_taken = NanoTime() - start_ns_;
David Sehred793012016-05-05 13:39:43 -0700840 if (time_taken > kLogThresholdTime) {
David Sehrd8557182016-05-06 12:29:35 -0700841 LOG(WARNING) << "profman took " << PrettyDuration(time_taken);
David Sehred793012016-05-05 13:39:43 -0700842 }
Calin Juravle2e2db782016-02-23 12:00:03 +0000843 }
844
845 std::vector<std::string> profile_files_;
846 std::vector<int> profile_files_fd_;
David Sehr546d24f2016-06-02 10:46:19 -0700847 std::vector<std::string> dex_locations_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800848 std::vector<std::string> apk_files_;
David Sehr546d24f2016-06-02 10:46:19 -0700849 std::vector<int> apks_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +0000850 std::string reference_profile_file_;
851 int reference_profile_file_fd_;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700852 bool dump_only_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800853 bool dump_classes_;
David Sehr4fcdd6d2016-05-24 14:52:31 -0700854 int dump_output_to_fd_;
Calin Juravle7bcdb532016-06-07 16:14:47 +0100855 std::string test_profile_;
David Sehr7c80f2d2017-02-07 16:47:58 -0800856 std::string create_profile_from_file_;
Calin Juravle7bcdb532016-06-07 16:14:47 +0100857 uint16_t test_profile_num_dex_;
858 uint16_t test_profile_method_ratio_;
859 uint16_t test_profile_class_ratio_;
Calin Juravle2e2db782016-02-23 12:00:03 +0000860 uint64_t start_ns_;
861};
862
863// See ProfileAssistant::ProcessingResult for return codes.
864static int profman(int argc, char** argv) {
865 ProfMan profman;
866
867 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
868 profman.ParseArgs(argc, argv);
869
Calin Juravle7bcdb532016-06-07 16:14:47 +0100870 if (profman.ShouldGenerateTestProfile()) {
871 return profman.GenerateTestProfile();
872 }
Calin Juravle876f3502016-03-24 16:16:34 +0000873 if (profman.ShouldOnlyDumpProfile()) {
874 return profman.DumpProfileInfo();
875 }
David Sehr7c80f2d2017-02-07 16:47:58 -0800876 if (profman.ShouldOnlyDumpClasses()) {
877 return profman.DumpClasses();
878 }
879 if (profman.ShouldCreateProfile()) {
880 return profman.CreateProfile();
881 }
Calin Juravle2e2db782016-02-23 12:00:03 +0000882 // Process profile information and assess if we need to do a profile guided compilation.
883 // This operation involves I/O.
884 return profman.ProcessProfiles();
885}
886
887} // namespace art
888
889int main(int argc, char **argv) {
890 return art::profman(argc, argv);
891}
892