blob: 09a01c671493e77d02847db1638e4ac1e6d27aa1 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Elliott Hughes11e45072011-08-16 17:40:46 -070016
Elliott Hughes42ee1422011-09-06 12:33:32 -070017#include "utils.h"
18
Elliott Hughes06e3ad42012-02-07 14:51:57 -080019#include <dynamic_annotations.h>
Elliott Hughes92b3b562011-09-08 16:32:26 -070020#include <pthread.h>
Brian Carlstroma9f19782011-10-13 00:14:47 -070021#include <sys/stat.h>
Elliott Hughes42ee1422011-09-06 12:33:32 -070022#include <sys/syscall.h>
23#include <sys/types.h>
24#include <unistd.h>
25
Elliott Hughes90a33692011-08-30 13:27:07 -070026#include "UniquePtr.h"
Ian Rogersd81871c2011-10-03 13:57:23 -070027#include "class_loader.h"
buzbeec143c552011-08-20 17:38:58 -070028#include "file.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070029#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080030#include "object_utils.h"
buzbeec143c552011-08-20 17:38:58 -070031#include "os.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070032
Elliott Hughesad6c9c32012-01-19 17:39:12 -080033#if !defined(HAVE_POSIX_CLOCKS)
34#include <sys/time.h>
35#endif
36
Elliott Hughesdcc24742011-09-07 14:02:44 -070037#if defined(HAVE_PRCTL)
38#include <sys/prctl.h>
39#endif
40
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080041#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080042#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080043#endif
44
Elliott Hughes11e45072011-08-16 17:40:46 -070045namespace art {
46
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080047pid_t GetTid() {
48#if defined(__APPLE__)
49 // Mac OS doesn't have gettid(2).
50 return getpid();
51#else
52 // Neither bionic nor glibc exposes gettid(2).
53 return syscall(__NR_gettid);
54#endif
55}
56
Elliott Hughesd92bec42011-09-02 17:04:36 -070057bool ReadFileToString(const std::string& file_name, std::string* result) {
58 UniquePtr<File> file(OS::OpenFile(file_name.c_str(), false));
59 if (file.get() == NULL) {
60 return false;
61 }
buzbeec143c552011-08-20 17:38:58 -070062
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070063 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -070064 while (true) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070065 int64_t n = file->Read(&buf[0], buf.size());
Elliott Hughesd92bec42011-09-02 17:04:36 -070066 if (n == -1) {
67 return false;
buzbeec143c552011-08-20 17:38:58 -070068 }
Elliott Hughesd92bec42011-09-02 17:04:36 -070069 if (n == 0) {
70 return true;
71 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070072 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -070073 }
buzbeec143c552011-08-20 17:38:58 -070074}
75
Elliott Hughese27955c2011-08-26 15:21:24 -070076std::string GetIsoDate() {
77 time_t now = time(NULL);
78 struct tm tmbuf;
79 struct tm* ptm = localtime_r(&now, &tmbuf);
80 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
81 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
82 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
83}
84
Elliott Hughes7162ad92011-10-27 14:08:42 -070085uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -080086#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7162ad92011-10-27 14:08:42 -070087 struct timespec now;
88 clock_gettime(CLOCK_MONOTONIC, &now);
89 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -080090#else
91 struct timeval now;
92 gettimeofday(&now, NULL);
93 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
94#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -070095}
96
jeffhaoa9ef3fd2011-12-13 18:33:43 -080097uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -080098#if defined(HAVE_POSIX_CLOCKS)
jeffhaoa9ef3fd2011-12-13 18:33:43 -080099 struct timespec now;
100 clock_gettime(CLOCK_MONOTONIC, &now);
101 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800102#else
103 struct timeval now;
104 gettimeofday(&now, NULL);
105 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec * 1000LL;
106#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800107}
108
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700109uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800110#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700111 struct timespec now;
112 clock_gettime(CLOCK_MONOTONIC, &now);
113 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800114#else
115 struct timeval now;
116 gettimeofday(&now, NULL);
117 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
118#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700119}
120
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800121uint64_t ThreadCpuMicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800122#if defined(HAVE_POSIX_CLOCKS)
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800123 struct timespec now;
124 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
125 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800126#else
127 UNIMPLEMENTED(WARNING);
128 return -1;
129#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800130}
131
Elliott Hughes5174fe62011-08-23 15:12:35 -0700132std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700133 if (java_descriptor == NULL) {
134 return "null";
135 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700136 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
137}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700138
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800139std::string PrettyDescriptor(const Class* klass) {
140 if (klass == NULL) {
141 return "null";
142 }
143 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800144}
145
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700146std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700147 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700148 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700149 size_t dim = 0;
150 while (*c == '[') {
151 dim++;
152 c++;
153 }
154
155 // Reference or primitive?
156 if (*c == 'L') {
157 // "[[La/b/C;" -> "a.b.C[][]".
158 c++; // Skip the 'L'.
159 } else {
160 // "[[B" -> "byte[][]".
161 // To make life easier, we make primitives look like unqualified
162 // reference types.
163 switch (*c) {
164 case 'B': c = "byte;"; break;
165 case 'C': c = "char;"; break;
166 case 'D': c = "double;"; break;
167 case 'F': c = "float;"; break;
168 case 'I': c = "int;"; break;
169 case 'J': c = "long;"; break;
170 case 'S': c = "short;"; break;
171 case 'Z': c = "boolean;"; break;
Elliott Hughes5174fe62011-08-23 15:12:35 -0700172 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700173 }
174 }
175
176 // At this point, 'c' is a string of the form "fully/qualified/Type;"
177 // or "primitive;". Rewrite the type with '.' instead of '/':
178 std::string result;
179 const char* p = c;
180 while (*p != ';') {
181 char ch = *p++;
182 if (ch == '/') {
183 ch = '.';
184 }
185 result.push_back(ch);
186 }
187 // ...and replace the semicolon with 'dim' "[]" pairs:
188 while (dim--) {
189 result += "[]";
190 }
191 return result;
192}
193
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700194std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800195 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700196 return PrettyDescriptor(descriptor_string);
197}
198
Elliott Hughes54e7df12011-09-16 11:47:04 -0700199std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700200 if (f == NULL) {
201 return "null";
202 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800203 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700204 std::string result;
205 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800206 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700207 result += ' ';
208 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800209 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700210 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800211 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700212 return result;
213}
214
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700215std::string PrettyMethod(const Method* m, bool with_signature) {
216 if (m == NULL) {
217 return "null";
218 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800219 MethodHelper mh(m);
220 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700221 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800222 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700223 if (with_signature) {
224 // TODO: iterate over the signature's elements and pass them all to
225 // PrettyDescriptor? We'd need to pull out the return type specially, too.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800226 result += mh.GetSignature();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700227 }
228 return result;
229}
230
Ian Rogers0571d352011-11-03 19:51:38 -0700231std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
232 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
233 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
234 result += '.';
235 result += dex_file.GetMethodName(method_id);
236 if (with_signature) {
237 // TODO: iterate over the signature's elements and pass them all to
238 // PrettyDescriptor? We'd need to pull out the return type specially, too.
239 result += dex_file.GetMethodSignature(method_id);
240 }
241 return result;
242}
243
Elliott Hughes54e7df12011-09-16 11:47:04 -0700244std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700245 if (obj == NULL) {
246 return "null";
247 }
248 if (obj->GetClass() == NULL) {
249 return "(raw)";
250 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800251 ClassHelper kh(obj->GetClass());
252 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700253 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800254 kh.ChangeClass(obj->AsClass());
255 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700256 }
257 return result;
258}
259
Elliott Hughes54e7df12011-09-16 11:47:04 -0700260std::string PrettyClass(const Class* c) {
261 if (c == NULL) {
262 return "null";
263 }
264 std::string result;
265 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800266 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700267 result += ">";
268 return result;
269}
270
Ian Rogersd81871c2011-10-03 13:57:23 -0700271std::string PrettyClassAndClassLoader(const Class* c) {
272 if (c == NULL) {
273 return "null";
274 }
275 std::string result;
276 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800277 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700278 result += ",";
279 result += PrettyTypeOf(c->GetClassLoader());
280 // TODO: add an identifying hash value for the loader
281 result += ">";
282 return result;
283}
284
Ian Rogers3bb17a62012-01-27 23:56:44 -0800285std::string PrettySize(size_t size_in_bytes) {
286 if ((size_in_bytes / GB) * GB == size_in_bytes) {
287 return StringPrintf("%zdGB", size_in_bytes / GB);
288 } else if ((size_in_bytes / MB) * MB == size_in_bytes) {
289 return StringPrintf("%zdMB", size_in_bytes / MB);
290 } else if ((size_in_bytes / KB) * KB == size_in_bytes) {
291 return StringPrintf("%zdKiB", size_in_bytes / KB);
292 } else {
293 return StringPrintf("%zdB", size_in_bytes);
294 }
295}
296
297std::string PrettyDuration(uint64_t nano_duration) {
298 if (nano_duration == 0) {
299 return "0";
300 } else {
301 const uint64_t one_sec = 1000 * 1000 * 1000;
302 const uint64_t one_ms = 1000 * 1000;
303 const uint64_t one_us = 1000;
304 const char* unit;
305 uint64_t divisor;
306 uint32_t zero_fill;
307 if (nano_duration >= one_sec) {
308 unit = "s";
309 divisor = one_sec;
310 zero_fill = 9;
311 } else if(nano_duration >= one_ms) {
312 unit = "ms";
313 divisor = one_ms;
314 zero_fill = 6;
315 } else if(nano_duration >= one_us) {
316 unit = "us";
317 divisor = one_us;
318 zero_fill = 3;
319 } else {
320 unit = "ns";
321 divisor = 1;
322 zero_fill = 0;
323 }
324 uint64_t whole_part = nano_duration / divisor;
325 uint64_t fractional_part = nano_duration % divisor;
326 if (fractional_part == 0) {
327 return StringPrintf("%llu%s", whole_part, unit);
328 } else {
329 while ((fractional_part % 1000) == 0) {
330 zero_fill -= 3;
331 fractional_part /= 1000;
332 }
333 if (zero_fill == 3) {
334 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
335 } else if (zero_fill == 6) {
336 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
337 } else {
338 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
339 }
340 }
341 }
342}
343
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800344// 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 -0700345std::string MangleForJni(const std::string& s) {
346 std::string result;
347 size_t char_count = CountModifiedUtf8Chars(s.c_str());
348 const char* cp = &s[0];
349 for (size_t i = 0; i < char_count; ++i) {
350 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800351 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
352 result.push_back(ch);
353 } else if (ch == '.' || ch == '/') {
354 result += "_";
355 } else if (ch == '_') {
356 result += "_1";
357 } else if (ch == ';') {
358 result += "_2";
359 } else if (ch == '[') {
360 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700361 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800362 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700363 }
364 }
365 return result;
366}
367
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700368std::string DotToDescriptor(const char* class_name) {
369 std::string descriptor(class_name);
370 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
371 if (descriptor.length() > 0 && descriptor[0] != '[') {
372 descriptor = "L" + descriptor + ";";
373 }
374 return descriptor;
375}
376
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800377std::string DescriptorToDot(const char* descriptor) {
378 size_t length = strlen(descriptor);
379 DCHECK_GT(length, 0U);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700380 DCHECK_EQ(descriptor[0], 'L');
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800381 DCHECK_EQ(descriptor[length - 1], ';');
382 std::string dot(descriptor + 1, length - 2);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700383 std::replace(dot.begin(), dot.end(), '/', '.');
384 return dot;
385}
386
Elliott Hughes79082e32011-08-25 12:07:32 -0700387std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800388 MethodHelper mh(m);
389 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700390 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700391 CHECK_EQ(class_name[0], 'L') << class_name;
392 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700393 class_name.erase(0, 1);
394 class_name.erase(class_name.size() - 1, 1);
395
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800396 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700397
398 std::string short_name;
399 short_name += "Java_";
400 short_name += MangleForJni(class_name);
401 short_name += "_";
402 short_name += MangleForJni(method_name);
403 return short_name;
404}
405
406std::string JniLongName(const Method* m) {
407 std::string long_name;
408 long_name += JniShortName(m);
409 long_name += "__";
410
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800411 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700412 signature.erase(0, 1);
413 signature.erase(signature.begin() + signature.find(')'), signature.end());
414
415 long_name += MangleForJni(signature);
416
417 return long_name;
418}
419
jeffhao10037c82012-01-23 15:06:23 -0800420// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700421uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
422 0x00000000, // 00..1f low control characters; nothing valid
423 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
424 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
425 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
426};
427
jeffhao10037c82012-01-23 15:06:23 -0800428// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
429bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700430 /*
431 * It's a multibyte encoded character. Decode it and analyze. We
432 * accept anything that isn't (a) an improperly encoded low value,
433 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
434 * control character, or (e) a high space, layout, or special
435 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
436 * U+fff0..U+ffff). This is all specified in the dex format
437 * document.
438 */
439
440 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
441
442 // Perform follow-up tests based on the high 8 bits.
443 switch (utf16 >> 8) {
444 case 0x00:
445 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
446 return (utf16 > 0x00a0);
447 case 0xd8:
448 case 0xd9:
449 case 0xda:
450 case 0xdb:
451 // It's a leading surrogate. Check to see that a trailing
452 // surrogate follows.
453 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
454 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
455 case 0xdc:
456 case 0xdd:
457 case 0xde:
458 case 0xdf:
459 // It's a trailing surrogate, which is not valid at this point.
460 return false;
461 case 0x20:
462 case 0xff:
463 // It's in the range that has spaces, controls, and specials.
464 switch (utf16 & 0xfff8) {
465 case 0x2000:
466 case 0x2008:
467 case 0x2028:
468 case 0xfff0:
469 case 0xfff8:
470 return false;
471 }
472 break;
473 }
474 return true;
475}
476
477/* Return whether the pointed-at modified-UTF-8 encoded character is
478 * valid as part of a member name, updating the pointer to point past
479 * the consumed character. This will consume two encoded UTF-16 code
480 * points if the character is encoded as a surrogate pair. Also, if
481 * this function returns false, then the given pointer may only have
482 * been partially advanced.
483 */
jeffhao10037c82012-01-23 15:06:23 -0800484bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700485 uint8_t c = (uint8_t) **pUtf8Ptr;
486 if (c <= 0x7f) {
487 // It's low-ascii, so check the table.
488 uint32_t wordIdx = c >> 5;
489 uint32_t bitIdx = c & 0x1f;
490 (*pUtf8Ptr)++;
491 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
492 }
493
494 // It's a multibyte encoded character. Call a non-inline function
495 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800496 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
497}
498
499bool IsValidMemberName(const char* s) {
500 bool angle_name = false;
501
502 switch(*s) {
503 case '\0':
504 // The empty string is not a valid name.
505 return false;
506 case '<':
507 angle_name = true;
508 s++;
509 break;
510 }
511
512 while (true) {
513 switch (*s) {
514 case '\0':
515 return !angle_name;
516 case '>':
517 return angle_name && s[1] == '\0';
518 }
519
520 if (!IsValidPartOfMemberNameUtf8(&s)) {
521 return false;
522 }
523 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700524}
525
Elliott Hughes906e6852011-10-28 14:52:10 -0700526enum ClassNameType { kName, kDescriptor };
527bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700528 int arrayCount = 0;
529 while (*s == '[') {
530 arrayCount++;
531 s++;
532 }
533
534 if (arrayCount > 255) {
535 // Arrays may have no more than 255 dimensions.
536 return false;
537 }
538
539 if (arrayCount != 0) {
540 /*
541 * If we're looking at an array of some sort, then it doesn't
542 * matter if what is being asked for is a class name; the
543 * format looks the same as a type descriptor in that case, so
544 * treat it as such.
545 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700546 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700547 }
548
Elliott Hughes906e6852011-10-28 14:52:10 -0700549 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700550 /*
551 * We are looking for a descriptor. Either validate it as a
552 * single-character primitive type, or continue on to check the
553 * embedded class name (bracketed by "L" and ";").
554 */
555 switch (*(s++)) {
556 case 'B':
557 case 'C':
558 case 'D':
559 case 'F':
560 case 'I':
561 case 'J':
562 case 'S':
563 case 'Z':
564 // These are all single-character descriptors for primitive types.
565 return (*s == '\0');
566 case 'V':
567 // Non-array void is valid, but you can't have an array of void.
568 return (arrayCount == 0) && (*s == '\0');
569 case 'L':
570 // Class name: Break out and continue below.
571 break;
572 default:
573 // Oddball descriptor character.
574 return false;
575 }
576 }
577
578 /*
579 * We just consumed the 'L' that introduces a class name as part
580 * of a type descriptor, or we are looking for an unadorned class
581 * name.
582 */
583
584 bool sepOrFirst = true; // first character or just encountered a separator.
585 for (;;) {
586 uint8_t c = (uint8_t) *s;
587 switch (c) {
588 case '\0':
589 /*
590 * Premature end for a type descriptor, but valid for
591 * a class name as long as we haven't encountered an
592 * empty component (including the degenerate case of
593 * the empty string "").
594 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700595 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700596 case ';':
597 /*
598 * Invalid character for a class name, but the
599 * legitimate end of a type descriptor. In the latter
600 * case, make sure that this is the end of the string
601 * and that it doesn't end with an empty component
602 * (including the degenerate case of "L;").
603 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700604 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700605 case '/':
606 case '.':
607 if (c != separator) {
608 // The wrong separator character.
609 return false;
610 }
611 if (sepOrFirst) {
612 // Separator at start or two separators in a row.
613 return false;
614 }
615 sepOrFirst = true;
616 s++;
617 break;
618 default:
jeffhao10037c82012-01-23 15:06:23 -0800619 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700620 return false;
621 }
622 sepOrFirst = false;
623 break;
624 }
625 }
626}
627
Elliott Hughes906e6852011-10-28 14:52:10 -0700628bool IsValidBinaryClassName(const char* s) {
629 return IsValidClassName(s, kName, '.');
630}
631
632bool IsValidJniClassName(const char* s) {
633 return IsValidClassName(s, kName, '/');
634}
635
636bool IsValidDescriptor(const char* s) {
637 return IsValidClassName(s, kDescriptor, '/');
638}
639
Elliott Hughes48436bb2012-02-07 15:23:28 -0800640void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700641 const char* p = s.data();
642 const char* end = p + s.size();
643 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800644 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700645 ++p;
646 } else {
647 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800648 while (++p != end && *p != separator) {
649 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700650 }
651 result.push_back(std::string(start, p - start));
652 }
653 }
654}
655
Elliott Hughes48436bb2012-02-07 15:23:28 -0800656template <typename StringT>
657std::string Join(std::vector<StringT>& strings, char separator) {
658 if (strings.empty()) {
659 return "";
660 }
661
662 std::string result(strings[0]);
663 for (size_t i = 1; i < strings.size(); ++i) {
664 result += separator;
665 result += strings[i];
666 }
667 return result;
668}
669
670// Explicit instantiations.
671template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
672template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
673template std::string Join<char*>(std::vector<char*>& strings, char separator);
674
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800675bool StartsWith(const std::string& s, const char* prefix) {
676 return s.compare(0, strlen(prefix), prefix) == 0;
677}
678
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800679void SetThreadName(const char* threadName) {
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800680 ANNOTATE_THREAD_NAME(threadName); // For tsan.
681
Elliott Hughesdcc24742011-09-07 14:02:44 -0700682 int hasAt = 0;
683 int hasDot = 0;
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800684 const char* s = threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700685 while (*s) {
686 if (*s == '.') {
687 hasDot = 1;
688 } else if (*s == '@') {
689 hasAt = 1;
690 }
691 s++;
692 }
693 int len = s - threadName;
694 if (len < 15 || hasAt || !hasDot) {
695 s = threadName;
696 } else {
697 s = threadName + len - 15;
698 }
699#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
700 /* pthread_setname_np fails rather than truncating long strings */
701 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
702 strncpy(buf, s, sizeof(buf)-1);
703 buf[sizeof(buf)-1] = '\0';
704 errno = pthread_setname_np(pthread_self(), buf);
705 if (errno != 0) {
706 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
707 }
708#elif defined(HAVE_PRCTL)
709 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
710#else
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800711 UNIMPLEMENTED(WARNING) << threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700712#endif
713}
714
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700715void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
716 utime = stime = task_cpu = 0;
717 std::string stats;
718 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
719 return;
720 }
721 // Skip the command, which may contain spaces.
722 stats = stats.substr(stats.find(')') + 2);
723 // Extract the three fields we care about.
724 std::vector<std::string> fields;
725 Split(stats, ' ', fields);
726 utime = strtoull(fields[11].c_str(), NULL, 10);
727 stime = strtoull(fields[12].c_str(), NULL, 10);
728 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
729}
730
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800731const char* GetAndroidRoot() {
732 const char* android_root = getenv("ANDROID_ROOT");
733 if (android_root == NULL) {
734 if (OS::DirectoryExists("/system")) {
735 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700736 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800737 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
738 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700739 }
740 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800741 if (!OS::DirectoryExists(android_root)) {
742 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700743 return "";
744 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800745 return android_root;
746}
Brian Carlstroma9f19782011-10-13 00:14:47 -0700747
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800748const char* GetAndroidData() {
749 const char* android_data = getenv("ANDROID_DATA");
750 if (android_data == NULL) {
751 if (OS::DirectoryExists("/data")) {
752 android_data = "/data";
753 } else {
754 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
755 return "";
756 }
757 }
758 if (!OS::DirectoryExists(android_data)) {
759 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
760 return "";
761 }
762 return android_data;
763}
764
765std::string GetArtCacheOrDie() {
766 std::string art_cache(StringPrintf("%s/art-cache", GetAndroidData()));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700767
768 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800769 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700770 int result = mkdir(art_cache.c_str(), 0700);
771 if (result != 0) {
772 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
773 return "";
774 }
775 } else {
776 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
777 return "";
778 }
779 }
780 return art_cache;
781}
782
jeffhao262bf462011-10-20 18:36:32 -0700783std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800784 std::string art_cache(GetArtCacheOrDie());
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700785 CHECK_EQ(location[0], '/');
786 std::string cache_file(location, 1); // skip leading slash
787 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
788 return art_cache + "/" + cache_file;
789}
790
jeffhao262bf462011-10-20 18:36:32 -0700791bool IsValidZipFilename(const std::string& filename) {
792 if (filename.size() < 4) {
793 return false;
794 }
795 std::string suffix(filename.substr(filename.size() - 4));
796 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
797}
798
799bool IsValidDexFilename(const std::string& filename) {
800 if (filename.size() < 4) {
801 return false;
802 }
803 std::string suffix(filename.substr(filename.size() - 4));
804 return (suffix == ".dex");
805}
806
Elliott Hughes42ee1422011-09-06 12:33:32 -0700807} // namespace art