blob: ced68de1e8fc35c49627e6b5dc7b4312b2eb6402 [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 Hughes11e45072011-08-16 17:40:46 -070023namespace art {
24
Elliott Hughesd92bec42011-09-02 17:04:36 -070025bool ReadFileToString(const std::string& file_name, std::string* result) {
26 UniquePtr<File> file(OS::OpenFile(file_name.c_str(), false));
27 if (file.get() == NULL) {
28 return false;
29 }
buzbeec143c552011-08-20 17:38:58 -070030
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070031 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -070032 while (true) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070033 int64_t n = file->Read(&buf[0], buf.size());
Elliott Hughesd92bec42011-09-02 17:04:36 -070034 if (n == -1) {
35 return false;
buzbeec143c552011-08-20 17:38:58 -070036 }
Elliott Hughesd92bec42011-09-02 17:04:36 -070037 if (n == 0) {
38 return true;
39 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070040 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -070041 }
buzbeec143c552011-08-20 17:38:58 -070042}
43
Elliott Hughese27955c2011-08-26 15:21:24 -070044std::string GetIsoDate() {
45 time_t now = time(NULL);
46 struct tm tmbuf;
47 struct tm* ptm = localtime_r(&now, &tmbuf);
48 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
49 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
50 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
51}
52
Elliott Hughes7162ad92011-10-27 14:08:42 -070053uint64_t MilliTime() {
54 struct timespec now;
55 clock_gettime(CLOCK_MONOTONIC, &now);
56 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
57}
58
jeffhaoa9ef3fd2011-12-13 18:33:43 -080059uint64_t MicroTime() {
60 struct timespec now;
61 clock_gettime(CLOCK_MONOTONIC, &now);
62 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
63}
64
Elliott Hughes83df2ac2011-10-11 16:37:54 -070065uint64_t NanoTime() {
66 struct timespec now;
67 clock_gettime(CLOCK_MONOTONIC, &now);
68 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
69}
70
jeffhaoa9ef3fd2011-12-13 18:33:43 -080071uint64_t ThreadCpuMicroTime() {
72 struct timespec now;
73 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
74 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
75}
76
Elliott Hughes5174fe62011-08-23 15:12:35 -070077std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -070078 if (java_descriptor == NULL) {
79 return "null";
80 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -070081 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
82}
Elliott Hughes5174fe62011-08-23 15:12:35 -070083
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080084std::string PrettyDescriptor(const Class* klass) {
85 if (klass == NULL) {
86 return "null";
87 }
88 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
89
90}
91
Elliott Hughes6c8867d2011-10-03 16:34:05 -070092std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -070093 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -070094 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -070095 size_t dim = 0;
96 while (*c == '[') {
97 dim++;
98 c++;
99 }
100
101 // Reference or primitive?
102 if (*c == 'L') {
103 // "[[La/b/C;" -> "a.b.C[][]".
104 c++; // Skip the 'L'.
105 } else {
106 // "[[B" -> "byte[][]".
107 // To make life easier, we make primitives look like unqualified
108 // reference types.
109 switch (*c) {
110 case 'B': c = "byte;"; break;
111 case 'C': c = "char;"; break;
112 case 'D': c = "double;"; break;
113 case 'F': c = "float;"; break;
114 case 'I': c = "int;"; break;
115 case 'J': c = "long;"; break;
116 case 'S': c = "short;"; break;
117 case 'Z': c = "boolean;"; break;
Elliott Hughes5174fe62011-08-23 15:12:35 -0700118 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700119 }
120 }
121
122 // At this point, 'c' is a string of the form "fully/qualified/Type;"
123 // or "primitive;". Rewrite the type with '.' instead of '/':
124 std::string result;
125 const char* p = c;
126 while (*p != ';') {
127 char ch = *p++;
128 if (ch == '/') {
129 ch = '.';
130 }
131 result.push_back(ch);
132 }
133 // ...and replace the semicolon with 'dim' "[]" pairs:
134 while (dim--) {
135 result += "[]";
136 }
137 return result;
138}
139
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700140std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800141 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700142 return PrettyDescriptor(descriptor_string);
143}
144
Elliott Hughes54e7df12011-09-16 11:47:04 -0700145std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700146 if (f == NULL) {
147 return "null";
148 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800149 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700150 std::string result;
151 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800152 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700153 result += ' ';
154 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800155 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700156 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800157 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700158 return result;
159}
160
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700161std::string PrettyMethod(const Method* m, bool with_signature) {
162 if (m == NULL) {
163 return "null";
164 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800165 MethodHelper mh(m);
166 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700167 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800168 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700169 if (with_signature) {
170 // TODO: iterate over the signature's elements and pass them all to
171 // PrettyDescriptor? We'd need to pull out the return type specially, too.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800172 result += mh.GetSignature();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700173 }
174 return result;
175}
176
Ian Rogers0571d352011-11-03 19:51:38 -0700177std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
178 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
179 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
180 result += '.';
181 result += dex_file.GetMethodName(method_id);
182 if (with_signature) {
183 // TODO: iterate over the signature's elements and pass them all to
184 // PrettyDescriptor? We'd need to pull out the return type specially, too.
185 result += dex_file.GetMethodSignature(method_id);
186 }
187 return result;
188}
189
Elliott Hughes54e7df12011-09-16 11:47:04 -0700190std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700191 if (obj == NULL) {
192 return "null";
193 }
194 if (obj->GetClass() == NULL) {
195 return "(raw)";
196 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800197 ClassHelper kh(obj->GetClass());
198 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700199 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800200 kh.ChangeClass(obj->AsClass());
201 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700202 }
203 return result;
204}
205
Elliott Hughes54e7df12011-09-16 11:47:04 -0700206std::string PrettyClass(const Class* c) {
207 if (c == NULL) {
208 return "null";
209 }
210 std::string result;
211 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800212 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700213 result += ">";
214 return result;
215}
216
Ian Rogersd81871c2011-10-03 13:57:23 -0700217std::string PrettyClassAndClassLoader(const Class* c) {
218 if (c == NULL) {
219 return "null";
220 }
221 std::string result;
222 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800223 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700224 result += ",";
225 result += PrettyTypeOf(c->GetClassLoader());
226 // TODO: add an identifying hash value for the loader
227 result += ">";
228 return result;
229}
230
Elliott Hughes79082e32011-08-25 12:07:32 -0700231std::string MangleForJni(const std::string& s) {
232 std::string result;
233 size_t char_count = CountModifiedUtf8Chars(s.c_str());
234 const char* cp = &s[0];
235 for (size_t i = 0; i < char_count; ++i) {
236 uint16_t ch = GetUtf16FromUtf8(&cp);
237 if (ch == '$' || ch > 127) {
238 StringAppendF(&result, "_0%04x", ch);
239 } else {
240 switch (ch) {
241 case '_':
242 result += "_1";
243 break;
244 case ';':
245 result += "_2";
246 break;
247 case '[':
248 result += "_3";
249 break;
250 case '/':
251 result += "_";
252 break;
253 default:
254 result.push_back(ch);
255 break;
256 }
257 }
258 }
259 return result;
260}
261
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700262std::string DotToDescriptor(const char* class_name) {
263 std::string descriptor(class_name);
264 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
265 if (descriptor.length() > 0 && descriptor[0] != '[') {
266 descriptor = "L" + descriptor + ";";
267 }
268 return descriptor;
269}
270
Brian Carlstromaded5f72011-10-07 17:15:04 -0700271std::string DescriptorToDot(const std::string& descriptor) {
272 DCHECK_EQ(descriptor[0], 'L');
273 DCHECK_EQ(descriptor[descriptor.size()-1], ';');
Elliott Hughes95572412011-12-13 18:14:20 -0800274 std::string dot(descriptor.substr(1, descriptor.size() - 2));
Brian Carlstromaded5f72011-10-07 17:15:04 -0700275 std::replace(dot.begin(), dot.end(), '/', '.');
276 return dot;
277}
278
Elliott Hughes79082e32011-08-25 12:07:32 -0700279std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800280 MethodHelper mh(m);
281 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700282 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700283 CHECK_EQ(class_name[0], 'L') << class_name;
284 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700285 class_name.erase(0, 1);
286 class_name.erase(class_name.size() - 1, 1);
287
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800288 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700289
290 std::string short_name;
291 short_name += "Java_";
292 short_name += MangleForJni(class_name);
293 short_name += "_";
294 short_name += MangleForJni(method_name);
295 return short_name;
296}
297
298std::string JniLongName(const Method* m) {
299 std::string long_name;
300 long_name += JniShortName(m);
301 long_name += "__";
302
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800303 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700304 signature.erase(0, 1);
305 signature.erase(signature.begin() + signature.find(')'), signature.end());
306
307 long_name += MangleForJni(signature);
308
309 return long_name;
310}
311
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700312// Helper for IsValidMemberNameUtf8(), a bit vector indicating valid low ascii.
313uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
314 0x00000000, // 00..1f low control characters; nothing valid
315 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
316 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
317 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
318};
319
320// Helper for IsValidMemberNameUtf8(); do not call directly.
321bool IsValidMemberNameUtf8Slow(const char** pUtf8Ptr) {
322 /*
323 * It's a multibyte encoded character. Decode it and analyze. We
324 * accept anything that isn't (a) an improperly encoded low value,
325 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
326 * control character, or (e) a high space, layout, or special
327 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
328 * U+fff0..U+ffff). This is all specified in the dex format
329 * document.
330 */
331
332 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
333
334 // Perform follow-up tests based on the high 8 bits.
335 switch (utf16 >> 8) {
336 case 0x00:
337 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
338 return (utf16 > 0x00a0);
339 case 0xd8:
340 case 0xd9:
341 case 0xda:
342 case 0xdb:
343 // It's a leading surrogate. Check to see that a trailing
344 // surrogate follows.
345 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
346 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
347 case 0xdc:
348 case 0xdd:
349 case 0xde:
350 case 0xdf:
351 // It's a trailing surrogate, which is not valid at this point.
352 return false;
353 case 0x20:
354 case 0xff:
355 // It's in the range that has spaces, controls, and specials.
356 switch (utf16 & 0xfff8) {
357 case 0x2000:
358 case 0x2008:
359 case 0x2028:
360 case 0xfff0:
361 case 0xfff8:
362 return false;
363 }
364 break;
365 }
366 return true;
367}
368
369/* Return whether the pointed-at modified-UTF-8 encoded character is
370 * valid as part of a member name, updating the pointer to point past
371 * the consumed character. This will consume two encoded UTF-16 code
372 * points if the character is encoded as a surrogate pair. Also, if
373 * this function returns false, then the given pointer may only have
374 * been partially advanced.
375 */
376bool IsValidMemberNameUtf8(const char** pUtf8Ptr) {
377 uint8_t c = (uint8_t) **pUtf8Ptr;
378 if (c <= 0x7f) {
379 // It's low-ascii, so check the table.
380 uint32_t wordIdx = c >> 5;
381 uint32_t bitIdx = c & 0x1f;
382 (*pUtf8Ptr)++;
383 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
384 }
385
386 // It's a multibyte encoded character. Call a non-inline function
387 // for the heavy lifting.
388 return IsValidMemberNameUtf8Slow(pUtf8Ptr);
389}
390
Elliott Hughes906e6852011-10-28 14:52:10 -0700391enum ClassNameType { kName, kDescriptor };
392bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700393 int arrayCount = 0;
394 while (*s == '[') {
395 arrayCount++;
396 s++;
397 }
398
399 if (arrayCount > 255) {
400 // Arrays may have no more than 255 dimensions.
401 return false;
402 }
403
404 if (arrayCount != 0) {
405 /*
406 * If we're looking at an array of some sort, then it doesn't
407 * matter if what is being asked for is a class name; the
408 * format looks the same as a type descriptor in that case, so
409 * treat it as such.
410 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700411 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700412 }
413
Elliott Hughes906e6852011-10-28 14:52:10 -0700414 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700415 /*
416 * We are looking for a descriptor. Either validate it as a
417 * single-character primitive type, or continue on to check the
418 * embedded class name (bracketed by "L" and ";").
419 */
420 switch (*(s++)) {
421 case 'B':
422 case 'C':
423 case 'D':
424 case 'F':
425 case 'I':
426 case 'J':
427 case 'S':
428 case 'Z':
429 // These are all single-character descriptors for primitive types.
430 return (*s == '\0');
431 case 'V':
432 // Non-array void is valid, but you can't have an array of void.
433 return (arrayCount == 0) && (*s == '\0');
434 case 'L':
435 // Class name: Break out and continue below.
436 break;
437 default:
438 // Oddball descriptor character.
439 return false;
440 }
441 }
442
443 /*
444 * We just consumed the 'L' that introduces a class name as part
445 * of a type descriptor, or we are looking for an unadorned class
446 * name.
447 */
448
449 bool sepOrFirst = true; // first character or just encountered a separator.
450 for (;;) {
451 uint8_t c = (uint8_t) *s;
452 switch (c) {
453 case '\0':
454 /*
455 * Premature end for a type descriptor, but valid for
456 * a class name as long as we haven't encountered an
457 * empty component (including the degenerate case of
458 * the empty string "").
459 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700460 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700461 case ';':
462 /*
463 * Invalid character for a class name, but the
464 * legitimate end of a type descriptor. In the latter
465 * case, make sure that this is the end of the string
466 * and that it doesn't end with an empty component
467 * (including the degenerate case of "L;").
468 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700469 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700470 case '/':
471 case '.':
472 if (c != separator) {
473 // The wrong separator character.
474 return false;
475 }
476 if (sepOrFirst) {
477 // Separator at start or two separators in a row.
478 return false;
479 }
480 sepOrFirst = true;
481 s++;
482 break;
483 default:
484 if (!IsValidMemberNameUtf8(&s)) {
485 return false;
486 }
487 sepOrFirst = false;
488 break;
489 }
490 }
491}
492
Elliott Hughes906e6852011-10-28 14:52:10 -0700493bool IsValidBinaryClassName(const char* s) {
494 return IsValidClassName(s, kName, '.');
495}
496
497bool IsValidJniClassName(const char* s) {
498 return IsValidClassName(s, kName, '/');
499}
500
501bool IsValidDescriptor(const char* s) {
502 return IsValidClassName(s, kDescriptor, '/');
503}
504
Elliott Hughes34023802011-08-30 12:06:17 -0700505void Split(const std::string& s, char delim, std::vector<std::string>& result) {
506 const char* p = s.data();
507 const char* end = p + s.size();
508 while (p != end) {
509 if (*p == delim) {
510 ++p;
511 } else {
512 const char* start = p;
513 while (++p != end && *p != delim) {
514 // Skip to the next occurrence of the delimiter.
515 }
516 result.push_back(std::string(start, p - start));
517 }
518 }
519}
520
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800521void SetThreadName(const char* threadName) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700522 int hasAt = 0;
523 int hasDot = 0;
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800524 const char* s = threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700525 while (*s) {
526 if (*s == '.') {
527 hasDot = 1;
528 } else if (*s == '@') {
529 hasAt = 1;
530 }
531 s++;
532 }
533 int len = s - threadName;
534 if (len < 15 || hasAt || !hasDot) {
535 s = threadName;
536 } else {
537 s = threadName + len - 15;
538 }
539#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
540 /* pthread_setname_np fails rather than truncating long strings */
541 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
542 strncpy(buf, s, sizeof(buf)-1);
543 buf[sizeof(buf)-1] = '\0';
544 errno = pthread_setname_np(pthread_self(), buf);
545 if (errno != 0) {
546 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
547 }
548#elif defined(HAVE_PRCTL)
549 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
550#else
551#error no implementation for SetThreadName
552#endif
553}
554
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700555void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
556 utime = stime = task_cpu = 0;
557 std::string stats;
558 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
559 return;
560 }
561 // Skip the command, which may contain spaces.
562 stats = stats.substr(stats.find(')') + 2);
563 // Extract the three fields we care about.
564 std::vector<std::string> fields;
565 Split(stats, ' ', fields);
566 utime = strtoull(fields[11].c_str(), NULL, 10);
567 stime = strtoull(fields[12].c_str(), NULL, 10);
568 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
569}
570
Brian Carlstroma9f19782011-10-13 00:14:47 -0700571std::string GetArtCacheOrDie() {
572 const char* data_root = getenv("ANDROID_DATA");
573 if (data_root == NULL) {
574 if (OS::DirectoryExists("/data")) {
575 data_root = "/data";
576 } else {
577 data_root = "/tmp";
578 }
579 }
580 if (!OS::DirectoryExists(data_root)) {
581 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << data_root;
582 return "";
583 }
584
Elliott Hughes95572412011-12-13 18:14:20 -0800585 std::string art_cache(StringPrintf("%s/art-cache", data_root));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700586
587 if (!OS::DirectoryExists(art_cache.c_str())) {
588 if (StringPiece(art_cache).starts_with("/tmp/")) {
589 int result = mkdir(art_cache.c_str(), 0700);
590 if (result != 0) {
591 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
592 return "";
593 }
594 } else {
595 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
596 return "";
597 }
598 }
599 return art_cache;
600}
601
jeffhao262bf462011-10-20 18:36:32 -0700602std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800603 std::string art_cache(GetArtCacheOrDie());
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700604 CHECK_EQ(location[0], '/');
605 std::string cache_file(location, 1); // skip leading slash
606 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
607 return art_cache + "/" + cache_file;
608}
609
jeffhao262bf462011-10-20 18:36:32 -0700610bool IsValidZipFilename(const std::string& filename) {
611 if (filename.size() < 4) {
612 return false;
613 }
614 std::string suffix(filename.substr(filename.size() - 4));
615 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
616}
617
618bool IsValidDexFilename(const std::string& filename) {
619 if (filename.size() < 4) {
620 return false;
621 }
622 std::string suffix(filename.substr(filename.size() - 4));
623 return (suffix == ".dex");
624}
625
Elliott Hughes11e45072011-08-16 17:40:46 -0700626} // namespace art
Elliott Hughes42ee1422011-09-06 12:33:32 -0700627
628// Neither bionic nor glibc exposes gettid(2).
629#define __KERNEL__
630#include <linux/unistd.h>
631namespace art {
632#ifdef _syscall0
633_syscall0(pid_t, GetTid)
634#else
635pid_t GetTid() { return syscall(__NR_gettid); }
636#endif
637} // namespace art
638#undef __KERNEL__