blob: f599c0e76e04c9837bff569476157eb966e49f7a [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 Hughes91bf6cd2012-02-14 17:27:48 -0800378 std::string result(DescriptorToName(descriptor));
379 std::replace(result.begin(), result.end(), '/', '.');
380 return result;
381}
382
383std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800384 size_t length = strlen(descriptor);
385 DCHECK_GT(length, 0U);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700386 DCHECK_EQ(descriptor[0], 'L');
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800387 DCHECK_EQ(descriptor[length - 1], ';');
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800388 std::string result(descriptor + 1, length - 2);
389 return result;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700390}
391
Elliott Hughes79082e32011-08-25 12:07:32 -0700392std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800393 MethodHelper mh(m);
394 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700395 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700396 CHECK_EQ(class_name[0], 'L') << class_name;
397 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700398 class_name.erase(0, 1);
399 class_name.erase(class_name.size() - 1, 1);
400
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800401 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700402
403 std::string short_name;
404 short_name += "Java_";
405 short_name += MangleForJni(class_name);
406 short_name += "_";
407 short_name += MangleForJni(method_name);
408 return short_name;
409}
410
411std::string JniLongName(const Method* m) {
412 std::string long_name;
413 long_name += JniShortName(m);
414 long_name += "__";
415
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800416 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700417 signature.erase(0, 1);
418 signature.erase(signature.begin() + signature.find(')'), signature.end());
419
420 long_name += MangleForJni(signature);
421
422 return long_name;
423}
424
jeffhao10037c82012-01-23 15:06:23 -0800425// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700426uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
427 0x00000000, // 00..1f low control characters; nothing valid
428 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
429 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
430 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
431};
432
jeffhao10037c82012-01-23 15:06:23 -0800433// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
434bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700435 /*
436 * It's a multibyte encoded character. Decode it and analyze. We
437 * accept anything that isn't (a) an improperly encoded low value,
438 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
439 * control character, or (e) a high space, layout, or special
440 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
441 * U+fff0..U+ffff). This is all specified in the dex format
442 * document.
443 */
444
445 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
446
447 // Perform follow-up tests based on the high 8 bits.
448 switch (utf16 >> 8) {
449 case 0x00:
450 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
451 return (utf16 > 0x00a0);
452 case 0xd8:
453 case 0xd9:
454 case 0xda:
455 case 0xdb:
456 // It's a leading surrogate. Check to see that a trailing
457 // surrogate follows.
458 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
459 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
460 case 0xdc:
461 case 0xdd:
462 case 0xde:
463 case 0xdf:
464 // It's a trailing surrogate, which is not valid at this point.
465 return false;
466 case 0x20:
467 case 0xff:
468 // It's in the range that has spaces, controls, and specials.
469 switch (utf16 & 0xfff8) {
470 case 0x2000:
471 case 0x2008:
472 case 0x2028:
473 case 0xfff0:
474 case 0xfff8:
475 return false;
476 }
477 break;
478 }
479 return true;
480}
481
482/* Return whether the pointed-at modified-UTF-8 encoded character is
483 * valid as part of a member name, updating the pointer to point past
484 * the consumed character. This will consume two encoded UTF-16 code
485 * points if the character is encoded as a surrogate pair. Also, if
486 * this function returns false, then the given pointer may only have
487 * been partially advanced.
488 */
jeffhao10037c82012-01-23 15:06:23 -0800489bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700490 uint8_t c = (uint8_t) **pUtf8Ptr;
491 if (c <= 0x7f) {
492 // It's low-ascii, so check the table.
493 uint32_t wordIdx = c >> 5;
494 uint32_t bitIdx = c & 0x1f;
495 (*pUtf8Ptr)++;
496 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
497 }
498
499 // It's a multibyte encoded character. Call a non-inline function
500 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800501 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
502}
503
504bool IsValidMemberName(const char* s) {
505 bool angle_name = false;
506
507 switch(*s) {
508 case '\0':
509 // The empty string is not a valid name.
510 return false;
511 case '<':
512 angle_name = true;
513 s++;
514 break;
515 }
516
517 while (true) {
518 switch (*s) {
519 case '\0':
520 return !angle_name;
521 case '>':
522 return angle_name && s[1] == '\0';
523 }
524
525 if (!IsValidPartOfMemberNameUtf8(&s)) {
526 return false;
527 }
528 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700529}
530
Elliott Hughes906e6852011-10-28 14:52:10 -0700531enum ClassNameType { kName, kDescriptor };
532bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700533 int arrayCount = 0;
534 while (*s == '[') {
535 arrayCount++;
536 s++;
537 }
538
539 if (arrayCount > 255) {
540 // Arrays may have no more than 255 dimensions.
541 return false;
542 }
543
544 if (arrayCount != 0) {
545 /*
546 * If we're looking at an array of some sort, then it doesn't
547 * matter if what is being asked for is a class name; the
548 * format looks the same as a type descriptor in that case, so
549 * treat it as such.
550 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700551 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700552 }
553
Elliott Hughes906e6852011-10-28 14:52:10 -0700554 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700555 /*
556 * We are looking for a descriptor. Either validate it as a
557 * single-character primitive type, or continue on to check the
558 * embedded class name (bracketed by "L" and ";").
559 */
560 switch (*(s++)) {
561 case 'B':
562 case 'C':
563 case 'D':
564 case 'F':
565 case 'I':
566 case 'J':
567 case 'S':
568 case 'Z':
569 // These are all single-character descriptors for primitive types.
570 return (*s == '\0');
571 case 'V':
572 // Non-array void is valid, but you can't have an array of void.
573 return (arrayCount == 0) && (*s == '\0');
574 case 'L':
575 // Class name: Break out and continue below.
576 break;
577 default:
578 // Oddball descriptor character.
579 return false;
580 }
581 }
582
583 /*
584 * We just consumed the 'L' that introduces a class name as part
585 * of a type descriptor, or we are looking for an unadorned class
586 * name.
587 */
588
589 bool sepOrFirst = true; // first character or just encountered a separator.
590 for (;;) {
591 uint8_t c = (uint8_t) *s;
592 switch (c) {
593 case '\0':
594 /*
595 * Premature end for a type descriptor, but valid for
596 * a class name as long as we haven't encountered an
597 * empty component (including the degenerate case of
598 * the empty string "").
599 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700600 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700601 case ';':
602 /*
603 * Invalid character for a class name, but the
604 * legitimate end of a type descriptor. In the latter
605 * case, make sure that this is the end of the string
606 * and that it doesn't end with an empty component
607 * (including the degenerate case of "L;").
608 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700609 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700610 case '/':
611 case '.':
612 if (c != separator) {
613 // The wrong separator character.
614 return false;
615 }
616 if (sepOrFirst) {
617 // Separator at start or two separators in a row.
618 return false;
619 }
620 sepOrFirst = true;
621 s++;
622 break;
623 default:
jeffhao10037c82012-01-23 15:06:23 -0800624 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700625 return false;
626 }
627 sepOrFirst = false;
628 break;
629 }
630 }
631}
632
Elliott Hughes906e6852011-10-28 14:52:10 -0700633bool IsValidBinaryClassName(const char* s) {
634 return IsValidClassName(s, kName, '.');
635}
636
637bool IsValidJniClassName(const char* s) {
638 return IsValidClassName(s, kName, '/');
639}
640
641bool IsValidDescriptor(const char* s) {
642 return IsValidClassName(s, kDescriptor, '/');
643}
644
Elliott Hughes48436bb2012-02-07 15:23:28 -0800645void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700646 const char* p = s.data();
647 const char* end = p + s.size();
648 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800649 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700650 ++p;
651 } else {
652 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800653 while (++p != end && *p != separator) {
654 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700655 }
656 result.push_back(std::string(start, p - start));
657 }
658 }
659}
660
Elliott Hughes48436bb2012-02-07 15:23:28 -0800661template <typename StringT>
662std::string Join(std::vector<StringT>& strings, char separator) {
663 if (strings.empty()) {
664 return "";
665 }
666
667 std::string result(strings[0]);
668 for (size_t i = 1; i < strings.size(); ++i) {
669 result += separator;
670 result += strings[i];
671 }
672 return result;
673}
674
675// Explicit instantiations.
676template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
677template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
678template std::string Join<char*>(std::vector<char*>& strings, char separator);
679
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800680bool StartsWith(const std::string& s, const char* prefix) {
681 return s.compare(0, strlen(prefix), prefix) == 0;
682}
683
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800684void SetThreadName(const char* threadName) {
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800685 ANNOTATE_THREAD_NAME(threadName); // For tsan.
686
Elliott Hughesdcc24742011-09-07 14:02:44 -0700687 int hasAt = 0;
688 int hasDot = 0;
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800689 const char* s = threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700690 while (*s) {
691 if (*s == '.') {
692 hasDot = 1;
693 } else if (*s == '@') {
694 hasAt = 1;
695 }
696 s++;
697 }
698 int len = s - threadName;
699 if (len < 15 || hasAt || !hasDot) {
700 s = threadName;
701 } else {
702 s = threadName + len - 15;
703 }
704#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
705 /* pthread_setname_np fails rather than truncating long strings */
706 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
707 strncpy(buf, s, sizeof(buf)-1);
708 buf[sizeof(buf)-1] = '\0';
709 errno = pthread_setname_np(pthread_self(), buf);
710 if (errno != 0) {
711 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
712 }
713#elif defined(HAVE_PRCTL)
714 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
715#else
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800716 UNIMPLEMENTED(WARNING) << threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700717#endif
718}
719
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700720void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
721 utime = stime = task_cpu = 0;
722 std::string stats;
723 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
724 return;
725 }
726 // Skip the command, which may contain spaces.
727 stats = stats.substr(stats.find(')') + 2);
728 // Extract the three fields we care about.
729 std::vector<std::string> fields;
730 Split(stats, ' ', fields);
731 utime = strtoull(fields[11].c_str(), NULL, 10);
732 stime = strtoull(fields[12].c_str(), NULL, 10);
733 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
734}
735
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800736const char* GetAndroidRoot() {
737 const char* android_root = getenv("ANDROID_ROOT");
738 if (android_root == NULL) {
739 if (OS::DirectoryExists("/system")) {
740 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700741 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800742 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
743 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700744 }
745 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800746 if (!OS::DirectoryExists(android_root)) {
747 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700748 return "";
749 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800750 return android_root;
751}
Brian Carlstroma9f19782011-10-13 00:14:47 -0700752
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800753const char* GetAndroidData() {
754 const char* android_data = getenv("ANDROID_DATA");
755 if (android_data == NULL) {
756 if (OS::DirectoryExists("/data")) {
757 android_data = "/data";
758 } else {
759 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
760 return "";
761 }
762 }
763 if (!OS::DirectoryExists(android_data)) {
764 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
765 return "";
766 }
767 return android_data;
768}
769
770std::string GetArtCacheOrDie() {
771 std::string art_cache(StringPrintf("%s/art-cache", GetAndroidData()));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700772
773 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800774 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700775 int result = mkdir(art_cache.c_str(), 0700);
776 if (result != 0) {
777 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
778 return "";
779 }
780 } else {
781 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
782 return "";
783 }
784 }
785 return art_cache;
786}
787
jeffhao262bf462011-10-20 18:36:32 -0700788std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800789 std::string art_cache(GetArtCacheOrDie());
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700790 CHECK_EQ(location[0], '/');
791 std::string cache_file(location, 1); // skip leading slash
792 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
793 return art_cache + "/" + cache_file;
794}
795
jeffhao262bf462011-10-20 18:36:32 -0700796bool IsValidZipFilename(const std::string& filename) {
797 if (filename.size() < 4) {
798 return false;
799 }
800 std::string suffix(filename.substr(filename.size() - 4));
801 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
802}
803
804bool IsValidDexFilename(const std::string& filename) {
805 if (filename.size() < 4) {
806 return false;
807 }
808 std::string suffix(filename.substr(filename.size() - 4));
809 return (suffix == ".dex");
810}
811
Elliott Hughes42ee1422011-09-06 12:33:32 -0700812} // namespace art