blob: dbbca28c61354e8aba38e09b6677792ad9d97e76 [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
jeffhao10037c82012-01-23 15:06:23 -0800352// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700353uint32_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
jeffhao10037c82012-01-23 15:06:23 -0800360// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
361bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700362 /*
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 */
jeffhao10037c82012-01-23 15:06:23 -0800416bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700417 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.
jeffhao10037c82012-01-23 15:06:23 -0800428 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
429}
430
431bool IsValidMemberName(const char* s) {
432 bool angle_name = false;
433
434 switch(*s) {
435 case '\0':
436 // The empty string is not a valid name.
437 return false;
438 case '<':
439 angle_name = true;
440 s++;
441 break;
442 }
443
444 while (true) {
445 switch (*s) {
446 case '\0':
447 return !angle_name;
448 case '>':
449 return angle_name && s[1] == '\0';
450 }
451
452 if (!IsValidPartOfMemberNameUtf8(&s)) {
453 return false;
454 }
455 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700456}
457
Elliott Hughes906e6852011-10-28 14:52:10 -0700458enum ClassNameType { kName, kDescriptor };
459bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700460 int arrayCount = 0;
461 while (*s == '[') {
462 arrayCount++;
463 s++;
464 }
465
466 if (arrayCount > 255) {
467 // Arrays may have no more than 255 dimensions.
468 return false;
469 }
470
471 if (arrayCount != 0) {
472 /*
473 * If we're looking at an array of some sort, then it doesn't
474 * matter if what is being asked for is a class name; the
475 * format looks the same as a type descriptor in that case, so
476 * treat it as such.
477 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700478 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700479 }
480
Elliott Hughes906e6852011-10-28 14:52:10 -0700481 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700482 /*
483 * We are looking for a descriptor. Either validate it as a
484 * single-character primitive type, or continue on to check the
485 * embedded class name (bracketed by "L" and ";").
486 */
487 switch (*(s++)) {
488 case 'B':
489 case 'C':
490 case 'D':
491 case 'F':
492 case 'I':
493 case 'J':
494 case 'S':
495 case 'Z':
496 // These are all single-character descriptors for primitive types.
497 return (*s == '\0');
498 case 'V':
499 // Non-array void is valid, but you can't have an array of void.
500 return (arrayCount == 0) && (*s == '\0');
501 case 'L':
502 // Class name: Break out and continue below.
503 break;
504 default:
505 // Oddball descriptor character.
506 return false;
507 }
508 }
509
510 /*
511 * We just consumed the 'L' that introduces a class name as part
512 * of a type descriptor, or we are looking for an unadorned class
513 * name.
514 */
515
516 bool sepOrFirst = true; // first character or just encountered a separator.
517 for (;;) {
518 uint8_t c = (uint8_t) *s;
519 switch (c) {
520 case '\0':
521 /*
522 * Premature end for a type descriptor, but valid for
523 * a class name as long as we haven't encountered an
524 * empty component (including the degenerate case of
525 * the empty string "").
526 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700527 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700528 case ';':
529 /*
530 * Invalid character for a class name, but the
531 * legitimate end of a type descriptor. In the latter
532 * case, make sure that this is the end of the string
533 * and that it doesn't end with an empty component
534 * (including the degenerate case of "L;").
535 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700536 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700537 case '/':
538 case '.':
539 if (c != separator) {
540 // The wrong separator character.
541 return false;
542 }
543 if (sepOrFirst) {
544 // Separator at start or two separators in a row.
545 return false;
546 }
547 sepOrFirst = true;
548 s++;
549 break;
550 default:
jeffhao10037c82012-01-23 15:06:23 -0800551 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700552 return false;
553 }
554 sepOrFirst = false;
555 break;
556 }
557 }
558}
559
Elliott Hughes906e6852011-10-28 14:52:10 -0700560bool IsValidBinaryClassName(const char* s) {
561 return IsValidClassName(s, kName, '.');
562}
563
564bool IsValidJniClassName(const char* s) {
565 return IsValidClassName(s, kName, '/');
566}
567
568bool IsValidDescriptor(const char* s) {
569 return IsValidClassName(s, kDescriptor, '/');
570}
571
Elliott Hughes34023802011-08-30 12:06:17 -0700572void Split(const std::string& s, char delim, std::vector<std::string>& result) {
573 const char* p = s.data();
574 const char* end = p + s.size();
575 while (p != end) {
576 if (*p == delim) {
577 ++p;
578 } else {
579 const char* start = p;
580 while (++p != end && *p != delim) {
581 // Skip to the next occurrence of the delimiter.
582 }
583 result.push_back(std::string(start, p - start));
584 }
585 }
586}
587
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800588void SetThreadName(const char* threadName) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700589 int hasAt = 0;
590 int hasDot = 0;
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800591 const char* s = threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700592 while (*s) {
593 if (*s == '.') {
594 hasDot = 1;
595 } else if (*s == '@') {
596 hasAt = 1;
597 }
598 s++;
599 }
600 int len = s - threadName;
601 if (len < 15 || hasAt || !hasDot) {
602 s = threadName;
603 } else {
604 s = threadName + len - 15;
605 }
606#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
607 /* pthread_setname_np fails rather than truncating long strings */
608 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
609 strncpy(buf, s, sizeof(buf)-1);
610 buf[sizeof(buf)-1] = '\0';
611 errno = pthread_setname_np(pthread_self(), buf);
612 if (errno != 0) {
613 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
614 }
615#elif defined(HAVE_PRCTL)
616 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
617#else
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800618 UNIMPLEMENTED(WARNING) << threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700619#endif
620}
621
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700622void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
623 utime = stime = task_cpu = 0;
624 std::string stats;
625 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
626 return;
627 }
628 // Skip the command, which may contain spaces.
629 stats = stats.substr(stats.find(')') + 2);
630 // Extract the three fields we care about.
631 std::vector<std::string> fields;
632 Split(stats, ' ', fields);
633 utime = strtoull(fields[11].c_str(), NULL, 10);
634 stime = strtoull(fields[12].c_str(), NULL, 10);
635 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
636}
637
Brian Carlstroma9f19782011-10-13 00:14:47 -0700638std::string GetArtCacheOrDie() {
639 const char* data_root = getenv("ANDROID_DATA");
640 if (data_root == NULL) {
641 if (OS::DirectoryExists("/data")) {
642 data_root = "/data";
643 } else {
644 data_root = "/tmp";
645 }
646 }
647 if (!OS::DirectoryExists(data_root)) {
648 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << data_root;
649 return "";
650 }
651
Elliott Hughes95572412011-12-13 18:14:20 -0800652 std::string art_cache(StringPrintf("%s/art-cache", data_root));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700653
654 if (!OS::DirectoryExists(art_cache.c_str())) {
655 if (StringPiece(art_cache).starts_with("/tmp/")) {
656 int result = mkdir(art_cache.c_str(), 0700);
657 if (result != 0) {
658 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
659 return "";
660 }
661 } else {
662 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
663 return "";
664 }
665 }
666 return art_cache;
667}
668
jeffhao262bf462011-10-20 18:36:32 -0700669std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800670 std::string art_cache(GetArtCacheOrDie());
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700671 CHECK_EQ(location[0], '/');
672 std::string cache_file(location, 1); // skip leading slash
673 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
674 return art_cache + "/" + cache_file;
675}
676
jeffhao262bf462011-10-20 18:36:32 -0700677bool IsValidZipFilename(const std::string& filename) {
678 if (filename.size() < 4) {
679 return false;
680 }
681 std::string suffix(filename.substr(filename.size() - 4));
682 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
683}
684
685bool IsValidDexFilename(const std::string& filename) {
686 if (filename.size() < 4) {
687 return false;
688 }
689 std::string suffix(filename.substr(filename.size() - 4));
690 return (suffix == ".dex");
691}
692
Elliott Hughes42ee1422011-09-06 12:33:32 -0700693} // namespace art