blob: c0be9b4a44ef043cff131bef166a794c70a62518 [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());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800130}
131
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700132std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700133 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700134 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700135 size_t dim = 0;
136 while (*c == '[') {
137 dim++;
138 c++;
139 }
140
141 // Reference or primitive?
142 if (*c == 'L') {
143 // "[[La/b/C;" -> "a.b.C[][]".
144 c++; // Skip the 'L'.
145 } else {
146 // "[[B" -> "byte[][]".
147 // To make life easier, we make primitives look like unqualified
148 // reference types.
149 switch (*c) {
150 case 'B': c = "byte;"; break;
151 case 'C': c = "char;"; break;
152 case 'D': c = "double;"; break;
153 case 'F': c = "float;"; break;
154 case 'I': c = "int;"; break;
155 case 'J': c = "long;"; break;
156 case 'S': c = "short;"; break;
157 case 'Z': c = "boolean;"; break;
Elliott Hughes5174fe62011-08-23 15:12:35 -0700158 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700159 }
160 }
161
162 // At this point, 'c' is a string of the form "fully/qualified/Type;"
163 // or "primitive;". Rewrite the type with '.' instead of '/':
164 std::string result;
165 const char* p = c;
166 while (*p != ';') {
167 char ch = *p++;
168 if (ch == '/') {
169 ch = '.';
170 }
171 result.push_back(ch);
172 }
173 // ...and replace the semicolon with 'dim' "[]" pairs:
174 while (dim--) {
175 result += "[]";
176 }
177 return result;
178}
179
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700180std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800181 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700182 return PrettyDescriptor(descriptor_string);
183}
184
Elliott Hughes54e7df12011-09-16 11:47:04 -0700185std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700186 if (f == NULL) {
187 return "null";
188 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800189 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700190 std::string result;
191 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800192 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700193 result += ' ';
194 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800195 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700196 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800197 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700198 return result;
199}
200
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700201std::string PrettyMethod(const Method* m, bool with_signature) {
202 if (m == NULL) {
203 return "null";
204 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800205 MethodHelper mh(m);
206 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700207 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800208 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700209 if (with_signature) {
210 // TODO: iterate over the signature's elements and pass them all to
211 // PrettyDescriptor? We'd need to pull out the return type specially, too.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800212 result += mh.GetSignature();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700213 }
214 return result;
215}
216
Ian Rogers0571d352011-11-03 19:51:38 -0700217std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
218 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
219 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
220 result += '.';
221 result += dex_file.GetMethodName(method_id);
222 if (with_signature) {
223 // TODO: iterate over the signature's elements and pass them all to
224 // PrettyDescriptor? We'd need to pull out the return type specially, too.
225 result += dex_file.GetMethodSignature(method_id);
226 }
227 return result;
228}
229
Elliott Hughes54e7df12011-09-16 11:47:04 -0700230std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700231 if (obj == NULL) {
232 return "null";
233 }
234 if (obj->GetClass() == NULL) {
235 return "(raw)";
236 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800237 ClassHelper kh(obj->GetClass());
238 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700239 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800240 kh.ChangeClass(obj->AsClass());
241 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700242 }
243 return result;
244}
245
Elliott Hughes54e7df12011-09-16 11:47:04 -0700246std::string PrettyClass(const Class* c) {
247 if (c == NULL) {
248 return "null";
249 }
250 std::string result;
251 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800252 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700253 result += ">";
254 return result;
255}
256
Ian Rogersd81871c2011-10-03 13:57:23 -0700257std::string PrettyClassAndClassLoader(const Class* c) {
258 if (c == NULL) {
259 return "null";
260 }
261 std::string result;
262 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800263 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700264 result += ",";
265 result += PrettyTypeOf(c->GetClassLoader());
266 // TODO: add an identifying hash value for the loader
267 result += ">";
268 return result;
269}
270
Elliott Hughes79082e32011-08-25 12:07:32 -0700271std::string MangleForJni(const std::string& s) {
272 std::string result;
273 size_t char_count = CountModifiedUtf8Chars(s.c_str());
274 const char* cp = &s[0];
275 for (size_t i = 0; i < char_count; ++i) {
276 uint16_t ch = GetUtf16FromUtf8(&cp);
277 if (ch == '$' || ch > 127) {
278 StringAppendF(&result, "_0%04x", ch);
279 } else {
280 switch (ch) {
281 case '_':
282 result += "_1";
283 break;
284 case ';':
285 result += "_2";
286 break;
287 case '[':
288 result += "_3";
289 break;
290 case '/':
291 result += "_";
292 break;
293 default:
294 result.push_back(ch);
295 break;
296 }
297 }
298 }
299 return result;
300}
301
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700302std::string DotToDescriptor(const char* class_name) {
303 std::string descriptor(class_name);
304 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
305 if (descriptor.length() > 0 && descriptor[0] != '[') {
306 descriptor = "L" + descriptor + ";";
307 }
308 return descriptor;
309}
310
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800311std::string DescriptorToDot(const StringPiece& descriptor) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700312 DCHECK_EQ(descriptor[0], 'L');
313 DCHECK_EQ(descriptor[descriptor.size()-1], ';');
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800314 std::string dot(descriptor.substr(1, descriptor.size() - 2).ToString());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700315 std::replace(dot.begin(), dot.end(), '/', '.');
316 return dot;
317}
318
Elliott Hughes79082e32011-08-25 12:07:32 -0700319std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800320 MethodHelper mh(m);
321 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700322 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700323 CHECK_EQ(class_name[0], 'L') << class_name;
324 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700325 class_name.erase(0, 1);
326 class_name.erase(class_name.size() - 1, 1);
327
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800328 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700329
330 std::string short_name;
331 short_name += "Java_";
332 short_name += MangleForJni(class_name);
333 short_name += "_";
334 short_name += MangleForJni(method_name);
335 return short_name;
336}
337
338std::string JniLongName(const Method* m) {
339 std::string long_name;
340 long_name += JniShortName(m);
341 long_name += "__";
342
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800343 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700344 signature.erase(0, 1);
345 signature.erase(signature.begin() + signature.find(')'), signature.end());
346
347 long_name += MangleForJni(signature);
348
349 return long_name;
350}
351
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700352// Helper for IsValidMemberNameUtf8(), a bit vector indicating valid low ascii.
353uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
354 0x00000000, // 00..1f low control characters; nothing valid
355 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
356 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
357 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
358};
359
360// Helper for IsValidMemberNameUtf8(); do not call directly.
361bool IsValidMemberNameUtf8Slow(const char** pUtf8Ptr) {
362 /*
363 * It's a multibyte encoded character. Decode it and analyze. We
364 * accept anything that isn't (a) an improperly encoded low value,
365 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
366 * control character, or (e) a high space, layout, or special
367 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
368 * U+fff0..U+ffff). This is all specified in the dex format
369 * document.
370 */
371
372 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
373
374 // Perform follow-up tests based on the high 8 bits.
375 switch (utf16 >> 8) {
376 case 0x00:
377 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
378 return (utf16 > 0x00a0);
379 case 0xd8:
380 case 0xd9:
381 case 0xda:
382 case 0xdb:
383 // It's a leading surrogate. Check to see that a trailing
384 // surrogate follows.
385 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
386 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
387 case 0xdc:
388 case 0xdd:
389 case 0xde:
390 case 0xdf:
391 // It's a trailing surrogate, which is not valid at this point.
392 return false;
393 case 0x20:
394 case 0xff:
395 // It's in the range that has spaces, controls, and specials.
396 switch (utf16 & 0xfff8) {
397 case 0x2000:
398 case 0x2008:
399 case 0x2028:
400 case 0xfff0:
401 case 0xfff8:
402 return false;
403 }
404 break;
405 }
406 return true;
407}
408
409/* Return whether the pointed-at modified-UTF-8 encoded character is
410 * valid as part of a member name, updating the pointer to point past
411 * the consumed character. This will consume two encoded UTF-16 code
412 * points if the character is encoded as a surrogate pair. Also, if
413 * this function returns false, then the given pointer may only have
414 * been partially advanced.
415 */
416bool IsValidMemberNameUtf8(const char** pUtf8Ptr) {
417 uint8_t c = (uint8_t) **pUtf8Ptr;
418 if (c <= 0x7f) {
419 // It's low-ascii, so check the table.
420 uint32_t wordIdx = c >> 5;
421 uint32_t bitIdx = c & 0x1f;
422 (*pUtf8Ptr)++;
423 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
424 }
425
426 // It's a multibyte encoded character. Call a non-inline function
427 // for the heavy lifting.
428 return IsValidMemberNameUtf8Slow(pUtf8Ptr);
429}
430
Elliott Hughes906e6852011-10-28 14:52:10 -0700431enum ClassNameType { kName, kDescriptor };
432bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700433 int arrayCount = 0;
434 while (*s == '[') {
435 arrayCount++;
436 s++;
437 }
438
439 if (arrayCount > 255) {
440 // Arrays may have no more than 255 dimensions.
441 return false;
442 }
443
444 if (arrayCount != 0) {
445 /*
446 * If we're looking at an array of some sort, then it doesn't
447 * matter if what is being asked for is a class name; the
448 * format looks the same as a type descriptor in that case, so
449 * treat it as such.
450 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700451 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700452 }
453
Elliott Hughes906e6852011-10-28 14:52:10 -0700454 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700455 /*
456 * We are looking for a descriptor. Either validate it as a
457 * single-character primitive type, or continue on to check the
458 * embedded class name (bracketed by "L" and ";").
459 */
460 switch (*(s++)) {
461 case 'B':
462 case 'C':
463 case 'D':
464 case 'F':
465 case 'I':
466 case 'J':
467 case 'S':
468 case 'Z':
469 // These are all single-character descriptors for primitive types.
470 return (*s == '\0');
471 case 'V':
472 // Non-array void is valid, but you can't have an array of void.
473 return (arrayCount == 0) && (*s == '\0');
474 case 'L':
475 // Class name: Break out and continue below.
476 break;
477 default:
478 // Oddball descriptor character.
479 return false;
480 }
481 }
482
483 /*
484 * We just consumed the 'L' that introduces a class name as part
485 * of a type descriptor, or we are looking for an unadorned class
486 * name.
487 */
488
489 bool sepOrFirst = true; // first character or just encountered a separator.
490 for (;;) {
491 uint8_t c = (uint8_t) *s;
492 switch (c) {
493 case '\0':
494 /*
495 * Premature end for a type descriptor, but valid for
496 * a class name as long as we haven't encountered an
497 * empty component (including the degenerate case of
498 * the empty string "").
499 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700500 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700501 case ';':
502 /*
503 * Invalid character for a class name, but the
504 * legitimate end of a type descriptor. In the latter
505 * case, make sure that this is the end of the string
506 * and that it doesn't end with an empty component
507 * (including the degenerate case of "L;").
508 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700509 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700510 case '/':
511 case '.':
512 if (c != separator) {
513 // The wrong separator character.
514 return false;
515 }
516 if (sepOrFirst) {
517 // Separator at start or two separators in a row.
518 return false;
519 }
520 sepOrFirst = true;
521 s++;
522 break;
523 default:
524 if (!IsValidMemberNameUtf8(&s)) {
525 return false;
526 }
527 sepOrFirst = false;
528 break;
529 }
530 }
531}
532
Elliott Hughes906e6852011-10-28 14:52:10 -0700533bool IsValidBinaryClassName(const char* s) {
534 return IsValidClassName(s, kName, '.');
535}
536
537bool IsValidJniClassName(const char* s) {
538 return IsValidClassName(s, kName, '/');
539}
540
541bool IsValidDescriptor(const char* s) {
542 return IsValidClassName(s, kDescriptor, '/');
543}
544
Elliott Hughes34023802011-08-30 12:06:17 -0700545void Split(const std::string& s, char delim, std::vector<std::string>& result) {
546 const char* p = s.data();
547 const char* end = p + s.size();
548 while (p != end) {
549 if (*p == delim) {
550 ++p;
551 } else {
552 const char* start = p;
553 while (++p != end && *p != delim) {
554 // Skip to the next occurrence of the delimiter.
555 }
556 result.push_back(std::string(start, p - start));
557 }
558 }
559}
560
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800561void SetThreadName(const char* threadName) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700562 int hasAt = 0;
563 int hasDot = 0;
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800564 const char* s = threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700565 while (*s) {
566 if (*s == '.') {
567 hasDot = 1;
568 } else if (*s == '@') {
569 hasAt = 1;
570 }
571 s++;
572 }
573 int len = s - threadName;
574 if (len < 15 || hasAt || !hasDot) {
575 s = threadName;
576 } else {
577 s = threadName + len - 15;
578 }
579#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
580 /* pthread_setname_np fails rather than truncating long strings */
581 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
582 strncpy(buf, s, sizeof(buf)-1);
583 buf[sizeof(buf)-1] = '\0';
584 errno = pthread_setname_np(pthread_self(), buf);
585 if (errno != 0) {
586 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
587 }
588#elif defined(HAVE_PRCTL)
589 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
590#else
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800591 UNIMPLEMENTED(WARNING) << threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700592#endif
593}
594
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700595void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
596 utime = stime = task_cpu = 0;
597 std::string stats;
598 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
599 return;
600 }
601 // Skip the command, which may contain spaces.
602 stats = stats.substr(stats.find(')') + 2);
603 // Extract the three fields we care about.
604 std::vector<std::string> fields;
605 Split(stats, ' ', fields);
606 utime = strtoull(fields[11].c_str(), NULL, 10);
607 stime = strtoull(fields[12].c_str(), NULL, 10);
608 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
609}
610
Brian Carlstroma9f19782011-10-13 00:14:47 -0700611std::string GetArtCacheOrDie() {
612 const char* data_root = getenv("ANDROID_DATA");
613 if (data_root == NULL) {
614 if (OS::DirectoryExists("/data")) {
615 data_root = "/data";
616 } else {
617 data_root = "/tmp";
618 }
619 }
620 if (!OS::DirectoryExists(data_root)) {
621 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << data_root;
622 return "";
623 }
624
Elliott Hughes95572412011-12-13 18:14:20 -0800625 std::string art_cache(StringPrintf("%s/art-cache", data_root));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700626
627 if (!OS::DirectoryExists(art_cache.c_str())) {
628 if (StringPiece(art_cache).starts_with("/tmp/")) {
629 int result = mkdir(art_cache.c_str(), 0700);
630 if (result != 0) {
631 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
632 return "";
633 }
634 } else {
635 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
636 return "";
637 }
638 }
639 return art_cache;
640}
641
jeffhao262bf462011-10-20 18:36:32 -0700642std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800643 std::string art_cache(GetArtCacheOrDie());
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700644 CHECK_EQ(location[0], '/');
645 std::string cache_file(location, 1); // skip leading slash
646 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
647 return art_cache + "/" + cache_file;
648}
649
jeffhao262bf462011-10-20 18:36:32 -0700650bool IsValidZipFilename(const std::string& filename) {
651 if (filename.size() < 4) {
652 return false;
653 }
654 std::string suffix(filename.substr(filename.size() - 4));
655 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
656}
657
658bool IsValidDexFilename(const std::string& filename) {
659 if (filename.size() < 4) {
660 return false;
661 }
662 std::string suffix(filename.substr(filename.size() - 4));
663 return (suffix == ".dex");
664}
665
Elliott Hughes42ee1422011-09-06 12:33:32 -0700666} // namespace art