blob: 531424ea4f3f9f65027e80d8d8041a64dc417187 [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 Hughesbb551fa2012-01-25 16:35:29 -0800118uint64_t NsToMs(uint64_t ns) {
119 return ns/1000/1000;
120}
121
Elliott Hughes5174fe62011-08-23 15:12:35 -0700122std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700123 if (java_descriptor == NULL) {
124 return "null";
125 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700126 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
127}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700128
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800129std::string PrettyDescriptor(const Class* klass) {
130 if (klass == NULL) {
131 return "null";
132 }
133 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800134}
135
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700136std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700137 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700138 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700139 size_t dim = 0;
140 while (*c == '[') {
141 dim++;
142 c++;
143 }
144
145 // Reference or primitive?
146 if (*c == 'L') {
147 // "[[La/b/C;" -> "a.b.C[][]".
148 c++; // Skip the 'L'.
149 } else {
150 // "[[B" -> "byte[][]".
151 // To make life easier, we make primitives look like unqualified
152 // reference types.
153 switch (*c) {
154 case 'B': c = "byte;"; break;
155 case 'C': c = "char;"; break;
156 case 'D': c = "double;"; break;
157 case 'F': c = "float;"; break;
158 case 'I': c = "int;"; break;
159 case 'J': c = "long;"; break;
160 case 'S': c = "short;"; break;
161 case 'Z': c = "boolean;"; break;
Elliott Hughes5174fe62011-08-23 15:12:35 -0700162 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700163 }
164 }
165
166 // At this point, 'c' is a string of the form "fully/qualified/Type;"
167 // or "primitive;". Rewrite the type with '.' instead of '/':
168 std::string result;
169 const char* p = c;
170 while (*p != ';') {
171 char ch = *p++;
172 if (ch == '/') {
173 ch = '.';
174 }
175 result.push_back(ch);
176 }
177 // ...and replace the semicolon with 'dim' "[]" pairs:
178 while (dim--) {
179 result += "[]";
180 }
181 return result;
182}
183
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700184std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800185 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700186 return PrettyDescriptor(descriptor_string);
187}
188
Elliott Hughes54e7df12011-09-16 11:47:04 -0700189std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700190 if (f == NULL) {
191 return "null";
192 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800193 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700194 std::string result;
195 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800196 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700197 result += ' ';
198 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800199 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700200 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800201 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700202 return result;
203}
204
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700205std::string PrettyMethod(const Method* m, bool with_signature) {
206 if (m == NULL) {
207 return "null";
208 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800209 MethodHelper mh(m);
210 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700211 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800212 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700213 if (with_signature) {
214 // TODO: iterate over the signature's elements and pass them all to
215 // PrettyDescriptor? We'd need to pull out the return type specially, too.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800216 result += mh.GetSignature();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700217 }
218 return result;
219}
220
Ian Rogers0571d352011-11-03 19:51:38 -0700221std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
222 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
223 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
224 result += '.';
225 result += dex_file.GetMethodName(method_id);
226 if (with_signature) {
227 // TODO: iterate over the signature's elements and pass them all to
228 // PrettyDescriptor? We'd need to pull out the return type specially, too.
229 result += dex_file.GetMethodSignature(method_id);
230 }
231 return result;
232}
233
Elliott Hughes54e7df12011-09-16 11:47:04 -0700234std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700235 if (obj == NULL) {
236 return "null";
237 }
238 if (obj->GetClass() == NULL) {
239 return "(raw)";
240 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800241 ClassHelper kh(obj->GetClass());
242 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700243 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800244 kh.ChangeClass(obj->AsClass());
245 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700246 }
247 return result;
248}
249
Elliott Hughes54e7df12011-09-16 11:47:04 -0700250std::string PrettyClass(const Class* c) {
251 if (c == NULL) {
252 return "null";
253 }
254 std::string result;
255 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800256 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700257 result += ">";
258 return result;
259}
260
Ian Rogersd81871c2011-10-03 13:57:23 -0700261std::string PrettyClassAndClassLoader(const Class* c) {
262 if (c == NULL) {
263 return "null";
264 }
265 std::string result;
266 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800267 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700268 result += ",";
269 result += PrettyTypeOf(c->GetClassLoader());
270 // TODO: add an identifying hash value for the loader
271 result += ">";
272 return result;
273}
274
Elliott Hughes79082e32011-08-25 12:07:32 -0700275std::string MangleForJni(const std::string& s) {
276 std::string result;
277 size_t char_count = CountModifiedUtf8Chars(s.c_str());
278 const char* cp = &s[0];
279 for (size_t i = 0; i < char_count; ++i) {
280 uint16_t ch = GetUtf16FromUtf8(&cp);
281 if (ch == '$' || ch > 127) {
282 StringAppendF(&result, "_0%04x", ch);
283 } else {
284 switch (ch) {
285 case '_':
286 result += "_1";
287 break;
288 case ';':
289 result += "_2";
290 break;
291 case '[':
292 result += "_3";
293 break;
294 case '/':
295 result += "_";
296 break;
297 default:
298 result.push_back(ch);
299 break;
300 }
301 }
302 }
303 return result;
304}
305
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700306std::string DotToDescriptor(const char* class_name) {
307 std::string descriptor(class_name);
308 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
309 if (descriptor.length() > 0 && descriptor[0] != '[') {
310 descriptor = "L" + descriptor + ";";
311 }
312 return descriptor;
313}
314
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800315std::string DescriptorToDot(const StringPiece& descriptor) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700316 DCHECK_EQ(descriptor[0], 'L');
317 DCHECK_EQ(descriptor[descriptor.size()-1], ';');
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800318 std::string dot(descriptor.substr(1, descriptor.size() - 2).ToString());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700319 std::replace(dot.begin(), dot.end(), '/', '.');
320 return dot;
321}
322
Elliott Hughes79082e32011-08-25 12:07:32 -0700323std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800324 MethodHelper mh(m);
325 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700326 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700327 CHECK_EQ(class_name[0], 'L') << class_name;
328 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700329 class_name.erase(0, 1);
330 class_name.erase(class_name.size() - 1, 1);
331
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800332 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700333
334 std::string short_name;
335 short_name += "Java_";
336 short_name += MangleForJni(class_name);
337 short_name += "_";
338 short_name += MangleForJni(method_name);
339 return short_name;
340}
341
342std::string JniLongName(const Method* m) {
343 std::string long_name;
344 long_name += JniShortName(m);
345 long_name += "__";
346
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800347 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700348 signature.erase(0, 1);
349 signature.erase(signature.begin() + signature.find(')'), signature.end());
350
351 long_name += MangleForJni(signature);
352
353 return long_name;
354}
355
jeffhao10037c82012-01-23 15:06:23 -0800356// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700357uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
358 0x00000000, // 00..1f low control characters; nothing valid
359 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
360 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
361 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
362};
363
jeffhao10037c82012-01-23 15:06:23 -0800364// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
365bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700366 /*
367 * It's a multibyte encoded character. Decode it and analyze. We
368 * accept anything that isn't (a) an improperly encoded low value,
369 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
370 * control character, or (e) a high space, layout, or special
371 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
372 * U+fff0..U+ffff). This is all specified in the dex format
373 * document.
374 */
375
376 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
377
378 // Perform follow-up tests based on the high 8 bits.
379 switch (utf16 >> 8) {
380 case 0x00:
381 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
382 return (utf16 > 0x00a0);
383 case 0xd8:
384 case 0xd9:
385 case 0xda:
386 case 0xdb:
387 // It's a leading surrogate. Check to see that a trailing
388 // surrogate follows.
389 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
390 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
391 case 0xdc:
392 case 0xdd:
393 case 0xde:
394 case 0xdf:
395 // It's a trailing surrogate, which is not valid at this point.
396 return false;
397 case 0x20:
398 case 0xff:
399 // It's in the range that has spaces, controls, and specials.
400 switch (utf16 & 0xfff8) {
401 case 0x2000:
402 case 0x2008:
403 case 0x2028:
404 case 0xfff0:
405 case 0xfff8:
406 return false;
407 }
408 break;
409 }
410 return true;
411}
412
413/* Return whether the pointed-at modified-UTF-8 encoded character is
414 * valid as part of a member name, updating the pointer to point past
415 * the consumed character. This will consume two encoded UTF-16 code
416 * points if the character is encoded as a surrogate pair. Also, if
417 * this function returns false, then the given pointer may only have
418 * been partially advanced.
419 */
jeffhao10037c82012-01-23 15:06:23 -0800420bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700421 uint8_t c = (uint8_t) **pUtf8Ptr;
422 if (c <= 0x7f) {
423 // It's low-ascii, so check the table.
424 uint32_t wordIdx = c >> 5;
425 uint32_t bitIdx = c & 0x1f;
426 (*pUtf8Ptr)++;
427 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
428 }
429
430 // It's a multibyte encoded character. Call a non-inline function
431 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800432 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
433}
434
435bool IsValidMemberName(const char* s) {
436 bool angle_name = false;
437
438 switch(*s) {
439 case '\0':
440 // The empty string is not a valid name.
441 return false;
442 case '<':
443 angle_name = true;
444 s++;
445 break;
446 }
447
448 while (true) {
449 switch (*s) {
450 case '\0':
451 return !angle_name;
452 case '>':
453 return angle_name && s[1] == '\0';
454 }
455
456 if (!IsValidPartOfMemberNameUtf8(&s)) {
457 return false;
458 }
459 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700460}
461
Elliott Hughes906e6852011-10-28 14:52:10 -0700462enum ClassNameType { kName, kDescriptor };
463bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700464 int arrayCount = 0;
465 while (*s == '[') {
466 arrayCount++;
467 s++;
468 }
469
470 if (arrayCount > 255) {
471 // Arrays may have no more than 255 dimensions.
472 return false;
473 }
474
475 if (arrayCount != 0) {
476 /*
477 * If we're looking at an array of some sort, then it doesn't
478 * matter if what is being asked for is a class name; the
479 * format looks the same as a type descriptor in that case, so
480 * treat it as such.
481 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700482 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700483 }
484
Elliott Hughes906e6852011-10-28 14:52:10 -0700485 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700486 /*
487 * We are looking for a descriptor. Either validate it as a
488 * single-character primitive type, or continue on to check the
489 * embedded class name (bracketed by "L" and ";").
490 */
491 switch (*(s++)) {
492 case 'B':
493 case 'C':
494 case 'D':
495 case 'F':
496 case 'I':
497 case 'J':
498 case 'S':
499 case 'Z':
500 // These are all single-character descriptors for primitive types.
501 return (*s == '\0');
502 case 'V':
503 // Non-array void is valid, but you can't have an array of void.
504 return (arrayCount == 0) && (*s == '\0');
505 case 'L':
506 // Class name: Break out and continue below.
507 break;
508 default:
509 // Oddball descriptor character.
510 return false;
511 }
512 }
513
514 /*
515 * We just consumed the 'L' that introduces a class name as part
516 * of a type descriptor, or we are looking for an unadorned class
517 * name.
518 */
519
520 bool sepOrFirst = true; // first character or just encountered a separator.
521 for (;;) {
522 uint8_t c = (uint8_t) *s;
523 switch (c) {
524 case '\0':
525 /*
526 * Premature end for a type descriptor, but valid for
527 * a class name as long as we haven't encountered an
528 * empty component (including the degenerate case of
529 * the empty string "").
530 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700531 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700532 case ';':
533 /*
534 * Invalid character for a class name, but the
535 * legitimate end of a type descriptor. In the latter
536 * case, make sure that this is the end of the string
537 * and that it doesn't end with an empty component
538 * (including the degenerate case of "L;").
539 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700540 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700541 case '/':
542 case '.':
543 if (c != separator) {
544 // The wrong separator character.
545 return false;
546 }
547 if (sepOrFirst) {
548 // Separator at start or two separators in a row.
549 return false;
550 }
551 sepOrFirst = true;
552 s++;
553 break;
554 default:
jeffhao10037c82012-01-23 15:06:23 -0800555 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700556 return false;
557 }
558 sepOrFirst = false;
559 break;
560 }
561 }
562}
563
Elliott Hughes906e6852011-10-28 14:52:10 -0700564bool IsValidBinaryClassName(const char* s) {
565 return IsValidClassName(s, kName, '.');
566}
567
568bool IsValidJniClassName(const char* s) {
569 return IsValidClassName(s, kName, '/');
570}
571
572bool IsValidDescriptor(const char* s) {
573 return IsValidClassName(s, kDescriptor, '/');
574}
575
Elliott Hughes34023802011-08-30 12:06:17 -0700576void Split(const std::string& s, char delim, std::vector<std::string>& result) {
577 const char* p = s.data();
578 const char* end = p + s.size();
579 while (p != end) {
580 if (*p == delim) {
581 ++p;
582 } else {
583 const char* start = p;
584 while (++p != end && *p != delim) {
585 // Skip to the next occurrence of the delimiter.
586 }
587 result.push_back(std::string(start, p - start));
588 }
589 }
590}
591
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800592void SetThreadName(const char* threadName) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700593 int hasAt = 0;
594 int hasDot = 0;
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800595 const char* s = threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700596 while (*s) {
597 if (*s == '.') {
598 hasDot = 1;
599 } else if (*s == '@') {
600 hasAt = 1;
601 }
602 s++;
603 }
604 int len = s - threadName;
605 if (len < 15 || hasAt || !hasDot) {
606 s = threadName;
607 } else {
608 s = threadName + len - 15;
609 }
610#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
611 /* pthread_setname_np fails rather than truncating long strings */
612 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
613 strncpy(buf, s, sizeof(buf)-1);
614 buf[sizeof(buf)-1] = '\0';
615 errno = pthread_setname_np(pthread_self(), buf);
616 if (errno != 0) {
617 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
618 }
619#elif defined(HAVE_PRCTL)
620 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
621#else
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800622 UNIMPLEMENTED(WARNING) << threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700623#endif
624}
625
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700626void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
627 utime = stime = task_cpu = 0;
628 std::string stats;
629 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
630 return;
631 }
632 // Skip the command, which may contain spaces.
633 stats = stats.substr(stats.find(')') + 2);
634 // Extract the three fields we care about.
635 std::vector<std::string> fields;
636 Split(stats, ' ', fields);
637 utime = strtoull(fields[11].c_str(), NULL, 10);
638 stime = strtoull(fields[12].c_str(), NULL, 10);
639 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
640}
641
Brian Carlstroma9f19782011-10-13 00:14:47 -0700642std::string GetArtCacheOrDie() {
643 const char* data_root = getenv("ANDROID_DATA");
644 if (data_root == NULL) {
645 if (OS::DirectoryExists("/data")) {
646 data_root = "/data";
647 } else {
648 data_root = "/tmp";
649 }
650 }
651 if (!OS::DirectoryExists(data_root)) {
652 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << data_root;
653 return "";
654 }
655
Elliott Hughes95572412011-12-13 18:14:20 -0800656 std::string art_cache(StringPrintf("%s/art-cache", data_root));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700657
658 if (!OS::DirectoryExists(art_cache.c_str())) {
659 if (StringPiece(art_cache).starts_with("/tmp/")) {
660 int result = mkdir(art_cache.c_str(), 0700);
661 if (result != 0) {
662 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
663 return "";
664 }
665 } else {
666 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
667 return "";
668 }
669 }
670 return art_cache;
671}
672
jeffhao262bf462011-10-20 18:36:32 -0700673std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800674 std::string art_cache(GetArtCacheOrDie());
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700675 CHECK_EQ(location[0], '/');
676 std::string cache_file(location, 1); // skip leading slash
677 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
678 return art_cache + "/" + cache_file;
679}
680
jeffhao262bf462011-10-20 18:36:32 -0700681bool IsValidZipFilename(const std::string& filename) {
682 if (filename.size() < 4) {
683 return false;
684 }
685 std::string suffix(filename.substr(filename.size() - 4));
686 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
687}
688
689bool IsValidDexFilename(const std::string& filename) {
690 if (filename.size() < 4) {
691 return false;
692 }
693 std::string suffix(filename.substr(filename.size() - 4));
694 return (suffix == ".dex");
695}
696
Elliott Hughes42ee1422011-09-06 12:33:32 -0700697} // namespace art