blob: bf15bd7912d829a1e38bee907d1e24a90ea6397f [file] [log] [blame]
Elliott Hughes11e45072011-08-16 17:40:46 -07001// Copyright 2011 Google Inc. All Rights Reserved.
2// Author: enh@google.com (Elliott Hughes)
3
Elliott Hughes42ee1422011-09-06 12:33:32 -07004#include "utils.h"
5
Elliott Hughes92b3b562011-09-08 16:32:26 -07006#include <pthread.h>
Brian Carlstroma9f19782011-10-13 00:14:47 -07007#include <sys/stat.h>
Elliott Hughes42ee1422011-09-06 12:33:32 -07008#include <sys/syscall.h>
9#include <sys/types.h>
10#include <unistd.h>
11
Elliott Hughes90a33692011-08-30 13:27:07 -070012#include "UniquePtr.h"
Ian Rogersd81871c2011-10-03 13:57:23 -070013#include "class_loader.h"
buzbeec143c552011-08-20 17:38:58 -070014#include "file.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070015#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080016#include "object_utils.h"
buzbeec143c552011-08-20 17:38:58 -070017#include "os.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070018
Elliott Hughesdcc24742011-09-07 14:02:44 -070019#if defined(HAVE_PRCTL)
20#include <sys/prctl.h>
21#endif
22
Elliott Hughese1aee692012-01-17 16:40:10 -080023#if defined(__APPLE__)
24// Mac OS doesn't have gettid(2).
25pid_t gettid() { return getpid(); }
26#else
27// Neither bionic nor glibc exposes gettid(2).
28#define __KERNEL__
29#include <linux/unistd.h>
30#ifdef _syscall0
31_syscall0(pid_t, gettid)
32#else
33pid_t gettid() { return syscall(__NR_gettid); }
34#endif
35#undef __KERNEL__
36#endif
37
Elliott Hughes11e45072011-08-16 17:40:46 -070038namespace art {
39
Elliott Hughesd92bec42011-09-02 17:04:36 -070040bool ReadFileToString(const std::string& file_name, std::string* result) {
41 UniquePtr<File> file(OS::OpenFile(file_name.c_str(), false));
42 if (file.get() == NULL) {
43 return false;
44 }
buzbeec143c552011-08-20 17:38:58 -070045
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070046 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -070047 while (true) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070048 int64_t n = file->Read(&buf[0], buf.size());
Elliott Hughesd92bec42011-09-02 17:04:36 -070049 if (n == -1) {
50 return false;
buzbeec143c552011-08-20 17:38:58 -070051 }
Elliott Hughesd92bec42011-09-02 17:04:36 -070052 if (n == 0) {
53 return true;
54 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070055 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -070056 }
buzbeec143c552011-08-20 17:38:58 -070057}
58
Elliott Hughese27955c2011-08-26 15:21:24 -070059std::string GetIsoDate() {
60 time_t now = time(NULL);
61 struct tm tmbuf;
62 struct tm* ptm = localtime_r(&now, &tmbuf);
63 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
64 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
65 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
66}
67
Elliott Hughes7162ad92011-10-27 14:08:42 -070068uint64_t MilliTime() {
69 struct timespec now;
70 clock_gettime(CLOCK_MONOTONIC, &now);
71 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
72}
73
jeffhaoa9ef3fd2011-12-13 18:33:43 -080074uint64_t MicroTime() {
75 struct timespec now;
76 clock_gettime(CLOCK_MONOTONIC, &now);
77 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
78}
79
Elliott Hughes83df2ac2011-10-11 16:37:54 -070080uint64_t NanoTime() {
81 struct timespec now;
82 clock_gettime(CLOCK_MONOTONIC, &now);
83 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
84}
85
jeffhaoa9ef3fd2011-12-13 18:33:43 -080086uint64_t ThreadCpuMicroTime() {
87 struct timespec now;
88 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
89 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
90}
91
Elliott Hughes5174fe62011-08-23 15:12:35 -070092std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -070093 if (java_descriptor == NULL) {
94 return "null";
95 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -070096 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
97}
Elliott Hughes5174fe62011-08-23 15:12:35 -070098
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080099std::string PrettyDescriptor(const Class* klass) {
100 if (klass == NULL) {
101 return "null";
102 }
103 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
104
105}
106
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700107std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700108 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700109 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700110 size_t dim = 0;
111 while (*c == '[') {
112 dim++;
113 c++;
114 }
115
116 // Reference or primitive?
117 if (*c == 'L') {
118 // "[[La/b/C;" -> "a.b.C[][]".
119 c++; // Skip the 'L'.
120 } else {
121 // "[[B" -> "byte[][]".
122 // To make life easier, we make primitives look like unqualified
123 // reference types.
124 switch (*c) {
125 case 'B': c = "byte;"; break;
126 case 'C': c = "char;"; break;
127 case 'D': c = "double;"; break;
128 case 'F': c = "float;"; break;
129 case 'I': c = "int;"; break;
130 case 'J': c = "long;"; break;
131 case 'S': c = "short;"; break;
132 case 'Z': c = "boolean;"; break;
Elliott Hughes5174fe62011-08-23 15:12:35 -0700133 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700134 }
135 }
136
137 // At this point, 'c' is a string of the form "fully/qualified/Type;"
138 // or "primitive;". Rewrite the type with '.' instead of '/':
139 std::string result;
140 const char* p = c;
141 while (*p != ';') {
142 char ch = *p++;
143 if (ch == '/') {
144 ch = '.';
145 }
146 result.push_back(ch);
147 }
148 // ...and replace the semicolon with 'dim' "[]" pairs:
149 while (dim--) {
150 result += "[]";
151 }
152 return result;
153}
154
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700155std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800156 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700157 return PrettyDescriptor(descriptor_string);
158}
159
Elliott Hughes54e7df12011-09-16 11:47:04 -0700160std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700161 if (f == NULL) {
162 return "null";
163 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800164 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700165 std::string result;
166 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800167 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700168 result += ' ';
169 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800170 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700171 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800172 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700173 return result;
174}
175
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700176std::string PrettyMethod(const Method* m, bool with_signature) {
177 if (m == NULL) {
178 return "null";
179 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800180 MethodHelper mh(m);
181 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700182 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800183 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700184 if (with_signature) {
185 // TODO: iterate over the signature's elements and pass them all to
186 // PrettyDescriptor? We'd need to pull out the return type specially, too.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800187 result += mh.GetSignature();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700188 }
189 return result;
190}
191
Ian Rogers0571d352011-11-03 19:51:38 -0700192std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
193 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
194 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
195 result += '.';
196 result += dex_file.GetMethodName(method_id);
197 if (with_signature) {
198 // TODO: iterate over the signature's elements and pass them all to
199 // PrettyDescriptor? We'd need to pull out the return type specially, too.
200 result += dex_file.GetMethodSignature(method_id);
201 }
202 return result;
203}
204
Elliott Hughes54e7df12011-09-16 11:47:04 -0700205std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700206 if (obj == NULL) {
207 return "null";
208 }
209 if (obj->GetClass() == NULL) {
210 return "(raw)";
211 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800212 ClassHelper kh(obj->GetClass());
213 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700214 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800215 kh.ChangeClass(obj->AsClass());
216 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700217 }
218 return result;
219}
220
Elliott Hughes54e7df12011-09-16 11:47:04 -0700221std::string PrettyClass(const Class* c) {
222 if (c == NULL) {
223 return "null";
224 }
225 std::string result;
226 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800227 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700228 result += ">";
229 return result;
230}
231
Ian Rogersd81871c2011-10-03 13:57:23 -0700232std::string PrettyClassAndClassLoader(const Class* c) {
233 if (c == NULL) {
234 return "null";
235 }
236 std::string result;
237 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800238 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700239 result += ",";
240 result += PrettyTypeOf(c->GetClassLoader());
241 // TODO: add an identifying hash value for the loader
242 result += ">";
243 return result;
244}
245
Elliott Hughes79082e32011-08-25 12:07:32 -0700246std::string MangleForJni(const std::string& s) {
247 std::string result;
248 size_t char_count = CountModifiedUtf8Chars(s.c_str());
249 const char* cp = &s[0];
250 for (size_t i = 0; i < char_count; ++i) {
251 uint16_t ch = GetUtf16FromUtf8(&cp);
252 if (ch == '$' || ch > 127) {
253 StringAppendF(&result, "_0%04x", ch);
254 } else {
255 switch (ch) {
256 case '_':
257 result += "_1";
258 break;
259 case ';':
260 result += "_2";
261 break;
262 case '[':
263 result += "_3";
264 break;
265 case '/':
266 result += "_";
267 break;
268 default:
269 result.push_back(ch);
270 break;
271 }
272 }
273 }
274 return result;
275}
276
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700277std::string DotToDescriptor(const char* class_name) {
278 std::string descriptor(class_name);
279 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
280 if (descriptor.length() > 0 && descriptor[0] != '[') {
281 descriptor = "L" + descriptor + ";";
282 }
283 return descriptor;
284}
285
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800286std::string DescriptorToDot(const StringPiece& descriptor) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700287 DCHECK_EQ(descriptor[0], 'L');
288 DCHECK_EQ(descriptor[descriptor.size()-1], ';');
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800289 std::string dot(descriptor.substr(1, descriptor.size() - 2).ToString());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700290 std::replace(dot.begin(), dot.end(), '/', '.');
291 return dot;
292}
293
Elliott Hughes79082e32011-08-25 12:07:32 -0700294std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800295 MethodHelper mh(m);
296 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700297 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700298 CHECK_EQ(class_name[0], 'L') << class_name;
299 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700300 class_name.erase(0, 1);
301 class_name.erase(class_name.size() - 1, 1);
302
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800303 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700304
305 std::string short_name;
306 short_name += "Java_";
307 short_name += MangleForJni(class_name);
308 short_name += "_";
309 short_name += MangleForJni(method_name);
310 return short_name;
311}
312
313std::string JniLongName(const Method* m) {
314 std::string long_name;
315 long_name += JniShortName(m);
316 long_name += "__";
317
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800318 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700319 signature.erase(0, 1);
320 signature.erase(signature.begin() + signature.find(')'), signature.end());
321
322 long_name += MangleForJni(signature);
323
324 return long_name;
325}
326
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700327// Helper for IsValidMemberNameUtf8(), a bit vector indicating valid low ascii.
328uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
329 0x00000000, // 00..1f low control characters; nothing valid
330 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
331 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
332 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
333};
334
335// Helper for IsValidMemberNameUtf8(); do not call directly.
336bool IsValidMemberNameUtf8Slow(const char** pUtf8Ptr) {
337 /*
338 * It's a multibyte encoded character. Decode it and analyze. We
339 * accept anything that isn't (a) an improperly encoded low value,
340 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
341 * control character, or (e) a high space, layout, or special
342 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
343 * U+fff0..U+ffff). This is all specified in the dex format
344 * document.
345 */
346
347 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
348
349 // Perform follow-up tests based on the high 8 bits.
350 switch (utf16 >> 8) {
351 case 0x00:
352 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
353 return (utf16 > 0x00a0);
354 case 0xd8:
355 case 0xd9:
356 case 0xda:
357 case 0xdb:
358 // It's a leading surrogate. Check to see that a trailing
359 // surrogate follows.
360 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
361 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
362 case 0xdc:
363 case 0xdd:
364 case 0xde:
365 case 0xdf:
366 // It's a trailing surrogate, which is not valid at this point.
367 return false;
368 case 0x20:
369 case 0xff:
370 // It's in the range that has spaces, controls, and specials.
371 switch (utf16 & 0xfff8) {
372 case 0x2000:
373 case 0x2008:
374 case 0x2028:
375 case 0xfff0:
376 case 0xfff8:
377 return false;
378 }
379 break;
380 }
381 return true;
382}
383
384/* Return whether the pointed-at modified-UTF-8 encoded character is
385 * valid as part of a member name, updating the pointer to point past
386 * the consumed character. This will consume two encoded UTF-16 code
387 * points if the character is encoded as a surrogate pair. Also, if
388 * this function returns false, then the given pointer may only have
389 * been partially advanced.
390 */
391bool IsValidMemberNameUtf8(const char** pUtf8Ptr) {
392 uint8_t c = (uint8_t) **pUtf8Ptr;
393 if (c <= 0x7f) {
394 // It's low-ascii, so check the table.
395 uint32_t wordIdx = c >> 5;
396 uint32_t bitIdx = c & 0x1f;
397 (*pUtf8Ptr)++;
398 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
399 }
400
401 // It's a multibyte encoded character. Call a non-inline function
402 // for the heavy lifting.
403 return IsValidMemberNameUtf8Slow(pUtf8Ptr);
404}
405
Elliott Hughes906e6852011-10-28 14:52:10 -0700406enum ClassNameType { kName, kDescriptor };
407bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700408 int arrayCount = 0;
409 while (*s == '[') {
410 arrayCount++;
411 s++;
412 }
413
414 if (arrayCount > 255) {
415 // Arrays may have no more than 255 dimensions.
416 return false;
417 }
418
419 if (arrayCount != 0) {
420 /*
421 * If we're looking at an array of some sort, then it doesn't
422 * matter if what is being asked for is a class name; the
423 * format looks the same as a type descriptor in that case, so
424 * treat it as such.
425 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700426 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700427 }
428
Elliott Hughes906e6852011-10-28 14:52:10 -0700429 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700430 /*
431 * We are looking for a descriptor. Either validate it as a
432 * single-character primitive type, or continue on to check the
433 * embedded class name (bracketed by "L" and ";").
434 */
435 switch (*(s++)) {
436 case 'B':
437 case 'C':
438 case 'D':
439 case 'F':
440 case 'I':
441 case 'J':
442 case 'S':
443 case 'Z':
444 // These are all single-character descriptors for primitive types.
445 return (*s == '\0');
446 case 'V':
447 // Non-array void is valid, but you can't have an array of void.
448 return (arrayCount == 0) && (*s == '\0');
449 case 'L':
450 // Class name: Break out and continue below.
451 break;
452 default:
453 // Oddball descriptor character.
454 return false;
455 }
456 }
457
458 /*
459 * We just consumed the 'L' that introduces a class name as part
460 * of a type descriptor, or we are looking for an unadorned class
461 * name.
462 */
463
464 bool sepOrFirst = true; // first character or just encountered a separator.
465 for (;;) {
466 uint8_t c = (uint8_t) *s;
467 switch (c) {
468 case '\0':
469 /*
470 * Premature end for a type descriptor, but valid for
471 * a class name as long as we haven't encountered an
472 * empty component (including the degenerate case of
473 * the empty string "").
474 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700475 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700476 case ';':
477 /*
478 * Invalid character for a class name, but the
479 * legitimate end of a type descriptor. In the latter
480 * case, make sure that this is the end of the string
481 * and that it doesn't end with an empty component
482 * (including the degenerate case of "L;").
483 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700484 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700485 case '/':
486 case '.':
487 if (c != separator) {
488 // The wrong separator character.
489 return false;
490 }
491 if (sepOrFirst) {
492 // Separator at start or two separators in a row.
493 return false;
494 }
495 sepOrFirst = true;
496 s++;
497 break;
498 default:
499 if (!IsValidMemberNameUtf8(&s)) {
500 return false;
501 }
502 sepOrFirst = false;
503 break;
504 }
505 }
506}
507
Elliott Hughes906e6852011-10-28 14:52:10 -0700508bool IsValidBinaryClassName(const char* s) {
509 return IsValidClassName(s, kName, '.');
510}
511
512bool IsValidJniClassName(const char* s) {
513 return IsValidClassName(s, kName, '/');
514}
515
516bool IsValidDescriptor(const char* s) {
517 return IsValidClassName(s, kDescriptor, '/');
518}
519
Elliott Hughes34023802011-08-30 12:06:17 -0700520void Split(const std::string& s, char delim, std::vector<std::string>& result) {
521 const char* p = s.data();
522 const char* end = p + s.size();
523 while (p != end) {
524 if (*p == delim) {
525 ++p;
526 } else {
527 const char* start = p;
528 while (++p != end && *p != delim) {
529 // Skip to the next occurrence of the delimiter.
530 }
531 result.push_back(std::string(start, p - start));
532 }
533 }
534}
535
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800536void SetThreadName(const char* threadName) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700537 int hasAt = 0;
538 int hasDot = 0;
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800539 const char* s = threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700540 while (*s) {
541 if (*s == '.') {
542 hasDot = 1;
543 } else if (*s == '@') {
544 hasAt = 1;
545 }
546 s++;
547 }
548 int len = s - threadName;
549 if (len < 15 || hasAt || !hasDot) {
550 s = threadName;
551 } else {
552 s = threadName + len - 15;
553 }
554#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
555 /* pthread_setname_np fails rather than truncating long strings */
556 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
557 strncpy(buf, s, sizeof(buf)-1);
558 buf[sizeof(buf)-1] = '\0';
559 errno = pthread_setname_np(pthread_self(), buf);
560 if (errno != 0) {
561 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
562 }
563#elif defined(HAVE_PRCTL)
564 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
565#else
566#error no implementation for SetThreadName
567#endif
568}
569
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700570void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
571 utime = stime = task_cpu = 0;
572 std::string stats;
573 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
574 return;
575 }
576 // Skip the command, which may contain spaces.
577 stats = stats.substr(stats.find(')') + 2);
578 // Extract the three fields we care about.
579 std::vector<std::string> fields;
580 Split(stats, ' ', fields);
581 utime = strtoull(fields[11].c_str(), NULL, 10);
582 stime = strtoull(fields[12].c_str(), NULL, 10);
583 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
584}
585
Brian Carlstroma9f19782011-10-13 00:14:47 -0700586std::string GetArtCacheOrDie() {
587 const char* data_root = getenv("ANDROID_DATA");
588 if (data_root == NULL) {
589 if (OS::DirectoryExists("/data")) {
590 data_root = "/data";
591 } else {
592 data_root = "/tmp";
593 }
594 }
595 if (!OS::DirectoryExists(data_root)) {
596 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << data_root;
597 return "";
598 }
599
Elliott Hughes95572412011-12-13 18:14:20 -0800600 std::string art_cache(StringPrintf("%s/art-cache", data_root));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700601
602 if (!OS::DirectoryExists(art_cache.c_str())) {
603 if (StringPiece(art_cache).starts_with("/tmp/")) {
604 int result = mkdir(art_cache.c_str(), 0700);
605 if (result != 0) {
606 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
607 return "";
608 }
609 } else {
610 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
611 return "";
612 }
613 }
614 return art_cache;
615}
616
jeffhao262bf462011-10-20 18:36:32 -0700617std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800618 std::string art_cache(GetArtCacheOrDie());
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700619 CHECK_EQ(location[0], '/');
620 std::string cache_file(location, 1); // skip leading slash
621 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
622 return art_cache + "/" + cache_file;
623}
624
jeffhao262bf462011-10-20 18:36:32 -0700625bool IsValidZipFilename(const std::string& filename) {
626 if (filename.size() < 4) {
627 return false;
628 }
629 std::string suffix(filename.substr(filename.size() - 4));
630 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
631}
632
633bool IsValidDexFilename(const std::string& filename) {
634 if (filename.size() < 4) {
635 return false;
636 }
637 std::string suffix(filename.substr(filename.size() - 4));
638 return (suffix == ".dex");
639}
640
Elliott Hughese1aee692012-01-17 16:40:10 -0800641pid_t GetTid() {
642 return gettid();
643}
Elliott Hughes42ee1422011-09-06 12:33:32 -0700644
Elliott Hughes42ee1422011-09-06 12:33:32 -0700645} // namespace art