blob: cc0a70269d39a1f84b0a4f2a7bb477faf3351c8a [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 Hughese1aee692012-01-17 16:40:10 -080027#if defined(__APPLE__)
28// Mac OS doesn't have gettid(2).
29pid_t gettid() { return getpid(); }
30#else
31// Neither bionic nor glibc exposes gettid(2).
32#define __KERNEL__
33#include <linux/unistd.h>
34#ifdef _syscall0
35_syscall0(pid_t, gettid)
36#else
37pid_t gettid() { return syscall(__NR_gettid); }
38#endif
39#undef __KERNEL__
40#endif
41
Elliott Hughes11e45072011-08-16 17:40:46 -070042namespace art {
43
Elliott Hughesd92bec42011-09-02 17:04:36 -070044bool ReadFileToString(const std::string& file_name, std::string* result) {
45 UniquePtr<File> file(OS::OpenFile(file_name.c_str(), false));
46 if (file.get() == NULL) {
47 return false;
48 }
buzbeec143c552011-08-20 17:38:58 -070049
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070050 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -070051 while (true) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070052 int64_t n = file->Read(&buf[0], buf.size());
Elliott Hughesd92bec42011-09-02 17:04:36 -070053 if (n == -1) {
54 return false;
buzbeec143c552011-08-20 17:38:58 -070055 }
Elliott Hughesd92bec42011-09-02 17:04:36 -070056 if (n == 0) {
57 return true;
58 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070059 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -070060 }
buzbeec143c552011-08-20 17:38:58 -070061}
62
Elliott Hughese27955c2011-08-26 15:21:24 -070063std::string GetIsoDate() {
64 time_t now = time(NULL);
65 struct tm tmbuf;
66 struct tm* ptm = localtime_r(&now, &tmbuf);
67 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
68 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
69 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
70}
71
Elliott Hughes7162ad92011-10-27 14:08:42 -070072uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -080073#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7162ad92011-10-27 14:08:42 -070074 struct timespec now;
75 clock_gettime(CLOCK_MONOTONIC, &now);
76 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -080077#else
78 struct timeval now;
79 gettimeofday(&now, NULL);
80 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
81#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -070082}
83
jeffhaoa9ef3fd2011-12-13 18:33:43 -080084uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -080085#if defined(HAVE_POSIX_CLOCKS)
jeffhaoa9ef3fd2011-12-13 18:33:43 -080086 struct timespec now;
87 clock_gettime(CLOCK_MONOTONIC, &now);
88 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -080089#else
90 struct timeval now;
91 gettimeofday(&now, NULL);
92 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec * 1000LL;
93#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -080094}
95
Elliott Hughes83df2ac2011-10-11 16:37:54 -070096uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -080097#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes83df2ac2011-10-11 16:37:54 -070098 struct timespec now;
99 clock_gettime(CLOCK_MONOTONIC, &now);
100 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800101#else
102 struct timeval now;
103 gettimeofday(&now, NULL);
104 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
105#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700106}
107
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800108uint64_t ThreadCpuMicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800109#if defined(HAVE_POSIX_CLOCKS)
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800110 struct timespec now;
111 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
112 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800113#else
114 UNIMPLEMENTED(WARNING);
115 return -1;
116#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800117}
118
Elliott Hughes5174fe62011-08-23 15:12:35 -0700119std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700120 if (java_descriptor == NULL) {
121 return "null";
122 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700123 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
124}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700125
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800126std::string PrettyDescriptor(const Class* klass) {
127 if (klass == NULL) {
128 return "null";
129 }
130 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
131
132}
133
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700134std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700135 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700136 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700137 size_t dim = 0;
138 while (*c == '[') {
139 dim++;
140 c++;
141 }
142
143 // Reference or primitive?
144 if (*c == 'L') {
145 // "[[La/b/C;" -> "a.b.C[][]".
146 c++; // Skip the 'L'.
147 } else {
148 // "[[B" -> "byte[][]".
149 // To make life easier, we make primitives look like unqualified
150 // reference types.
151 switch (*c) {
152 case 'B': c = "byte;"; break;
153 case 'C': c = "char;"; break;
154 case 'D': c = "double;"; break;
155 case 'F': c = "float;"; break;
156 case 'I': c = "int;"; break;
157 case 'J': c = "long;"; break;
158 case 'S': c = "short;"; break;
159 case 'Z': c = "boolean;"; break;
Elliott Hughes5174fe62011-08-23 15:12:35 -0700160 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700161 }
162 }
163
164 // At this point, 'c' is a string of the form "fully/qualified/Type;"
165 // or "primitive;". Rewrite the type with '.' instead of '/':
166 std::string result;
167 const char* p = c;
168 while (*p != ';') {
169 char ch = *p++;
170 if (ch == '/') {
171 ch = '.';
172 }
173 result.push_back(ch);
174 }
175 // ...and replace the semicolon with 'dim' "[]" pairs:
176 while (dim--) {
177 result += "[]";
178 }
179 return result;
180}
181
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700182std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800183 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700184 return PrettyDescriptor(descriptor_string);
185}
186
Elliott Hughes54e7df12011-09-16 11:47:04 -0700187std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700188 if (f == NULL) {
189 return "null";
190 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800191 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700192 std::string result;
193 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800194 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700195 result += ' ';
196 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800197 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700198 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800199 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700200 return result;
201}
202
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700203std::string PrettyMethod(const Method* m, bool with_signature) {
204 if (m == NULL) {
205 return "null";
206 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800207 MethodHelper mh(m);
208 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700209 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800210 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700211 if (with_signature) {
212 // TODO: iterate over the signature's elements and pass them all to
213 // PrettyDescriptor? We'd need to pull out the return type specially, too.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800214 result += mh.GetSignature();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700215 }
216 return result;
217}
218
Ian Rogers0571d352011-11-03 19:51:38 -0700219std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
220 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
221 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
222 result += '.';
223 result += dex_file.GetMethodName(method_id);
224 if (with_signature) {
225 // TODO: iterate over the signature's elements and pass them all to
226 // PrettyDescriptor? We'd need to pull out the return type specially, too.
227 result += dex_file.GetMethodSignature(method_id);
228 }
229 return result;
230}
231
Elliott Hughes54e7df12011-09-16 11:47:04 -0700232std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700233 if (obj == NULL) {
234 return "null";
235 }
236 if (obj->GetClass() == NULL) {
237 return "(raw)";
238 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800239 ClassHelper kh(obj->GetClass());
240 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700241 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800242 kh.ChangeClass(obj->AsClass());
243 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700244 }
245 return result;
246}
247
Elliott Hughes54e7df12011-09-16 11:47:04 -0700248std::string PrettyClass(const Class* c) {
249 if (c == NULL) {
250 return "null";
251 }
252 std::string result;
253 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800254 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700255 result += ">";
256 return result;
257}
258
Ian Rogersd81871c2011-10-03 13:57:23 -0700259std::string PrettyClassAndClassLoader(const Class* c) {
260 if (c == NULL) {
261 return "null";
262 }
263 std::string result;
264 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800265 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700266 result += ",";
267 result += PrettyTypeOf(c->GetClassLoader());
268 // TODO: add an identifying hash value for the loader
269 result += ">";
270 return result;
271}
272
Elliott Hughes79082e32011-08-25 12:07:32 -0700273std::string MangleForJni(const std::string& s) {
274 std::string result;
275 size_t char_count = CountModifiedUtf8Chars(s.c_str());
276 const char* cp = &s[0];
277 for (size_t i = 0; i < char_count; ++i) {
278 uint16_t ch = GetUtf16FromUtf8(&cp);
279 if (ch == '$' || ch > 127) {
280 StringAppendF(&result, "_0%04x", ch);
281 } else {
282 switch (ch) {
283 case '_':
284 result += "_1";
285 break;
286 case ';':
287 result += "_2";
288 break;
289 case '[':
290 result += "_3";
291 break;
292 case '/':
293 result += "_";
294 break;
295 default:
296 result.push_back(ch);
297 break;
298 }
299 }
300 }
301 return result;
302}
303
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700304std::string DotToDescriptor(const char* class_name) {
305 std::string descriptor(class_name);
306 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
307 if (descriptor.length() > 0 && descriptor[0] != '[') {
308 descriptor = "L" + descriptor + ";";
309 }
310 return descriptor;
311}
312
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800313std::string DescriptorToDot(const StringPiece& descriptor) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700314 DCHECK_EQ(descriptor[0], 'L');
315 DCHECK_EQ(descriptor[descriptor.size()-1], ';');
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800316 std::string dot(descriptor.substr(1, descriptor.size() - 2).ToString());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700317 std::replace(dot.begin(), dot.end(), '/', '.');
318 return dot;
319}
320
Elliott Hughes79082e32011-08-25 12:07:32 -0700321std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800322 MethodHelper mh(m);
323 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700324 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700325 CHECK_EQ(class_name[0], 'L') << class_name;
326 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700327 class_name.erase(0, 1);
328 class_name.erase(class_name.size() - 1, 1);
329
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800330 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700331
332 std::string short_name;
333 short_name += "Java_";
334 short_name += MangleForJni(class_name);
335 short_name += "_";
336 short_name += MangleForJni(method_name);
337 return short_name;
338}
339
340std::string JniLongName(const Method* m) {
341 std::string long_name;
342 long_name += JniShortName(m);
343 long_name += "__";
344
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800345 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700346 signature.erase(0, 1);
347 signature.erase(signature.begin() + signature.find(')'), signature.end());
348
349 long_name += MangleForJni(signature);
350
351 return long_name;
352}
353
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700354// Helper for IsValidMemberNameUtf8(), a bit vector indicating valid low ascii.
355uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
356 0x00000000, // 00..1f low control characters; nothing valid
357 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
358 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
359 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
360};
361
362// Helper for IsValidMemberNameUtf8(); do not call directly.
363bool IsValidMemberNameUtf8Slow(const char** pUtf8Ptr) {
364 /*
365 * It's a multibyte encoded character. Decode it and analyze. We
366 * accept anything that isn't (a) an improperly encoded low value,
367 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
368 * control character, or (e) a high space, layout, or special
369 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
370 * U+fff0..U+ffff). This is all specified in the dex format
371 * document.
372 */
373
374 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
375
376 // Perform follow-up tests based on the high 8 bits.
377 switch (utf16 >> 8) {
378 case 0x00:
379 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
380 return (utf16 > 0x00a0);
381 case 0xd8:
382 case 0xd9:
383 case 0xda:
384 case 0xdb:
385 // It's a leading surrogate. Check to see that a trailing
386 // surrogate follows.
387 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
388 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
389 case 0xdc:
390 case 0xdd:
391 case 0xde:
392 case 0xdf:
393 // It's a trailing surrogate, which is not valid at this point.
394 return false;
395 case 0x20:
396 case 0xff:
397 // It's in the range that has spaces, controls, and specials.
398 switch (utf16 & 0xfff8) {
399 case 0x2000:
400 case 0x2008:
401 case 0x2028:
402 case 0xfff0:
403 case 0xfff8:
404 return false;
405 }
406 break;
407 }
408 return true;
409}
410
411/* Return whether the pointed-at modified-UTF-8 encoded character is
412 * valid as part of a member name, updating the pointer to point past
413 * the consumed character. This will consume two encoded UTF-16 code
414 * points if the character is encoded as a surrogate pair. Also, if
415 * this function returns false, then the given pointer may only have
416 * been partially advanced.
417 */
418bool IsValidMemberNameUtf8(const char** pUtf8Ptr) {
419 uint8_t c = (uint8_t) **pUtf8Ptr;
420 if (c <= 0x7f) {
421 // It's low-ascii, so check the table.
422 uint32_t wordIdx = c >> 5;
423 uint32_t bitIdx = c & 0x1f;
424 (*pUtf8Ptr)++;
425 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
426 }
427
428 // It's a multibyte encoded character. Call a non-inline function
429 // for the heavy lifting.
430 return IsValidMemberNameUtf8Slow(pUtf8Ptr);
431}
432
Elliott Hughes906e6852011-10-28 14:52:10 -0700433enum ClassNameType { kName, kDescriptor };
434bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700435 int arrayCount = 0;
436 while (*s == '[') {
437 arrayCount++;
438 s++;
439 }
440
441 if (arrayCount > 255) {
442 // Arrays may have no more than 255 dimensions.
443 return false;
444 }
445
446 if (arrayCount != 0) {
447 /*
448 * If we're looking at an array of some sort, then it doesn't
449 * matter if what is being asked for is a class name; the
450 * format looks the same as a type descriptor in that case, so
451 * treat it as such.
452 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700453 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700454 }
455
Elliott Hughes906e6852011-10-28 14:52:10 -0700456 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700457 /*
458 * We are looking for a descriptor. Either validate it as a
459 * single-character primitive type, or continue on to check the
460 * embedded class name (bracketed by "L" and ";").
461 */
462 switch (*(s++)) {
463 case 'B':
464 case 'C':
465 case 'D':
466 case 'F':
467 case 'I':
468 case 'J':
469 case 'S':
470 case 'Z':
471 // These are all single-character descriptors for primitive types.
472 return (*s == '\0');
473 case 'V':
474 // Non-array void is valid, but you can't have an array of void.
475 return (arrayCount == 0) && (*s == '\0');
476 case 'L':
477 // Class name: Break out and continue below.
478 break;
479 default:
480 // Oddball descriptor character.
481 return false;
482 }
483 }
484
485 /*
486 * We just consumed the 'L' that introduces a class name as part
487 * of a type descriptor, or we are looking for an unadorned class
488 * name.
489 */
490
491 bool sepOrFirst = true; // first character or just encountered a separator.
492 for (;;) {
493 uint8_t c = (uint8_t) *s;
494 switch (c) {
495 case '\0':
496 /*
497 * Premature end for a type descriptor, but valid for
498 * a class name as long as we haven't encountered an
499 * empty component (including the degenerate case of
500 * the empty string "").
501 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700502 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700503 case ';':
504 /*
505 * Invalid character for a class name, but the
506 * legitimate end of a type descriptor. In the latter
507 * case, make sure that this is the end of the string
508 * and that it doesn't end with an empty component
509 * (including the degenerate case of "L;").
510 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700511 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700512 case '/':
513 case '.':
514 if (c != separator) {
515 // The wrong separator character.
516 return false;
517 }
518 if (sepOrFirst) {
519 // Separator at start or two separators in a row.
520 return false;
521 }
522 sepOrFirst = true;
523 s++;
524 break;
525 default:
526 if (!IsValidMemberNameUtf8(&s)) {
527 return false;
528 }
529 sepOrFirst = false;
530 break;
531 }
532 }
533}
534
Elliott Hughes906e6852011-10-28 14:52:10 -0700535bool IsValidBinaryClassName(const char* s) {
536 return IsValidClassName(s, kName, '.');
537}
538
539bool IsValidJniClassName(const char* s) {
540 return IsValidClassName(s, kName, '/');
541}
542
543bool IsValidDescriptor(const char* s) {
544 return IsValidClassName(s, kDescriptor, '/');
545}
546
Elliott Hughes34023802011-08-30 12:06:17 -0700547void Split(const std::string& s, char delim, std::vector<std::string>& result) {
548 const char* p = s.data();
549 const char* end = p + s.size();
550 while (p != end) {
551 if (*p == delim) {
552 ++p;
553 } else {
554 const char* start = p;
555 while (++p != end && *p != delim) {
556 // Skip to the next occurrence of the delimiter.
557 }
558 result.push_back(std::string(start, p - start));
559 }
560 }
561}
562
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800563void SetThreadName(const char* threadName) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700564 int hasAt = 0;
565 int hasDot = 0;
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800566 const char* s = threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700567 while (*s) {
568 if (*s == '.') {
569 hasDot = 1;
570 } else if (*s == '@') {
571 hasAt = 1;
572 }
573 s++;
574 }
575 int len = s - threadName;
576 if (len < 15 || hasAt || !hasDot) {
577 s = threadName;
578 } else {
579 s = threadName + len - 15;
580 }
581#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
582 /* pthread_setname_np fails rather than truncating long strings */
583 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
584 strncpy(buf, s, sizeof(buf)-1);
585 buf[sizeof(buf)-1] = '\0';
586 errno = pthread_setname_np(pthread_self(), buf);
587 if (errno != 0) {
588 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
589 }
590#elif defined(HAVE_PRCTL)
591 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
592#else
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800593 UNIMPLEMENTED(WARNING) << threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700594#endif
595}
596
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700597void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
598 utime = stime = task_cpu = 0;
599 std::string stats;
600 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
601 return;
602 }
603 // Skip the command, which may contain spaces.
604 stats = stats.substr(stats.find(')') + 2);
605 // Extract the three fields we care about.
606 std::vector<std::string> fields;
607 Split(stats, ' ', fields);
608 utime = strtoull(fields[11].c_str(), NULL, 10);
609 stime = strtoull(fields[12].c_str(), NULL, 10);
610 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
611}
612
Brian Carlstroma9f19782011-10-13 00:14:47 -0700613std::string GetArtCacheOrDie() {
614 const char* data_root = getenv("ANDROID_DATA");
615 if (data_root == NULL) {
616 if (OS::DirectoryExists("/data")) {
617 data_root = "/data";
618 } else {
619 data_root = "/tmp";
620 }
621 }
622 if (!OS::DirectoryExists(data_root)) {
623 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << data_root;
624 return "";
625 }
626
Elliott Hughes95572412011-12-13 18:14:20 -0800627 std::string art_cache(StringPrintf("%s/art-cache", data_root));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700628
629 if (!OS::DirectoryExists(art_cache.c_str())) {
630 if (StringPiece(art_cache).starts_with("/tmp/")) {
631 int result = mkdir(art_cache.c_str(), 0700);
632 if (result != 0) {
633 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
634 return "";
635 }
636 } else {
637 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
638 return "";
639 }
640 }
641 return art_cache;
642}
643
jeffhao262bf462011-10-20 18:36:32 -0700644std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800645 std::string art_cache(GetArtCacheOrDie());
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700646 CHECK_EQ(location[0], '/');
647 std::string cache_file(location, 1); // skip leading slash
648 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
649 return art_cache + "/" + cache_file;
650}
651
jeffhao262bf462011-10-20 18:36:32 -0700652bool IsValidZipFilename(const std::string& filename) {
653 if (filename.size() < 4) {
654 return false;
655 }
656 std::string suffix(filename.substr(filename.size() - 4));
657 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
658}
659
660bool IsValidDexFilename(const std::string& filename) {
661 if (filename.size() < 4) {
662 return false;
663 }
664 std::string suffix(filename.substr(filename.size() - 4));
665 return (suffix == ".dex");
666}
667
Elliott Hughese1aee692012-01-17 16:40:10 -0800668pid_t GetTid() {
669 return gettid();
670}
Elliott Hughes42ee1422011-09-06 12:33:32 -0700671
Elliott Hughes42ee1422011-09-06 12:33:32 -0700672} // namespace art