blob: 3922033dd79066dc41f7a70b977b29363f66c8ad [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"
buzbeec143c552011-08-20 17:38:58 -070016#include "os.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070017
Elliott Hughesdcc24742011-09-07 14:02:44 -070018#if defined(HAVE_PRCTL)
19#include <sys/prctl.h>
20#endif
21
Elliott Hughes11e45072011-08-16 17:40:46 -070022namespace art {
23
Elliott Hughesd92bec42011-09-02 17:04:36 -070024bool ReadFileToString(const std::string& file_name, std::string* result) {
25 UniquePtr<File> file(OS::OpenFile(file_name.c_str(), false));
26 if (file.get() == NULL) {
27 return false;
28 }
buzbeec143c552011-08-20 17:38:58 -070029
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070030 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -070031 while (true) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070032 int64_t n = file->Read(&buf[0], buf.size());
Elliott Hughesd92bec42011-09-02 17:04:36 -070033 if (n == -1) {
34 return false;
buzbeec143c552011-08-20 17:38:58 -070035 }
Elliott Hughesd92bec42011-09-02 17:04:36 -070036 if (n == 0) {
37 return true;
38 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070039 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -070040 }
buzbeec143c552011-08-20 17:38:58 -070041}
42
Elliott Hughese27955c2011-08-26 15:21:24 -070043std::string GetIsoDate() {
44 time_t now = time(NULL);
45 struct tm tmbuf;
46 struct tm* ptm = localtime_r(&now, &tmbuf);
47 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
48 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
49 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
50}
51
Elliott Hughes83df2ac2011-10-11 16:37:54 -070052uint64_t NanoTime() {
53 struct timespec now;
54 clock_gettime(CLOCK_MONOTONIC, &now);
55 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
56}
57
Elliott Hughes5174fe62011-08-23 15:12:35 -070058std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -070059 if (java_descriptor == NULL) {
60 return "null";
61 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -070062 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
63}
Elliott Hughes5174fe62011-08-23 15:12:35 -070064
Elliott Hughes6c8867d2011-10-03 16:34:05 -070065std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -070066 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -070067 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -070068 size_t dim = 0;
69 while (*c == '[') {
70 dim++;
71 c++;
72 }
73
74 // Reference or primitive?
75 if (*c == 'L') {
76 // "[[La/b/C;" -> "a.b.C[][]".
77 c++; // Skip the 'L'.
78 } else {
79 // "[[B" -> "byte[][]".
80 // To make life easier, we make primitives look like unqualified
81 // reference types.
82 switch (*c) {
83 case 'B': c = "byte;"; break;
84 case 'C': c = "char;"; break;
85 case 'D': c = "double;"; break;
86 case 'F': c = "float;"; break;
87 case 'I': c = "int;"; break;
88 case 'J': c = "long;"; break;
89 case 'S': c = "short;"; break;
90 case 'Z': c = "boolean;"; break;
Elliott Hughes5174fe62011-08-23 15:12:35 -070091 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -070092 }
93 }
94
95 // At this point, 'c' is a string of the form "fully/qualified/Type;"
96 // or "primitive;". Rewrite the type with '.' instead of '/':
97 std::string result;
98 const char* p = c;
99 while (*p != ';') {
100 char ch = *p++;
101 if (ch == '/') {
102 ch = '.';
103 }
104 result.push_back(ch);
105 }
106 // ...and replace the semicolon with 'dim' "[]" pairs:
107 while (dim--) {
108 result += "[]";
109 }
110 return result;
111}
112
Elliott Hughes54e7df12011-09-16 11:47:04 -0700113std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700114 if (f == NULL) {
115 return "null";
116 }
Elliott Hughes54e7df12011-09-16 11:47:04 -0700117 std::string result;
118 if (with_type) {
119 result += PrettyDescriptor(f->GetType()->GetDescriptor());
120 result += ' ';
121 }
122 result += PrettyDescriptor(f->GetDeclaringClass()->GetDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700123 result += '.';
124 result += f->GetName()->ToModifiedUtf8();
125 return result;
126}
127
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700128std::string PrettyMethod(const Method* m, bool with_signature) {
129 if (m == NULL) {
130 return "null";
131 }
132 Class* c = m->GetDeclaringClass();
Elliott Hughes5174fe62011-08-23 15:12:35 -0700133 std::string result(PrettyDescriptor(c->GetDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700134 result += '.';
135 result += m->GetName()->ToModifiedUtf8();
136 if (with_signature) {
137 // TODO: iterate over the signature's elements and pass them all to
138 // PrettyDescriptor? We'd need to pull out the return type specially, too.
139 result += m->GetSignature()->ToModifiedUtf8();
140 }
141 return result;
142}
143
Elliott Hughes54e7df12011-09-16 11:47:04 -0700144std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700145 if (obj == NULL) {
146 return "null";
147 }
148 if (obj->GetClass() == NULL) {
149 return "(raw)";
150 }
Elliott Hughes5174fe62011-08-23 15:12:35 -0700151 std::string result(PrettyDescriptor(obj->GetClass()->GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700152 if (obj->IsClass()) {
Elliott Hughes5174fe62011-08-23 15:12:35 -0700153 result += "<" + PrettyDescriptor(obj->AsClass()->GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700154 }
155 return result;
156}
157
Elliott Hughes54e7df12011-09-16 11:47:04 -0700158std::string PrettyClass(const Class* c) {
159 if (c == NULL) {
160 return "null";
161 }
162 std::string result;
163 result += "java.lang.Class<";
164 result += PrettyDescriptor(c->GetDescriptor());
165 result += ">";
166 return result;
167}
168
Ian Rogersd81871c2011-10-03 13:57:23 -0700169std::string PrettyClassAndClassLoader(const Class* c) {
170 if (c == NULL) {
171 return "null";
172 }
173 std::string result;
174 result += "java.lang.Class<";
175 result += PrettyDescriptor(c->GetDescriptor());
176 result += ",";
177 result += PrettyTypeOf(c->GetClassLoader());
178 // TODO: add an identifying hash value for the loader
179 result += ">";
180 return result;
181}
182
Elliott Hughes79082e32011-08-25 12:07:32 -0700183std::string MangleForJni(const std::string& s) {
184 std::string result;
185 size_t char_count = CountModifiedUtf8Chars(s.c_str());
186 const char* cp = &s[0];
187 for (size_t i = 0; i < char_count; ++i) {
188 uint16_t ch = GetUtf16FromUtf8(&cp);
189 if (ch == '$' || ch > 127) {
190 StringAppendF(&result, "_0%04x", ch);
191 } else {
192 switch (ch) {
193 case '_':
194 result += "_1";
195 break;
196 case ';':
197 result += "_2";
198 break;
199 case '[':
200 result += "_3";
201 break;
202 case '/':
203 result += "_";
204 break;
205 default:
206 result.push_back(ch);
207 break;
208 }
209 }
210 }
211 return result;
212}
213
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700214std::string DotToDescriptor(const char* class_name) {
215 std::string descriptor(class_name);
216 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
217 if (descriptor.length() > 0 && descriptor[0] != '[') {
218 descriptor = "L" + descriptor + ";";
219 }
220 return descriptor;
221}
222
Brian Carlstromaded5f72011-10-07 17:15:04 -0700223std::string DescriptorToDot(const std::string& descriptor) {
224 DCHECK_EQ(descriptor[0], 'L');
225 DCHECK_EQ(descriptor[descriptor.size()-1], ';');
226 std::string dot = descriptor.substr(1, descriptor.size()-2);
227 std::replace(dot.begin(), dot.end(), '/', '.');
228 return dot;
229}
230
Elliott Hughes79082e32011-08-25 12:07:32 -0700231std::string JniShortName(const Method* m) {
232 Class* declaring_class = m->GetDeclaringClass();
233
234 std::string class_name(declaring_class->GetDescriptor()->ToModifiedUtf8());
235 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700236 CHECK_EQ(class_name[0], 'L') << class_name;
237 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700238 class_name.erase(0, 1);
239 class_name.erase(class_name.size() - 1, 1);
240
241 std::string method_name(m->GetName()->ToModifiedUtf8());
242
243 std::string short_name;
244 short_name += "Java_";
245 short_name += MangleForJni(class_name);
246 short_name += "_";
247 short_name += MangleForJni(method_name);
248 return short_name;
249}
250
251std::string JniLongName(const Method* m) {
252 std::string long_name;
253 long_name += JniShortName(m);
254 long_name += "__";
255
256 std::string signature(m->GetSignature()->ToModifiedUtf8());
257 signature.erase(0, 1);
258 signature.erase(signature.begin() + signature.find(')'), signature.end());
259
260 long_name += MangleForJni(signature);
261
262 return long_name;
263}
264
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700265namespace {
266
267// Helper for IsValidMemberNameUtf8(), a bit vector indicating valid low ascii.
268uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
269 0x00000000, // 00..1f low control characters; nothing valid
270 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
271 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
272 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
273};
274
275// Helper for IsValidMemberNameUtf8(); do not call directly.
276bool IsValidMemberNameUtf8Slow(const char** pUtf8Ptr) {
277 /*
278 * It's a multibyte encoded character. Decode it and analyze. We
279 * accept anything that isn't (a) an improperly encoded low value,
280 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
281 * control character, or (e) a high space, layout, or special
282 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
283 * U+fff0..U+ffff). This is all specified in the dex format
284 * document.
285 */
286
287 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
288
289 // Perform follow-up tests based on the high 8 bits.
290 switch (utf16 >> 8) {
291 case 0x00:
292 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
293 return (utf16 > 0x00a0);
294 case 0xd8:
295 case 0xd9:
296 case 0xda:
297 case 0xdb:
298 // It's a leading surrogate. Check to see that a trailing
299 // surrogate follows.
300 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
301 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
302 case 0xdc:
303 case 0xdd:
304 case 0xde:
305 case 0xdf:
306 // It's a trailing surrogate, which is not valid at this point.
307 return false;
308 case 0x20:
309 case 0xff:
310 // It's in the range that has spaces, controls, and specials.
311 switch (utf16 & 0xfff8) {
312 case 0x2000:
313 case 0x2008:
314 case 0x2028:
315 case 0xfff0:
316 case 0xfff8:
317 return false;
318 }
319 break;
320 }
321 return true;
322}
323
324/* Return whether the pointed-at modified-UTF-8 encoded character is
325 * valid as part of a member name, updating the pointer to point past
326 * the consumed character. This will consume two encoded UTF-16 code
327 * points if the character is encoded as a surrogate pair. Also, if
328 * this function returns false, then the given pointer may only have
329 * been partially advanced.
330 */
331bool IsValidMemberNameUtf8(const char** pUtf8Ptr) {
332 uint8_t c = (uint8_t) **pUtf8Ptr;
333 if (c <= 0x7f) {
334 // It's low-ascii, so check the table.
335 uint32_t wordIdx = c >> 5;
336 uint32_t bitIdx = c & 0x1f;
337 (*pUtf8Ptr)++;
338 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
339 }
340
341 // It's a multibyte encoded character. Call a non-inline function
342 // for the heavy lifting.
343 return IsValidMemberNameUtf8Slow(pUtf8Ptr);
344}
345
346} // namespace
347
348bool IsValidClassName(const char* s, bool isClassName, bool dot_or_slash) {
349 char separator = (dot_or_slash ? '.' : '/');
350
351 int arrayCount = 0;
352 while (*s == '[') {
353 arrayCount++;
354 s++;
355 }
356
357 if (arrayCount > 255) {
358 // Arrays may have no more than 255 dimensions.
359 return false;
360 }
361
362 if (arrayCount != 0) {
363 /*
364 * If we're looking at an array of some sort, then it doesn't
365 * matter if what is being asked for is a class name; the
366 * format looks the same as a type descriptor in that case, so
367 * treat it as such.
368 */
369 isClassName = false;
370 }
371
372 if (!isClassName) {
373 /*
374 * We are looking for a descriptor. Either validate it as a
375 * single-character primitive type, or continue on to check the
376 * embedded class name (bracketed by "L" and ";").
377 */
378 switch (*(s++)) {
379 case 'B':
380 case 'C':
381 case 'D':
382 case 'F':
383 case 'I':
384 case 'J':
385 case 'S':
386 case 'Z':
387 // These are all single-character descriptors for primitive types.
388 return (*s == '\0');
389 case 'V':
390 // Non-array void is valid, but you can't have an array of void.
391 return (arrayCount == 0) && (*s == '\0');
392 case 'L':
393 // Class name: Break out and continue below.
394 break;
395 default:
396 // Oddball descriptor character.
397 return false;
398 }
399 }
400
401 /*
402 * We just consumed the 'L' that introduces a class name as part
403 * of a type descriptor, or we are looking for an unadorned class
404 * name.
405 */
406
407 bool sepOrFirst = true; // first character or just encountered a separator.
408 for (;;) {
409 uint8_t c = (uint8_t) *s;
410 switch (c) {
411 case '\0':
412 /*
413 * Premature end for a type descriptor, but valid for
414 * a class name as long as we haven't encountered an
415 * empty component (including the degenerate case of
416 * the empty string "").
417 */
418 return isClassName && !sepOrFirst;
419 case ';':
420 /*
421 * Invalid character for a class name, but the
422 * legitimate end of a type descriptor. In the latter
423 * case, make sure that this is the end of the string
424 * and that it doesn't end with an empty component
425 * (including the degenerate case of "L;").
426 */
427 return !isClassName && !sepOrFirst && (s[1] == '\0');
428 case '/':
429 case '.':
430 if (c != separator) {
431 // The wrong separator character.
432 return false;
433 }
434 if (sepOrFirst) {
435 // Separator at start or two separators in a row.
436 return false;
437 }
438 sepOrFirst = true;
439 s++;
440 break;
441 default:
442 if (!IsValidMemberNameUtf8(&s)) {
443 return false;
444 }
445 sepOrFirst = false;
446 break;
447 }
448 }
449}
450
Elliott Hughes34023802011-08-30 12:06:17 -0700451void Split(const std::string& s, char delim, std::vector<std::string>& result) {
452 const char* p = s.data();
453 const char* end = p + s.size();
454 while (p != end) {
455 if (*p == delim) {
456 ++p;
457 } else {
458 const char* start = p;
459 while (++p != end && *p != delim) {
460 // Skip to the next occurrence of the delimiter.
461 }
462 result.push_back(std::string(start, p - start));
463 }
464 }
465}
466
Elliott Hughesdcc24742011-09-07 14:02:44 -0700467void SetThreadName(const char *threadName) {
468 int hasAt = 0;
469 int hasDot = 0;
470 const char *s = threadName;
471 while (*s) {
472 if (*s == '.') {
473 hasDot = 1;
474 } else if (*s == '@') {
475 hasAt = 1;
476 }
477 s++;
478 }
479 int len = s - threadName;
480 if (len < 15 || hasAt || !hasDot) {
481 s = threadName;
482 } else {
483 s = threadName + len - 15;
484 }
485#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
486 /* pthread_setname_np fails rather than truncating long strings */
487 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
488 strncpy(buf, s, sizeof(buf)-1);
489 buf[sizeof(buf)-1] = '\0';
490 errno = pthread_setname_np(pthread_self(), buf);
491 if (errno != 0) {
492 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
493 }
494#elif defined(HAVE_PRCTL)
495 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
496#else
497#error no implementation for SetThreadName
498#endif
499}
500
Brian Carlstroma9f19782011-10-13 00:14:47 -0700501std::string GetArtCacheOrDie() {
502 const char* data_root = getenv("ANDROID_DATA");
503 if (data_root == NULL) {
504 if (OS::DirectoryExists("/data")) {
505 data_root = "/data";
506 } else {
507 data_root = "/tmp";
508 }
509 }
510 if (!OS::DirectoryExists(data_root)) {
511 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << data_root;
512 return "";
513 }
514
515 std::string art_cache = StringPrintf("%s/art-cache", data_root);
516
517 if (!OS::DirectoryExists(art_cache.c_str())) {
518 if (StringPiece(art_cache).starts_with("/tmp/")) {
519 int result = mkdir(art_cache.c_str(), 0700);
520 if (result != 0) {
521 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
522 return "";
523 }
524 } else {
525 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
526 return "";
527 }
528 }
529 return art_cache;
530}
531
jeffhao262bf462011-10-20 18:36:32 -0700532std::string GetArtCacheFilenameOrDie(const std::string& location) {
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700533 std::string art_cache = GetArtCacheOrDie();
534 CHECK_EQ(location[0], '/');
535 std::string cache_file(location, 1); // skip leading slash
536 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
537 return art_cache + "/" + cache_file;
538}
539
jeffhao262bf462011-10-20 18:36:32 -0700540bool IsValidZipFilename(const std::string& filename) {
541 if (filename.size() < 4) {
542 return false;
543 }
544 std::string suffix(filename.substr(filename.size() - 4));
545 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
546}
547
548bool IsValidDexFilename(const std::string& filename) {
549 if (filename.size() < 4) {
550 return false;
551 }
552 std::string suffix(filename.substr(filename.size() - 4));
553 return (suffix == ".dex");
554}
555
Elliott Hughes11e45072011-08-16 17:40:46 -0700556} // namespace art
Elliott Hughes42ee1422011-09-06 12:33:32 -0700557
558// Neither bionic nor glibc exposes gettid(2).
559#define __KERNEL__
560#include <linux/unistd.h>
561namespace art {
562#ifdef _syscall0
563_syscall0(pid_t, GetTid)
564#else
565pid_t GetTid() { return syscall(__NR_gettid); }
566#endif
567} // namespace art
568#undef __KERNEL__