blob: 4895fe5a5b45164991426cfd743adb2c4488dbec [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 Hughes4ae722a2012-03-13 11:08:51 -070041#if defined(__APPLE__)
42#include "AvailabilityMacros.h"
43#endif
44
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080045#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080046#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080047#endif
48
Elliott Hughes11e45072011-08-16 17:40:46 -070049namespace art {
50
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080051pid_t GetTid() {
52#if defined(__APPLE__)
53 // Mac OS doesn't have gettid(2).
54 return getpid();
55#else
56 // Neither bionic nor glibc exposes gettid(2).
57 return syscall(__NR_gettid);
58#endif
59}
60
Elliott Hughesd92bec42011-09-02 17:04:36 -070061bool ReadFileToString(const std::string& file_name, std::string* result) {
62 UniquePtr<File> file(OS::OpenFile(file_name.c_str(), false));
63 if (file.get() == NULL) {
64 return false;
65 }
buzbeec143c552011-08-20 17:38:58 -070066
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070067 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -070068 while (true) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070069 int64_t n = file->Read(&buf[0], buf.size());
Elliott Hughesd92bec42011-09-02 17:04:36 -070070 if (n == -1) {
71 return false;
buzbeec143c552011-08-20 17:38:58 -070072 }
Elliott Hughesd92bec42011-09-02 17:04:36 -070073 if (n == 0) {
74 return true;
75 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070076 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -070077 }
buzbeec143c552011-08-20 17:38:58 -070078}
79
Elliott Hughese27955c2011-08-26 15:21:24 -070080std::string GetIsoDate() {
81 time_t now = time(NULL);
82 struct tm tmbuf;
83 struct tm* ptm = localtime_r(&now, &tmbuf);
84 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
85 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
86 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
87}
88
Elliott Hughes7162ad92011-10-27 14:08:42 -070089uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -080090#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7162ad92011-10-27 14:08:42 -070091 struct timespec now;
92 clock_gettime(CLOCK_MONOTONIC, &now);
93 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -080094#else
95 struct timeval now;
96 gettimeofday(&now, NULL);
97 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
98#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -070099}
100
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800101uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800102#if defined(HAVE_POSIX_CLOCKS)
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800103 struct timespec now;
104 clock_gettime(CLOCK_MONOTONIC, &now);
105 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800106#else
107 struct timeval now;
108 gettimeofday(&now, NULL);
109 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec * 1000LL;
110#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800111}
112
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700113uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800114#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700115 struct timespec now;
116 clock_gettime(CLOCK_MONOTONIC, &now);
117 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800118#else
119 struct timeval now;
120 gettimeofday(&now, NULL);
121 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
122#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700123}
124
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800125uint64_t ThreadCpuMicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800126#if defined(HAVE_POSIX_CLOCKS)
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800127 struct timespec now;
128 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
129 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800130#else
131 UNIMPLEMENTED(WARNING);
132 return -1;
133#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800134}
135
Elliott Hughes5174fe62011-08-23 15:12:35 -0700136std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700137 if (java_descriptor == NULL) {
138 return "null";
139 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700140 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
141}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700142
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800143std::string PrettyDescriptor(const Class* klass) {
144 if (klass == NULL) {
145 return "null";
146 }
147 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800148}
149
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700150std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700151 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700152 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700153 size_t dim = 0;
154 while (*c == '[') {
155 dim++;
156 c++;
157 }
158
159 // Reference or primitive?
160 if (*c == 'L') {
161 // "[[La/b/C;" -> "a.b.C[][]".
162 c++; // Skip the 'L'.
163 } else {
164 // "[[B" -> "byte[][]".
165 // To make life easier, we make primitives look like unqualified
166 // reference types.
167 switch (*c) {
168 case 'B': c = "byte;"; break;
169 case 'C': c = "char;"; break;
170 case 'D': c = "double;"; break;
171 case 'F': c = "float;"; break;
172 case 'I': c = "int;"; break;
173 case 'J': c = "long;"; break;
174 case 'S': c = "short;"; break;
175 case 'Z': c = "boolean;"; break;
Elliott Hughes5174fe62011-08-23 15:12:35 -0700176 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700177 }
178 }
179
180 // At this point, 'c' is a string of the form "fully/qualified/Type;"
181 // or "primitive;". Rewrite the type with '.' instead of '/':
182 std::string result;
183 const char* p = c;
184 while (*p != ';') {
185 char ch = *p++;
186 if (ch == '/') {
187 ch = '.';
188 }
189 result.push_back(ch);
190 }
191 // ...and replace the semicolon with 'dim' "[]" pairs:
192 while (dim--) {
193 result += "[]";
194 }
195 return result;
196}
197
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700198std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800199 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700200 return PrettyDescriptor(descriptor_string);
201}
202
Elliott Hughes54e7df12011-09-16 11:47:04 -0700203std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700204 if (f == NULL) {
205 return "null";
206 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800207 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700208 std::string result;
209 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800210 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700211 result += ' ';
212 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800213 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700214 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800215 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700216 return result;
217}
218
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700219std::string PrettyMethod(const Method* m, bool with_signature) {
220 if (m == NULL) {
221 return "null";
222 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800223 MethodHelper mh(m);
224 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700225 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800226 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700227 if (with_signature) {
228 // TODO: iterate over the signature's elements and pass them all to
229 // PrettyDescriptor? We'd need to pull out the return type specially, too.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800230 result += mh.GetSignature();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700231 }
232 return result;
233}
234
Ian Rogers0571d352011-11-03 19:51:38 -0700235std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
236 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
237 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
238 result += '.';
239 result += dex_file.GetMethodName(method_id);
240 if (with_signature) {
241 // TODO: iterate over the signature's elements and pass them all to
242 // PrettyDescriptor? We'd need to pull out the return type specially, too.
243 result += dex_file.GetMethodSignature(method_id);
244 }
245 return result;
246}
247
Elliott Hughes54e7df12011-09-16 11:47:04 -0700248std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700249 if (obj == NULL) {
250 return "null";
251 }
252 if (obj->GetClass() == NULL) {
253 return "(raw)";
254 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800255 ClassHelper kh(obj->GetClass());
256 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700257 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800258 kh.ChangeClass(obj->AsClass());
259 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700260 }
261 return result;
262}
263
Elliott Hughes54e7df12011-09-16 11:47:04 -0700264std::string PrettyClass(const Class* c) {
265 if (c == NULL) {
266 return "null";
267 }
268 std::string result;
269 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800270 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700271 result += ">";
272 return result;
273}
274
Ian Rogersd81871c2011-10-03 13:57:23 -0700275std::string PrettyClassAndClassLoader(const Class* c) {
276 if (c == NULL) {
277 return "null";
278 }
279 std::string result;
280 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800281 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700282 result += ",";
283 result += PrettyTypeOf(c->GetClassLoader());
284 // TODO: add an identifying hash value for the loader
285 result += ">";
286 return result;
287}
288
Ian Rogers3bb17a62012-01-27 23:56:44 -0800289std::string PrettySize(size_t size_in_bytes) {
290 if ((size_in_bytes / GB) * GB == size_in_bytes) {
291 return StringPrintf("%zdGB", size_in_bytes / GB);
292 } else if ((size_in_bytes / MB) * MB == size_in_bytes) {
293 return StringPrintf("%zdMB", size_in_bytes / MB);
294 } else if ((size_in_bytes / KB) * KB == size_in_bytes) {
295 return StringPrintf("%zdKiB", size_in_bytes / KB);
296 } else {
297 return StringPrintf("%zdB", size_in_bytes);
298 }
299}
300
301std::string PrettyDuration(uint64_t nano_duration) {
302 if (nano_duration == 0) {
303 return "0";
304 } else {
305 const uint64_t one_sec = 1000 * 1000 * 1000;
306 const uint64_t one_ms = 1000 * 1000;
307 const uint64_t one_us = 1000;
308 const char* unit;
309 uint64_t divisor;
310 uint32_t zero_fill;
311 if (nano_duration >= one_sec) {
312 unit = "s";
313 divisor = one_sec;
314 zero_fill = 9;
315 } else if(nano_duration >= one_ms) {
316 unit = "ms";
317 divisor = one_ms;
318 zero_fill = 6;
319 } else if(nano_duration >= one_us) {
320 unit = "us";
321 divisor = one_us;
322 zero_fill = 3;
323 } else {
324 unit = "ns";
325 divisor = 1;
326 zero_fill = 0;
327 }
328 uint64_t whole_part = nano_duration / divisor;
329 uint64_t fractional_part = nano_duration % divisor;
330 if (fractional_part == 0) {
331 return StringPrintf("%llu%s", whole_part, unit);
332 } else {
333 while ((fractional_part % 1000) == 0) {
334 zero_fill -= 3;
335 fractional_part /= 1000;
336 }
337 if (zero_fill == 3) {
338 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
339 } else if (zero_fill == 6) {
340 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
341 } else {
342 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
343 }
344 }
345 }
346}
347
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800348// 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 -0700349std::string MangleForJni(const std::string& s) {
350 std::string result;
351 size_t char_count = CountModifiedUtf8Chars(s.c_str());
352 const char* cp = &s[0];
353 for (size_t i = 0; i < char_count; ++i) {
354 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800355 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
356 result.push_back(ch);
357 } else if (ch == '.' || ch == '/') {
358 result += "_";
359 } else if (ch == '_') {
360 result += "_1";
361 } else if (ch == ';') {
362 result += "_2";
363 } else if (ch == '[') {
364 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700365 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800366 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700367 }
368 }
369 return result;
370}
371
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700372std::string DotToDescriptor(const char* class_name) {
373 std::string descriptor(class_name);
374 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
375 if (descriptor.length() > 0 && descriptor[0] != '[') {
376 descriptor = "L" + descriptor + ";";
377 }
378 return descriptor;
379}
380
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800381std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800382 size_t length = strlen(descriptor);
383 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
384 std::string result(descriptor + 1, length - 2);
385 std::replace(result.begin(), result.end(), '/', '.');
386 return result;
387 }
388 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800389}
390
391std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800392 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800393 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
394 std::string result(descriptor + 1, length - 2);
395 return result;
396 }
397 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700398}
399
Elliott Hughes79082e32011-08-25 12:07:32 -0700400std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800401 MethodHelper mh(m);
402 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700403 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700404 CHECK_EQ(class_name[0], 'L') << class_name;
405 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700406 class_name.erase(0, 1);
407 class_name.erase(class_name.size() - 1, 1);
408
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800409 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700410
411 std::string short_name;
412 short_name += "Java_";
413 short_name += MangleForJni(class_name);
414 short_name += "_";
415 short_name += MangleForJni(method_name);
416 return short_name;
417}
418
419std::string JniLongName(const Method* m) {
420 std::string long_name;
421 long_name += JniShortName(m);
422 long_name += "__";
423
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800424 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700425 signature.erase(0, 1);
426 signature.erase(signature.begin() + signature.find(')'), signature.end());
427
428 long_name += MangleForJni(signature);
429
430 return long_name;
431}
432
jeffhao10037c82012-01-23 15:06:23 -0800433// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700434uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
435 0x00000000, // 00..1f low control characters; nothing valid
436 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
437 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
438 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
439};
440
jeffhao10037c82012-01-23 15:06:23 -0800441// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
442bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700443 /*
444 * It's a multibyte encoded character. Decode it and analyze. We
445 * accept anything that isn't (a) an improperly encoded low value,
446 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
447 * control character, or (e) a high space, layout, or special
448 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
449 * U+fff0..U+ffff). This is all specified in the dex format
450 * document.
451 */
452
453 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
454
455 // Perform follow-up tests based on the high 8 bits.
456 switch (utf16 >> 8) {
457 case 0x00:
458 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
459 return (utf16 > 0x00a0);
460 case 0xd8:
461 case 0xd9:
462 case 0xda:
463 case 0xdb:
464 // It's a leading surrogate. Check to see that a trailing
465 // surrogate follows.
466 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
467 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
468 case 0xdc:
469 case 0xdd:
470 case 0xde:
471 case 0xdf:
472 // It's a trailing surrogate, which is not valid at this point.
473 return false;
474 case 0x20:
475 case 0xff:
476 // It's in the range that has spaces, controls, and specials.
477 switch (utf16 & 0xfff8) {
478 case 0x2000:
479 case 0x2008:
480 case 0x2028:
481 case 0xfff0:
482 case 0xfff8:
483 return false;
484 }
485 break;
486 }
487 return true;
488}
489
490/* Return whether the pointed-at modified-UTF-8 encoded character is
491 * valid as part of a member name, updating the pointer to point past
492 * the consumed character. This will consume two encoded UTF-16 code
493 * points if the character is encoded as a surrogate pair. Also, if
494 * this function returns false, then the given pointer may only have
495 * been partially advanced.
496 */
jeffhao10037c82012-01-23 15:06:23 -0800497bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700498 uint8_t c = (uint8_t) **pUtf8Ptr;
499 if (c <= 0x7f) {
500 // It's low-ascii, so check the table.
501 uint32_t wordIdx = c >> 5;
502 uint32_t bitIdx = c & 0x1f;
503 (*pUtf8Ptr)++;
504 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
505 }
506
507 // It's a multibyte encoded character. Call a non-inline function
508 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800509 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
510}
511
512bool IsValidMemberName(const char* s) {
513 bool angle_name = false;
514
515 switch(*s) {
516 case '\0':
517 // The empty string is not a valid name.
518 return false;
519 case '<':
520 angle_name = true;
521 s++;
522 break;
523 }
524
525 while (true) {
526 switch (*s) {
527 case '\0':
528 return !angle_name;
529 case '>':
530 return angle_name && s[1] == '\0';
531 }
532
533 if (!IsValidPartOfMemberNameUtf8(&s)) {
534 return false;
535 }
536 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700537}
538
Elliott Hughes906e6852011-10-28 14:52:10 -0700539enum ClassNameType { kName, kDescriptor };
540bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700541 int arrayCount = 0;
542 while (*s == '[') {
543 arrayCount++;
544 s++;
545 }
546
547 if (arrayCount > 255) {
548 // Arrays may have no more than 255 dimensions.
549 return false;
550 }
551
552 if (arrayCount != 0) {
553 /*
554 * If we're looking at an array of some sort, then it doesn't
555 * matter if what is being asked for is a class name; the
556 * format looks the same as a type descriptor in that case, so
557 * treat it as such.
558 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700559 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700560 }
561
Elliott Hughes906e6852011-10-28 14:52:10 -0700562 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700563 /*
564 * We are looking for a descriptor. Either validate it as a
565 * single-character primitive type, or continue on to check the
566 * embedded class name (bracketed by "L" and ";").
567 */
568 switch (*(s++)) {
569 case 'B':
570 case 'C':
571 case 'D':
572 case 'F':
573 case 'I':
574 case 'J':
575 case 'S':
576 case 'Z':
577 // These are all single-character descriptors for primitive types.
578 return (*s == '\0');
579 case 'V':
580 // Non-array void is valid, but you can't have an array of void.
581 return (arrayCount == 0) && (*s == '\0');
582 case 'L':
583 // Class name: Break out and continue below.
584 break;
585 default:
586 // Oddball descriptor character.
587 return false;
588 }
589 }
590
591 /*
592 * We just consumed the 'L' that introduces a class name as part
593 * of a type descriptor, or we are looking for an unadorned class
594 * name.
595 */
596
597 bool sepOrFirst = true; // first character or just encountered a separator.
598 for (;;) {
599 uint8_t c = (uint8_t) *s;
600 switch (c) {
601 case '\0':
602 /*
603 * Premature end for a type descriptor, but valid for
604 * a class name as long as we haven't encountered an
605 * empty component (including the degenerate case of
606 * the empty string "").
607 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700608 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700609 case ';':
610 /*
611 * Invalid character for a class name, but the
612 * legitimate end of a type descriptor. In the latter
613 * case, make sure that this is the end of the string
614 * and that it doesn't end with an empty component
615 * (including the degenerate case of "L;").
616 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700617 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700618 case '/':
619 case '.':
620 if (c != separator) {
621 // The wrong separator character.
622 return false;
623 }
624 if (sepOrFirst) {
625 // Separator at start or two separators in a row.
626 return false;
627 }
628 sepOrFirst = true;
629 s++;
630 break;
631 default:
jeffhao10037c82012-01-23 15:06:23 -0800632 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700633 return false;
634 }
635 sepOrFirst = false;
636 break;
637 }
638 }
639}
640
Elliott Hughes906e6852011-10-28 14:52:10 -0700641bool IsValidBinaryClassName(const char* s) {
642 return IsValidClassName(s, kName, '.');
643}
644
645bool IsValidJniClassName(const char* s) {
646 return IsValidClassName(s, kName, '/');
647}
648
649bool IsValidDescriptor(const char* s) {
650 return IsValidClassName(s, kDescriptor, '/');
651}
652
Elliott Hughes48436bb2012-02-07 15:23:28 -0800653void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700654 const char* p = s.data();
655 const char* end = p + s.size();
656 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800657 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700658 ++p;
659 } else {
660 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800661 while (++p != end && *p != separator) {
662 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700663 }
664 result.push_back(std::string(start, p - start));
665 }
666 }
667}
668
Elliott Hughes48436bb2012-02-07 15:23:28 -0800669template <typename StringT>
670std::string Join(std::vector<StringT>& strings, char separator) {
671 if (strings.empty()) {
672 return "";
673 }
674
675 std::string result(strings[0]);
676 for (size_t i = 1; i < strings.size(); ++i) {
677 result += separator;
678 result += strings[i];
679 }
680 return result;
681}
682
683// Explicit instantiations.
684template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
685template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
686template std::string Join<char*>(std::vector<char*>& strings, char separator);
687
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800688bool StartsWith(const std::string& s, const char* prefix) {
689 return s.compare(0, strlen(prefix), prefix) == 0;
690}
691
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800692void SetThreadName(const char* threadName) {
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800693 ANNOTATE_THREAD_NAME(threadName); // For tsan.
694
Elliott Hughesdcc24742011-09-07 14:02:44 -0700695 int hasAt = 0;
696 int hasDot = 0;
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800697 const char* s = threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700698 while (*s) {
699 if (*s == '.') {
700 hasDot = 1;
701 } else if (*s == '@') {
702 hasAt = 1;
703 }
704 s++;
705 }
706 int len = s - threadName;
707 if (len < 15 || hasAt || !hasDot) {
708 s = threadName;
709 } else {
710 s = threadName + len - 15;
711 }
712#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700713 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700714 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
715 strncpy(buf, s, sizeof(buf)-1);
716 buf[sizeof(buf)-1] = '\0';
717 errno = pthread_setname_np(pthread_self(), buf);
718 if (errno != 0) {
719 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
720 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700721#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700722 pthread_setname_np(threadName);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700723#elif defined(HAVE_PRCTL)
724 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
725#else
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800726 UNIMPLEMENTED(WARNING) << threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700727#endif
728}
729
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700730void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
731 utime = stime = task_cpu = 0;
732 std::string stats;
733 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
734 return;
735 }
736 // Skip the command, which may contain spaces.
737 stats = stats.substr(stats.find(')') + 2);
738 // Extract the three fields we care about.
739 std::vector<std::string> fields;
740 Split(stats, ' ', fields);
741 utime = strtoull(fields[11].c_str(), NULL, 10);
742 stime = strtoull(fields[12].c_str(), NULL, 10);
743 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
744}
745
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800746const char* GetAndroidRoot() {
747 const char* android_root = getenv("ANDROID_ROOT");
748 if (android_root == NULL) {
749 if (OS::DirectoryExists("/system")) {
750 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700751 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800752 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
753 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700754 }
755 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800756 if (!OS::DirectoryExists(android_root)) {
757 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700758 return "";
759 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800760 return android_root;
761}
Brian Carlstroma9f19782011-10-13 00:14:47 -0700762
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800763const char* GetAndroidData() {
764 const char* android_data = getenv("ANDROID_DATA");
765 if (android_data == NULL) {
766 if (OS::DirectoryExists("/data")) {
767 android_data = "/data";
768 } else {
769 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
770 return "";
771 }
772 }
773 if (!OS::DirectoryExists(android_data)) {
774 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
775 return "";
776 }
777 return android_data;
778}
779
780std::string GetArtCacheOrDie() {
781 std::string art_cache(StringPrintf("%s/art-cache", GetAndroidData()));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700782
783 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800784 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700785 int result = mkdir(art_cache.c_str(), 0700);
786 if (result != 0) {
787 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
788 return "";
789 }
790 } else {
791 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
792 return "";
793 }
794 }
795 return art_cache;
796}
797
jeffhao262bf462011-10-20 18:36:32 -0700798std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800799 std::string art_cache(GetArtCacheOrDie());
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800800 CHECK_EQ(location[0], '/') << location;
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700801 std::string cache_file(location, 1); // skip leading slash
802 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
803 return art_cache + "/" + cache_file;
804}
805
jeffhao262bf462011-10-20 18:36:32 -0700806bool IsValidZipFilename(const std::string& filename) {
807 if (filename.size() < 4) {
808 return false;
809 }
810 std::string suffix(filename.substr(filename.size() - 4));
811 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
812}
813
814bool IsValidDexFilename(const std::string& filename) {
815 if (filename.size() < 4) {
816 return false;
817 }
818 std::string suffix(filename.substr(filename.size() - 4));
819 return (suffix == ".dex");
820}
821
Elliott Hughes42ee1422011-09-06 12:33:32 -0700822} // namespace art