blob: 393b18e1b3e9563bad0cfdbac6f565d251c284ea [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>
Brian Carlstroma9f19782011-10-13 00:14:47 -070021#include <sys/stat.h>
Elliott Hughes42ee1422011-09-06 12:33:32 -070022#include <sys/syscall.h>
23#include <sys/types.h>
Brian Carlstrom4cf5e572014-02-25 11:47:48 -080024#include <sys/wait.h>
Elliott Hughes42ee1422011-09-06 12:33:32 -070025#include <unistd.h>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070026
Ian Rogers700a4022014-05-19 16:49:03 -070027#include <memory>
Elliott Hughes42ee1422011-09-06 12:33:32 -070028
David Sehr013fd802018-01-11 22:55:24 -080029#include "android-base/file.h"
Andreas Gampe46ee31b2016-12-14 10:11:49 -080030#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080031#include "android-base/strings.h"
32
David Sehr0225f8e2018-01-31 08:52:24 +000033#include "dex/utf-inl.h"
buzbeec143c552011-08-20 17:38:58 -070034#include "os.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070035
Elliott Hughes4ae722a2012-03-13 11:08:51 -070036#if defined(__APPLE__)
David Sehrfa442002016-08-22 18:42:08 -070037#include <crt_externs.h>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070038#include <sys/syscall.h>
39#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
Elliott Hughes4ae722a2012-03-13 11:08:51 -070040#endif
41
Elliott Hughes058a6de2012-05-24 19:13:02 -070042#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080043#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080044#endif
45
Elliott Hughes11e45072011-08-16 17:40:46 -070046namespace art {
47
David Sehr013fd802018-01-11 22:55:24 -080048using android::base::ReadFileToString;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080049using android::base::StringAppendF;
50using android::base::StringPrintf;
51
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080052pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070053#if defined(__APPLE__)
54 uint64_t owner;
Mathieu Chartier2cebb242015-04-21 16:50:40 -070055 CHECK_PTHREAD_CALL(pthread_threadid_np, (nullptr, &owner), __FUNCTION__); // Requires Mac OS 10.6
Brian Carlstromf3a26412012-08-24 11:06:02 -070056 return owner;
Elliott Hughes323aa862014-08-20 15:00:04 -070057#elif defined(__BIONIC__)
58 return gettid();
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080059#else
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080060 return syscall(__NR_gettid);
61#endif
62}
63
Elliott Hughes289be852012-06-12 13:57:20 -070064std::string GetThreadName(pid_t tid) {
65 std::string result;
David Sehr013fd802018-01-11 22:55:24 -080066 // TODO: make this less Linux-specific.
Elliott Hughes289be852012-06-12 13:57:20 -070067 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070068 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -070069 } else {
70 result = "<unknown>";
71 }
72 return result;
73}
74
Vladimir Markob8a55f82017-09-21 16:21:43 +010075void AppendPrettyDescriptor(const char* descriptor, std::string* result) {
Elliott Hughes11e45072011-08-16 17:40:46 -070076 // Count the number of '['s to get the dimensionality.
Ian Rogers1ff3c982014-08-12 02:30:58 -070077 const char* c = descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -070078 size_t dim = 0;
79 while (*c == '[') {
80 dim++;
81 c++;
82 }
83
84 // Reference or primitive?
85 if (*c == 'L') {
86 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -070087 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -070088 } else {
89 // "[[B" -> "byte[][]".
90 // To make life easier, we make primitives look like unqualified
91 // reference types.
92 switch (*c) {
Vladimir Markob8a55f82017-09-21 16:21:43 +010093 case 'B': c = "byte;"; break;
94 case 'C': c = "char;"; break;
95 case 'D': c = "double;"; break;
96 case 'F': c = "float;"; break;
97 case 'I': c = "int;"; break;
98 case 'J': c = "long;"; break;
99 case 'S': c = "short;"; break;
100 case 'Z': c = "boolean;"; break;
101 case 'V': c = "void;"; break; // Used when decoding return types.
102 default: result->append(descriptor); return;
Elliott Hughes11e45072011-08-16 17:40:46 -0700103 }
104 }
105
106 // At this point, 'c' is a string of the form "fully/qualified/Type;"
107 // or "primitive;". Rewrite the type with '.' instead of '/':
Elliott Hughes11e45072011-08-16 17:40:46 -0700108 const char* p = c;
109 while (*p != ';') {
110 char ch = *p++;
111 if (ch == '/') {
112 ch = '.';
113 }
Vladimir Markob8a55f82017-09-21 16:21:43 +0100114 result->push_back(ch);
Elliott Hughes11e45072011-08-16 17:40:46 -0700115 }
116 // ...and replace the semicolon with 'dim' "[]" pairs:
Ian Rogers1ff3c982014-08-12 02:30:58 -0700117 for (size_t i = 0; i < dim; ++i) {
Vladimir Markob8a55f82017-09-21 16:21:43 +0100118 result->append("[]");
Elliott Hughes11e45072011-08-16 17:40:46 -0700119 }
Elliott Hughes11e45072011-08-16 17:40:46 -0700120}
121
Vladimir Markob8a55f82017-09-21 16:21:43 +0100122std::string PrettyDescriptor(const char* descriptor) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700123 std::string result;
Vladimir Markob8a55f82017-09-21 16:21:43 +0100124 AppendPrettyDescriptor(descriptor, &result);
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700125 return result;
126}
127
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800128std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700129 // The byte thresholds at which we display amounts. A byte count is displayed
130 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800131 static const int64_t kUnitThresholds[] = {
Elliott Hughesc967f782012-04-16 10:23:15 -0700132 0, // B up to...
133 3*1024, // KB up to...
134 2*1024*1024, // MB up to...
135 1024*1024*1024 // GB from here.
136 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800137 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700138 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800139 const char* negative_str = "";
140 if (byte_count < 0) {
141 negative_str = "-";
142 byte_count = -byte_count;
143 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700144 int i = arraysize(kUnitThresholds);
145 while (--i > 0) {
146 if (byte_count >= kUnitThresholds[i]) {
147 break;
148 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800149 }
Brian Carlstrom474cc792014-03-07 14:18:15 -0800150 return StringPrintf("%s%" PRId64 "%s",
151 negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800152}
153
Alex Light888a59e2017-01-25 11:41:41 -0800154std::string GetJniShortName(const std::string& class_descriptor, const std::string& method) {
155 // Remove the leading 'L' and trailing ';'...
156 std::string class_name(class_descriptor);
157 CHECK_EQ(class_name[0], 'L') << class_name;
158 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
159 class_name.erase(0, 1);
160 class_name.erase(class_name.size() - 1, 1);
161
162 std::string short_name;
163 short_name += "Java_";
164 short_name += MangleForJni(class_name);
165 short_name += "_";
166 short_name += MangleForJni(method);
167 return short_name;
168}
169
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800170// 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 -0700171std::string MangleForJni(const std::string& s) {
172 std::string result;
173 size_t char_count = CountModifiedUtf8Chars(s.c_str());
174 const char* cp = &s[0];
175 for (size_t i = 0; i < char_count; ++i) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000176 uint32_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800177 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
178 result.push_back(ch);
179 } else if (ch == '.' || ch == '/') {
180 result += "_";
181 } else if (ch == '_') {
182 result += "_1";
183 } else if (ch == ';') {
184 result += "_2";
185 } else if (ch == '[') {
186 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700187 } else {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000188 const uint16_t leading = GetLeadingUtf16Char(ch);
189 const uint32_t trailing = GetTrailingUtf16Char(ch);
190
191 StringAppendF(&result, "_0%04x", leading);
192 if (trailing != 0) {
193 StringAppendF(&result, "_0%04x", trailing);
194 }
Elliott Hughes79082e32011-08-25 12:07:32 -0700195 }
196 }
197 return result;
198}
199
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700200std::string DotToDescriptor(const char* class_name) {
201 std::string descriptor(class_name);
202 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
203 if (descriptor.length() > 0 && descriptor[0] != '[') {
204 descriptor = "L" + descriptor + ";";
205 }
206 return descriptor;
207}
208
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800209std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800210 size_t length = strlen(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -0700211 if (length > 1) {
212 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
213 // Descriptors have the leading 'L' and trailing ';' stripped.
214 std::string result(descriptor + 1, length - 2);
215 std::replace(result.begin(), result.end(), '/', '.');
216 return result;
217 } else {
218 // For arrays the 'L' and ';' remain intact.
219 std::string result(descriptor);
220 std::replace(result.begin(), result.end(), '/', '.');
221 return result;
222 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800223 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700224 // Do nothing for non-class/array descriptors.
Elliott Hughes2435a572012-02-17 16:07:41 -0800225 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800226}
227
228std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800229 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800230 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
231 std::string result(descriptor + 1, length - 2);
232 return result;
233 }
234 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700235}
236
jeffhao10037c82012-01-23 15:06:23 -0800237// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700238uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700239 0x00000000, // 00..1f low control characters; nothing valid
240 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
241 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
242 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700243};
244
jeffhao10037c82012-01-23 15:06:23 -0800245// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
246bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700247 /*
248 * It's a multibyte encoded character. Decode it and analyze. We
249 * accept anything that isn't (a) an improperly encoded low value,
250 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
251 * control character, or (e) a high space, layout, or special
252 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
253 * U+fff0..U+ffff). This is all specified in the dex format
254 * document.
255 */
256
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000257 const uint32_t pair = GetUtf16FromUtf8(pUtf8Ptr);
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000258 const uint16_t leading = GetLeadingUtf16Char(pair);
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000259
Narayan Kamath8508e372015-05-06 14:55:43 +0100260 // We have a surrogate pair resulting from a valid 4 byte UTF sequence.
261 // No further checks are necessary because 4 byte sequences span code
262 // points [U+10000, U+1FFFFF], which are valid codepoints in a dex
263 // identifier. Furthermore, GetUtf16FromUtf8 guarantees that each of
264 // the surrogate halves are valid and well formed in this instance.
265 if (GetTrailingUtf16Char(pair) != 0) {
266 return true;
267 }
268
269
270 // We've encountered a one, two or three byte UTF-8 sequence. The
271 // three byte UTF-8 sequence could be one half of a surrogate pair.
272 switch (leading >> 8) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000273 case 0x00:
274 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
275 return (leading > 0x00a0);
276 case 0xd8:
277 case 0xd9:
278 case 0xda:
279 case 0xdb:
Narayan Kamath8508e372015-05-06 14:55:43 +0100280 {
281 // We found a three byte sequence encoding one half of a surrogate.
282 // Look for the other half.
283 const uint32_t pair2 = GetUtf16FromUtf8(pUtf8Ptr);
284 const uint16_t trailing = GetLeadingUtf16Char(pair2);
285
286 return (GetTrailingUtf16Char(pair2) == 0) && (0xdc00 <= trailing && trailing <= 0xdfff);
287 }
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000288 case 0xdc:
289 case 0xdd:
290 case 0xde:
291 case 0xdf:
292 // It's a trailing surrogate, which is not valid at this point.
293 return false;
294 case 0x20:
295 case 0xff:
296 // It's in the range that has spaces, controls, and specials.
297 switch (leading & 0xfff8) {
Narayan Kamath8508e372015-05-06 14:55:43 +0100298 case 0x2000:
299 case 0x2008:
300 case 0x2028:
301 case 0xfff0:
302 case 0xfff8:
303 return false;
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000304 }
Narayan Kamath8508e372015-05-06 14:55:43 +0100305 return true;
306 default:
307 return true;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700308 }
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000309
Narayan Kamath8508e372015-05-06 14:55:43 +0100310 UNREACHABLE();
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700311}
312
313/* Return whether the pointed-at modified-UTF-8 encoded character is
314 * valid as part of a member name, updating the pointer to point past
315 * the consumed character. This will consume two encoded UTF-16 code
316 * points if the character is encoded as a surrogate pair. Also, if
317 * this function returns false, then the given pointer may only have
318 * been partially advanced.
319 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700320static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700321 uint8_t c = (uint8_t) **pUtf8Ptr;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700322 if (LIKELY(c <= 0x7f)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700323 // It's low-ascii, so check the table.
324 uint32_t wordIdx = c >> 5;
325 uint32_t bitIdx = c & 0x1f;
326 (*pUtf8Ptr)++;
327 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
328 }
329
330 // It's a multibyte encoded character. Call a non-inline function
331 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800332 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
333}
334
335bool IsValidMemberName(const char* s) {
336 bool angle_name = false;
337
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700338 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800339 case '\0':
340 // The empty string is not a valid name.
341 return false;
342 case '<':
343 angle_name = true;
344 s++;
345 break;
346 }
347
348 while (true) {
349 switch (*s) {
350 case '\0':
351 return !angle_name;
352 case '>':
353 return angle_name && s[1] == '\0';
354 }
355
356 if (!IsValidPartOfMemberNameUtf8(&s)) {
357 return false;
358 }
359 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700360}
361
Elliott Hughes906e6852011-10-28 14:52:10 -0700362enum ClassNameType { kName, kDescriptor };
Ian Rogers7b078e82014-09-10 14:44:24 -0700363template<ClassNameType kType, char kSeparator>
364static bool IsValidClassName(const char* s) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700365 int arrayCount = 0;
366 while (*s == '[') {
367 arrayCount++;
368 s++;
369 }
370
371 if (arrayCount > 255) {
372 // Arrays may have no more than 255 dimensions.
373 return false;
374 }
375
Ian Rogers7b078e82014-09-10 14:44:24 -0700376 ClassNameType type = kType;
377 if (type != kDescriptor && arrayCount != 0) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700378 /*
379 * If we're looking at an array of some sort, then it doesn't
380 * matter if what is being asked for is a class name; the
381 * format looks the same as a type descriptor in that case, so
382 * treat it as such.
383 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700384 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700385 }
386
Elliott Hughes906e6852011-10-28 14:52:10 -0700387 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700388 /*
389 * We are looking for a descriptor. Either validate it as a
390 * single-character primitive type, or continue on to check the
391 * embedded class name (bracketed by "L" and ";").
392 */
393 switch (*(s++)) {
394 case 'B':
395 case 'C':
396 case 'D':
397 case 'F':
398 case 'I':
399 case 'J':
400 case 'S':
401 case 'Z':
402 // These are all single-character descriptors for primitive types.
403 return (*s == '\0');
404 case 'V':
405 // Non-array void is valid, but you can't have an array of void.
406 return (arrayCount == 0) && (*s == '\0');
407 case 'L':
408 // Class name: Break out and continue below.
409 break;
410 default:
411 // Oddball descriptor character.
412 return false;
413 }
414 }
415
416 /*
417 * We just consumed the 'L' that introduces a class name as part
418 * of a type descriptor, or we are looking for an unadorned class
419 * name.
420 */
421
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700422 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700423 for (;;) {
424 uint8_t c = (uint8_t) *s;
425 switch (c) {
426 case '\0':
427 /*
428 * Premature end for a type descriptor, but valid for
429 * a class name as long as we haven't encountered an
430 * empty component (including the degenerate case of
431 * the empty string "").
432 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700433 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700434 case ';':
435 /*
436 * Invalid character for a class name, but the
437 * legitimate end of a type descriptor. In the latter
438 * case, make sure that this is the end of the string
439 * and that it doesn't end with an empty component
440 * (including the degenerate case of "L;").
441 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700442 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700443 case '/':
444 case '.':
Ian Rogers7b078e82014-09-10 14:44:24 -0700445 if (c != kSeparator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700446 // The wrong separator character.
447 return false;
448 }
449 if (sepOrFirst) {
450 // Separator at start or two separators in a row.
451 return false;
452 }
453 sepOrFirst = true;
454 s++;
455 break;
456 default:
jeffhao10037c82012-01-23 15:06:23 -0800457 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700458 return false;
459 }
460 sepOrFirst = false;
461 break;
462 }
463 }
464}
465
Elliott Hughes906e6852011-10-28 14:52:10 -0700466bool IsValidBinaryClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700467 return IsValidClassName<kName, '.'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700468}
469
470bool IsValidJniClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700471 return IsValidClassName<kName, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700472}
473
474bool IsValidDescriptor(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700475 return IsValidClassName<kDescriptor, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700476}
477
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700478void Split(const std::string& s, char separator, std::vector<std::string>* result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700479 const char* p = s.data();
480 const char* end = p + s.size();
481 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800482 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700483 ++p;
484 } else {
485 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800486 while (++p != end && *p != separator) {
487 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700488 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700489 result->push_back(std::string(start, p - start));
Elliott Hughes34023802011-08-30 12:06:17 -0700490 }
491 }
492}
493
Elliott Hughes22869a92012-03-27 14:08:24 -0700494void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700495 int hasAt = 0;
496 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700497 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700498 while (*s) {
499 if (*s == '.') {
500 hasDot = 1;
501 } else if (*s == '@') {
502 hasAt = 1;
503 }
504 s++;
505 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700506 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700507 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700508 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700509 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700510 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700511 }
Elliott Hughes0a18df82015-01-09 15:16:16 -0800512#if defined(__linux__)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700513 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughes0a18df82015-01-09 15:16:16 -0800514 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded in the kernel.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700515 strncpy(buf, s, sizeof(buf)-1);
516 buf[sizeof(buf)-1] = '\0';
517 errno = pthread_setname_np(pthread_self(), buf);
518 if (errno != 0) {
519 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
520 }
Elliott Hughes0a18df82015-01-09 15:16:16 -0800521#else // __APPLE__
Elliott Hughes22869a92012-03-27 14:08:24 -0700522 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700523#endif
524}
525
Brian Carlstrom29212012013-09-12 22:18:30 -0700526void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
527 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700528 std::string stats;
David Sehr013fd802018-01-11 22:55:24 -0800529 // TODO: make this less Linux-specific.
Elliott Hughes8a31b502012-04-30 19:36:11 -0700530 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700531 return;
532 }
533 // Skip the command, which may contain spaces.
534 stats = stats.substr(stats.find(')') + 2);
535 // Extract the three fields we care about.
536 std::vector<std::string> fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700537 Split(stats, ' ', &fields);
Brian Carlstrom29212012013-09-12 22:18:30 -0700538 *state = fields[0][0];
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700539 *utime = strtoull(fields[11].c_str(), nullptr, 10);
540 *stime = strtoull(fields[12].c_str(), nullptr, 10);
541 *task_cpu = strtoull(fields[36].c_str(), nullptr, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700542}
543
Mathieu Chartier76433272014-09-26 14:32:37 -0700544std::string PrettyDescriptor(Primitive::Type type) {
545 return PrettyDescriptor(Primitive::Descriptor(type));
546}
547
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000548static void ParseStringAfterChar(const std::string& s,
549 char c,
550 std::string* parsed_value,
551 UsageFn Usage) {
552 std::string::size_type colon = s.find(c);
553 if (colon == std::string::npos) {
554 Usage("Missing char %c in option %s\n", c, s.c_str());
555 }
556 // Add one to remove the char we were trimming until.
557 *parsed_value = s.substr(colon + 1);
558}
559
560void ParseDouble(const std::string& option,
561 char after_char,
562 double min,
563 double max,
564 double* parsed_value,
565 UsageFn Usage) {
566 std::string substring;
567 ParseStringAfterChar(option, after_char, &substring, Usage);
568 bool sane_val = true;
569 double value;
570 if ((false)) {
571 // TODO: this doesn't seem to work on the emulator. b/15114595
572 std::stringstream iss(substring);
573 iss >> value;
574 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
575 sane_val = iss.eof() && (value >= min) && (value <= max);
576 } else {
577 char* end = nullptr;
578 value = strtod(substring.c_str(), &end);
579 sane_val = *end == '\0' && value >= min && value <= max;
580 }
581 if (!sane_val) {
582 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
583 }
584 *parsed_value = value;
585}
586
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800587void SleepForever() {
588 while (true) {
589 usleep(1000000);
590 }
591}
592
Elliott Hughes42ee1422011-09-06 12:33:32 -0700593} // namespace art