blob: b72dec62bdca8a47509d2f68bb75d4fc33dbc00a [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 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 */
Elliott Hughes11e45072011-08-16 17:40:46 -070016
Elliott Hughes42ee1422011-09-06 12:33:32 -070017#include "utils.h"
18
Christopher Ferris943af7d2014-01-16 12:41:46 -080019#include <inttypes.h>
Elliott Hughes92b3b562011-09-08 16:32:26 -070020#include <pthread.h>
Mathieu Chartier120aa282017-08-05 16:03:03 -070021#include <sys/mman.h> // For madvise
Brian Carlstroma9f19782011-10-13 00:14:47 -070022#include <sys/stat.h>
Elliott Hughes42ee1422011-09-06 12:33:32 -070023#include <sys/syscall.h>
24#include <sys/types.h>
Brian Carlstrom4cf5e572014-02-25 11:47:48 -080025#include <sys/wait.h>
Elliott Hughes42ee1422011-09-06 12:33:32 -070026#include <unistd.h>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070027
Andreas Gampe3f093892017-09-14 15:11:01 -070028// We need dladdr.
29#ifndef __APPLE__
30#ifndef _GNU_SOURCE
31#define _GNU_SOURCE
32#define DEFINED_GNU_SOURCE
33#endif
34#include <dlfcn.h>
35#include <libgen.h>
36#ifdef DEFINED_GNU_SOURCE
37#undef _GNU_SOURCE
38#undef DEFINED_GNU_SOURCE
39#endif
40#endif
41
42
Ian Rogers700a4022014-05-19 16:49:03 -070043#include <memory>
Elliott Hughes42ee1422011-09-06 12:33:32 -070044
Andreas Gampe46ee31b2016-12-14 10:11:49 -080045#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080046#include "android-base/strings.h"
47
Brian Carlstrom6449c622014-02-10 23:48:36 -080048#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080049#include "base/unix_file/fd_file.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070050#include "dex_file-inl.h"
Andreas Gampe5073fed2015-08-10 11:40:25 -070051#include "dex_instruction.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010052#include "oat_quick_method_header.h"
buzbeec143c552011-08-20 17:38:58 -070053#include "os.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070054#include "scoped_thread_state_change-inl.h"
Ian Rogersa6724902013-09-23 09:23:37 -070055#include "utf-inl.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070056
Elliott Hughes4ae722a2012-03-13 11:08:51 -070057#if defined(__APPLE__)
David Sehrfa442002016-08-22 18:42:08 -070058#include <crt_externs.h>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070059#include <sys/syscall.h>
60#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
Elliott Hughes4ae722a2012-03-13 11:08:51 -070061#endif
62
Elliott Hughes058a6de2012-05-24 19:13:02 -070063#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080064#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080065#endif
66
Elliott Hughes11e45072011-08-16 17:40:46 -070067namespace art {
68
Andreas Gampe46ee31b2016-12-14 10:11:49 -080069using android::base::StringAppendF;
70using android::base::StringPrintf;
71
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080072pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070073#if defined(__APPLE__)
74 uint64_t owner;
Mathieu Chartier2cebb242015-04-21 16:50:40 -070075 CHECK_PTHREAD_CALL(pthread_threadid_np, (nullptr, &owner), __FUNCTION__); // Requires Mac OS 10.6
Brian Carlstromf3a26412012-08-24 11:06:02 -070076 return owner;
Elliott Hughes323aa862014-08-20 15:00:04 -070077#elif defined(__BIONIC__)
78 return gettid();
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080079#else
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080080 return syscall(__NR_gettid);
81#endif
82}
83
Elliott Hughes289be852012-06-12 13:57:20 -070084std::string GetThreadName(pid_t tid) {
85 std::string result;
86 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070087 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -070088 } else {
89 result = "<unknown>";
90 }
91 return result;
92}
93
Elliott Hughesd92bec42011-09-02 17:04:36 -070094bool ReadFileToString(const std::string& file_name, std::string* result) {
Andreas Gampedf878922015-08-13 16:44:54 -070095 File file(file_name, O_RDONLY, false);
96 if (!file.IsOpened()) {
Elliott Hughesd92bec42011-09-02 17:04:36 -070097 return false;
98 }
buzbeec143c552011-08-20 17:38:58 -070099
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700100 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700101 while (true) {
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800102 int64_t n = TEMP_FAILURE_RETRY(read(file.Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700103 if (n == -1) {
104 return false;
buzbeec143c552011-08-20 17:38:58 -0700105 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700106 if (n == 0) {
107 return true;
108 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700109 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700110 }
buzbeec143c552011-08-20 17:38:58 -0700111}
112
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800113bool PrintFileToLog(const std::string& file_name, LogSeverity level) {
Andreas Gampedf878922015-08-13 16:44:54 -0700114 File file(file_name, O_RDONLY, false);
115 if (!file.IsOpened()) {
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800116 return false;
117 }
118
119 constexpr size_t kBufSize = 256; // Small buffer. Avoid stack overflow and stack size warnings.
120 char buf[kBufSize + 1]; // +1 for terminator.
121 size_t filled_to = 0;
122 while (true) {
123 DCHECK_LT(filled_to, kBufSize);
124 int64_t n = TEMP_FAILURE_RETRY(read(file.Fd(), &buf[filled_to], kBufSize - filled_to));
125 if (n <= 0) {
126 // Print the rest of the buffer, if it exists.
127 if (filled_to > 0) {
128 buf[filled_to] = 0;
129 LOG(level) << buf;
130 }
131 return n == 0;
132 }
133 // Scan for '\n'.
134 size_t i = filled_to;
135 bool found_newline = false;
136 for (; i < filled_to + n; ++i) {
137 if (buf[i] == '\n') {
138 // Found a line break, that's something to print now.
139 buf[i] = 0;
140 LOG(level) << buf;
141 // Copy the rest to the front.
142 if (i + 1 < filled_to + n) {
143 memmove(&buf[0], &buf[i + 1], filled_to + n - i - 1);
144 filled_to = filled_to + n - i - 1;
145 } else {
146 filled_to = 0;
147 }
148 found_newline = true;
149 break;
150 }
151 }
152 if (found_newline) {
153 continue;
154 } else {
155 filled_to += n;
156 // Check if we must flush now.
157 if (filled_to == kBufSize) {
158 buf[kBufSize] = 0;
159 LOG(level) << buf;
160 filled_to = 0;
161 }
162 }
163 }
164}
165
Vladimir Markob8a55f82017-09-21 16:21:43 +0100166void AppendPrettyDescriptor(const char* descriptor, std::string* result) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700167 // Count the number of '['s to get the dimensionality.
Ian Rogers1ff3c982014-08-12 02:30:58 -0700168 const char* c = descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700169 size_t dim = 0;
170 while (*c == '[') {
171 dim++;
172 c++;
173 }
174
175 // Reference or primitive?
176 if (*c == 'L') {
177 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700178 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700179 } else {
180 // "[[B" -> "byte[][]".
181 // To make life easier, we make primitives look like unqualified
182 // reference types.
183 switch (*c) {
Vladimir Markob8a55f82017-09-21 16:21:43 +0100184 case 'B': c = "byte;"; break;
185 case 'C': c = "char;"; break;
186 case 'D': c = "double;"; break;
187 case 'F': c = "float;"; break;
188 case 'I': c = "int;"; break;
189 case 'J': c = "long;"; break;
190 case 'S': c = "short;"; break;
191 case 'Z': c = "boolean;"; break;
192 case 'V': c = "void;"; break; // Used when decoding return types.
193 default: result->append(descriptor); return;
Elliott Hughes11e45072011-08-16 17:40:46 -0700194 }
195 }
196
197 // At this point, 'c' is a string of the form "fully/qualified/Type;"
198 // or "primitive;". Rewrite the type with '.' instead of '/':
Elliott Hughes11e45072011-08-16 17:40:46 -0700199 const char* p = c;
200 while (*p != ';') {
201 char ch = *p++;
202 if (ch == '/') {
203 ch = '.';
204 }
Vladimir Markob8a55f82017-09-21 16:21:43 +0100205 result->push_back(ch);
Elliott Hughes11e45072011-08-16 17:40:46 -0700206 }
207 // ...and replace the semicolon with 'dim' "[]" pairs:
Ian Rogers1ff3c982014-08-12 02:30:58 -0700208 for (size_t i = 0; i < dim; ++i) {
Vladimir Markob8a55f82017-09-21 16:21:43 +0100209 result->append("[]");
Elliott Hughes11e45072011-08-16 17:40:46 -0700210 }
Elliott Hughes11e45072011-08-16 17:40:46 -0700211}
212
Vladimir Markob8a55f82017-09-21 16:21:43 +0100213std::string PrettyDescriptor(const char* descriptor) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700214 std::string result;
Vladimir Markob8a55f82017-09-21 16:21:43 +0100215 AppendPrettyDescriptor(descriptor, &result);
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700216 return result;
217}
218
Andreas Gampec0d82292014-09-23 10:38:30 -0700219std::string PrettyJavaAccessFlags(uint32_t access_flags) {
220 std::string result;
221 if ((access_flags & kAccPublic) != 0) {
222 result += "public ";
223 }
224 if ((access_flags & kAccProtected) != 0) {
225 result += "protected ";
226 }
227 if ((access_flags & kAccPrivate) != 0) {
228 result += "private ";
229 }
230 if ((access_flags & kAccFinal) != 0) {
231 result += "final ";
232 }
233 if ((access_flags & kAccStatic) != 0) {
234 result += "static ";
235 }
David Brazdilca3c8c32016-09-06 14:04:48 +0100236 if ((access_flags & kAccAbstract) != 0) {
237 result += "abstract ";
238 }
239 if ((access_flags & kAccInterface) != 0) {
240 result += "interface ";
241 }
Andreas Gampec0d82292014-09-23 10:38:30 -0700242 if ((access_flags & kAccTransient) != 0) {
243 result += "transient ";
244 }
245 if ((access_flags & kAccVolatile) != 0) {
246 result += "volatile ";
247 }
248 if ((access_flags & kAccSynchronized) != 0) {
249 result += "synchronized ";
250 }
251 return result;
252}
253
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800254std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700255 // The byte thresholds at which we display amounts. A byte count is displayed
256 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800257 static const int64_t kUnitThresholds[] = {
Elliott Hughesc967f782012-04-16 10:23:15 -0700258 0, // B up to...
259 3*1024, // KB up to...
260 2*1024*1024, // MB up to...
261 1024*1024*1024 // GB from here.
262 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800263 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700264 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800265 const char* negative_str = "";
266 if (byte_count < 0) {
267 negative_str = "-";
268 byte_count = -byte_count;
269 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700270 int i = arraysize(kUnitThresholds);
271 while (--i > 0) {
272 if (byte_count >= kUnitThresholds[i]) {
273 break;
274 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800275 }
Brian Carlstrom474cc792014-03-07 14:18:15 -0800276 return StringPrintf("%s%" PRId64 "%s",
277 negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800278}
279
Andreas Gampe9186ced2016-12-12 14:28:21 -0800280static inline constexpr bool NeedsEscaping(uint16_t ch) {
281 return (ch < ' ' || ch > '~');
282}
283
Ian Rogers576ca0c2014-06-06 15:58:22 -0700284std::string PrintableChar(uint16_t ch) {
285 std::string result;
286 result += '\'';
287 if (NeedsEscaping(ch)) {
288 StringAppendF(&result, "\\u%04x", ch);
289 } else {
Andreas Gampef45d61c2017-06-07 10:29:33 -0700290 result += static_cast<std::string::value_type>(ch);
Ian Rogers576ca0c2014-06-06 15:58:22 -0700291 }
292 result += '\'';
293 return result;
294}
295
Ian Rogers68b56852014-08-29 20:19:11 -0700296std::string PrintableString(const char* utf) {
Elliott Hughes82914b62012-04-09 15:56:29 -0700297 std::string result;
298 result += '"';
Ian Rogers68b56852014-08-29 20:19:11 -0700299 const char* p = utf;
Elliott Hughes82914b62012-04-09 15:56:29 -0700300 size_t char_count = CountModifiedUtf8Chars(p);
301 for (size_t i = 0; i < char_count; ++i) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000302 uint32_t ch = GetUtf16FromUtf8(&p);
Elliott Hughes82914b62012-04-09 15:56:29 -0700303 if (ch == '\\') {
304 result += "\\\\";
305 } else if (ch == '\n') {
306 result += "\\n";
307 } else if (ch == '\r') {
308 result += "\\r";
309 } else if (ch == '\t') {
310 result += "\\t";
Elliott Hughes82914b62012-04-09 15:56:29 -0700311 } else {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000312 const uint16_t leading = GetLeadingUtf16Char(ch);
313
314 if (NeedsEscaping(leading)) {
315 StringAppendF(&result, "\\u%04x", leading);
316 } else {
Andreas Gampef45d61c2017-06-07 10:29:33 -0700317 result += static_cast<std::string::value_type>(leading);
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000318 }
319
320 const uint32_t trailing = GetTrailingUtf16Char(ch);
321 if (trailing != 0) {
322 // All high surrogates will need escaping.
323 StringAppendF(&result, "\\u%04x", trailing);
324 }
Elliott Hughes82914b62012-04-09 15:56:29 -0700325 }
326 }
327 result += '"';
328 return result;
329}
330
Alex Light888a59e2017-01-25 11:41:41 -0800331std::string GetJniShortName(const std::string& class_descriptor, const std::string& method) {
332 // Remove the leading 'L' and trailing ';'...
333 std::string class_name(class_descriptor);
334 CHECK_EQ(class_name[0], 'L') << class_name;
335 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
336 class_name.erase(0, 1);
337 class_name.erase(class_name.size() - 1, 1);
338
339 std::string short_name;
340 short_name += "Java_";
341 short_name += MangleForJni(class_name);
342 short_name += "_";
343 short_name += MangleForJni(method);
344 return short_name;
345}
346
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800347// See http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/design.html#wp615 for the full rules.
Elliott Hughes79082e32011-08-25 12:07:32 -0700348std::string MangleForJni(const std::string& s) {
349 std::string result;
350 size_t char_count = CountModifiedUtf8Chars(s.c_str());
351 const char* cp = &s[0];
352 for (size_t i = 0; i < char_count; ++i) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000353 uint32_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800354 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
355 result.push_back(ch);
356 } else if (ch == '.' || ch == '/') {
357 result += "_";
358 } else if (ch == '_') {
359 result += "_1";
360 } else if (ch == ';') {
361 result += "_2";
362 } else if (ch == '[') {
363 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700364 } else {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000365 const uint16_t leading = GetLeadingUtf16Char(ch);
366 const uint32_t trailing = GetTrailingUtf16Char(ch);
367
368 StringAppendF(&result, "_0%04x", leading);
369 if (trailing != 0) {
370 StringAppendF(&result, "_0%04x", trailing);
371 }
Elliott Hughes79082e32011-08-25 12:07:32 -0700372 }
373 }
374 return result;
375}
376
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700377std::string DotToDescriptor(const char* class_name) {
378 std::string descriptor(class_name);
379 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
380 if (descriptor.length() > 0 && descriptor[0] != '[') {
381 descriptor = "L" + descriptor + ";";
382 }
383 return descriptor;
384}
385
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800386std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800387 size_t length = strlen(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -0700388 if (length > 1) {
389 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
390 // Descriptors have the leading 'L' and trailing ';' stripped.
391 std::string result(descriptor + 1, length - 2);
392 std::replace(result.begin(), result.end(), '/', '.');
393 return result;
394 } else {
395 // For arrays the 'L' and ';' remain intact.
396 std::string result(descriptor);
397 std::replace(result.begin(), result.end(), '/', '.');
398 return result;
399 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800400 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700401 // Do nothing for non-class/array descriptors.
Elliott Hughes2435a572012-02-17 16:07:41 -0800402 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800403}
404
405std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800406 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800407 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
408 std::string result(descriptor + 1, length - 2);
409 return result;
410 }
411 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700412}
413
jeffhao10037c82012-01-23 15:06:23 -0800414// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700415uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700416 0x00000000, // 00..1f low control characters; nothing valid
417 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
418 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
419 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700420};
421
jeffhao10037c82012-01-23 15:06:23 -0800422// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
423bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700424 /*
425 * It's a multibyte encoded character. Decode it and analyze. We
426 * accept anything that isn't (a) an improperly encoded low value,
427 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
428 * control character, or (e) a high space, layout, or special
429 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
430 * U+fff0..U+ffff). This is all specified in the dex format
431 * document.
432 */
433
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000434 const uint32_t pair = GetUtf16FromUtf8(pUtf8Ptr);
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000435 const uint16_t leading = GetLeadingUtf16Char(pair);
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000436
Narayan Kamath8508e372015-05-06 14:55:43 +0100437 // We have a surrogate pair resulting from a valid 4 byte UTF sequence.
438 // No further checks are necessary because 4 byte sequences span code
439 // points [U+10000, U+1FFFFF], which are valid codepoints in a dex
440 // identifier. Furthermore, GetUtf16FromUtf8 guarantees that each of
441 // the surrogate halves are valid and well formed in this instance.
442 if (GetTrailingUtf16Char(pair) != 0) {
443 return true;
444 }
445
446
447 // We've encountered a one, two or three byte UTF-8 sequence. The
448 // three byte UTF-8 sequence could be one half of a surrogate pair.
449 switch (leading >> 8) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000450 case 0x00:
451 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
452 return (leading > 0x00a0);
453 case 0xd8:
454 case 0xd9:
455 case 0xda:
456 case 0xdb:
Narayan Kamath8508e372015-05-06 14:55:43 +0100457 {
458 // We found a three byte sequence encoding one half of a surrogate.
459 // Look for the other half.
460 const uint32_t pair2 = GetUtf16FromUtf8(pUtf8Ptr);
461 const uint16_t trailing = GetLeadingUtf16Char(pair2);
462
463 return (GetTrailingUtf16Char(pair2) == 0) && (0xdc00 <= trailing && trailing <= 0xdfff);
464 }
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000465 case 0xdc:
466 case 0xdd:
467 case 0xde:
468 case 0xdf:
469 // It's a trailing surrogate, which is not valid at this point.
470 return false;
471 case 0x20:
472 case 0xff:
473 // It's in the range that has spaces, controls, and specials.
474 switch (leading & 0xfff8) {
Narayan Kamath8508e372015-05-06 14:55:43 +0100475 case 0x2000:
476 case 0x2008:
477 case 0x2028:
478 case 0xfff0:
479 case 0xfff8:
480 return false;
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000481 }
Narayan Kamath8508e372015-05-06 14:55:43 +0100482 return true;
483 default:
484 return true;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700485 }
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000486
Narayan Kamath8508e372015-05-06 14:55:43 +0100487 UNREACHABLE();
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700488}
489
490/* Return whether the pointed-at modified-UTF-8 encoded character is
491 * valid as part of a member name, updating the pointer to point past
492 * the consumed character. This will consume two encoded UTF-16 code
493 * points if the character is encoded as a surrogate pair. Also, if
494 * this function returns false, then the given pointer may only have
495 * been partially advanced.
496 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700497static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700498 uint8_t c = (uint8_t) **pUtf8Ptr;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700499 if (LIKELY(c <= 0x7f)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700500 // It's low-ascii, so check the table.
501 uint32_t wordIdx = c >> 5;
502 uint32_t bitIdx = c & 0x1f;
503 (*pUtf8Ptr)++;
504 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
505 }
506
507 // It's a multibyte encoded character. Call a non-inline function
508 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800509 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
510}
511
512bool IsValidMemberName(const char* s) {
513 bool angle_name = false;
514
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700515 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800516 case '\0':
517 // The empty string is not a valid name.
518 return false;
519 case '<':
520 angle_name = true;
521 s++;
522 break;
523 }
524
525 while (true) {
526 switch (*s) {
527 case '\0':
528 return !angle_name;
529 case '>':
530 return angle_name && s[1] == '\0';
531 }
532
533 if (!IsValidPartOfMemberNameUtf8(&s)) {
534 return false;
535 }
536 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700537}
538
Elliott Hughes906e6852011-10-28 14:52:10 -0700539enum ClassNameType { kName, kDescriptor };
Ian Rogers7b078e82014-09-10 14:44:24 -0700540template<ClassNameType kType, char kSeparator>
541static bool IsValidClassName(const char* s) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700542 int arrayCount = 0;
543 while (*s == '[') {
544 arrayCount++;
545 s++;
546 }
547
548 if (arrayCount > 255) {
549 // Arrays may have no more than 255 dimensions.
550 return false;
551 }
552
Ian Rogers7b078e82014-09-10 14:44:24 -0700553 ClassNameType type = kType;
554 if (type != kDescriptor && arrayCount != 0) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700555 /*
556 * If we're looking at an array of some sort, then it doesn't
557 * matter if what is being asked for is a class name; the
558 * format looks the same as a type descriptor in that case, so
559 * treat it as such.
560 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700561 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700562 }
563
Elliott Hughes906e6852011-10-28 14:52:10 -0700564 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700565 /*
566 * We are looking for a descriptor. Either validate it as a
567 * single-character primitive type, or continue on to check the
568 * embedded class name (bracketed by "L" and ";").
569 */
570 switch (*(s++)) {
571 case 'B':
572 case 'C':
573 case 'D':
574 case 'F':
575 case 'I':
576 case 'J':
577 case 'S':
578 case 'Z':
579 // These are all single-character descriptors for primitive types.
580 return (*s == '\0');
581 case 'V':
582 // Non-array void is valid, but you can't have an array of void.
583 return (arrayCount == 0) && (*s == '\0');
584 case 'L':
585 // Class name: Break out and continue below.
586 break;
587 default:
588 // Oddball descriptor character.
589 return false;
590 }
591 }
592
593 /*
594 * We just consumed the 'L' that introduces a class name as part
595 * of a type descriptor, or we are looking for an unadorned class
596 * name.
597 */
598
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700599 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700600 for (;;) {
601 uint8_t c = (uint8_t) *s;
602 switch (c) {
603 case '\0':
604 /*
605 * Premature end for a type descriptor, but valid for
606 * a class name as long as we haven't encountered an
607 * empty component (including the degenerate case of
608 * the empty string "").
609 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700610 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700611 case ';':
612 /*
613 * Invalid character for a class name, but the
614 * legitimate end of a type descriptor. In the latter
615 * case, make sure that this is the end of the string
616 * and that it doesn't end with an empty component
617 * (including the degenerate case of "L;").
618 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700619 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700620 case '/':
621 case '.':
Ian Rogers7b078e82014-09-10 14:44:24 -0700622 if (c != kSeparator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700623 // The wrong separator character.
624 return false;
625 }
626 if (sepOrFirst) {
627 // Separator at start or two separators in a row.
628 return false;
629 }
630 sepOrFirst = true;
631 s++;
632 break;
633 default:
jeffhao10037c82012-01-23 15:06:23 -0800634 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700635 return false;
636 }
637 sepOrFirst = false;
638 break;
639 }
640 }
641}
642
Elliott Hughes906e6852011-10-28 14:52:10 -0700643bool IsValidBinaryClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700644 return IsValidClassName<kName, '.'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700645}
646
647bool IsValidJniClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700648 return IsValidClassName<kName, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700649}
650
651bool IsValidDescriptor(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700652 return IsValidClassName<kDescriptor, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700653}
654
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700655void Split(const std::string& s, char separator, std::vector<std::string>* result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700656 const char* p = s.data();
657 const char* end = p + s.size();
658 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800659 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700660 ++p;
661 } else {
662 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800663 while (++p != end && *p != separator) {
664 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700665 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700666 result->push_back(std::string(start, p - start));
Elliott Hughes34023802011-08-30 12:06:17 -0700667 }
668 }
669}
670
Elliott Hughes22869a92012-03-27 14:08:24 -0700671void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700672 int hasAt = 0;
673 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700674 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700675 while (*s) {
676 if (*s == '.') {
677 hasDot = 1;
678 } else if (*s == '@') {
679 hasAt = 1;
680 }
681 s++;
682 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700683 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700684 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700685 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700686 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700687 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700688 }
Elliott Hughes0a18df82015-01-09 15:16:16 -0800689#if defined(__linux__)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700690 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughes0a18df82015-01-09 15:16:16 -0800691 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded in the kernel.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700692 strncpy(buf, s, sizeof(buf)-1);
693 buf[sizeof(buf)-1] = '\0';
694 errno = pthread_setname_np(pthread_self(), buf);
695 if (errno != 0) {
696 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
697 }
Elliott Hughes0a18df82015-01-09 15:16:16 -0800698#else // __APPLE__
Elliott Hughes22869a92012-03-27 14:08:24 -0700699 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700700#endif
701}
702
Brian Carlstrom29212012013-09-12 22:18:30 -0700703void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
704 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700705 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -0700706 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700707 return;
708 }
709 // Skip the command, which may contain spaces.
710 stats = stats.substr(stats.find(')') + 2);
711 // Extract the three fields we care about.
712 std::vector<std::string> fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700713 Split(stats, ' ', &fields);
Brian Carlstrom29212012013-09-12 22:18:30 -0700714 *state = fields[0][0];
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700715 *utime = strtoull(fields[11].c_str(), nullptr, 10);
716 *stime = strtoull(fields[12].c_str(), nullptr, 10);
717 *task_cpu = strtoull(fields[36].c_str(), nullptr, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700718}
719
Andreas Gampe3f093892017-09-14 15:11:01 -0700720std::string GetAndroidRootSafe(std::string* error_msg) {
721 // Prefer ANDROID_ROOT if it's set.
722 const char* android_dir = getenv("ANDROID_ROOT");
723 if (android_dir != nullptr) {
724 if (!OS::DirectoryExists(android_dir)) {
725 *error_msg = StringPrintf("Failed to find ANDROID_ROOT directory %s", android_dir);
726 return "";
727 }
728 return android_dir;
729 }
730
731 // Check where libart is from, and derive from there. Only do this for non-Mac.
732#ifndef __APPLE__
733 {
734 Dl_info info;
735 if (dladdr(reinterpret_cast<const void*>(&GetAndroidRootSafe), /* out */ &info) != 0) {
736 // Make a duplicate of the fname so dirname can modify it.
737 UniqueCPtr<char> fname(strdup(info.dli_fname));
738
739 char* dir1 = dirname(fname.get()); // This is the lib directory.
740 char* dir2 = dirname(dir1); // This is the "system" directory.
741 if (OS::DirectoryExists(dir2)) {
742 std::string tmp = dir2; // Make a copy here so that fname can be released.
743 return tmp;
744 }
745 }
746 }
747#endif
748
749 // Try "/system".
750 if (!OS::DirectoryExists("/system")) {
751 *error_msg = "Failed to find ANDROID_ROOT directory /system";
752 return "";
753 }
754 return "/system";
755}
756
757std::string GetAndroidRoot() {
758 std::string error_msg;
759 std::string ret = GetAndroidRootSafe(&error_msg);
760 if (ret.empty()) {
761 LOG(FATAL) << error_msg;
762 UNREACHABLE();
763 }
764 return ret;
765}
766
767
Calin Juravle36eb3132017-01-13 16:32:38 -0800768static const char* GetAndroidDirSafe(const char* env_var,
769 const char* default_dir,
770 std::string* error_msg) {
771 const char* android_dir = getenv(env_var);
772 if (android_dir == nullptr) {
773 if (OS::DirectoryExists(default_dir)) {
774 android_dir = default_dir;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700775 } else {
Calin Juravle36eb3132017-01-13 16:32:38 -0800776 *error_msg = StringPrintf("%s not set and %s does not exist", env_var, default_dir);
777 return nullptr;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700778 }
779 }
Calin Juravle36eb3132017-01-13 16:32:38 -0800780 if (!OS::DirectoryExists(android_dir)) {
781 *error_msg = StringPrintf("Failed to find %s directory %s", env_var, android_dir);
782 return nullptr;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700783 }
Calin Juravle36eb3132017-01-13 16:32:38 -0800784 return android_dir;
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800785}
Brian Carlstroma9f19782011-10-13 00:14:47 -0700786
Andreas Gampe3f093892017-09-14 15:11:01 -0700787static const char* GetAndroidDir(const char* env_var, const char* default_dir) {
Alex Lighta59dd802014-07-02 16:28:08 -0700788 std::string error_msg;
Calin Juravle36eb3132017-01-13 16:32:38 -0800789 const char* dir = GetAndroidDirSafe(env_var, default_dir, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700790 if (dir != nullptr) {
791 return dir;
792 } else {
793 LOG(FATAL) << error_msg;
Calin Juravle36eb3132017-01-13 16:32:38 -0800794 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -0700795 }
796}
797
Calin Juravle36eb3132017-01-13 16:32:38 -0800798const char* GetAndroidData() {
799 return GetAndroidDir("ANDROID_DATA", "/data");
800}
801
Alex Lighta59dd802014-07-02 16:28:08 -0700802const char* GetAndroidDataSafe(std::string* error_msg) {
Calin Juravle36eb3132017-01-13 16:32:38 -0800803 return GetAndroidDirSafe("ANDROID_DATA", "/data", error_msg);
804}
805
806std::string GetDefaultBootImageLocation(std::string* error_msg) {
Andreas Gampe3f093892017-09-14 15:11:01 -0700807 std::string android_root = GetAndroidRootSafe(error_msg);
808 if (android_root.empty()) {
Calin Juravle36eb3132017-01-13 16:32:38 -0800809 return "";
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800810 }
Andreas Gampe3f093892017-09-14 15:11:01 -0700811 return StringPrintf("%s/framework/boot.art", android_root.c_str());
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800812}
813
Alex Lighta59dd802014-07-02 16:28:08 -0700814void GetDalvikCache(const char* subdir, const bool create_if_absent, std::string* dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700815 bool* have_android_data, bool* dalvik_cache_exists, bool* is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -0700816 CHECK(subdir != nullptr);
817 std::string error_msg;
818 const char* android_data = GetAndroidDataSafe(&error_msg);
819 if (android_data == nullptr) {
820 *have_android_data = false;
821 *dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700822 *is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -0700823 return;
824 } else {
825 *have_android_data = true;
826 }
827 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
828 *dalvik_cache = dalvik_cache_root + subdir;
829 *dalvik_cache_exists = OS::DirectoryExists(dalvik_cache->c_str());
Andreas Gampe3c13a792014-09-18 20:56:04 -0700830 *is_global_cache = strcmp(android_data, "/data") == 0;
831 if (create_if_absent && !*dalvik_cache_exists && !*is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -0700832 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
833 *dalvik_cache_exists = ((mkdir(dalvik_cache_root.c_str(), 0700) == 0 || errno == EEXIST) &&
834 (mkdir(dalvik_cache->c_str(), 0700) == 0 || errno == EEXIST));
835 }
836}
837
Richard Uhler55b58b62016-08-12 09:05:13 -0700838std::string GetDalvikCache(const char* subdir) {
Narayan Kamath11d9f062014-04-23 20:24:57 +0100839 CHECK(subdir != nullptr);
Brian Carlstrom41ccffd2014-05-06 10:37:30 -0700840 const char* android_data = GetAndroidData();
841 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
Narayan Kamath11d9f062014-04-23 20:24:57 +0100842 const std::string dalvik_cache = dalvik_cache_root + subdir;
Andreas Gampe40da2862015-02-27 12:49:04 -0800843 if (!OS::DirectoryExists(dalvik_cache.c_str())) {
Richard Uhler55b58b62016-08-12 09:05:13 -0700844 // TODO: Check callers. Traditional behavior is to not abort.
845 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700846 }
Brian Carlstrom7675e162013-06-10 16:18:04 -0700847 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700848}
849
Alex Lighta59dd802014-07-02 16:28:08 -0700850bool GetDalvikCacheFilename(const char* location, const char* cache_location,
851 std::string* filename, std::string* error_msg) {
Ian Rogerse6060102013-05-16 12:01:04 -0700852 if (location[0] != '/') {
Alex Lighta59dd802014-07-02 16:28:08 -0700853 *error_msg = StringPrintf("Expected path in location to be absolute: %s", location);
854 return false;
Ian Rogerse6060102013-05-16 12:01:04 -0700855 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700856 std::string cache_file(&location[1]); // skip leading slash
Andreas Gampe9186ced2016-12-12 14:28:21 -0800857 if (!android::base::EndsWith(location, ".dex") &&
858 !android::base::EndsWith(location, ".art") &&
859 !android::base::EndsWith(location, ".oat")) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -0700860 cache_file += "/";
861 cache_file += DexFile::kClassesDex;
862 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700863 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Alex Lighta59dd802014-07-02 16:28:08 -0700864 *filename = StringPrintf("%s/%s", cache_location, cache_file.c_str());
865 return true;
866}
867
Calin Juravle367b9d82017-05-15 18:18:39 -0700868std::string GetVdexFilename(const std::string& oat_location) {
869 return ReplaceFileExtension(oat_location, "vdex");
870}
871
Brian Carlstrom2afe4942014-05-19 10:25:33 -0700872static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700873 // in = /foo/bar/baz
874 // out = /foo/bar/<isa>/baz
875 size_t pos = filename->rfind('/');
876 CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
877 filename->insert(pos, "/", 1);
878 filename->insert(pos + 1, GetInstructionSetString(isa));
879}
880
881std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
882 // location = /system/framework/boot.art
883 // filename = /system/framework/<isa>/boot.art
884 std::string filename(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -0700885 InsertIsaDirectory(isa, &filename);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700886 return filename;
887}
888
Calin Juravle5e2b9712015-12-18 14:10:00 +0200889bool FileExists(const std::string& filename) {
890 struct stat buffer;
891 return stat(filename.c_str(), &buffer) == 0;
892}
893
Calin Juravleb9c1b9b2016-03-17 17:07:52 +0000894bool FileExistsAndNotEmpty(const std::string& filename) {
895 struct stat buffer;
896 if (stat(filename.c_str(), &buffer) != 0) {
897 return false;
898 }
899 return buffer.st_size > 0;
900}
901
David Brazdil7b49e6c2016-09-01 11:06:18 +0100902std::string ReplaceFileExtension(const std::string& filename, const std::string& new_extension) {
903 const size_t last_ext = filename.find_last_of('.');
904 if (last_ext == std::string::npos) {
905 return filename + "." + new_extension;
906 } else {
907 return filename.substr(0, last_ext + 1) + new_extension;
908 }
909}
910
Mathieu Chartier76433272014-09-26 14:32:37 -0700911std::string PrettyDescriptor(Primitive::Type type) {
912 return PrettyDescriptor(Primitive::Descriptor(type));
913}
914
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000915static void ParseStringAfterChar(const std::string& s,
916 char c,
917 std::string* parsed_value,
918 UsageFn Usage) {
919 std::string::size_type colon = s.find(c);
920 if (colon == std::string::npos) {
921 Usage("Missing char %c in option %s\n", c, s.c_str());
922 }
923 // Add one to remove the char we were trimming until.
924 *parsed_value = s.substr(colon + 1);
925}
926
927void ParseDouble(const std::string& option,
928 char after_char,
929 double min,
930 double max,
931 double* parsed_value,
932 UsageFn Usage) {
933 std::string substring;
934 ParseStringAfterChar(option, after_char, &substring, Usage);
935 bool sane_val = true;
936 double value;
937 if ((false)) {
938 // TODO: this doesn't seem to work on the emulator. b/15114595
939 std::stringstream iss(substring);
940 iss >> value;
941 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
942 sane_val = iss.eof() && (value >= min) && (value <= max);
943 } else {
944 char* end = nullptr;
945 value = strtod(substring.c_str(), &end);
946 sane_val = *end == '\0' && value >= min && value <= max;
947 }
948 if (!sane_val) {
949 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
950 }
951 *parsed_value = value;
952}
953
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000954int64_t GetFileSizeBytes(const std::string& filename) {
955 struct stat stat_buf;
956 int rc = stat(filename.c_str(), &stat_buf);
957 return rc == 0 ? stat_buf.st_size : -1;
958}
959
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800960void SleepForever() {
961 while (true) {
962 usleep(1000000);
963 }
964}
965
Mathieu Chartier120aa282017-08-05 16:03:03 -0700966int MadviseLargestPageAlignedRegion(const uint8_t* begin, const uint8_t* end, int advice) {
967 DCHECK_LE(begin, end);
968 begin = AlignUp(begin, kPageSize);
969 end = AlignDown(end, kPageSize);
970 if (begin < end) {
971 int result = madvise(const_cast<uint8_t*>(begin), end - begin, advice);
972 if (result != 0) {
973 PLOG(WARNING) << "madvise failed " << result;
974 }
975 return result;
976 }
977 return 0;
978}
979
Elliott Hughes42ee1422011-09-06 12:33:32 -0700980} // namespace art