blob: 97efcde899bc39aa335b76cca3a55abd9a8f8a09 [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 Hughes92b3b562011-09-08 16:32:26 -070019#include <pthread.h>
Brian Carlstroma9f19782011-10-13 00:14:47 -070020#include <sys/stat.h>
Elliott Hughes42ee1422011-09-06 12:33:32 -070021#include <sys/syscall.h>
22#include <sys/types.h>
23#include <unistd.h>
24
Elliott Hughes90a33692011-08-30 13:27:07 -070025#include "UniquePtr.h"
Ian Rogersd81871c2011-10-03 13:57:23 -070026#include "class_loader.h"
buzbeec143c552011-08-20 17:38:58 -070027#include "file.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070028#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080029#include "object_utils.h"
buzbeec143c552011-08-20 17:38:58 -070030#include "os.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070031
Elliott Hughesad6c9c32012-01-19 17:39:12 -080032#if !defined(HAVE_POSIX_CLOCKS)
33#include <sys/time.h>
34#endif
35
Elliott Hughesdcc24742011-09-07 14:02:44 -070036#if defined(HAVE_PRCTL)
37#include <sys/prctl.h>
38#endif
39
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080040#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080041#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080042#endif
43
Elliott Hughes11e45072011-08-16 17:40:46 -070044namespace art {
45
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080046pid_t GetTid() {
47#if defined(__APPLE__)
48 // Mac OS doesn't have gettid(2).
49 return getpid();
50#else
51 // Neither bionic nor glibc exposes gettid(2).
52 return syscall(__NR_gettid);
53#endif
54}
55
Elliott Hughesd92bec42011-09-02 17:04:36 -070056bool ReadFileToString(const std::string& file_name, std::string* result) {
57 UniquePtr<File> file(OS::OpenFile(file_name.c_str(), false));
58 if (file.get() == NULL) {
59 return false;
60 }
buzbeec143c552011-08-20 17:38:58 -070061
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070062 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -070063 while (true) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070064 int64_t n = file->Read(&buf[0], buf.size());
Elliott Hughesd92bec42011-09-02 17:04:36 -070065 if (n == -1) {
66 return false;
buzbeec143c552011-08-20 17:38:58 -070067 }
Elliott Hughesd92bec42011-09-02 17:04:36 -070068 if (n == 0) {
69 return true;
70 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070071 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -070072 }
buzbeec143c552011-08-20 17:38:58 -070073}
74
Elliott Hughese27955c2011-08-26 15:21:24 -070075std::string GetIsoDate() {
76 time_t now = time(NULL);
77 struct tm tmbuf;
78 struct tm* ptm = localtime_r(&now, &tmbuf);
79 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
80 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
81 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
82}
83
Elliott Hughes7162ad92011-10-27 14:08:42 -070084uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -080085#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7162ad92011-10-27 14:08:42 -070086 struct timespec now;
87 clock_gettime(CLOCK_MONOTONIC, &now);
88 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -080089#else
90 struct timeval now;
91 gettimeofday(&now, NULL);
92 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
93#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -070094}
95
jeffhaoa9ef3fd2011-12-13 18:33:43 -080096uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -080097#if defined(HAVE_POSIX_CLOCKS)
jeffhaoa9ef3fd2011-12-13 18:33:43 -080098 struct timespec now;
99 clock_gettime(CLOCK_MONOTONIC, &now);
100 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800101#else
102 struct timeval now;
103 gettimeofday(&now, NULL);
104 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec * 1000LL;
105#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800106}
107
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700108uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800109#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700110 struct timespec now;
111 clock_gettime(CLOCK_MONOTONIC, &now);
112 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800113#else
114 struct timeval now;
115 gettimeofday(&now, NULL);
116 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
117#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700118}
119
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800120uint64_t ThreadCpuMicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800121#if defined(HAVE_POSIX_CLOCKS)
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800122 struct timespec now;
123 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
124 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800125#else
126 UNIMPLEMENTED(WARNING);
127 return -1;
128#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800129}
130
Elliott Hughes5174fe62011-08-23 15:12:35 -0700131std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700132 if (java_descriptor == NULL) {
133 return "null";
134 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700135 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
136}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700137
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800138std::string PrettyDescriptor(const Class* klass) {
139 if (klass == NULL) {
140 return "null";
141 }
142 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800143}
144
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700145std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700146 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700147 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700148 size_t dim = 0;
149 while (*c == '[') {
150 dim++;
151 c++;
152 }
153
154 // Reference or primitive?
155 if (*c == 'L') {
156 // "[[La/b/C;" -> "a.b.C[][]".
157 c++; // Skip the 'L'.
158 } else {
159 // "[[B" -> "byte[][]".
160 // To make life easier, we make primitives look like unqualified
161 // reference types.
162 switch (*c) {
163 case 'B': c = "byte;"; break;
164 case 'C': c = "char;"; break;
165 case 'D': c = "double;"; break;
166 case 'F': c = "float;"; break;
167 case 'I': c = "int;"; break;
168 case 'J': c = "long;"; break;
169 case 'S': c = "short;"; break;
170 case 'Z': c = "boolean;"; break;
Elliott Hughes5174fe62011-08-23 15:12:35 -0700171 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700172 }
173 }
174
175 // At this point, 'c' is a string of the form "fully/qualified/Type;"
176 // or "primitive;". Rewrite the type with '.' instead of '/':
177 std::string result;
178 const char* p = c;
179 while (*p != ';') {
180 char ch = *p++;
181 if (ch == '/') {
182 ch = '.';
183 }
184 result.push_back(ch);
185 }
186 // ...and replace the semicolon with 'dim' "[]" pairs:
187 while (dim--) {
188 result += "[]";
189 }
190 return result;
191}
192
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700193std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800194 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700195 return PrettyDescriptor(descriptor_string);
196}
197
Elliott Hughes54e7df12011-09-16 11:47:04 -0700198std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700199 if (f == NULL) {
200 return "null";
201 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800202 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700203 std::string result;
204 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800205 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700206 result += ' ';
207 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800208 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700209 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800210 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700211 return result;
212}
213
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700214std::string PrettyMethod(const Method* m, bool with_signature) {
215 if (m == NULL) {
216 return "null";
217 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800218 MethodHelper mh(m);
219 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700220 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800221 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700222 if (with_signature) {
223 // TODO: iterate over the signature's elements and pass them all to
224 // PrettyDescriptor? We'd need to pull out the return type specially, too.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800225 result += mh.GetSignature();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700226 }
227 return result;
228}
229
Ian Rogers0571d352011-11-03 19:51:38 -0700230std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
231 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
232 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
233 result += '.';
234 result += dex_file.GetMethodName(method_id);
235 if (with_signature) {
236 // TODO: iterate over the signature's elements and pass them all to
237 // PrettyDescriptor? We'd need to pull out the return type specially, too.
238 result += dex_file.GetMethodSignature(method_id);
239 }
240 return result;
241}
242
Elliott Hughes54e7df12011-09-16 11:47:04 -0700243std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700244 if (obj == NULL) {
245 return "null";
246 }
247 if (obj->GetClass() == NULL) {
248 return "(raw)";
249 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800250 ClassHelper kh(obj->GetClass());
251 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700252 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800253 kh.ChangeClass(obj->AsClass());
254 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700255 }
256 return result;
257}
258
Elliott Hughes54e7df12011-09-16 11:47:04 -0700259std::string PrettyClass(const Class* c) {
260 if (c == NULL) {
261 return "null";
262 }
263 std::string result;
264 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800265 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700266 result += ">";
267 return result;
268}
269
Ian Rogersd81871c2011-10-03 13:57:23 -0700270std::string PrettyClassAndClassLoader(const Class* c) {
271 if (c == NULL) {
272 return "null";
273 }
274 std::string result;
275 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800276 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700277 result += ",";
278 result += PrettyTypeOf(c->GetClassLoader());
279 // TODO: add an identifying hash value for the loader
280 result += ">";
281 return result;
282}
283
Ian Rogers3bb17a62012-01-27 23:56:44 -0800284std::string PrettySize(size_t size_in_bytes) {
285 if ((size_in_bytes / GB) * GB == size_in_bytes) {
286 return StringPrintf("%zdGB", size_in_bytes / GB);
287 } else if ((size_in_bytes / MB) * MB == size_in_bytes) {
288 return StringPrintf("%zdMB", size_in_bytes / MB);
289 } else if ((size_in_bytes / KB) * KB == size_in_bytes) {
290 return StringPrintf("%zdKiB", size_in_bytes / KB);
291 } else {
292 return StringPrintf("%zdB", size_in_bytes);
293 }
294}
295
296std::string PrettyDuration(uint64_t nano_duration) {
297 if (nano_duration == 0) {
298 return "0";
299 } else {
300 const uint64_t one_sec = 1000 * 1000 * 1000;
301 const uint64_t one_ms = 1000 * 1000;
302 const uint64_t one_us = 1000;
303 const char* unit;
304 uint64_t divisor;
305 uint32_t zero_fill;
306 if (nano_duration >= one_sec) {
307 unit = "s";
308 divisor = one_sec;
309 zero_fill = 9;
310 } else if(nano_duration >= one_ms) {
311 unit = "ms";
312 divisor = one_ms;
313 zero_fill = 6;
314 } else if(nano_duration >= one_us) {
315 unit = "us";
316 divisor = one_us;
317 zero_fill = 3;
318 } else {
319 unit = "ns";
320 divisor = 1;
321 zero_fill = 0;
322 }
323 uint64_t whole_part = nano_duration / divisor;
324 uint64_t fractional_part = nano_duration % divisor;
325 if (fractional_part == 0) {
326 return StringPrintf("%llu%s", whole_part, unit);
327 } else {
328 while ((fractional_part % 1000) == 0) {
329 zero_fill -= 3;
330 fractional_part /= 1000;
331 }
332 if (zero_fill == 3) {
333 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
334 } else if (zero_fill == 6) {
335 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
336 } else {
337 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
338 }
339 }
340 }
341}
342
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800343// 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 -0700344std::string MangleForJni(const std::string& s) {
345 std::string result;
346 size_t char_count = CountModifiedUtf8Chars(s.c_str());
347 const char* cp = &s[0];
348 for (size_t i = 0; i < char_count; ++i) {
349 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800350 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
351 result.push_back(ch);
352 } else if (ch == '.' || ch == '/') {
353 result += "_";
354 } else if (ch == '_') {
355 result += "_1";
356 } else if (ch == ';') {
357 result += "_2";
358 } else if (ch == '[') {
359 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700360 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800361 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700362 }
363 }
364 return result;
365}
366
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700367std::string DotToDescriptor(const char* class_name) {
368 std::string descriptor(class_name);
369 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
370 if (descriptor.length() > 0 && descriptor[0] != '[') {
371 descriptor = "L" + descriptor + ";";
372 }
373 return descriptor;
374}
375
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800376std::string DescriptorToDot(const StringPiece& descriptor) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700377 DCHECK_EQ(descriptor[0], 'L');
378 DCHECK_EQ(descriptor[descriptor.size()-1], ';');
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800379 std::string dot(descriptor.substr(1, descriptor.size() - 2).ToString());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700380 std::replace(dot.begin(), dot.end(), '/', '.');
381 return dot;
382}
383
Elliott Hughes79082e32011-08-25 12:07:32 -0700384std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800385 MethodHelper mh(m);
386 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700387 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700388 CHECK_EQ(class_name[0], 'L') << class_name;
389 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700390 class_name.erase(0, 1);
391 class_name.erase(class_name.size() - 1, 1);
392
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800393 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700394
395 std::string short_name;
396 short_name += "Java_";
397 short_name += MangleForJni(class_name);
398 short_name += "_";
399 short_name += MangleForJni(method_name);
400 return short_name;
401}
402
403std::string JniLongName(const Method* m) {
404 std::string long_name;
405 long_name += JniShortName(m);
406 long_name += "__";
407
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800408 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700409 signature.erase(0, 1);
410 signature.erase(signature.begin() + signature.find(')'), signature.end());
411
412 long_name += MangleForJni(signature);
413
414 return long_name;
415}
416
jeffhao10037c82012-01-23 15:06:23 -0800417// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700418uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
419 0x00000000, // 00..1f low control characters; nothing valid
420 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
421 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
422 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
423};
424
jeffhao10037c82012-01-23 15:06:23 -0800425// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
426bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700427 /*
428 * It's a multibyte encoded character. Decode it and analyze. We
429 * accept anything that isn't (a) an improperly encoded low value,
430 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
431 * control character, or (e) a high space, layout, or special
432 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
433 * U+fff0..U+ffff). This is all specified in the dex format
434 * document.
435 */
436
437 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
438
439 // Perform follow-up tests based on the high 8 bits.
440 switch (utf16 >> 8) {
441 case 0x00:
442 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
443 return (utf16 > 0x00a0);
444 case 0xd8:
445 case 0xd9:
446 case 0xda:
447 case 0xdb:
448 // It's a leading surrogate. Check to see that a trailing
449 // surrogate follows.
450 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
451 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
452 case 0xdc:
453 case 0xdd:
454 case 0xde:
455 case 0xdf:
456 // It's a trailing surrogate, which is not valid at this point.
457 return false;
458 case 0x20:
459 case 0xff:
460 // It's in the range that has spaces, controls, and specials.
461 switch (utf16 & 0xfff8) {
462 case 0x2000:
463 case 0x2008:
464 case 0x2028:
465 case 0xfff0:
466 case 0xfff8:
467 return false;
468 }
469 break;
470 }
471 return true;
472}
473
474/* Return whether the pointed-at modified-UTF-8 encoded character is
475 * valid as part of a member name, updating the pointer to point past
476 * the consumed character. This will consume two encoded UTF-16 code
477 * points if the character is encoded as a surrogate pair. Also, if
478 * this function returns false, then the given pointer may only have
479 * been partially advanced.
480 */
jeffhao10037c82012-01-23 15:06:23 -0800481bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700482 uint8_t c = (uint8_t) **pUtf8Ptr;
483 if (c <= 0x7f) {
484 // It's low-ascii, so check the table.
485 uint32_t wordIdx = c >> 5;
486 uint32_t bitIdx = c & 0x1f;
487 (*pUtf8Ptr)++;
488 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
489 }
490
491 // It's a multibyte encoded character. Call a non-inline function
492 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800493 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
494}
495
496bool IsValidMemberName(const char* s) {
497 bool angle_name = false;
498
499 switch(*s) {
500 case '\0':
501 // The empty string is not a valid name.
502 return false;
503 case '<':
504 angle_name = true;
505 s++;
506 break;
507 }
508
509 while (true) {
510 switch (*s) {
511 case '\0':
512 return !angle_name;
513 case '>':
514 return angle_name && s[1] == '\0';
515 }
516
517 if (!IsValidPartOfMemberNameUtf8(&s)) {
518 return false;
519 }
520 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700521}
522
Elliott Hughes906e6852011-10-28 14:52:10 -0700523enum ClassNameType { kName, kDescriptor };
524bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700525 int arrayCount = 0;
526 while (*s == '[') {
527 arrayCount++;
528 s++;
529 }
530
531 if (arrayCount > 255) {
532 // Arrays may have no more than 255 dimensions.
533 return false;
534 }
535
536 if (arrayCount != 0) {
537 /*
538 * If we're looking at an array of some sort, then it doesn't
539 * matter if what is being asked for is a class name; the
540 * format looks the same as a type descriptor in that case, so
541 * treat it as such.
542 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700543 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700544 }
545
Elliott Hughes906e6852011-10-28 14:52:10 -0700546 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700547 /*
548 * We are looking for a descriptor. Either validate it as a
549 * single-character primitive type, or continue on to check the
550 * embedded class name (bracketed by "L" and ";").
551 */
552 switch (*(s++)) {
553 case 'B':
554 case 'C':
555 case 'D':
556 case 'F':
557 case 'I':
558 case 'J':
559 case 'S':
560 case 'Z':
561 // These are all single-character descriptors for primitive types.
562 return (*s == '\0');
563 case 'V':
564 // Non-array void is valid, but you can't have an array of void.
565 return (arrayCount == 0) && (*s == '\0');
566 case 'L':
567 // Class name: Break out and continue below.
568 break;
569 default:
570 // Oddball descriptor character.
571 return false;
572 }
573 }
574
575 /*
576 * We just consumed the 'L' that introduces a class name as part
577 * of a type descriptor, or we are looking for an unadorned class
578 * name.
579 */
580
581 bool sepOrFirst = true; // first character or just encountered a separator.
582 for (;;) {
583 uint8_t c = (uint8_t) *s;
584 switch (c) {
585 case '\0':
586 /*
587 * Premature end for a type descriptor, but valid for
588 * a class name as long as we haven't encountered an
589 * empty component (including the degenerate case of
590 * the empty string "").
591 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700592 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700593 case ';':
594 /*
595 * Invalid character for a class name, but the
596 * legitimate end of a type descriptor. In the latter
597 * case, make sure that this is the end of the string
598 * and that it doesn't end with an empty component
599 * (including the degenerate case of "L;").
600 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700601 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700602 case '/':
603 case '.':
604 if (c != separator) {
605 // The wrong separator character.
606 return false;
607 }
608 if (sepOrFirst) {
609 // Separator at start or two separators in a row.
610 return false;
611 }
612 sepOrFirst = true;
613 s++;
614 break;
615 default:
jeffhao10037c82012-01-23 15:06:23 -0800616 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700617 return false;
618 }
619 sepOrFirst = false;
620 break;
621 }
622 }
623}
624
Elliott Hughes906e6852011-10-28 14:52:10 -0700625bool IsValidBinaryClassName(const char* s) {
626 return IsValidClassName(s, kName, '.');
627}
628
629bool IsValidJniClassName(const char* s) {
630 return IsValidClassName(s, kName, '/');
631}
632
633bool IsValidDescriptor(const char* s) {
634 return IsValidClassName(s, kDescriptor, '/');
635}
636
Elliott Hughes34023802011-08-30 12:06:17 -0700637void Split(const std::string& s, char delim, std::vector<std::string>& result) {
638 const char* p = s.data();
639 const char* end = p + s.size();
640 while (p != end) {
641 if (*p == delim) {
642 ++p;
643 } else {
644 const char* start = p;
645 while (++p != end && *p != delim) {
646 // Skip to the next occurrence of the delimiter.
647 }
648 result.push_back(std::string(start, p - start));
649 }
650 }
651}
652
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800653void SetThreadName(const char* threadName) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700654 int hasAt = 0;
655 int hasDot = 0;
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800656 const char* s = threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700657 while (*s) {
658 if (*s == '.') {
659 hasDot = 1;
660 } else if (*s == '@') {
661 hasAt = 1;
662 }
663 s++;
664 }
665 int len = s - threadName;
666 if (len < 15 || hasAt || !hasDot) {
667 s = threadName;
668 } else {
669 s = threadName + len - 15;
670 }
671#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
672 /* pthread_setname_np fails rather than truncating long strings */
673 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
674 strncpy(buf, s, sizeof(buf)-1);
675 buf[sizeof(buf)-1] = '\0';
676 errno = pthread_setname_np(pthread_self(), buf);
677 if (errno != 0) {
678 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
679 }
680#elif defined(HAVE_PRCTL)
681 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
682#else
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800683 UNIMPLEMENTED(WARNING) << threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700684#endif
685}
686
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700687void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
688 utime = stime = task_cpu = 0;
689 std::string stats;
690 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
691 return;
692 }
693 // Skip the command, which may contain spaces.
694 stats = stats.substr(stats.find(')') + 2);
695 // Extract the three fields we care about.
696 std::vector<std::string> fields;
697 Split(stats, ' ', fields);
698 utime = strtoull(fields[11].c_str(), NULL, 10);
699 stime = strtoull(fields[12].c_str(), NULL, 10);
700 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
701}
702
Brian Carlstroma9f19782011-10-13 00:14:47 -0700703std::string GetArtCacheOrDie() {
704 const char* data_root = getenv("ANDROID_DATA");
705 if (data_root == NULL) {
706 if (OS::DirectoryExists("/data")) {
707 data_root = "/data";
708 } else {
709 data_root = "/tmp";
710 }
711 }
712 if (!OS::DirectoryExists(data_root)) {
713 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << data_root;
714 return "";
715 }
716
Elliott Hughes95572412011-12-13 18:14:20 -0800717 std::string art_cache(StringPrintf("%s/art-cache", data_root));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700718
719 if (!OS::DirectoryExists(art_cache.c_str())) {
720 if (StringPiece(art_cache).starts_with("/tmp/")) {
721 int result = mkdir(art_cache.c_str(), 0700);
722 if (result != 0) {
723 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
724 return "";
725 }
726 } else {
727 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
728 return "";
729 }
730 }
731 return art_cache;
732}
733
jeffhao262bf462011-10-20 18:36:32 -0700734std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800735 std::string art_cache(GetArtCacheOrDie());
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700736 CHECK_EQ(location[0], '/');
737 std::string cache_file(location, 1); // skip leading slash
738 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
739 return art_cache + "/" + cache_file;
740}
741
jeffhao262bf462011-10-20 18:36:32 -0700742bool IsValidZipFilename(const std::string& filename) {
743 if (filename.size() < 4) {
744 return false;
745 }
746 std::string suffix(filename.substr(filename.size() - 4));
747 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
748}
749
750bool IsValidDexFilename(const std::string& filename) {
751 if (filename.size() < 4) {
752 return false;
753 }
754 std::string suffix(filename.substr(filename.size() - 4));
755 return (suffix == ".dex");
756}
757
Elliott Hughes42ee1422011-09-06 12:33:32 -0700758} // namespace art