blob: 86fa312007c749fa57adeeb37600bb0bf08869ab [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>
Elliott Hughes42ee1422011-09-06 12:33:32 -07007#include <sys/syscall.h>
8#include <sys/types.h>
9#include <unistd.h>
10
Elliott Hughes90a33692011-08-30 13:27:07 -070011#include "UniquePtr.h"
buzbeec143c552011-08-20 17:38:58 -070012#include "file.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070013#include "object.h"
buzbeec143c552011-08-20 17:38:58 -070014#include "os.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070015
Elliott Hughesdcc24742011-09-07 14:02:44 -070016#if defined(HAVE_PRCTL)
17#include <sys/prctl.h>
18#endif
19
Elliott Hughes11e45072011-08-16 17:40:46 -070020namespace art {
21
Elliott Hughesd92bec42011-09-02 17:04:36 -070022bool ReadFileToString(const std::string& file_name, std::string* result) {
23 UniquePtr<File> file(OS::OpenFile(file_name.c_str(), false));
24 if (file.get() == NULL) {
25 return false;
26 }
buzbeec143c552011-08-20 17:38:58 -070027
buzbeec143c552011-08-20 17:38:58 -070028 char buf[8 * KB];
29 while (true) {
30 int64_t n = file->Read(buf, sizeof(buf));
Elliott Hughesd92bec42011-09-02 17:04:36 -070031 if (n == -1) {
32 return false;
buzbeec143c552011-08-20 17:38:58 -070033 }
Elliott Hughesd92bec42011-09-02 17:04:36 -070034 if (n == 0) {
35 return true;
36 }
37 result->append(buf, n);
buzbeec143c552011-08-20 17:38:58 -070038 }
buzbeec143c552011-08-20 17:38:58 -070039}
40
Elliott Hughese27955c2011-08-26 15:21:24 -070041std::string GetIsoDate() {
42 time_t now = time(NULL);
43 struct tm tmbuf;
44 struct tm* ptm = localtime_r(&now, &tmbuf);
45 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
46 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
47 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
48}
49
Elliott Hughes5174fe62011-08-23 15:12:35 -070050std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -070051 if (java_descriptor == NULL) {
52 return "null";
53 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -070054 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
55}
Elliott Hughes5174fe62011-08-23 15:12:35 -070056
Elliott Hughes6c8867d2011-10-03 16:34:05 -070057std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -070058 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -070059 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -070060 size_t dim = 0;
61 while (*c == '[') {
62 dim++;
63 c++;
64 }
65
66 // Reference or primitive?
67 if (*c == 'L') {
68 // "[[La/b/C;" -> "a.b.C[][]".
69 c++; // Skip the 'L'.
70 } else {
71 // "[[B" -> "byte[][]".
72 // To make life easier, we make primitives look like unqualified
73 // reference types.
74 switch (*c) {
75 case 'B': c = "byte;"; break;
76 case 'C': c = "char;"; break;
77 case 'D': c = "double;"; break;
78 case 'F': c = "float;"; break;
79 case 'I': c = "int;"; break;
80 case 'J': c = "long;"; break;
81 case 'S': c = "short;"; break;
82 case 'Z': c = "boolean;"; break;
Elliott Hughes5174fe62011-08-23 15:12:35 -070083 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -070084 }
85 }
86
87 // At this point, 'c' is a string of the form "fully/qualified/Type;"
88 // or "primitive;". Rewrite the type with '.' instead of '/':
89 std::string result;
90 const char* p = c;
91 while (*p != ';') {
92 char ch = *p++;
93 if (ch == '/') {
94 ch = '.';
95 }
96 result.push_back(ch);
97 }
98 // ...and replace the semicolon with 'dim' "[]" pairs:
99 while (dim--) {
100 result += "[]";
101 }
102 return result;
103}
104
Elliott Hughes54e7df12011-09-16 11:47:04 -0700105std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700106 if (f == NULL) {
107 return "null";
108 }
Elliott Hughes54e7df12011-09-16 11:47:04 -0700109 std::string result;
110 if (with_type) {
111 result += PrettyDescriptor(f->GetType()->GetDescriptor());
112 result += ' ';
113 }
114 result += PrettyDescriptor(f->GetDeclaringClass()->GetDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700115 result += '.';
116 result += f->GetName()->ToModifiedUtf8();
117 return result;
118}
119
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700120std::string PrettyMethod(const Method* m, bool with_signature) {
121 if (m == NULL) {
122 return "null";
123 }
124 Class* c = m->GetDeclaringClass();
Elliott Hughes5174fe62011-08-23 15:12:35 -0700125 std::string result(PrettyDescriptor(c->GetDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700126 result += '.';
127 result += m->GetName()->ToModifiedUtf8();
128 if (with_signature) {
129 // TODO: iterate over the signature's elements and pass them all to
130 // PrettyDescriptor? We'd need to pull out the return type specially, too.
131 result += m->GetSignature()->ToModifiedUtf8();
132 }
133 return result;
134}
135
Elliott Hughes54e7df12011-09-16 11:47:04 -0700136std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700137 if (obj == NULL) {
138 return "null";
139 }
140 if (obj->GetClass() == NULL) {
141 return "(raw)";
142 }
Elliott Hughes5174fe62011-08-23 15:12:35 -0700143 std::string result(PrettyDescriptor(obj->GetClass()->GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700144 if (obj->IsClass()) {
Elliott Hughes5174fe62011-08-23 15:12:35 -0700145 result += "<" + PrettyDescriptor(obj->AsClass()->GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700146 }
147 return result;
148}
149
Elliott Hughes54e7df12011-09-16 11:47:04 -0700150std::string PrettyClass(const Class* c) {
151 if (c == NULL) {
152 return "null";
153 }
154 std::string result;
155 result += "java.lang.Class<";
156 result += PrettyDescriptor(c->GetDescriptor());
157 result += ">";
158 return result;
159}
160
Elliott Hughes79082e32011-08-25 12:07:32 -0700161std::string MangleForJni(const std::string& s) {
162 std::string result;
163 size_t char_count = CountModifiedUtf8Chars(s.c_str());
164 const char* cp = &s[0];
165 for (size_t i = 0; i < char_count; ++i) {
166 uint16_t ch = GetUtf16FromUtf8(&cp);
167 if (ch == '$' || ch > 127) {
168 StringAppendF(&result, "_0%04x", ch);
169 } else {
170 switch (ch) {
171 case '_':
172 result += "_1";
173 break;
174 case ';':
175 result += "_2";
176 break;
177 case '[':
178 result += "_3";
179 break;
180 case '/':
181 result += "_";
182 break;
183 default:
184 result.push_back(ch);
185 break;
186 }
187 }
188 }
189 return result;
190}
191
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700192std::string DotToDescriptor(const char* class_name) {
193 std::string descriptor(class_name);
194 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
195 if (descriptor.length() > 0 && descriptor[0] != '[') {
196 descriptor = "L" + descriptor + ";";
197 }
198 return descriptor;
199}
200
Brian Carlstromaded5f72011-10-07 17:15:04 -0700201std::string DescriptorToDot(const std::string& descriptor) {
202 DCHECK_EQ(descriptor[0], 'L');
203 DCHECK_EQ(descriptor[descriptor.size()-1], ';');
204 std::string dot = descriptor.substr(1, descriptor.size()-2);
205 std::replace(dot.begin(), dot.end(), '/', '.');
206 return dot;
207}
208
Elliott Hughes79082e32011-08-25 12:07:32 -0700209std::string JniShortName(const Method* m) {
210 Class* declaring_class = m->GetDeclaringClass();
211
212 std::string class_name(declaring_class->GetDescriptor()->ToModifiedUtf8());
213 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700214 CHECK_EQ(class_name[0], 'L') << class_name;
215 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700216 class_name.erase(0, 1);
217 class_name.erase(class_name.size() - 1, 1);
218
219 std::string method_name(m->GetName()->ToModifiedUtf8());
220
221 std::string short_name;
222 short_name += "Java_";
223 short_name += MangleForJni(class_name);
224 short_name += "_";
225 short_name += MangleForJni(method_name);
226 return short_name;
227}
228
229std::string JniLongName(const Method* m) {
230 std::string long_name;
231 long_name += JniShortName(m);
232 long_name += "__";
233
234 std::string signature(m->GetSignature()->ToModifiedUtf8());
235 signature.erase(0, 1);
236 signature.erase(signature.begin() + signature.find(')'), signature.end());
237
238 long_name += MangleForJni(signature);
239
240 return long_name;
241}
242
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700243namespace {
244
245// Helper for IsValidMemberNameUtf8(), a bit vector indicating valid low ascii.
246uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
247 0x00000000, // 00..1f low control characters; nothing valid
248 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
249 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
250 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
251};
252
253// Helper for IsValidMemberNameUtf8(); do not call directly.
254bool IsValidMemberNameUtf8Slow(const char** pUtf8Ptr) {
255 /*
256 * It's a multibyte encoded character. Decode it and analyze. We
257 * accept anything that isn't (a) an improperly encoded low value,
258 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
259 * control character, or (e) a high space, layout, or special
260 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
261 * U+fff0..U+ffff). This is all specified in the dex format
262 * document.
263 */
264
265 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
266
267 // Perform follow-up tests based on the high 8 bits.
268 switch (utf16 >> 8) {
269 case 0x00:
270 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
271 return (utf16 > 0x00a0);
272 case 0xd8:
273 case 0xd9:
274 case 0xda:
275 case 0xdb:
276 // It's a leading surrogate. Check to see that a trailing
277 // surrogate follows.
278 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
279 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
280 case 0xdc:
281 case 0xdd:
282 case 0xde:
283 case 0xdf:
284 // It's a trailing surrogate, which is not valid at this point.
285 return false;
286 case 0x20:
287 case 0xff:
288 // It's in the range that has spaces, controls, and specials.
289 switch (utf16 & 0xfff8) {
290 case 0x2000:
291 case 0x2008:
292 case 0x2028:
293 case 0xfff0:
294 case 0xfff8:
295 return false;
296 }
297 break;
298 }
299 return true;
300}
301
302/* Return whether the pointed-at modified-UTF-8 encoded character is
303 * valid as part of a member name, updating the pointer to point past
304 * the consumed character. This will consume two encoded UTF-16 code
305 * points if the character is encoded as a surrogate pair. Also, if
306 * this function returns false, then the given pointer may only have
307 * been partially advanced.
308 */
309bool IsValidMemberNameUtf8(const char** pUtf8Ptr) {
310 uint8_t c = (uint8_t) **pUtf8Ptr;
311 if (c <= 0x7f) {
312 // It's low-ascii, so check the table.
313 uint32_t wordIdx = c >> 5;
314 uint32_t bitIdx = c & 0x1f;
315 (*pUtf8Ptr)++;
316 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
317 }
318
319 // It's a multibyte encoded character. Call a non-inline function
320 // for the heavy lifting.
321 return IsValidMemberNameUtf8Slow(pUtf8Ptr);
322}
323
324} // namespace
325
326bool IsValidClassName(const char* s, bool isClassName, bool dot_or_slash) {
327 char separator = (dot_or_slash ? '.' : '/');
328
329 int arrayCount = 0;
330 while (*s == '[') {
331 arrayCount++;
332 s++;
333 }
334
335 if (arrayCount > 255) {
336 // Arrays may have no more than 255 dimensions.
337 return false;
338 }
339
340 if (arrayCount != 0) {
341 /*
342 * If we're looking at an array of some sort, then it doesn't
343 * matter if what is being asked for is a class name; the
344 * format looks the same as a type descriptor in that case, so
345 * treat it as such.
346 */
347 isClassName = false;
348 }
349
350 if (!isClassName) {
351 /*
352 * We are looking for a descriptor. Either validate it as a
353 * single-character primitive type, or continue on to check the
354 * embedded class name (bracketed by "L" and ";").
355 */
356 switch (*(s++)) {
357 case 'B':
358 case 'C':
359 case 'D':
360 case 'F':
361 case 'I':
362 case 'J':
363 case 'S':
364 case 'Z':
365 // These are all single-character descriptors for primitive types.
366 return (*s == '\0');
367 case 'V':
368 // Non-array void is valid, but you can't have an array of void.
369 return (arrayCount == 0) && (*s == '\0');
370 case 'L':
371 // Class name: Break out and continue below.
372 break;
373 default:
374 // Oddball descriptor character.
375 return false;
376 }
377 }
378
379 /*
380 * We just consumed the 'L' that introduces a class name as part
381 * of a type descriptor, or we are looking for an unadorned class
382 * name.
383 */
384
385 bool sepOrFirst = true; // first character or just encountered a separator.
386 for (;;) {
387 uint8_t c = (uint8_t) *s;
388 switch (c) {
389 case '\0':
390 /*
391 * Premature end for a type descriptor, but valid for
392 * a class name as long as we haven't encountered an
393 * empty component (including the degenerate case of
394 * the empty string "").
395 */
396 return isClassName && !sepOrFirst;
397 case ';':
398 /*
399 * Invalid character for a class name, but the
400 * legitimate end of a type descriptor. In the latter
401 * case, make sure that this is the end of the string
402 * and that it doesn't end with an empty component
403 * (including the degenerate case of "L;").
404 */
405 return !isClassName && !sepOrFirst && (s[1] == '\0');
406 case '/':
407 case '.':
408 if (c != separator) {
409 // The wrong separator character.
410 return false;
411 }
412 if (sepOrFirst) {
413 // Separator at start or two separators in a row.
414 return false;
415 }
416 sepOrFirst = true;
417 s++;
418 break;
419 default:
420 if (!IsValidMemberNameUtf8(&s)) {
421 return false;
422 }
423 sepOrFirst = false;
424 break;
425 }
426 }
427}
428
Elliott Hughes34023802011-08-30 12:06:17 -0700429void Split(const std::string& s, char delim, std::vector<std::string>& result) {
430 const char* p = s.data();
431 const char* end = p + s.size();
432 while (p != end) {
433 if (*p == delim) {
434 ++p;
435 } else {
436 const char* start = p;
437 while (++p != end && *p != delim) {
438 // Skip to the next occurrence of the delimiter.
439 }
440 result.push_back(std::string(start, p - start));
441 }
442 }
443}
444
Elliott Hughesdcc24742011-09-07 14:02:44 -0700445void SetThreadName(const char *threadName) {
446 int hasAt = 0;
447 int hasDot = 0;
448 const char *s = threadName;
449 while (*s) {
450 if (*s == '.') {
451 hasDot = 1;
452 } else if (*s == '@') {
453 hasAt = 1;
454 }
455 s++;
456 }
457 int len = s - threadName;
458 if (len < 15 || hasAt || !hasDot) {
459 s = threadName;
460 } else {
461 s = threadName + len - 15;
462 }
463#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
464 /* pthread_setname_np fails rather than truncating long strings */
465 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
466 strncpy(buf, s, sizeof(buf)-1);
467 buf[sizeof(buf)-1] = '\0';
468 errno = pthread_setname_np(pthread_self(), buf);
469 if (errno != 0) {
470 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
471 }
472#elif defined(HAVE_PRCTL)
473 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
474#else
475#error no implementation for SetThreadName
476#endif
477}
478
Elliott Hughes11e45072011-08-16 17:40:46 -0700479} // namespace art
Elliott Hughes42ee1422011-09-06 12:33:32 -0700480
481// Neither bionic nor glibc exposes gettid(2).
482#define __KERNEL__
483#include <linux/unistd.h>
484namespace art {
485#ifdef _syscall0
486_syscall0(pid_t, GetTid)
487#else
488pid_t GetTid() { return syscall(__NR_gettid); }
489#endif
490} // namespace art
491#undef __KERNEL__