blob: 4f4fa870646a1e5f635b7f5d5371812ae5ce8b4e [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
Ian Rogers3bb17a62012-01-27 23:56:44 -0800271std::string PrettySize(size_t size_in_bytes) {
272 if ((size_in_bytes / GB) * GB == size_in_bytes) {
273 return StringPrintf("%zdGB", size_in_bytes / GB);
274 } else if ((size_in_bytes / MB) * MB == size_in_bytes) {
275 return StringPrintf("%zdMB", size_in_bytes / MB);
276 } else if ((size_in_bytes / KB) * KB == size_in_bytes) {
277 return StringPrintf("%zdKiB", size_in_bytes / KB);
278 } else {
279 return StringPrintf("%zdB", size_in_bytes);
280 }
281}
282
283std::string PrettyDuration(uint64_t nano_duration) {
284 if (nano_duration == 0) {
285 return "0";
286 } else {
287 const uint64_t one_sec = 1000 * 1000 * 1000;
288 const uint64_t one_ms = 1000 * 1000;
289 const uint64_t one_us = 1000;
290 const char* unit;
291 uint64_t divisor;
292 uint32_t zero_fill;
293 if (nano_duration >= one_sec) {
294 unit = "s";
295 divisor = one_sec;
296 zero_fill = 9;
297 } else if(nano_duration >= one_ms) {
298 unit = "ms";
299 divisor = one_ms;
300 zero_fill = 6;
301 } else if(nano_duration >= one_us) {
302 unit = "us";
303 divisor = one_us;
304 zero_fill = 3;
305 } else {
306 unit = "ns";
307 divisor = 1;
308 zero_fill = 0;
309 }
310 uint64_t whole_part = nano_duration / divisor;
311 uint64_t fractional_part = nano_duration % divisor;
312 if (fractional_part == 0) {
313 return StringPrintf("%llu%s", whole_part, unit);
314 } else {
315 while ((fractional_part % 1000) == 0) {
316 zero_fill -= 3;
317 fractional_part /= 1000;
318 }
319 if (zero_fill == 3) {
320 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
321 } else if (zero_fill == 6) {
322 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
323 } else {
324 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
325 }
326 }
327 }
328}
329
Elliott Hughes79082e32011-08-25 12:07:32 -0700330std::string MangleForJni(const std::string& s) {
331 std::string result;
332 size_t char_count = CountModifiedUtf8Chars(s.c_str());
333 const char* cp = &s[0];
334 for (size_t i = 0; i < char_count; ++i) {
335 uint16_t ch = GetUtf16FromUtf8(&cp);
336 if (ch == '$' || ch > 127) {
337 StringAppendF(&result, "_0%04x", ch);
338 } else {
339 switch (ch) {
340 case '_':
341 result += "_1";
342 break;
343 case ';':
344 result += "_2";
345 break;
346 case '[':
347 result += "_3";
348 break;
349 case '/':
350 result += "_";
351 break;
352 default:
353 result.push_back(ch);
354 break;
355 }
356 }
357 }
358 return result;
359}
360
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700361std::string DotToDescriptor(const char* class_name) {
362 std::string descriptor(class_name);
363 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
364 if (descriptor.length() > 0 && descriptor[0] != '[') {
365 descriptor = "L" + descriptor + ";";
366 }
367 return descriptor;
368}
369
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800370std::string DescriptorToDot(const StringPiece& descriptor) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700371 DCHECK_EQ(descriptor[0], 'L');
372 DCHECK_EQ(descriptor[descriptor.size()-1], ';');
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800373 std::string dot(descriptor.substr(1, descriptor.size() - 2).ToString());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700374 std::replace(dot.begin(), dot.end(), '/', '.');
375 return dot;
376}
377
Elliott Hughes79082e32011-08-25 12:07:32 -0700378std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800379 MethodHelper mh(m);
380 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700381 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700382 CHECK_EQ(class_name[0], 'L') << class_name;
383 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700384 class_name.erase(0, 1);
385 class_name.erase(class_name.size() - 1, 1);
386
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800387 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700388
389 std::string short_name;
390 short_name += "Java_";
391 short_name += MangleForJni(class_name);
392 short_name += "_";
393 short_name += MangleForJni(method_name);
394 return short_name;
395}
396
397std::string JniLongName(const Method* m) {
398 std::string long_name;
399 long_name += JniShortName(m);
400 long_name += "__";
401
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800402 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700403 signature.erase(0, 1);
404 signature.erase(signature.begin() + signature.find(')'), signature.end());
405
406 long_name += MangleForJni(signature);
407
408 return long_name;
409}
410
jeffhao10037c82012-01-23 15:06:23 -0800411// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700412uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
413 0x00000000, // 00..1f low control characters; nothing valid
414 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
415 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
416 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
417};
418
jeffhao10037c82012-01-23 15:06:23 -0800419// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
420bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700421 /*
422 * It's a multibyte encoded character. Decode it and analyze. We
423 * accept anything that isn't (a) an improperly encoded low value,
424 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
425 * control character, or (e) a high space, layout, or special
426 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
427 * U+fff0..U+ffff). This is all specified in the dex format
428 * document.
429 */
430
431 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
432
433 // Perform follow-up tests based on the high 8 bits.
434 switch (utf16 >> 8) {
435 case 0x00:
436 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
437 return (utf16 > 0x00a0);
438 case 0xd8:
439 case 0xd9:
440 case 0xda:
441 case 0xdb:
442 // It's a leading surrogate. Check to see that a trailing
443 // surrogate follows.
444 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
445 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
446 case 0xdc:
447 case 0xdd:
448 case 0xde:
449 case 0xdf:
450 // It's a trailing surrogate, which is not valid at this point.
451 return false;
452 case 0x20:
453 case 0xff:
454 // It's in the range that has spaces, controls, and specials.
455 switch (utf16 & 0xfff8) {
456 case 0x2000:
457 case 0x2008:
458 case 0x2028:
459 case 0xfff0:
460 case 0xfff8:
461 return false;
462 }
463 break;
464 }
465 return true;
466}
467
468/* Return whether the pointed-at modified-UTF-8 encoded character is
469 * valid as part of a member name, updating the pointer to point past
470 * the consumed character. This will consume two encoded UTF-16 code
471 * points if the character is encoded as a surrogate pair. Also, if
472 * this function returns false, then the given pointer may only have
473 * been partially advanced.
474 */
jeffhao10037c82012-01-23 15:06:23 -0800475bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700476 uint8_t c = (uint8_t) **pUtf8Ptr;
477 if (c <= 0x7f) {
478 // It's low-ascii, so check the table.
479 uint32_t wordIdx = c >> 5;
480 uint32_t bitIdx = c & 0x1f;
481 (*pUtf8Ptr)++;
482 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
483 }
484
485 // It's a multibyte encoded character. Call a non-inline function
486 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800487 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
488}
489
490bool IsValidMemberName(const char* s) {
491 bool angle_name = false;
492
493 switch(*s) {
494 case '\0':
495 // The empty string is not a valid name.
496 return false;
497 case '<':
498 angle_name = true;
499 s++;
500 break;
501 }
502
503 while (true) {
504 switch (*s) {
505 case '\0':
506 return !angle_name;
507 case '>':
508 return angle_name && s[1] == '\0';
509 }
510
511 if (!IsValidPartOfMemberNameUtf8(&s)) {
512 return false;
513 }
514 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700515}
516
Elliott Hughes906e6852011-10-28 14:52:10 -0700517enum ClassNameType { kName, kDescriptor };
518bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700519 int arrayCount = 0;
520 while (*s == '[') {
521 arrayCount++;
522 s++;
523 }
524
525 if (arrayCount > 255) {
526 // Arrays may have no more than 255 dimensions.
527 return false;
528 }
529
530 if (arrayCount != 0) {
531 /*
532 * If we're looking at an array of some sort, then it doesn't
533 * matter if what is being asked for is a class name; the
534 * format looks the same as a type descriptor in that case, so
535 * treat it as such.
536 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700537 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700538 }
539
Elliott Hughes906e6852011-10-28 14:52:10 -0700540 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700541 /*
542 * We are looking for a descriptor. Either validate it as a
543 * single-character primitive type, or continue on to check the
544 * embedded class name (bracketed by "L" and ";").
545 */
546 switch (*(s++)) {
547 case 'B':
548 case 'C':
549 case 'D':
550 case 'F':
551 case 'I':
552 case 'J':
553 case 'S':
554 case 'Z':
555 // These are all single-character descriptors for primitive types.
556 return (*s == '\0');
557 case 'V':
558 // Non-array void is valid, but you can't have an array of void.
559 return (arrayCount == 0) && (*s == '\0');
560 case 'L':
561 // Class name: Break out and continue below.
562 break;
563 default:
564 // Oddball descriptor character.
565 return false;
566 }
567 }
568
569 /*
570 * We just consumed the 'L' that introduces a class name as part
571 * of a type descriptor, or we are looking for an unadorned class
572 * name.
573 */
574
575 bool sepOrFirst = true; // first character or just encountered a separator.
576 for (;;) {
577 uint8_t c = (uint8_t) *s;
578 switch (c) {
579 case '\0':
580 /*
581 * Premature end for a type descriptor, but valid for
582 * a class name as long as we haven't encountered an
583 * empty component (including the degenerate case of
584 * the empty string "").
585 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700586 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700587 case ';':
588 /*
589 * Invalid character for a class name, but the
590 * legitimate end of a type descriptor. In the latter
591 * case, make sure that this is the end of the string
592 * and that it doesn't end with an empty component
593 * (including the degenerate case of "L;").
594 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700595 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700596 case '/':
597 case '.':
598 if (c != separator) {
599 // The wrong separator character.
600 return false;
601 }
602 if (sepOrFirst) {
603 // Separator at start or two separators in a row.
604 return false;
605 }
606 sepOrFirst = true;
607 s++;
608 break;
609 default:
jeffhao10037c82012-01-23 15:06:23 -0800610 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700611 return false;
612 }
613 sepOrFirst = false;
614 break;
615 }
616 }
617}
618
Elliott Hughes906e6852011-10-28 14:52:10 -0700619bool IsValidBinaryClassName(const char* s) {
620 return IsValidClassName(s, kName, '.');
621}
622
623bool IsValidJniClassName(const char* s) {
624 return IsValidClassName(s, kName, '/');
625}
626
627bool IsValidDescriptor(const char* s) {
628 return IsValidClassName(s, kDescriptor, '/');
629}
630
Elliott Hughes34023802011-08-30 12:06:17 -0700631void Split(const std::string& s, char delim, std::vector<std::string>& result) {
632 const char* p = s.data();
633 const char* end = p + s.size();
634 while (p != end) {
635 if (*p == delim) {
636 ++p;
637 } else {
638 const char* start = p;
639 while (++p != end && *p != delim) {
640 // Skip to the next occurrence of the delimiter.
641 }
642 result.push_back(std::string(start, p - start));
643 }
644 }
645}
646
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800647void SetThreadName(const char* threadName) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700648 int hasAt = 0;
649 int hasDot = 0;
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800650 const char* s = threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700651 while (*s) {
652 if (*s == '.') {
653 hasDot = 1;
654 } else if (*s == '@') {
655 hasAt = 1;
656 }
657 s++;
658 }
659 int len = s - threadName;
660 if (len < 15 || hasAt || !hasDot) {
661 s = threadName;
662 } else {
663 s = threadName + len - 15;
664 }
665#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
666 /* pthread_setname_np fails rather than truncating long strings */
667 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
668 strncpy(buf, s, sizeof(buf)-1);
669 buf[sizeof(buf)-1] = '\0';
670 errno = pthread_setname_np(pthread_self(), buf);
671 if (errno != 0) {
672 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
673 }
674#elif defined(HAVE_PRCTL)
675 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
676#else
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800677 UNIMPLEMENTED(WARNING) << threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700678#endif
679}
680
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700681void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
682 utime = stime = task_cpu = 0;
683 std::string stats;
684 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
685 return;
686 }
687 // Skip the command, which may contain spaces.
688 stats = stats.substr(stats.find(')') + 2);
689 // Extract the three fields we care about.
690 std::vector<std::string> fields;
691 Split(stats, ' ', fields);
692 utime = strtoull(fields[11].c_str(), NULL, 10);
693 stime = strtoull(fields[12].c_str(), NULL, 10);
694 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
695}
696
Brian Carlstroma9f19782011-10-13 00:14:47 -0700697std::string GetArtCacheOrDie() {
698 const char* data_root = getenv("ANDROID_DATA");
699 if (data_root == NULL) {
700 if (OS::DirectoryExists("/data")) {
701 data_root = "/data";
702 } else {
703 data_root = "/tmp";
704 }
705 }
706 if (!OS::DirectoryExists(data_root)) {
707 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << data_root;
708 return "";
709 }
710
Elliott Hughes95572412011-12-13 18:14:20 -0800711 std::string art_cache(StringPrintf("%s/art-cache", data_root));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700712
713 if (!OS::DirectoryExists(art_cache.c_str())) {
714 if (StringPiece(art_cache).starts_with("/tmp/")) {
715 int result = mkdir(art_cache.c_str(), 0700);
716 if (result != 0) {
717 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
718 return "";
719 }
720 } else {
721 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
722 return "";
723 }
724 }
725 return art_cache;
726}
727
jeffhao262bf462011-10-20 18:36:32 -0700728std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800729 std::string art_cache(GetArtCacheOrDie());
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700730 CHECK_EQ(location[0], '/');
731 std::string cache_file(location, 1); // skip leading slash
732 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
733 return art_cache + "/" + cache_file;
734}
735
jeffhao262bf462011-10-20 18:36:32 -0700736bool IsValidZipFilename(const std::string& filename) {
737 if (filename.size() < 4) {
738 return false;
739 }
740 std::string suffix(filename.substr(filename.size() - 4));
741 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
742}
743
744bool IsValidDexFilename(const std::string& filename) {
745 if (filename.size() < 4) {
746 return false;
747 }
748 std::string suffix(filename.substr(filename.size() - 4));
749 return (suffix == ".dex");
750}
751
Elliott Hughes42ee1422011-09-06 12:33:32 -0700752} // namespace art