blob: 9ba2d1a3553af2e2ff2e81795ed604930b4f756d [file] [log] [blame]
Calin Juravle31f2c152015-10-23 17:56:15 +01001/*
2 * Copyright (C) 2015 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 Juravle33083d62017-01-18 15:29:12 -080017#include "profile_compilation_info.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010018
Calin Juravle64142952016-03-21 14:37:55 +000019#include "errno.h"
20#include <limits.h>
Calin Juravle4d77b6a2015-12-01 18:38:09 +000021#include <vector>
Calin Juravle7bcdb532016-06-07 16:14:47 +010022#include <stdlib.h>
Calin Juravle31f2c152015-10-23 17:56:15 +010023#include <sys/file.h>
24#include <sys/stat.h>
25#include <sys/uio.h>
26
27#include "art_method-inl.h"
28#include "base/mutex.h"
Calin Juravle877fd962016-01-05 14:29:29 +000029#include "base/scoped_flock.h"
Calin Juravle66f55232015-12-08 15:09:10 +000030#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080031#include "base/systrace.h"
Calin Juravle877fd962016-01-05 14:29:29 +000032#include "base/unix_file/fd_file.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010033#include "jit/profiling_info.h"
Calin Juravle877fd962016-01-05 14:29:29 +000034#include "os.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010035#include "safe_map.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010036
37namespace art {
38
Calin Juravle64142952016-03-21 14:37:55 +000039const uint8_t ProfileCompilationInfo::kProfileMagic[] = { 'p', 'r', 'o', '\0' };
Jeff Hao54b58552016-11-16 15:15:04 -080040const uint8_t ProfileCompilationInfo::kProfileVersion[] = { '0', '0', '2', '\0' };
Calin Juravle64142952016-03-21 14:37:55 +000041
42static constexpr uint16_t kMaxDexFileKeyLength = PATH_MAX;
43
Calin Juravlec4588572016-06-08 14:24:13 +010044// Debug flag to ignore checksums when testing if a method or a class is present in the profile.
Calin Juravle7bcdb532016-06-07 16:14:47 +010045// Used to facilitate testing profile guided compilation across a large number of apps
Calin Juravlec4588572016-06-08 14:24:13 +010046// using the same test profile.
47static constexpr bool kDebugIgnoreChecksum = false;
48
Calin Juravle34900cc2016-02-05 16:19:19 +000049// Transform the actual dex location into relative paths.
50// Note: this is OK because we don't store profiles of different apps into the same file.
51// Apps with split apks don't cause trouble because each split has a different name and will not
52// collide with other entries.
Calin Juravle31708b72016-02-05 19:44:05 +000053std::string ProfileCompilationInfo::GetProfileDexFileKey(const std::string& dex_location) {
Calin Juravle34900cc2016-02-05 16:19:19 +000054 DCHECK(!dex_location.empty());
55 size_t last_sep_index = dex_location.find_last_of('/');
56 if (last_sep_index == std::string::npos) {
57 return dex_location;
58 } else {
Calin Juravle31708b72016-02-05 19:44:05 +000059 DCHECK(last_sep_index < dex_location.size());
60 return dex_location.substr(last_sep_index + 1);
Calin Juravle34900cc2016-02-05 16:19:19 +000061 }
62}
63
Calin Juravle67265462016-03-18 16:23:40 +000064bool ProfileCompilationInfo::AddMethodsAndClasses(
Calin Juravle99629622016-04-19 16:33:46 +010065 const std::vector<MethodReference>& methods,
Calin Juravle67265462016-03-18 16:23:40 +000066 const std::set<DexCacheResolvedClasses>& resolved_classes) {
Calin Juravle99629622016-04-19 16:33:46 +010067 for (const MethodReference& method : methods) {
68 if (!AddMethodIndex(GetProfileDexFileKey(method.dex_file->GetLocation()),
69 method.dex_file->GetLocationChecksum(),
70 method.dex_method_index)) {
Calin Juravle67265462016-03-18 16:23:40 +000071 return false;
72 }
73 }
74 for (const DexCacheResolvedClasses& dex_cache : resolved_classes) {
75 if (!AddResolvedClasses(dex_cache)) {
76 return false;
77 }
78 }
79 return true;
80}
81
Calin Juravle5d1bd0a2016-03-24 20:33:22 +000082bool ProfileCompilationInfo::MergeAndSave(const std::string& filename,
83 uint64_t* bytes_written,
84 bool force) {
Calin Juravle67265462016-03-18 16:23:40 +000085 ScopedTrace trace(__PRETTY_FUNCTION__);
86 ScopedFlock flock;
87 std::string error;
88 if (!flock.Init(filename.c_str(), O_RDWR | O_NOFOLLOW | O_CLOEXEC, /* block */ false, &error)) {
89 LOG(WARNING) << "Couldn't lock the profile file " << filename << ": " << error;
90 return false;
91 }
92
93 int fd = flock.GetFile()->Fd();
94
95 // Load the file but keep a copy around to be able to infer if the content has changed.
96 ProfileCompilationInfo fileInfo;
Calin Juravle5d1bd0a2016-03-24 20:33:22 +000097 ProfileLoadSatus status = fileInfo.LoadInternal(fd, &error);
98 if (status == kProfileLoadSuccess) {
99 // Merge the content of file into the current object.
100 if (MergeWith(fileInfo)) {
101 // If after the merge we have the same data as what is the file there's no point
102 // in actually doing the write. The file will be exactly the same as before.
103 if (Equals(fileInfo)) {
104 if (bytes_written != nullptr) {
105 *bytes_written = 0;
106 }
107 return true;
108 }
109 } else {
110 LOG(WARNING) << "Could not merge previous profile data from file " << filename;
111 if (!force) {
112 return false;
113 }
114 }
115 } else if (force &&
116 ((status == kProfileLoadVersionMismatch) || (status == kProfileLoadBadData))) {
117 // Log a warning but don't return false. We will clear the profile anyway.
118 LOG(WARNING) << "Clearing bad or obsolete profile data from file "
119 << filename << ": " << error;
120 } else {
121 LOG(WARNING) << "Could not load profile data from file " << filename << ": " << error;
Calin Juravle67265462016-03-18 16:23:40 +0000122 return false;
123 }
124
Calin Juravle5d1bd0a2016-03-24 20:33:22 +0000125 // We need to clear the data because we don't support appending to the profiles yet.
Calin Juravle67265462016-03-18 16:23:40 +0000126 if (!flock.GetFile()->ClearContent()) {
127 PLOG(WARNING) << "Could not clear profile file: " << filename;
128 return false;
129 }
130
131 // This doesn't need locking because we are trying to lock the file for exclusive
132 // access and fail immediately if we can't.
133 bool result = Save(fd);
134 if (result) {
135 VLOG(profiler) << "Successfully saved profile info to " << filename
136 << " Size: " << GetFileSizeBytes(filename);
137 if (bytes_written != nullptr) {
138 *bytes_written = GetFileSizeBytes(filename);
139 }
140 } else {
141 VLOG(profiler) << "Failed to save profile info to " << filename;
142 }
143 return result;
144}
145
Calin Juravle64142952016-03-21 14:37:55 +0000146// Returns true if all the bytes were successfully written to the file descriptor.
147static bool WriteBuffer(int fd, const uint8_t* buffer, size_t byte_count) {
148 while (byte_count > 0) {
149 int bytes_written = TEMP_FAILURE_RETRY(write(fd, buffer, byte_count));
150 if (bytes_written == -1) {
Calin Juravle877fd962016-01-05 14:29:29 +0000151 return false;
152 }
Calin Juravle64142952016-03-21 14:37:55 +0000153 byte_count -= bytes_written; // Reduce the number of remaining bytes.
154 buffer += bytes_written; // Move the buffer forward.
155 }
Calin Juravle877fd962016-01-05 14:29:29 +0000156 return true;
Calin Juravle31f2c152015-10-23 17:56:15 +0100157}
158
Calin Juravle64142952016-03-21 14:37:55 +0000159// Add the string bytes to the buffer.
160static void AddStringToBuffer(std::vector<uint8_t>* buffer, const std::string& value) {
161 buffer->insert(buffer->end(), value.begin(), value.end());
162}
163
164// Insert each byte, from low to high into the buffer.
165template <typename T>
166static void AddUintToBuffer(std::vector<uint8_t>* buffer, T value) {
167 for (size_t i = 0; i < sizeof(T); i++) {
168 buffer->push_back((value >> (i * kBitsPerByte)) & 0xff);
169 }
170}
171
172static constexpr size_t kLineHeaderSize =
173 3 * sizeof(uint16_t) + // method_set.size + class_set.size + dex_location.size
174 sizeof(uint32_t); // checksum
Calin Juravle31f2c152015-10-23 17:56:15 +0100175
176/**
177 * Serialization format:
Calin Juravle64142952016-03-21 14:37:55 +0000178 * magic,version,number_of_lines
179 * dex_location1,number_of_methods1,number_of_classes1,dex_location_checksum1, \
180 * method_id11,method_id12...,class_id1,class_id2...
181 * dex_location2,number_of_methods2,number_of_classes2,dex_location_checksum2, \
182 * method_id21,method_id22...,,class_id1,class_id2...
183 * .....
Calin Juravle31f2c152015-10-23 17:56:15 +0100184 **/
Calin Juravle2e2db782016-02-23 12:00:03 +0000185bool ProfileCompilationInfo::Save(int fd) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800186 ScopedTrace trace(__PRETTY_FUNCTION__);
Calin Juravle2e2db782016-02-23 12:00:03 +0000187 DCHECK_GE(fd, 0);
Calin Juravle64142952016-03-21 14:37:55 +0000188
189 // Cache at most 5KB before writing.
190 static constexpr size_t kMaxSizeToKeepBeforeWriting = 5 * KB;
191 // Use a vector wrapper to avoid keeping track of offsets when we add elements.
192 std::vector<uint8_t> buffer;
193 WriteBuffer(fd, kProfileMagic, sizeof(kProfileMagic));
194 WriteBuffer(fd, kProfileVersion, sizeof(kProfileVersion));
195 AddUintToBuffer(&buffer, static_cast<uint16_t>(info_.size()));
196
Calin Juravle998c2162015-12-21 15:39:33 +0200197 for (const auto& it : info_) {
Calin Juravle64142952016-03-21 14:37:55 +0000198 if (buffer.size() > kMaxSizeToKeepBeforeWriting) {
199 if (!WriteBuffer(fd, buffer.data(), buffer.size())) {
200 return false;
201 }
202 buffer.clear();
203 }
Calin Juravle998c2162015-12-21 15:39:33 +0200204 const std::string& dex_location = it.first;
205 const DexFileData& dex_data = it.second;
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800206 if (dex_data.method_set.empty() && dex_data.class_set.empty()) {
207 continue;
208 }
Calin Juravle31f2c152015-10-23 17:56:15 +0100209
Calin Juravle64142952016-03-21 14:37:55 +0000210 if (dex_location.size() >= kMaxDexFileKeyLength) {
211 LOG(WARNING) << "DexFileKey exceeds allocated limit";
212 return false;
213 }
214
215 // Make sure that the buffer has enough capacity to avoid repeated resizings
216 // while we add data.
217 size_t required_capacity = buffer.size() +
218 kLineHeaderSize +
219 dex_location.size() +
220 sizeof(uint16_t) * (dex_data.class_set.size() + dex_data.method_set.size());
221
222 buffer.reserve(required_capacity);
223
224 DCHECK_LE(dex_location.size(), std::numeric_limits<uint16_t>::max());
225 DCHECK_LE(dex_data.method_set.size(), std::numeric_limits<uint16_t>::max());
226 DCHECK_LE(dex_data.class_set.size(), std::numeric_limits<uint16_t>::max());
227 AddUintToBuffer(&buffer, static_cast<uint16_t>(dex_location.size()));
228 AddUintToBuffer(&buffer, static_cast<uint16_t>(dex_data.method_set.size()));
229 AddUintToBuffer(&buffer, static_cast<uint16_t>(dex_data.class_set.size()));
230 AddUintToBuffer(&buffer, dex_data.checksum); // uint32_t
231
232 AddStringToBuffer(&buffer, dex_location);
233
Calin Juravle998c2162015-12-21 15:39:33 +0200234 for (auto method_it : dex_data.method_set) {
Calin Juravle64142952016-03-21 14:37:55 +0000235 AddUintToBuffer(&buffer, method_it);
Calin Juravle31f2c152015-10-23 17:56:15 +0100236 }
Calin Juravle64142952016-03-21 14:37:55 +0000237 for (auto class_id : dex_data.class_set) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800238 AddUintToBuffer(&buffer, class_id.index_);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800239 }
Calin Juravle64142952016-03-21 14:37:55 +0000240 DCHECK_EQ(required_capacity, buffer.size())
241 << "Failed to add the expected number of bytes in the buffer";
Calin Juravle31f2c152015-10-23 17:56:15 +0100242 }
243
Calin Juravle64142952016-03-21 14:37:55 +0000244 return WriteBuffer(fd, buffer.data(), buffer.size());
Calin Juravle226501b2015-12-11 14:41:31 +0000245}
246
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800247ProfileCompilationInfo::DexFileData* ProfileCompilationInfo::GetOrAddDexFileData(
248 const std::string& dex_location,
249 uint32_t checksum) {
Calin Juravle998c2162015-12-21 15:39:33 +0200250 auto info_it = info_.find(dex_location);
251 if (info_it == info_.end()) {
252 info_it = info_.Put(dex_location, DexFileData(checksum));
253 }
254 if (info_it->second.checksum != checksum) {
255 LOG(WARNING) << "Checksum mismatch for dex " << dex_location;
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800256 return nullptr;
257 }
258 return &info_it->second;
259}
260
261bool ProfileCompilationInfo::AddResolvedClasses(const DexCacheResolvedClasses& classes) {
262 const std::string dex_location = GetProfileDexFileKey(classes.GetDexLocation());
263 const uint32_t checksum = classes.GetLocationChecksum();
264 DexFileData* const data = GetOrAddDexFileData(dex_location, checksum);
265 if (data == nullptr) {
Calin Juravle998c2162015-12-21 15:39:33 +0200266 return false;
267 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800268 data->class_set.insert(classes.GetClasses().begin(), classes.GetClasses().end());
269 return true;
270}
271
272bool ProfileCompilationInfo::AddMethodIndex(const std::string& dex_location,
273 uint32_t checksum,
274 uint16_t method_idx) {
275 DexFileData* const data = GetOrAddDexFileData(dex_location, checksum);
276 if (data == nullptr) {
277 return false;
278 }
279 data->method_set.insert(method_idx);
280 return true;
281}
282
283bool ProfileCompilationInfo::AddClassIndex(const std::string& dex_location,
284 uint32_t checksum,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800285 dex::TypeIndex type_idx) {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800286 DexFileData* const data = GetOrAddDexFileData(dex_location, checksum);
287 if (data == nullptr) {
288 return false;
289 }
Jeff Hao54b58552016-11-16 15:15:04 -0800290 data->class_set.insert(type_idx);
Calin Juravle998c2162015-12-21 15:39:33 +0200291 return true;
292}
293
Calin Juravle64142952016-03-21 14:37:55 +0000294bool ProfileCompilationInfo::ProcessLine(SafeBuffer& line_buffer,
295 uint16_t method_set_size,
296 uint16_t class_set_size,
297 uint32_t checksum,
298 const std::string& dex_location) {
299 for (uint16_t i = 0; i < method_set_size; i++) {
300 uint16_t method_idx = line_buffer.ReadUintAndAdvance<uint16_t>();
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800301 if (!AddMethodIndex(dex_location, checksum, method_idx)) {
Calin Juravle877fd962016-01-05 14:29:29 +0000302 return false;
303 }
Calin Juravle226501b2015-12-11 14:41:31 +0000304 }
Calin Juravle64142952016-03-21 14:37:55 +0000305
306 for (uint16_t i = 0; i < class_set_size; i++) {
Jeff Hao54b58552016-11-16 15:15:04 -0800307 uint16_t type_idx = line_buffer.ReadUintAndAdvance<uint16_t>();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800308 if (!AddClassIndex(dex_location, checksum, dex::TypeIndex(type_idx))) {
Calin Juravle64142952016-03-21 14:37:55 +0000309 return false;
310 }
311 }
Calin Juravle226501b2015-12-11 14:41:31 +0000312 return true;
313}
314
Calin Juravle64142952016-03-21 14:37:55 +0000315// Tests for EOF by trying to read 1 byte from the descriptor.
316// Returns:
317// 0 if the descriptor is at the EOF,
318// -1 if there was an IO error
319// 1 if the descriptor has more content to read
320static int testEOF(int fd) {
321 uint8_t buffer[1];
322 return TEMP_FAILURE_RETRY(read(fd, buffer, 1));
323}
324
325// Reads an uint value previously written with AddUintToBuffer.
326template <typename T>
327T ProfileCompilationInfo::SafeBuffer::ReadUintAndAdvance() {
328 static_assert(std::is_unsigned<T>::value, "Type is not unsigned");
329 CHECK_LE(ptr_current_ + sizeof(T), ptr_end_);
330 T value = 0;
331 for (size_t i = 0; i < sizeof(T); i++) {
332 value += ptr_current_[i] << (i * kBitsPerByte);
Calin Juravle226501b2015-12-11 14:41:31 +0000333 }
Calin Juravle64142952016-03-21 14:37:55 +0000334 ptr_current_ += sizeof(T);
335 return value;
336}
337
338bool ProfileCompilationInfo::SafeBuffer::CompareAndAdvance(const uint8_t* data, size_t data_size) {
339 if (ptr_current_ + data_size > ptr_end_) {
340 return false;
341 }
342 if (memcmp(ptr_current_, data, data_size) == 0) {
343 ptr_current_ += data_size;
344 return true;
345 }
346 return false;
347}
348
349ProfileCompilationInfo::ProfileLoadSatus ProfileCompilationInfo::SafeBuffer::FillFromFd(
350 int fd,
351 const std::string& source,
352 /*out*/std::string* error) {
353 size_t byte_count = ptr_end_ - ptr_current_;
354 uint8_t* buffer = ptr_current_;
355 while (byte_count > 0) {
356 int bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, byte_count));
357 if (bytes_read == 0) {
358 *error += "Profile EOF reached prematurely for " + source;
359 return kProfileLoadBadData;
360 } else if (bytes_read < 0) {
361 *error += "Profile IO error for " + source + strerror(errno);
362 return kProfileLoadIOError;
Calin Juravle226501b2015-12-11 14:41:31 +0000363 }
Calin Juravle64142952016-03-21 14:37:55 +0000364 byte_count -= bytes_read;
365 buffer += bytes_read;
Calin Juravle226501b2015-12-11 14:41:31 +0000366 }
Calin Juravle64142952016-03-21 14:37:55 +0000367 return kProfileLoadSuccess;
368}
369
370ProfileCompilationInfo::ProfileLoadSatus ProfileCompilationInfo::ReadProfileHeader(
371 int fd,
372 /*out*/uint16_t* number_of_lines,
373 /*out*/std::string* error) {
374 // Read magic and version
375 const size_t kMagicVersionSize =
376 sizeof(kProfileMagic) +
377 sizeof(kProfileVersion) +
378 sizeof(uint16_t); // number of lines
379
380 SafeBuffer safe_buffer(kMagicVersionSize);
381
382 ProfileLoadSatus status = safe_buffer.FillFromFd(fd, "ReadProfileHeader", error);
383 if (status != kProfileLoadSuccess) {
384 return status;
385 }
386
387 if (!safe_buffer.CompareAndAdvance(kProfileMagic, sizeof(kProfileMagic))) {
388 *error = "Profile missing magic";
389 return kProfileLoadVersionMismatch;
390 }
391 if (!safe_buffer.CompareAndAdvance(kProfileVersion, sizeof(kProfileVersion))) {
392 *error = "Profile version mismatch";
393 return kProfileLoadVersionMismatch;
394 }
395 *number_of_lines = safe_buffer.ReadUintAndAdvance<uint16_t>();
396 return kProfileLoadSuccess;
397}
398
399ProfileCompilationInfo::ProfileLoadSatus ProfileCompilationInfo::ReadProfileLineHeader(
400 int fd,
401 /*out*/ProfileLineHeader* line_header,
402 /*out*/std::string* error) {
403 SafeBuffer header_buffer(kLineHeaderSize);
404 ProfileLoadSatus status = header_buffer.FillFromFd(fd, "ReadProfileHeader", error);
405 if (status != kProfileLoadSuccess) {
406 return status;
407 }
408
409 uint16_t dex_location_size = header_buffer.ReadUintAndAdvance<uint16_t>();
410 line_header->method_set_size = header_buffer.ReadUintAndAdvance<uint16_t>();
411 line_header->class_set_size = header_buffer.ReadUintAndAdvance<uint16_t>();
412 line_header->checksum = header_buffer.ReadUintAndAdvance<uint32_t>();
413
414 if (dex_location_size == 0 || dex_location_size > kMaxDexFileKeyLength) {
Goran Jakovljevic4eb6fbf2016-04-25 19:14:17 +0200415 *error = "DexFileKey has an invalid size: " +
416 std::to_string(static_cast<uint32_t>(dex_location_size));
Calin Juravle64142952016-03-21 14:37:55 +0000417 return kProfileLoadBadData;
418 }
419
420 SafeBuffer location_buffer(dex_location_size);
421 status = location_buffer.FillFromFd(fd, "ReadProfileHeaderDexLocation", error);
422 if (status != kProfileLoadSuccess) {
423 return status;
424 }
425 line_header->dex_location.assign(
426 reinterpret_cast<char*>(location_buffer.Get()), dex_location_size);
427 return kProfileLoadSuccess;
428}
429
430ProfileCompilationInfo::ProfileLoadSatus ProfileCompilationInfo::ReadProfileLine(
431 int fd,
432 const ProfileLineHeader& line_header,
433 /*out*/std::string* error) {
434 // Make sure that we don't try to read everything in memory (in case the profile if full).
435 // Split readings in chunks of at most 10kb.
436 static constexpr uint16_t kMaxNumberOfEntriesToRead = 5120;
437 uint16_t methods_left_to_read = line_header.method_set_size;
438 uint16_t classes_left_to_read = line_header.class_set_size;
439
440 while ((methods_left_to_read > 0) || (classes_left_to_read > 0)) {
441 uint16_t methods_to_read = std::min(kMaxNumberOfEntriesToRead, methods_left_to_read);
442 uint16_t max_classes_to_read = kMaxNumberOfEntriesToRead - methods_to_read;
443 uint16_t classes_to_read = std::min(max_classes_to_read, classes_left_to_read);
444
445 size_t line_size = sizeof(uint16_t) * (methods_to_read + classes_to_read);
446 SafeBuffer line_buffer(line_size);
447
448 ProfileLoadSatus status = line_buffer.FillFromFd(fd, "ReadProfileLine", error);
449 if (status != kProfileLoadSuccess) {
450 return status;
451 }
452 if (!ProcessLine(line_buffer,
453 methods_to_read,
454 classes_to_read,
455 line_header.checksum,
456 line_header.dex_location)) {
457 *error = "Error when reading profile file line";
458 return kProfileLoadBadData;
459 }
460 methods_left_to_read -= methods_to_read;
461 classes_left_to_read -= classes_to_read;
462 }
463 return kProfileLoadSuccess;
Calin Juravle226501b2015-12-11 14:41:31 +0000464}
465
Calin Juravle2e2db782016-02-23 12:00:03 +0000466bool ProfileCompilationInfo::Load(int fd) {
Calin Juravle64142952016-03-21 14:37:55 +0000467 std::string error;
468 ProfileLoadSatus status = LoadInternal(fd, &error);
469
470 if (status == kProfileLoadSuccess) {
471 return true;
472 } else {
473 PLOG(WARNING) << "Error when reading profile " << error;
474 return false;
475 }
476}
477
478ProfileCompilationInfo::ProfileLoadSatus ProfileCompilationInfo::LoadInternal(
479 int fd, std::string* error) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800480 ScopedTrace trace(__PRETTY_FUNCTION__);
Calin Juravle2e2db782016-02-23 12:00:03 +0000481 DCHECK_GE(fd, 0);
Calin Juravle226501b2015-12-11 14:41:31 +0000482
Calin Juravle64142952016-03-21 14:37:55 +0000483 struct stat stat_buffer;
484 if (fstat(fd, &stat_buffer) != 0) {
485 return kProfileLoadIOError;
Calin Juravle226501b2015-12-11 14:41:31 +0000486 }
Calin Juravle64142952016-03-21 14:37:55 +0000487 // We allow empty profile files.
488 // Profiles may be created by ActivityManager or installd before we manage to
489 // process them in the runtime or profman.
490 if (stat_buffer.st_size == 0) {
491 return kProfileLoadSuccess;
492 }
493 // Read profile header: magic + version + number_of_lines.
494 uint16_t number_of_lines;
495 ProfileLoadSatus status = ReadProfileHeader(fd, &number_of_lines, error);
496 if (status != kProfileLoadSuccess) {
497 return status;
498 }
499
500 while (number_of_lines > 0) {
501 ProfileLineHeader line_header;
502 // First, read the line header to get the amount of data we need to read.
503 status = ReadProfileLineHeader(fd, &line_header, error);
504 if (status != kProfileLoadSuccess) {
505 return status;
506 }
507
508 // Now read the actual profile line.
509 status = ReadProfileLine(fd, line_header, error);
510 if (status != kProfileLoadSuccess) {
511 return status;
512 }
513 number_of_lines--;
514 }
515
516 // Check that we read everything and that profiles don't contain junk data.
517 int result = testEOF(fd);
518 if (result == 0) {
519 return kProfileLoadSuccess;
520 } else if (result < 0) {
521 return kProfileLoadIOError;
522 } else {
523 *error = "Unexpected content in the profile file";
524 return kProfileLoadBadData;
525 }
Calin Juravle998c2162015-12-21 15:39:33 +0200526}
527
Calin Juravle67265462016-03-18 16:23:40 +0000528bool ProfileCompilationInfo::MergeWith(const ProfileCompilationInfo& other) {
Calin Juravle5d1bd0a2016-03-24 20:33:22 +0000529 // First verify that all checksums match. This will avoid adding garbage to
530 // the current profile info.
531 // Note that the number of elements should be very small, so this should not
532 // be a performance issue.
533 for (const auto& other_it : other.info_) {
534 auto info_it = info_.find(other_it.first);
535 if ((info_it != info_.end()) && (info_it->second.checksum != other_it.second.checksum)) {
536 LOG(WARNING) << "Checksum mismatch for dex " << other_it.first;
537 return false;
538 }
539 }
540 // All checksums match. Import the data.
Calin Juravle998c2162015-12-21 15:39:33 +0200541 for (const auto& other_it : other.info_) {
542 const std::string& other_dex_location = other_it.first;
543 const DexFileData& other_dex_data = other_it.second;
Calin Juravle998c2162015-12-21 15:39:33 +0200544 auto info_it = info_.find(other_dex_location);
545 if (info_it == info_.end()) {
546 info_it = info_.Put(other_dex_location, DexFileData(other_dex_data.checksum));
547 }
Calin Juravle998c2162015-12-21 15:39:33 +0200548 info_it->second.method_set.insert(other_dex_data.method_set.begin(),
549 other_dex_data.method_set.end());
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800550 info_it->second.class_set.insert(other_dex_data.class_set.begin(),
551 other_dex_data.class_set.end());
Calin Juravle998c2162015-12-21 15:39:33 +0200552 }
553 return true;
Calin Juravle226501b2015-12-11 14:41:31 +0000554}
555
Calin Juravlec4588572016-06-08 14:24:13 +0100556static bool ChecksumMatch(const DexFile& dex_file, uint32_t checksum) {
557 return kDebugIgnoreChecksum || dex_file.GetLocationChecksum() == checksum;
558}
559
Calin Juravle226501b2015-12-11 14:41:31 +0000560bool ProfileCompilationInfo::ContainsMethod(const MethodReference& method_ref) const {
Calin Juravle34900cc2016-02-05 16:19:19 +0000561 auto info_it = info_.find(GetProfileDexFileKey(method_ref.dex_file->GetLocation()));
Calin Juravle226501b2015-12-11 14:41:31 +0000562 if (info_it != info_.end()) {
Calin Juravlec4588572016-06-08 14:24:13 +0100563 if (!ChecksumMatch(*method_ref.dex_file, info_it->second.checksum)) {
Calin Juravle998c2162015-12-21 15:39:33 +0200564 return false;
Calin Juravle226501b2015-12-11 14:41:31 +0000565 }
Calin Juravle998c2162015-12-21 15:39:33 +0200566 const std::set<uint16_t>& methods = info_it->second.method_set;
567 return methods.find(method_ref.dex_method_index) != methods.end();
Calin Juravle226501b2015-12-11 14:41:31 +0000568 }
569 return false;
570}
571
Andreas Gampea5b09a62016-11-17 15:21:22 -0800572bool ProfileCompilationInfo::ContainsClass(const DexFile& dex_file, dex::TypeIndex type_idx) const {
Mathieu Chartiera8077802016-03-16 19:08:31 -0700573 auto info_it = info_.find(GetProfileDexFileKey(dex_file.GetLocation()));
574 if (info_it != info_.end()) {
Calin Juravlec4588572016-06-08 14:24:13 +0100575 if (!ChecksumMatch(dex_file, info_it->second.checksum)) {
Mathieu Chartiera8077802016-03-16 19:08:31 -0700576 return false;
577 }
Andreas Gampea5b09a62016-11-17 15:21:22 -0800578 const std::set<dex::TypeIndex>& classes = info_it->second.class_set;
Jeff Hao54b58552016-11-16 15:15:04 -0800579 return classes.find(type_idx) != classes.end();
Mathieu Chartiera8077802016-03-16 19:08:31 -0700580 }
581 return false;
582}
583
Calin Juravle998c2162015-12-21 15:39:33 +0200584uint32_t ProfileCompilationInfo::GetNumberOfMethods() const {
585 uint32_t total = 0;
586 for (const auto& it : info_) {
587 total += it.second.method_set.size();
588 }
589 return total;
590}
591
Calin Juravle67265462016-03-18 16:23:40 +0000592uint32_t ProfileCompilationInfo::GetNumberOfResolvedClasses() const {
593 uint32_t total = 0;
594 for (const auto& it : info_) {
595 total += it.second.class_set.size();
596 }
597 return total;
598}
599
David Sehrb18991b2017-02-08 20:58:10 -0800600// Produce a non-owning vector from a vector.
601template<typename T>
602const std::vector<T*>* MakeNonOwningVector(const std::vector<std::unique_ptr<T>>* owning_vector) {
603 auto non_owning_vector = new std::vector<T*>();
604 for (auto& element : *owning_vector) {
605 non_owning_vector->push_back(element.get());
606 }
607 return non_owning_vector;
608}
609
610std::string ProfileCompilationInfo::DumpInfo(
611 const std::vector<std::unique_ptr<const DexFile>>* dex_files,
612 bool print_full_dex_location) const {
613 std::unique_ptr<const std::vector<const DexFile*>> non_owning_dex_files(
614 MakeNonOwningVector(dex_files));
615 return DumpInfo(non_owning_dex_files.get(), print_full_dex_location);
616}
617
Calin Juravle998c2162015-12-21 15:39:33 +0200618std::string ProfileCompilationInfo::DumpInfo(const std::vector<const DexFile*>* dex_files,
619 bool print_full_dex_location) const {
Calin Juravle226501b2015-12-11 14:41:31 +0000620 std::ostringstream os;
621 if (info_.empty()) {
622 return "ProfileInfo: empty";
623 }
624
625 os << "ProfileInfo:";
626
Calin Juravle226501b2015-12-11 14:41:31 +0000627 const std::string kFirstDexFileKeySubstitute = ":classes.dex";
Calin Juravle998c2162015-12-21 15:39:33 +0200628 for (const auto& it : info_) {
Calin Juravle226501b2015-12-11 14:41:31 +0000629 os << "\n";
Calin Juravle998c2162015-12-21 15:39:33 +0200630 const std::string& location = it.first;
631 const DexFileData& dex_data = it.second;
Calin Juravle226501b2015-12-11 14:41:31 +0000632 if (print_full_dex_location) {
633 os << location;
634 } else {
635 // Replace the (empty) multidex suffix of the first key with a substitute for easier reading.
636 std::string multidex_suffix = DexFile::GetMultiDexSuffix(location);
637 os << (multidex_suffix.empty() ? kFirstDexFileKeySubstitute : multidex_suffix);
638 }
Calin Juravle876f3502016-03-24 16:16:34 +0000639 const DexFile* dex_file = nullptr;
640 if (dex_files != nullptr) {
641 for (size_t i = 0; i < dex_files->size(); i++) {
642 if (location == (*dex_files)[i]->GetLocation()) {
643 dex_file = (*dex_files)[i];
Calin Juravle998c2162015-12-21 15:39:33 +0200644 }
Calin Juravle226501b2015-12-11 14:41:31 +0000645 }
Calin Juravle876f3502016-03-24 16:16:34 +0000646 }
647 os << "\n\tmethods: ";
648 for (const auto method_it : dex_data.method_set) {
649 if (dex_file != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700650 os << "\n\t\t" << dex_file->PrettyMethod(method_it, true);
Calin Juravle876f3502016-03-24 16:16:34 +0000651 } else {
652 os << method_it << ",";
653 }
654 }
655 os << "\n\tclasses: ";
656 for (const auto class_it : dex_data.class_set) {
657 if (dex_file != nullptr) {
Jeff Hao54b58552016-11-16 15:15:04 -0800658 os << "\n\t\t" << dex_file->PrettyType(class_it);
Calin Juravle876f3502016-03-24 16:16:34 +0000659 } else {
660 os << class_it << ",";
661 }
Calin Juravle226501b2015-12-11 14:41:31 +0000662 }
663 }
664 return os.str();
665}
666
Calin Juravle2e2db782016-02-23 12:00:03 +0000667bool ProfileCompilationInfo::Equals(const ProfileCompilationInfo& other) {
Calin Juravle877fd962016-01-05 14:29:29 +0000668 return info_.Equals(other.info_);
669}
670
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800671std::set<DexCacheResolvedClasses> ProfileCompilationInfo::GetResolvedClasses() const {
672 std::set<DexCacheResolvedClasses> ret;
673 for (auto&& pair : info_) {
674 const std::string& profile_key = pair.first;
675 const DexFileData& data = pair.second;
Mathieu Chartierb384e5e2016-04-29 12:03:56 -0700676 // TODO: Is it OK to use the same location for both base and dex location here?
677 DexCacheResolvedClasses classes(profile_key, profile_key, data.checksum);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800678 classes.AddClasses(data.class_set.begin(), data.class_set.end());
679 ret.insert(classes);
680 }
681 return ret;
682}
683
Calin Juravle67265462016-03-18 16:23:40 +0000684void ProfileCompilationInfo::ClearResolvedClasses() {
685 for (auto& pair : info_) {
686 pair.second.class_set.clear();
687 }
688}
689
Calin Juravle7bcdb532016-06-07 16:14:47 +0100690// Naive implementation to generate a random profile file suitable for testing.
691bool ProfileCompilationInfo::GenerateTestProfile(int fd,
692 uint16_t number_of_dex_files,
693 uint16_t method_ratio,
694 uint16_t class_ratio) {
695 const std::string base_dex_location = "base.apk";
696 ProfileCompilationInfo info;
697 // The limits are defined by the dex specification.
698 uint16_t max_method = std::numeric_limits<uint16_t>::max();
699 uint16_t max_classes = std::numeric_limits<uint16_t>::max();
700 uint16_t number_of_methods = max_method * method_ratio / 100;
701 uint16_t number_of_classes = max_classes * class_ratio / 100;
702
703 srand(MicroTime());
704
705 // Make sure we generate more samples with a low index value.
706 // This makes it more likely to hit valid method/class indices in small apps.
707 const uint16_t kFavorFirstN = 10000;
708 const uint16_t kFavorSplit = 2;
709
710 for (uint16_t i = 0; i < number_of_dex_files; i++) {
711 std::string dex_location = DexFile::GetMultiDexLocation(i, base_dex_location.c_str());
712 std::string profile_key = GetProfileDexFileKey(dex_location);
713
714 for (uint16_t m = 0; m < number_of_methods; m++) {
715 uint16_t method_idx = rand() % max_method;
716 if (m < (number_of_methods / kFavorSplit)) {
717 method_idx %= kFavorFirstN;
718 }
719 info.AddMethodIndex(profile_key, 0, method_idx);
720 }
721
722 for (uint16_t c = 0; c < number_of_classes; c++) {
Jeff Hao54b58552016-11-16 15:15:04 -0800723 uint16_t type_idx = rand() % max_classes;
Calin Juravle7bcdb532016-06-07 16:14:47 +0100724 if (c < (number_of_classes / kFavorSplit)) {
Jeff Hao54b58552016-11-16 15:15:04 -0800725 type_idx %= kFavorFirstN;
Calin Juravle7bcdb532016-06-07 16:14:47 +0100726 }
Andreas Gampea5b09a62016-11-17 15:21:22 -0800727 info.AddClassIndex(profile_key, 0, dex::TypeIndex(type_idx));
Calin Juravle7bcdb532016-06-07 16:14:47 +0100728 }
729 }
730 return info.Save(fd);
731}
732
Calin Juravle31f2c152015-10-23 17:56:15 +0100733} // namespace art