blob: d4d2e3a8b63db062a316de6d72c4d40c28c1c284 [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 Hughesad6c9c32012-01-19 17:39:12 -080019#if !defined(HAVE_POSIX_CLOCKS)
20#include <sys/time.h>
21#endif
22
Elliott Hughesdcc24742011-09-07 14:02:44 -070023#if defined(HAVE_PRCTL)
24#include <sys/prctl.h>
25#endif
26
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080027#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080028#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080029#endif
30
Elliott Hughes11e45072011-08-16 17:40:46 -070031namespace art {
32
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080033pid_t GetTid() {
34#if defined(__APPLE__)
35 // Mac OS doesn't have gettid(2).
36 return getpid();
37#else
38 // Neither bionic nor glibc exposes gettid(2).
39 return syscall(__NR_gettid);
40#endif
41}
42
Elliott Hughesd92bec42011-09-02 17:04:36 -070043bool ReadFileToString(const std::string& file_name, std::string* result) {
44 UniquePtr<File> file(OS::OpenFile(file_name.c_str(), false));
45 if (file.get() == NULL) {
46 return false;
47 }
buzbeec143c552011-08-20 17:38:58 -070048
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070049 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -070050 while (true) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070051 int64_t n = file->Read(&buf[0], buf.size());
Elliott Hughesd92bec42011-09-02 17:04:36 -070052 if (n == -1) {
53 return false;
buzbeec143c552011-08-20 17:38:58 -070054 }
Elliott Hughesd92bec42011-09-02 17:04:36 -070055 if (n == 0) {
56 return true;
57 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070058 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -070059 }
buzbeec143c552011-08-20 17:38:58 -070060}
61
Elliott Hughese27955c2011-08-26 15:21:24 -070062std::string GetIsoDate() {
63 time_t now = time(NULL);
64 struct tm tmbuf;
65 struct tm* ptm = localtime_r(&now, &tmbuf);
66 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
67 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
68 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
69}
70
Elliott Hughes7162ad92011-10-27 14:08:42 -070071uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -080072#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7162ad92011-10-27 14:08:42 -070073 struct timespec now;
74 clock_gettime(CLOCK_MONOTONIC, &now);
75 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -080076#else
77 struct timeval now;
78 gettimeofday(&now, NULL);
79 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
80#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -070081}
82
jeffhaoa9ef3fd2011-12-13 18:33:43 -080083uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -080084#if defined(HAVE_POSIX_CLOCKS)
jeffhaoa9ef3fd2011-12-13 18:33:43 -080085 struct timespec now;
86 clock_gettime(CLOCK_MONOTONIC, &now);
87 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -080088#else
89 struct timeval now;
90 gettimeofday(&now, NULL);
91 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec * 1000LL;
92#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -080093}
94
Elliott Hughes83df2ac2011-10-11 16:37:54 -070095uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -080096#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes83df2ac2011-10-11 16:37:54 -070097 struct timespec now;
98 clock_gettime(CLOCK_MONOTONIC, &now);
99 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800100#else
101 struct timeval now;
102 gettimeofday(&now, NULL);
103 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
104#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700105}
106
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800107uint64_t ThreadCpuMicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800108#if defined(HAVE_POSIX_CLOCKS)
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800109 struct timespec now;
110 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
111 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800112#else
113 UNIMPLEMENTED(WARNING);
114 return -1;
115#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800116}
117
Elliott Hughes5174fe62011-08-23 15:12:35 -0700118std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700119 if (java_descriptor == NULL) {
120 return "null";
121 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700122 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
123}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700124
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800125std::string PrettyDescriptor(const Class* klass) {
126 if (klass == NULL) {
127 return "null";
128 }
129 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
130
131}
132
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700133std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700134 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700135 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700136 size_t dim = 0;
137 while (*c == '[') {
138 dim++;
139 c++;
140 }
141
142 // Reference or primitive?
143 if (*c == 'L') {
144 // "[[La/b/C;" -> "a.b.C[][]".
145 c++; // Skip the 'L'.
146 } else {
147 // "[[B" -> "byte[][]".
148 // To make life easier, we make primitives look like unqualified
149 // reference types.
150 switch (*c) {
151 case 'B': c = "byte;"; break;
152 case 'C': c = "char;"; break;
153 case 'D': c = "double;"; break;
154 case 'F': c = "float;"; break;
155 case 'I': c = "int;"; break;
156 case 'J': c = "long;"; break;
157 case 'S': c = "short;"; break;
158 case 'Z': c = "boolean;"; break;
Elliott Hughes5174fe62011-08-23 15:12:35 -0700159 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700160 }
161 }
162
163 // At this point, 'c' is a string of the form "fully/qualified/Type;"
164 // or "primitive;". Rewrite the type with '.' instead of '/':
165 std::string result;
166 const char* p = c;
167 while (*p != ';') {
168 char ch = *p++;
169 if (ch == '/') {
170 ch = '.';
171 }
172 result.push_back(ch);
173 }
174 // ...and replace the semicolon with 'dim' "[]" pairs:
175 while (dim--) {
176 result += "[]";
177 }
178 return result;
179}
180
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700181std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800182 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700183 return PrettyDescriptor(descriptor_string);
184}
185
Elliott Hughes54e7df12011-09-16 11:47:04 -0700186std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700187 if (f == NULL) {
188 return "null";
189 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800190 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700191 std::string result;
192 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800193 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700194 result += ' ';
195 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800196 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700197 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800198 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700199 return result;
200}
201
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700202std::string PrettyMethod(const Method* m, bool with_signature) {
203 if (m == NULL) {
204 return "null";
205 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800206 MethodHelper mh(m);
207 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700208 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800209 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700210 if (with_signature) {
211 // TODO: iterate over the signature's elements and pass them all to
212 // PrettyDescriptor? We'd need to pull out the return type specially, too.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800213 result += mh.GetSignature();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700214 }
215 return result;
216}
217
Ian Rogers0571d352011-11-03 19:51:38 -0700218std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
219 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
220 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
221 result += '.';
222 result += dex_file.GetMethodName(method_id);
223 if (with_signature) {
224 // TODO: iterate over the signature's elements and pass them all to
225 // PrettyDescriptor? We'd need to pull out the return type specially, too.
226 result += dex_file.GetMethodSignature(method_id);
227 }
228 return result;
229}
230
Elliott Hughes54e7df12011-09-16 11:47:04 -0700231std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700232 if (obj == NULL) {
233 return "null";
234 }
235 if (obj->GetClass() == NULL) {
236 return "(raw)";
237 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800238 ClassHelper kh(obj->GetClass());
239 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700240 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800241 kh.ChangeClass(obj->AsClass());
242 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700243 }
244 return result;
245}
246
Elliott Hughes54e7df12011-09-16 11:47:04 -0700247std::string PrettyClass(const Class* c) {
248 if (c == NULL) {
249 return "null";
250 }
251 std::string result;
252 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800253 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700254 result += ">";
255 return result;
256}
257
Ian Rogersd81871c2011-10-03 13:57:23 -0700258std::string PrettyClassAndClassLoader(const Class* c) {
259 if (c == NULL) {
260 return "null";
261 }
262 std::string result;
263 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800264 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700265 result += ",";
266 result += PrettyTypeOf(c->GetClassLoader());
267 // TODO: add an identifying hash value for the loader
268 result += ">";
269 return result;
270}
271
Elliott Hughes79082e32011-08-25 12:07:32 -0700272std::string MangleForJni(const std::string& s) {
273 std::string result;
274 size_t char_count = CountModifiedUtf8Chars(s.c_str());
275 const char* cp = &s[0];
276 for (size_t i = 0; i < char_count; ++i) {
277 uint16_t ch = GetUtf16FromUtf8(&cp);
278 if (ch == '$' || ch > 127) {
279 StringAppendF(&result, "_0%04x", ch);
280 } else {
281 switch (ch) {
282 case '_':
283 result += "_1";
284 break;
285 case ';':
286 result += "_2";
287 break;
288 case '[':
289 result += "_3";
290 break;
291 case '/':
292 result += "_";
293 break;
294 default:
295 result.push_back(ch);
296 break;
297 }
298 }
299 }
300 return result;
301}
302
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700303std::string DotToDescriptor(const char* class_name) {
304 std::string descriptor(class_name);
305 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
306 if (descriptor.length() > 0 && descriptor[0] != '[') {
307 descriptor = "L" + descriptor + ";";
308 }
309 return descriptor;
310}
311
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800312std::string DescriptorToDot(const StringPiece& descriptor) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700313 DCHECK_EQ(descriptor[0], 'L');
314 DCHECK_EQ(descriptor[descriptor.size()-1], ';');
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800315 std::string dot(descriptor.substr(1, descriptor.size() - 2).ToString());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700316 std::replace(dot.begin(), dot.end(), '/', '.');
317 return dot;
318}
319
Elliott Hughes79082e32011-08-25 12:07:32 -0700320std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800321 MethodHelper mh(m);
322 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700323 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700324 CHECK_EQ(class_name[0], 'L') << class_name;
325 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700326 class_name.erase(0, 1);
327 class_name.erase(class_name.size() - 1, 1);
328
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800329 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700330
331 std::string short_name;
332 short_name += "Java_";
333 short_name += MangleForJni(class_name);
334 short_name += "_";
335 short_name += MangleForJni(method_name);
336 return short_name;
337}
338
339std::string JniLongName(const Method* m) {
340 std::string long_name;
341 long_name += JniShortName(m);
342 long_name += "__";
343
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800344 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700345 signature.erase(0, 1);
346 signature.erase(signature.begin() + signature.find(')'), signature.end());
347
348 long_name += MangleForJni(signature);
349
350 return long_name;
351}
352
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700353// Helper for IsValidMemberNameUtf8(), a bit vector indicating valid low ascii.
354uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
355 0x00000000, // 00..1f low control characters; nothing valid
356 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
357 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
358 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
359};
360
361// Helper for IsValidMemberNameUtf8(); do not call directly.
362bool IsValidMemberNameUtf8Slow(const char** pUtf8Ptr) {
363 /*
364 * It's a multibyte encoded character. Decode it and analyze. We
365 * accept anything that isn't (a) an improperly encoded low value,
366 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
367 * control character, or (e) a high space, layout, or special
368 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
369 * U+fff0..U+ffff). This is all specified in the dex format
370 * document.
371 */
372
373 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
374
375 // Perform follow-up tests based on the high 8 bits.
376 switch (utf16 >> 8) {
377 case 0x00:
378 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
379 return (utf16 > 0x00a0);
380 case 0xd8:
381 case 0xd9:
382 case 0xda:
383 case 0xdb:
384 // It's a leading surrogate. Check to see that a trailing
385 // surrogate follows.
386 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
387 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
388 case 0xdc:
389 case 0xdd:
390 case 0xde:
391 case 0xdf:
392 // It's a trailing surrogate, which is not valid at this point.
393 return false;
394 case 0x20:
395 case 0xff:
396 // It's in the range that has spaces, controls, and specials.
397 switch (utf16 & 0xfff8) {
398 case 0x2000:
399 case 0x2008:
400 case 0x2028:
401 case 0xfff0:
402 case 0xfff8:
403 return false;
404 }
405 break;
406 }
407 return true;
408}
409
410/* Return whether the pointed-at modified-UTF-8 encoded character is
411 * valid as part of a member name, updating the pointer to point past
412 * the consumed character. This will consume two encoded UTF-16 code
413 * points if the character is encoded as a surrogate pair. Also, if
414 * this function returns false, then the given pointer may only have
415 * been partially advanced.
416 */
417bool IsValidMemberNameUtf8(const char** pUtf8Ptr) {
418 uint8_t c = (uint8_t) **pUtf8Ptr;
419 if (c <= 0x7f) {
420 // It's low-ascii, so check the table.
421 uint32_t wordIdx = c >> 5;
422 uint32_t bitIdx = c & 0x1f;
423 (*pUtf8Ptr)++;
424 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
425 }
426
427 // It's a multibyte encoded character. Call a non-inline function
428 // for the heavy lifting.
429 return IsValidMemberNameUtf8Slow(pUtf8Ptr);
430}
431
Elliott Hughes906e6852011-10-28 14:52:10 -0700432enum ClassNameType { kName, kDescriptor };
433bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700434 int arrayCount = 0;
435 while (*s == '[') {
436 arrayCount++;
437 s++;
438 }
439
440 if (arrayCount > 255) {
441 // Arrays may have no more than 255 dimensions.
442 return false;
443 }
444
445 if (arrayCount != 0) {
446 /*
447 * If we're looking at an array of some sort, then it doesn't
448 * matter if what is being asked for is a class name; the
449 * format looks the same as a type descriptor in that case, so
450 * treat it as such.
451 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700452 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700453 }
454
Elliott Hughes906e6852011-10-28 14:52:10 -0700455 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700456 /*
457 * We are looking for a descriptor. Either validate it as a
458 * single-character primitive type, or continue on to check the
459 * embedded class name (bracketed by "L" and ";").
460 */
461 switch (*(s++)) {
462 case 'B':
463 case 'C':
464 case 'D':
465 case 'F':
466 case 'I':
467 case 'J':
468 case 'S':
469 case 'Z':
470 // These are all single-character descriptors for primitive types.
471 return (*s == '\0');
472 case 'V':
473 // Non-array void is valid, but you can't have an array of void.
474 return (arrayCount == 0) && (*s == '\0');
475 case 'L':
476 // Class name: Break out and continue below.
477 break;
478 default:
479 // Oddball descriptor character.
480 return false;
481 }
482 }
483
484 /*
485 * We just consumed the 'L' that introduces a class name as part
486 * of a type descriptor, or we are looking for an unadorned class
487 * name.
488 */
489
490 bool sepOrFirst = true; // first character or just encountered a separator.
491 for (;;) {
492 uint8_t c = (uint8_t) *s;
493 switch (c) {
494 case '\0':
495 /*
496 * Premature end for a type descriptor, but valid for
497 * a class name as long as we haven't encountered an
498 * empty component (including the degenerate case of
499 * the empty string "").
500 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700501 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700502 case ';':
503 /*
504 * Invalid character for a class name, but the
505 * legitimate end of a type descriptor. In the latter
506 * case, make sure that this is the end of the string
507 * and that it doesn't end with an empty component
508 * (including the degenerate case of "L;").
509 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700510 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700511 case '/':
512 case '.':
513 if (c != separator) {
514 // The wrong separator character.
515 return false;
516 }
517 if (sepOrFirst) {
518 // Separator at start or two separators in a row.
519 return false;
520 }
521 sepOrFirst = true;
522 s++;
523 break;
524 default:
525 if (!IsValidMemberNameUtf8(&s)) {
526 return false;
527 }
528 sepOrFirst = false;
529 break;
530 }
531 }
532}
533
Elliott Hughes906e6852011-10-28 14:52:10 -0700534bool IsValidBinaryClassName(const char* s) {
535 return IsValidClassName(s, kName, '.');
536}
537
538bool IsValidJniClassName(const char* s) {
539 return IsValidClassName(s, kName, '/');
540}
541
542bool IsValidDescriptor(const char* s) {
543 return IsValidClassName(s, kDescriptor, '/');
544}
545
Elliott Hughes34023802011-08-30 12:06:17 -0700546void Split(const std::string& s, char delim, std::vector<std::string>& result) {
547 const char* p = s.data();
548 const char* end = p + s.size();
549 while (p != end) {
550 if (*p == delim) {
551 ++p;
552 } else {
553 const char* start = p;
554 while (++p != end && *p != delim) {
555 // Skip to the next occurrence of the delimiter.
556 }
557 result.push_back(std::string(start, p - start));
558 }
559 }
560}
561
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800562void SetThreadName(const char* threadName) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700563 int hasAt = 0;
564 int hasDot = 0;
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800565 const char* s = threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700566 while (*s) {
567 if (*s == '.') {
568 hasDot = 1;
569 } else if (*s == '@') {
570 hasAt = 1;
571 }
572 s++;
573 }
574 int len = s - threadName;
575 if (len < 15 || hasAt || !hasDot) {
576 s = threadName;
577 } else {
578 s = threadName + len - 15;
579 }
580#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
581 /* pthread_setname_np fails rather than truncating long strings */
582 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
583 strncpy(buf, s, sizeof(buf)-1);
584 buf[sizeof(buf)-1] = '\0';
585 errno = pthread_setname_np(pthread_self(), buf);
586 if (errno != 0) {
587 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
588 }
589#elif defined(HAVE_PRCTL)
590 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
591#else
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800592 UNIMPLEMENTED(WARNING) << threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700593#endif
594}
595
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700596void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
597 utime = stime = task_cpu = 0;
598 std::string stats;
599 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
600 return;
601 }
602 // Skip the command, which may contain spaces.
603 stats = stats.substr(stats.find(')') + 2);
604 // Extract the three fields we care about.
605 std::vector<std::string> fields;
606 Split(stats, ' ', fields);
607 utime = strtoull(fields[11].c_str(), NULL, 10);
608 stime = strtoull(fields[12].c_str(), NULL, 10);
609 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
610}
611
Brian Carlstroma9f19782011-10-13 00:14:47 -0700612std::string GetArtCacheOrDie() {
613 const char* data_root = getenv("ANDROID_DATA");
614 if (data_root == NULL) {
615 if (OS::DirectoryExists("/data")) {
616 data_root = "/data";
617 } else {
618 data_root = "/tmp";
619 }
620 }
621 if (!OS::DirectoryExists(data_root)) {
622 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << data_root;
623 return "";
624 }
625
Elliott Hughes95572412011-12-13 18:14:20 -0800626 std::string art_cache(StringPrintf("%s/art-cache", data_root));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700627
628 if (!OS::DirectoryExists(art_cache.c_str())) {
629 if (StringPiece(art_cache).starts_with("/tmp/")) {
630 int result = mkdir(art_cache.c_str(), 0700);
631 if (result != 0) {
632 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
633 return "";
634 }
635 } else {
636 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
637 return "";
638 }
639 }
640 return art_cache;
641}
642
jeffhao262bf462011-10-20 18:36:32 -0700643std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800644 std::string art_cache(GetArtCacheOrDie());
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700645 CHECK_EQ(location[0], '/');
646 std::string cache_file(location, 1); // skip leading slash
647 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
648 return art_cache + "/" + cache_file;
649}
650
jeffhao262bf462011-10-20 18:36:32 -0700651bool IsValidZipFilename(const std::string& filename) {
652 if (filename.size() < 4) {
653 return false;
654 }
655 std::string suffix(filename.substr(filename.size() - 4));
656 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
657}
658
659bool IsValidDexFilename(const std::string& filename) {
660 if (filename.size() < 4) {
661 return false;
662 }
663 std::string suffix(filename.substr(filename.size() - 4));
664 return (suffix == ".dex");
665}
666
Elliott Hughes42ee1422011-09-06 12:33:32 -0700667} // namespace art