blob: a74e2310a7978e522fe956d901985f3bbbf5f470 [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
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700113std::string PrettyDescriptor(Primitive::Type type) {
114 char descriptor_char = Primitive::DescriptorChar(type);
115 std::string descriptor_string(1, descriptor_char);
116 return PrettyDescriptor(descriptor_string);
117}
118
Elliott Hughes54e7df12011-09-16 11:47:04 -0700119std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700120 if (f == NULL) {
121 return "null";
122 }
Elliott Hughes54e7df12011-09-16 11:47:04 -0700123 std::string result;
124 if (with_type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700125 result += PrettyDescriptor(f->GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700126 result += ' ';
127 }
128 result += PrettyDescriptor(f->GetDeclaringClass()->GetDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700129 result += '.';
130 result += f->GetName()->ToModifiedUtf8();
131 return result;
132}
133
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700134std::string PrettyMethod(const Method* m, bool with_signature) {
135 if (m == NULL) {
136 return "null";
137 }
138 Class* c = m->GetDeclaringClass();
Elliott Hughes5174fe62011-08-23 15:12:35 -0700139 std::string result(PrettyDescriptor(c->GetDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700140 result += '.';
141 result += m->GetName()->ToModifiedUtf8();
142 if (with_signature) {
143 // TODO: iterate over the signature's elements and pass them all to
144 // PrettyDescriptor? We'd need to pull out the return type specially, too.
145 result += m->GetSignature()->ToModifiedUtf8();
146 }
147 return result;
148}
149
Elliott Hughes54e7df12011-09-16 11:47:04 -0700150std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700151 if (obj == NULL) {
152 return "null";
153 }
154 if (obj->GetClass() == NULL) {
155 return "(raw)";
156 }
Elliott Hughes5174fe62011-08-23 15:12:35 -0700157 std::string result(PrettyDescriptor(obj->GetClass()->GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700158 if (obj->IsClass()) {
Elliott Hughes5174fe62011-08-23 15:12:35 -0700159 result += "<" + PrettyDescriptor(obj->AsClass()->GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700160 }
161 return result;
162}
163
Elliott Hughes54e7df12011-09-16 11:47:04 -0700164std::string PrettyClass(const Class* c) {
165 if (c == NULL) {
166 return "null";
167 }
168 std::string result;
169 result += "java.lang.Class<";
170 result += PrettyDescriptor(c->GetDescriptor());
171 result += ">";
172 return result;
173}
174
Ian Rogersd81871c2011-10-03 13:57:23 -0700175std::string PrettyClassAndClassLoader(const Class* c) {
176 if (c == NULL) {
177 return "null";
178 }
179 std::string result;
180 result += "java.lang.Class<";
181 result += PrettyDescriptor(c->GetDescriptor());
182 result += ",";
183 result += PrettyTypeOf(c->GetClassLoader());
184 // TODO: add an identifying hash value for the loader
185 result += ">";
186 return result;
187}
188
Elliott Hughes79082e32011-08-25 12:07:32 -0700189std::string MangleForJni(const std::string& s) {
190 std::string result;
191 size_t char_count = CountModifiedUtf8Chars(s.c_str());
192 const char* cp = &s[0];
193 for (size_t i = 0; i < char_count; ++i) {
194 uint16_t ch = GetUtf16FromUtf8(&cp);
195 if (ch == '$' || ch > 127) {
196 StringAppendF(&result, "_0%04x", ch);
197 } else {
198 switch (ch) {
199 case '_':
200 result += "_1";
201 break;
202 case ';':
203 result += "_2";
204 break;
205 case '[':
206 result += "_3";
207 break;
208 case '/':
209 result += "_";
210 break;
211 default:
212 result.push_back(ch);
213 break;
214 }
215 }
216 }
217 return result;
218}
219
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700220std::string DotToDescriptor(const char* class_name) {
221 std::string descriptor(class_name);
222 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
223 if (descriptor.length() > 0 && descriptor[0] != '[') {
224 descriptor = "L" + descriptor + ";";
225 }
226 return descriptor;
227}
228
Brian Carlstromaded5f72011-10-07 17:15:04 -0700229std::string DescriptorToDot(const std::string& descriptor) {
230 DCHECK_EQ(descriptor[0], 'L');
231 DCHECK_EQ(descriptor[descriptor.size()-1], ';');
232 std::string dot = descriptor.substr(1, descriptor.size()-2);
233 std::replace(dot.begin(), dot.end(), '/', '.');
234 return dot;
235}
236
Elliott Hughes79082e32011-08-25 12:07:32 -0700237std::string JniShortName(const Method* m) {
238 Class* declaring_class = m->GetDeclaringClass();
239
240 std::string class_name(declaring_class->GetDescriptor()->ToModifiedUtf8());
241 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700242 CHECK_EQ(class_name[0], 'L') << class_name;
243 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700244 class_name.erase(0, 1);
245 class_name.erase(class_name.size() - 1, 1);
246
247 std::string method_name(m->GetName()->ToModifiedUtf8());
248
249 std::string short_name;
250 short_name += "Java_";
251 short_name += MangleForJni(class_name);
252 short_name += "_";
253 short_name += MangleForJni(method_name);
254 return short_name;
255}
256
257std::string JniLongName(const Method* m) {
258 std::string long_name;
259 long_name += JniShortName(m);
260 long_name += "__";
261
262 std::string signature(m->GetSignature()->ToModifiedUtf8());
263 signature.erase(0, 1);
264 signature.erase(signature.begin() + signature.find(')'), signature.end());
265
266 long_name += MangleForJni(signature);
267
268 return long_name;
269}
270
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700271namespace {
272
273// Helper for IsValidMemberNameUtf8(), a bit vector indicating valid low ascii.
274uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
275 0x00000000, // 00..1f low control characters; nothing valid
276 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
277 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
278 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
279};
280
281// Helper for IsValidMemberNameUtf8(); do not call directly.
282bool IsValidMemberNameUtf8Slow(const char** pUtf8Ptr) {
283 /*
284 * It's a multibyte encoded character. Decode it and analyze. We
285 * accept anything that isn't (a) an improperly encoded low value,
286 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
287 * control character, or (e) a high space, layout, or special
288 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
289 * U+fff0..U+ffff). This is all specified in the dex format
290 * document.
291 */
292
293 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
294
295 // Perform follow-up tests based on the high 8 bits.
296 switch (utf16 >> 8) {
297 case 0x00:
298 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
299 return (utf16 > 0x00a0);
300 case 0xd8:
301 case 0xd9:
302 case 0xda:
303 case 0xdb:
304 // It's a leading surrogate. Check to see that a trailing
305 // surrogate follows.
306 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
307 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
308 case 0xdc:
309 case 0xdd:
310 case 0xde:
311 case 0xdf:
312 // It's a trailing surrogate, which is not valid at this point.
313 return false;
314 case 0x20:
315 case 0xff:
316 // It's in the range that has spaces, controls, and specials.
317 switch (utf16 & 0xfff8) {
318 case 0x2000:
319 case 0x2008:
320 case 0x2028:
321 case 0xfff0:
322 case 0xfff8:
323 return false;
324 }
325 break;
326 }
327 return true;
328}
329
330/* Return whether the pointed-at modified-UTF-8 encoded character is
331 * valid as part of a member name, updating the pointer to point past
332 * the consumed character. This will consume two encoded UTF-16 code
333 * points if the character is encoded as a surrogate pair. Also, if
334 * this function returns false, then the given pointer may only have
335 * been partially advanced.
336 */
337bool IsValidMemberNameUtf8(const char** pUtf8Ptr) {
338 uint8_t c = (uint8_t) **pUtf8Ptr;
339 if (c <= 0x7f) {
340 // It's low-ascii, so check the table.
341 uint32_t wordIdx = c >> 5;
342 uint32_t bitIdx = c & 0x1f;
343 (*pUtf8Ptr)++;
344 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
345 }
346
347 // It's a multibyte encoded character. Call a non-inline function
348 // for the heavy lifting.
349 return IsValidMemberNameUtf8Slow(pUtf8Ptr);
350}
351
352} // namespace
353
354bool IsValidClassName(const char* s, bool isClassName, bool dot_or_slash) {
355 char separator = (dot_or_slash ? '.' : '/');
356
357 int arrayCount = 0;
358 while (*s == '[') {
359 arrayCount++;
360 s++;
361 }
362
363 if (arrayCount > 255) {
364 // Arrays may have no more than 255 dimensions.
365 return false;
366 }
367
368 if (arrayCount != 0) {
369 /*
370 * If we're looking at an array of some sort, then it doesn't
371 * matter if what is being asked for is a class name; the
372 * format looks the same as a type descriptor in that case, so
373 * treat it as such.
374 */
375 isClassName = false;
376 }
377
378 if (!isClassName) {
379 /*
380 * We are looking for a descriptor. Either validate it as a
381 * single-character primitive type, or continue on to check the
382 * embedded class name (bracketed by "L" and ";").
383 */
384 switch (*(s++)) {
385 case 'B':
386 case 'C':
387 case 'D':
388 case 'F':
389 case 'I':
390 case 'J':
391 case 'S':
392 case 'Z':
393 // These are all single-character descriptors for primitive types.
394 return (*s == '\0');
395 case 'V':
396 // Non-array void is valid, but you can't have an array of void.
397 return (arrayCount == 0) && (*s == '\0');
398 case 'L':
399 // Class name: Break out and continue below.
400 break;
401 default:
402 // Oddball descriptor character.
403 return false;
404 }
405 }
406
407 /*
408 * We just consumed the 'L' that introduces a class name as part
409 * of a type descriptor, or we are looking for an unadorned class
410 * name.
411 */
412
413 bool sepOrFirst = true; // first character or just encountered a separator.
414 for (;;) {
415 uint8_t c = (uint8_t) *s;
416 switch (c) {
417 case '\0':
418 /*
419 * Premature end for a type descriptor, but valid for
420 * a class name as long as we haven't encountered an
421 * empty component (including the degenerate case of
422 * the empty string "").
423 */
424 return isClassName && !sepOrFirst;
425 case ';':
426 /*
427 * Invalid character for a class name, but the
428 * legitimate end of a type descriptor. In the latter
429 * case, make sure that this is the end of the string
430 * and that it doesn't end with an empty component
431 * (including the degenerate case of "L;").
432 */
433 return !isClassName && !sepOrFirst && (s[1] == '\0');
434 case '/':
435 case '.':
436 if (c != separator) {
437 // The wrong separator character.
438 return false;
439 }
440 if (sepOrFirst) {
441 // Separator at start or two separators in a row.
442 return false;
443 }
444 sepOrFirst = true;
445 s++;
446 break;
447 default:
448 if (!IsValidMemberNameUtf8(&s)) {
449 return false;
450 }
451 sepOrFirst = false;
452 break;
453 }
454 }
455}
456
Elliott Hughes34023802011-08-30 12:06:17 -0700457void Split(const std::string& s, char delim, std::vector<std::string>& result) {
458 const char* p = s.data();
459 const char* end = p + s.size();
460 while (p != end) {
461 if (*p == delim) {
462 ++p;
463 } else {
464 const char* start = p;
465 while (++p != end && *p != delim) {
466 // Skip to the next occurrence of the delimiter.
467 }
468 result.push_back(std::string(start, p - start));
469 }
470 }
471}
472
Elliott Hughesdcc24742011-09-07 14:02:44 -0700473void SetThreadName(const char *threadName) {
474 int hasAt = 0;
475 int hasDot = 0;
476 const char *s = threadName;
477 while (*s) {
478 if (*s == '.') {
479 hasDot = 1;
480 } else if (*s == '@') {
481 hasAt = 1;
482 }
483 s++;
484 }
485 int len = s - threadName;
486 if (len < 15 || hasAt || !hasDot) {
487 s = threadName;
488 } else {
489 s = threadName + len - 15;
490 }
491#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
492 /* pthread_setname_np fails rather than truncating long strings */
493 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
494 strncpy(buf, s, sizeof(buf)-1);
495 buf[sizeof(buf)-1] = '\0';
496 errno = pthread_setname_np(pthread_self(), buf);
497 if (errno != 0) {
498 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
499 }
500#elif defined(HAVE_PRCTL)
501 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
502#else
503#error no implementation for SetThreadName
504#endif
505}
506
Brian Carlstroma9f19782011-10-13 00:14:47 -0700507std::string GetArtCacheOrDie() {
508 const char* data_root = getenv("ANDROID_DATA");
509 if (data_root == NULL) {
510 if (OS::DirectoryExists("/data")) {
511 data_root = "/data";
512 } else {
513 data_root = "/tmp";
514 }
515 }
516 if (!OS::DirectoryExists(data_root)) {
517 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << data_root;
518 return "";
519 }
520
521 std::string art_cache = StringPrintf("%s/art-cache", data_root);
522
523 if (!OS::DirectoryExists(art_cache.c_str())) {
524 if (StringPiece(art_cache).starts_with("/tmp/")) {
525 int result = mkdir(art_cache.c_str(), 0700);
526 if (result != 0) {
527 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
528 return "";
529 }
530 } else {
531 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
532 return "";
533 }
534 }
535 return art_cache;
536}
537
jeffhao262bf462011-10-20 18:36:32 -0700538std::string GetArtCacheFilenameOrDie(const std::string& location) {
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700539 std::string art_cache = GetArtCacheOrDie();
540 CHECK_EQ(location[0], '/');
541 std::string cache_file(location, 1); // skip leading slash
542 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
543 return art_cache + "/" + cache_file;
544}
545
jeffhao262bf462011-10-20 18:36:32 -0700546bool IsValidZipFilename(const std::string& filename) {
547 if (filename.size() < 4) {
548 return false;
549 }
550 std::string suffix(filename.substr(filename.size() - 4));
551 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
552}
553
554bool IsValidDexFilename(const std::string& filename) {
555 if (filename.size() < 4) {
556 return false;
557 }
558 std::string suffix(filename.substr(filename.size() - 4));
559 return (suffix == ".dex");
560}
561
Elliott Hughes11e45072011-08-16 17:40:46 -0700562} // namespace art
Elliott Hughes42ee1422011-09-06 12:33:32 -0700563
564// Neither bionic nor glibc exposes gettid(2).
565#define __KERNEL__
566#include <linux/unistd.h>
567namespace art {
568#ifdef _syscall0
569_syscall0(pid_t, GetTid)
570#else
571pid_t GetTid() { return syscall(__NR_gettid); }
572#endif
573} // namespace art
574#undef __KERNEL__