blob: cf3e6c322319b9ef0cb3feaa70863bfd616aba91 [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) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800378 size_t length = strlen(descriptor);
379 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
380 std::string result(descriptor + 1, length - 2);
381 std::replace(result.begin(), result.end(), '/', '.');
382 return result;
383 }
384 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800385}
386
387std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800388 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800389 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
390 std::string result(descriptor + 1, length - 2);
391 return result;
392 }
393 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700394}
395
Elliott Hughes79082e32011-08-25 12:07:32 -0700396std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800397 MethodHelper mh(m);
398 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700399 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700400 CHECK_EQ(class_name[0], 'L') << class_name;
401 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700402 class_name.erase(0, 1);
403 class_name.erase(class_name.size() - 1, 1);
404
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800405 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700406
407 std::string short_name;
408 short_name += "Java_";
409 short_name += MangleForJni(class_name);
410 short_name += "_";
411 short_name += MangleForJni(method_name);
412 return short_name;
413}
414
415std::string JniLongName(const Method* m) {
416 std::string long_name;
417 long_name += JniShortName(m);
418 long_name += "__";
419
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800420 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700421 signature.erase(0, 1);
422 signature.erase(signature.begin() + signature.find(')'), signature.end());
423
424 long_name += MangleForJni(signature);
425
426 return long_name;
427}
428
jeffhao10037c82012-01-23 15:06:23 -0800429// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700430uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
431 0x00000000, // 00..1f low control characters; nothing valid
432 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
433 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
434 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
435};
436
jeffhao10037c82012-01-23 15:06:23 -0800437// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
438bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700439 /*
440 * It's a multibyte encoded character. Decode it and analyze. We
441 * accept anything that isn't (a) an improperly encoded low value,
442 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
443 * control character, or (e) a high space, layout, or special
444 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
445 * U+fff0..U+ffff). This is all specified in the dex format
446 * document.
447 */
448
449 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
450
451 // Perform follow-up tests based on the high 8 bits.
452 switch (utf16 >> 8) {
453 case 0x00:
454 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
455 return (utf16 > 0x00a0);
456 case 0xd8:
457 case 0xd9:
458 case 0xda:
459 case 0xdb:
460 // It's a leading surrogate. Check to see that a trailing
461 // surrogate follows.
462 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
463 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
464 case 0xdc:
465 case 0xdd:
466 case 0xde:
467 case 0xdf:
468 // It's a trailing surrogate, which is not valid at this point.
469 return false;
470 case 0x20:
471 case 0xff:
472 // It's in the range that has spaces, controls, and specials.
473 switch (utf16 & 0xfff8) {
474 case 0x2000:
475 case 0x2008:
476 case 0x2028:
477 case 0xfff0:
478 case 0xfff8:
479 return false;
480 }
481 break;
482 }
483 return true;
484}
485
486/* Return whether the pointed-at modified-UTF-8 encoded character is
487 * valid as part of a member name, updating the pointer to point past
488 * the consumed character. This will consume two encoded UTF-16 code
489 * points if the character is encoded as a surrogate pair. Also, if
490 * this function returns false, then the given pointer may only have
491 * been partially advanced.
492 */
jeffhao10037c82012-01-23 15:06:23 -0800493bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700494 uint8_t c = (uint8_t) **pUtf8Ptr;
495 if (c <= 0x7f) {
496 // It's low-ascii, so check the table.
497 uint32_t wordIdx = c >> 5;
498 uint32_t bitIdx = c & 0x1f;
499 (*pUtf8Ptr)++;
500 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
501 }
502
503 // It's a multibyte encoded character. Call a non-inline function
504 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800505 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
506}
507
508bool IsValidMemberName(const char* s) {
509 bool angle_name = false;
510
511 switch(*s) {
512 case '\0':
513 // The empty string is not a valid name.
514 return false;
515 case '<':
516 angle_name = true;
517 s++;
518 break;
519 }
520
521 while (true) {
522 switch (*s) {
523 case '\0':
524 return !angle_name;
525 case '>':
526 return angle_name && s[1] == '\0';
527 }
528
529 if (!IsValidPartOfMemberNameUtf8(&s)) {
530 return false;
531 }
532 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700533}
534
Elliott Hughes906e6852011-10-28 14:52:10 -0700535enum ClassNameType { kName, kDescriptor };
536bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700537 int arrayCount = 0;
538 while (*s == '[') {
539 arrayCount++;
540 s++;
541 }
542
543 if (arrayCount > 255) {
544 // Arrays may have no more than 255 dimensions.
545 return false;
546 }
547
548 if (arrayCount != 0) {
549 /*
550 * If we're looking at an array of some sort, then it doesn't
551 * matter if what is being asked for is a class name; the
552 * format looks the same as a type descriptor in that case, so
553 * treat it as such.
554 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700555 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700556 }
557
Elliott Hughes906e6852011-10-28 14:52:10 -0700558 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700559 /*
560 * We are looking for a descriptor. Either validate it as a
561 * single-character primitive type, or continue on to check the
562 * embedded class name (bracketed by "L" and ";").
563 */
564 switch (*(s++)) {
565 case 'B':
566 case 'C':
567 case 'D':
568 case 'F':
569 case 'I':
570 case 'J':
571 case 'S':
572 case 'Z':
573 // These are all single-character descriptors for primitive types.
574 return (*s == '\0');
575 case 'V':
576 // Non-array void is valid, but you can't have an array of void.
577 return (arrayCount == 0) && (*s == '\0');
578 case 'L':
579 // Class name: Break out and continue below.
580 break;
581 default:
582 // Oddball descriptor character.
583 return false;
584 }
585 }
586
587 /*
588 * We just consumed the 'L' that introduces a class name as part
589 * of a type descriptor, or we are looking for an unadorned class
590 * name.
591 */
592
593 bool sepOrFirst = true; // first character or just encountered a separator.
594 for (;;) {
595 uint8_t c = (uint8_t) *s;
596 switch (c) {
597 case '\0':
598 /*
599 * Premature end for a type descriptor, but valid for
600 * a class name as long as we haven't encountered an
601 * empty component (including the degenerate case of
602 * the empty string "").
603 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700604 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700605 case ';':
606 /*
607 * Invalid character for a class name, but the
608 * legitimate end of a type descriptor. In the latter
609 * case, make sure that this is the end of the string
610 * and that it doesn't end with an empty component
611 * (including the degenerate case of "L;").
612 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700613 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700614 case '/':
615 case '.':
616 if (c != separator) {
617 // The wrong separator character.
618 return false;
619 }
620 if (sepOrFirst) {
621 // Separator at start or two separators in a row.
622 return false;
623 }
624 sepOrFirst = true;
625 s++;
626 break;
627 default:
jeffhao10037c82012-01-23 15:06:23 -0800628 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700629 return false;
630 }
631 sepOrFirst = false;
632 break;
633 }
634 }
635}
636
Elliott Hughes906e6852011-10-28 14:52:10 -0700637bool IsValidBinaryClassName(const char* s) {
638 return IsValidClassName(s, kName, '.');
639}
640
641bool IsValidJniClassName(const char* s) {
642 return IsValidClassName(s, kName, '/');
643}
644
645bool IsValidDescriptor(const char* s) {
646 return IsValidClassName(s, kDescriptor, '/');
647}
648
Elliott Hughes48436bb2012-02-07 15:23:28 -0800649void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700650 const char* p = s.data();
651 const char* end = p + s.size();
652 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800653 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700654 ++p;
655 } else {
656 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800657 while (++p != end && *p != separator) {
658 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700659 }
660 result.push_back(std::string(start, p - start));
661 }
662 }
663}
664
Elliott Hughes48436bb2012-02-07 15:23:28 -0800665template <typename StringT>
666std::string Join(std::vector<StringT>& strings, char separator) {
667 if (strings.empty()) {
668 return "";
669 }
670
671 std::string result(strings[0]);
672 for (size_t i = 1; i < strings.size(); ++i) {
673 result += separator;
674 result += strings[i];
675 }
676 return result;
677}
678
679// Explicit instantiations.
680template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
681template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
682template std::string Join<char*>(std::vector<char*>& strings, char separator);
683
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800684bool StartsWith(const std::string& s, const char* prefix) {
685 return s.compare(0, strlen(prefix), prefix) == 0;
686}
687
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800688void SetThreadName(const char* threadName) {
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800689 ANNOTATE_THREAD_NAME(threadName); // For tsan.
690
Elliott Hughesdcc24742011-09-07 14:02:44 -0700691 int hasAt = 0;
692 int hasDot = 0;
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800693 const char* s = threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700694 while (*s) {
695 if (*s == '.') {
696 hasDot = 1;
697 } else if (*s == '@') {
698 hasAt = 1;
699 }
700 s++;
701 }
702 int len = s - threadName;
703 if (len < 15 || hasAt || !hasDot) {
704 s = threadName;
705 } else {
706 s = threadName + len - 15;
707 }
708#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700709 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700710 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
711 strncpy(buf, s, sizeof(buf)-1);
712 buf[sizeof(buf)-1] = '\0';
713 errno = pthread_setname_np(pthread_self(), buf);
714 if (errno != 0) {
715 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
716 }
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700717#elif defined(__APPLE__)
718 pthread_setname_np(threadName);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700719#elif defined(HAVE_PRCTL)
720 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
721#else
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800722 UNIMPLEMENTED(WARNING) << threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700723#endif
724}
725
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700726void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
727 utime = stime = task_cpu = 0;
728 std::string stats;
729 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
730 return;
731 }
732 // Skip the command, which may contain spaces.
733 stats = stats.substr(stats.find(')') + 2);
734 // Extract the three fields we care about.
735 std::vector<std::string> fields;
736 Split(stats, ' ', fields);
737 utime = strtoull(fields[11].c_str(), NULL, 10);
738 stime = strtoull(fields[12].c_str(), NULL, 10);
739 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
740}
741
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800742const char* GetAndroidRoot() {
743 const char* android_root = getenv("ANDROID_ROOT");
744 if (android_root == NULL) {
745 if (OS::DirectoryExists("/system")) {
746 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700747 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800748 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
749 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700750 }
751 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800752 if (!OS::DirectoryExists(android_root)) {
753 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700754 return "";
755 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800756 return android_root;
757}
Brian Carlstroma9f19782011-10-13 00:14:47 -0700758
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800759const char* GetAndroidData() {
760 const char* android_data = getenv("ANDROID_DATA");
761 if (android_data == NULL) {
762 if (OS::DirectoryExists("/data")) {
763 android_data = "/data";
764 } else {
765 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
766 return "";
767 }
768 }
769 if (!OS::DirectoryExists(android_data)) {
770 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
771 return "";
772 }
773 return android_data;
774}
775
776std::string GetArtCacheOrDie() {
777 std::string art_cache(StringPrintf("%s/art-cache", GetAndroidData()));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700778
779 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800780 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700781 int result = mkdir(art_cache.c_str(), 0700);
782 if (result != 0) {
783 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
784 return "";
785 }
786 } else {
787 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
788 return "";
789 }
790 }
791 return art_cache;
792}
793
jeffhao262bf462011-10-20 18:36:32 -0700794std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800795 std::string art_cache(GetArtCacheOrDie());
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800796 CHECK_EQ(location[0], '/') << location;
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700797 std::string cache_file(location, 1); // skip leading slash
798 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
799 return art_cache + "/" + cache_file;
800}
801
jeffhao262bf462011-10-20 18:36:32 -0700802bool IsValidZipFilename(const std::string& filename) {
803 if (filename.size() < 4) {
804 return false;
805 }
806 std::string suffix(filename.substr(filename.size() - 4));
807 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
808}
809
810bool IsValidDexFilename(const std::string& filename) {
811 if (filename.size() < 4) {
812 return false;
813 }
814 std::string suffix(filename.substr(filename.size() - 4));
815 return (suffix == ".dex");
816}
817
Elliott Hughes42ee1422011-09-06 12:33:32 -0700818} // namespace art