blob: 14a8facab07f8cf16926947742db084bea55294a [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 Hughesd8c00d02012-01-30 14:08:31 -0800330// See http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/design.html#wp615 for the full rules.
Elliott Hughes79082e32011-08-25 12:07:32 -0700331std::string MangleForJni(const std::string& s) {
332 std::string result;
333 size_t char_count = CountModifiedUtf8Chars(s.c_str());
334 const char* cp = &s[0];
335 for (size_t i = 0; i < char_count; ++i) {
336 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800337 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
338 result.push_back(ch);
339 } else if (ch == '.' || ch == '/') {
340 result += "_";
341 } else if (ch == '_') {
342 result += "_1";
343 } else if (ch == ';') {
344 result += "_2";
345 } else if (ch == '[') {
346 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700347 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800348 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700349 }
350 }
351 return result;
352}
353
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700354std::string DotToDescriptor(const char* class_name) {
355 std::string descriptor(class_name);
356 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
357 if (descriptor.length() > 0 && descriptor[0] != '[') {
358 descriptor = "L" + descriptor + ";";
359 }
360 return descriptor;
361}
362
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800363std::string DescriptorToDot(const StringPiece& descriptor) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700364 DCHECK_EQ(descriptor[0], 'L');
365 DCHECK_EQ(descriptor[descriptor.size()-1], ';');
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800366 std::string dot(descriptor.substr(1, descriptor.size() - 2).ToString());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700367 std::replace(dot.begin(), dot.end(), '/', '.');
368 return dot;
369}
370
Elliott Hughes79082e32011-08-25 12:07:32 -0700371std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800372 MethodHelper mh(m);
373 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700374 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700375 CHECK_EQ(class_name[0], 'L') << class_name;
376 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700377 class_name.erase(0, 1);
378 class_name.erase(class_name.size() - 1, 1);
379
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800380 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700381
382 std::string short_name;
383 short_name += "Java_";
384 short_name += MangleForJni(class_name);
385 short_name += "_";
386 short_name += MangleForJni(method_name);
387 return short_name;
388}
389
390std::string JniLongName(const Method* m) {
391 std::string long_name;
392 long_name += JniShortName(m);
393 long_name += "__";
394
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800395 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700396 signature.erase(0, 1);
397 signature.erase(signature.begin() + signature.find(')'), signature.end());
398
399 long_name += MangleForJni(signature);
400
401 return long_name;
402}
403
jeffhao10037c82012-01-23 15:06:23 -0800404// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700405uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
406 0x00000000, // 00..1f low control characters; nothing valid
407 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
408 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
409 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
410};
411
jeffhao10037c82012-01-23 15:06:23 -0800412// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
413bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700414 /*
415 * It's a multibyte encoded character. Decode it and analyze. We
416 * accept anything that isn't (a) an improperly encoded low value,
417 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
418 * control character, or (e) a high space, layout, or special
419 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
420 * U+fff0..U+ffff). This is all specified in the dex format
421 * document.
422 */
423
424 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
425
426 // Perform follow-up tests based on the high 8 bits.
427 switch (utf16 >> 8) {
428 case 0x00:
429 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
430 return (utf16 > 0x00a0);
431 case 0xd8:
432 case 0xd9:
433 case 0xda:
434 case 0xdb:
435 // It's a leading surrogate. Check to see that a trailing
436 // surrogate follows.
437 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
438 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
439 case 0xdc:
440 case 0xdd:
441 case 0xde:
442 case 0xdf:
443 // It's a trailing surrogate, which is not valid at this point.
444 return false;
445 case 0x20:
446 case 0xff:
447 // It's in the range that has spaces, controls, and specials.
448 switch (utf16 & 0xfff8) {
449 case 0x2000:
450 case 0x2008:
451 case 0x2028:
452 case 0xfff0:
453 case 0xfff8:
454 return false;
455 }
456 break;
457 }
458 return true;
459}
460
461/* Return whether the pointed-at modified-UTF-8 encoded character is
462 * valid as part of a member name, updating the pointer to point past
463 * the consumed character. This will consume two encoded UTF-16 code
464 * points if the character is encoded as a surrogate pair. Also, if
465 * this function returns false, then the given pointer may only have
466 * been partially advanced.
467 */
jeffhao10037c82012-01-23 15:06:23 -0800468bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700469 uint8_t c = (uint8_t) **pUtf8Ptr;
470 if (c <= 0x7f) {
471 // It's low-ascii, so check the table.
472 uint32_t wordIdx = c >> 5;
473 uint32_t bitIdx = c & 0x1f;
474 (*pUtf8Ptr)++;
475 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
476 }
477
478 // It's a multibyte encoded character. Call a non-inline function
479 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800480 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
481}
482
483bool IsValidMemberName(const char* s) {
484 bool angle_name = false;
485
486 switch(*s) {
487 case '\0':
488 // The empty string is not a valid name.
489 return false;
490 case '<':
491 angle_name = true;
492 s++;
493 break;
494 }
495
496 while (true) {
497 switch (*s) {
498 case '\0':
499 return !angle_name;
500 case '>':
501 return angle_name && s[1] == '\0';
502 }
503
504 if (!IsValidPartOfMemberNameUtf8(&s)) {
505 return false;
506 }
507 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700508}
509
Elliott Hughes906e6852011-10-28 14:52:10 -0700510enum ClassNameType { kName, kDescriptor };
511bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700512 int arrayCount = 0;
513 while (*s == '[') {
514 arrayCount++;
515 s++;
516 }
517
518 if (arrayCount > 255) {
519 // Arrays may have no more than 255 dimensions.
520 return false;
521 }
522
523 if (arrayCount != 0) {
524 /*
525 * If we're looking at an array of some sort, then it doesn't
526 * matter if what is being asked for is a class name; the
527 * format looks the same as a type descriptor in that case, so
528 * treat it as such.
529 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700530 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700531 }
532
Elliott Hughes906e6852011-10-28 14:52:10 -0700533 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700534 /*
535 * We are looking for a descriptor. Either validate it as a
536 * single-character primitive type, or continue on to check the
537 * embedded class name (bracketed by "L" and ";").
538 */
539 switch (*(s++)) {
540 case 'B':
541 case 'C':
542 case 'D':
543 case 'F':
544 case 'I':
545 case 'J':
546 case 'S':
547 case 'Z':
548 // These are all single-character descriptors for primitive types.
549 return (*s == '\0');
550 case 'V':
551 // Non-array void is valid, but you can't have an array of void.
552 return (arrayCount == 0) && (*s == '\0');
553 case 'L':
554 // Class name: Break out and continue below.
555 break;
556 default:
557 // Oddball descriptor character.
558 return false;
559 }
560 }
561
562 /*
563 * We just consumed the 'L' that introduces a class name as part
564 * of a type descriptor, or we are looking for an unadorned class
565 * name.
566 */
567
568 bool sepOrFirst = true; // first character or just encountered a separator.
569 for (;;) {
570 uint8_t c = (uint8_t) *s;
571 switch (c) {
572 case '\0':
573 /*
574 * Premature end for a type descriptor, but valid for
575 * a class name as long as we haven't encountered an
576 * empty component (including the degenerate case of
577 * the empty string "").
578 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700579 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700580 case ';':
581 /*
582 * Invalid character for a class name, but the
583 * legitimate end of a type descriptor. In the latter
584 * case, make sure that this is the end of the string
585 * and that it doesn't end with an empty component
586 * (including the degenerate case of "L;").
587 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700588 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700589 case '/':
590 case '.':
591 if (c != separator) {
592 // The wrong separator character.
593 return false;
594 }
595 if (sepOrFirst) {
596 // Separator at start or two separators in a row.
597 return false;
598 }
599 sepOrFirst = true;
600 s++;
601 break;
602 default:
jeffhao10037c82012-01-23 15:06:23 -0800603 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700604 return false;
605 }
606 sepOrFirst = false;
607 break;
608 }
609 }
610}
611
Elliott Hughes906e6852011-10-28 14:52:10 -0700612bool IsValidBinaryClassName(const char* s) {
613 return IsValidClassName(s, kName, '.');
614}
615
616bool IsValidJniClassName(const char* s) {
617 return IsValidClassName(s, kName, '/');
618}
619
620bool IsValidDescriptor(const char* s) {
621 return IsValidClassName(s, kDescriptor, '/');
622}
623
Elliott Hughes34023802011-08-30 12:06:17 -0700624void Split(const std::string& s, char delim, std::vector<std::string>& result) {
625 const char* p = s.data();
626 const char* end = p + s.size();
627 while (p != end) {
628 if (*p == delim) {
629 ++p;
630 } else {
631 const char* start = p;
632 while (++p != end && *p != delim) {
633 // Skip to the next occurrence of the delimiter.
634 }
635 result.push_back(std::string(start, p - start));
636 }
637 }
638}
639
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800640void SetThreadName(const char* threadName) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700641 int hasAt = 0;
642 int hasDot = 0;
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800643 const char* s = threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700644 while (*s) {
645 if (*s == '.') {
646 hasDot = 1;
647 } else if (*s == '@') {
648 hasAt = 1;
649 }
650 s++;
651 }
652 int len = s - threadName;
653 if (len < 15 || hasAt || !hasDot) {
654 s = threadName;
655 } else {
656 s = threadName + len - 15;
657 }
658#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
659 /* pthread_setname_np fails rather than truncating long strings */
660 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
661 strncpy(buf, s, sizeof(buf)-1);
662 buf[sizeof(buf)-1] = '\0';
663 errno = pthread_setname_np(pthread_self(), buf);
664 if (errno != 0) {
665 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
666 }
667#elif defined(HAVE_PRCTL)
668 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
669#else
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800670 UNIMPLEMENTED(WARNING) << threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700671#endif
672}
673
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700674void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
675 utime = stime = task_cpu = 0;
676 std::string stats;
677 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
678 return;
679 }
680 // Skip the command, which may contain spaces.
681 stats = stats.substr(stats.find(')') + 2);
682 // Extract the three fields we care about.
683 std::vector<std::string> fields;
684 Split(stats, ' ', fields);
685 utime = strtoull(fields[11].c_str(), NULL, 10);
686 stime = strtoull(fields[12].c_str(), NULL, 10);
687 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
688}
689
Brian Carlstroma9f19782011-10-13 00:14:47 -0700690std::string GetArtCacheOrDie() {
691 const char* data_root = getenv("ANDROID_DATA");
692 if (data_root == NULL) {
693 if (OS::DirectoryExists("/data")) {
694 data_root = "/data";
695 } else {
696 data_root = "/tmp";
697 }
698 }
699 if (!OS::DirectoryExists(data_root)) {
700 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << data_root;
701 return "";
702 }
703
Elliott Hughes95572412011-12-13 18:14:20 -0800704 std::string art_cache(StringPrintf("%s/art-cache", data_root));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700705
706 if (!OS::DirectoryExists(art_cache.c_str())) {
707 if (StringPiece(art_cache).starts_with("/tmp/")) {
708 int result = mkdir(art_cache.c_str(), 0700);
709 if (result != 0) {
710 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
711 return "";
712 }
713 } else {
714 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
715 return "";
716 }
717 }
718 return art_cache;
719}
720
jeffhao262bf462011-10-20 18:36:32 -0700721std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800722 std::string art_cache(GetArtCacheOrDie());
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700723 CHECK_EQ(location[0], '/');
724 std::string cache_file(location, 1); // skip leading slash
725 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
726 return art_cache + "/" + cache_file;
727}
728
jeffhao262bf462011-10-20 18:36:32 -0700729bool IsValidZipFilename(const std::string& filename) {
730 if (filename.size() < 4) {
731 return false;
732 }
733 std::string suffix(filename.substr(filename.size() - 4));
734 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
735}
736
737bool IsValidDexFilename(const std::string& filename) {
738 if (filename.size() < 4) {
739 return false;
740 }
741 std::string suffix(filename.substr(filename.size() - 4));
742 return (suffix == ".dex");
743}
744
Elliott Hughes42ee1422011-09-06 12:33:32 -0700745} // namespace art