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