blob: e80de5b14db57ac52eba9ca76551d07e7d0e6280 [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__)
Elliott Hughesb08e8a32012-04-02 10:51:41 -070042#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
Elliott Hughesf1498432012-03-28 19:34:27 -070043#include <sys/syscall.h>
Elliott Hughes4ae722a2012-03-13 11:08:51 -070044#endif
45
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080046#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080047#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080048#endif
49
Elliott Hughes11e45072011-08-16 17:40:46 -070050namespace art {
51
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080052pid_t GetTid() {
Elliott Hughes5d6d5dc2012-03-29 11:59:27 -070053#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
54 // Darwin has a gettid(2), but it does something completely unrelated to tids.
55 // There is a thread_selfid(2) that does what we want though, and it seems to be what their
Elliott Hughesf1498432012-03-28 19:34:27 -070056 // pthreads implementation uses.
57 return syscall(SYS_thread_selfid);
Elliott Hughes5d6d5dc2012-03-29 11:59:27 -070058#elif defined(__APPLE__)
59 // On Mac OS 10.5 (which the build servers are still running) there was nothing usable.
Elliott Hughesd23f5202012-03-30 19:50:04 -070060 // We know we build 32-bit binaries and that the pthread_t is a pointer that uniquely identifies
61 // the calling thread.
62 return reinterpret_cast<pid_t>(pthread_self());
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080063#else
64 // Neither bionic nor glibc exposes gettid(2).
65 return syscall(__NR_gettid);
66#endif
67}
68
Elliott Hughesd92bec42011-09-02 17:04:36 -070069bool ReadFileToString(const std::string& file_name, std::string* result) {
70 UniquePtr<File> file(OS::OpenFile(file_name.c_str(), false));
71 if (file.get() == NULL) {
72 return false;
73 }
buzbeec143c552011-08-20 17:38:58 -070074
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070075 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -070076 while (true) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070077 int64_t n = file->Read(&buf[0], buf.size());
Elliott Hughesd92bec42011-09-02 17:04:36 -070078 if (n == -1) {
79 return false;
buzbeec143c552011-08-20 17:38:58 -070080 }
Elliott Hughesd92bec42011-09-02 17:04:36 -070081 if (n == 0) {
82 return true;
83 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070084 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -070085 }
buzbeec143c552011-08-20 17:38:58 -070086}
87
Elliott Hughese27955c2011-08-26 15:21:24 -070088std::string GetIsoDate() {
89 time_t now = time(NULL);
90 struct tm tmbuf;
91 struct tm* ptm = localtime_r(&now, &tmbuf);
92 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
93 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
94 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
95}
96
Elliott Hughes7162ad92011-10-27 14:08:42 -070097uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -080098#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7162ad92011-10-27 14:08:42 -070099 struct timespec now;
100 clock_gettime(CLOCK_MONOTONIC, &now);
101 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
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) * 1000LL + now.tv_usec / 1000LL;
106#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700107}
108
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800109uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800110#if defined(HAVE_POSIX_CLOCKS)
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800111 struct timespec now;
112 clock_gettime(CLOCK_MONOTONIC, &now);
113 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
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) * 1000000LL + now.tv_usec * 1000LL;
118#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800119}
120
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700121uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800122#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700123 struct timespec now;
124 clock_gettime(CLOCK_MONOTONIC, &now);
125 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800126#else
127 struct timeval now;
128 gettimeofday(&now, NULL);
129 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
130#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700131}
132
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800133uint64_t ThreadCpuMicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800134#if defined(HAVE_POSIX_CLOCKS)
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800135 struct timespec now;
136 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
137 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800138#else
139 UNIMPLEMENTED(WARNING);
140 return -1;
141#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800142}
143
Elliott Hughes0512f022012-03-15 22:10:52 -0700144uint64_t ThreadCpuNanoTime() {
145#if defined(HAVE_POSIX_CLOCKS)
146 struct timespec now;
147 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
148 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
149#else
150 UNIMPLEMENTED(WARNING);
151 return -1;
152#endif
153}
154
Elliott Hughes5174fe62011-08-23 15:12:35 -0700155std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700156 if (java_descriptor == NULL) {
157 return "null";
158 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700159 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
160}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700161
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800162std::string PrettyDescriptor(const Class* klass) {
163 if (klass == NULL) {
164 return "null";
165 }
166 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800167}
168
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700169std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700170 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700171 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700172 size_t dim = 0;
173 while (*c == '[') {
174 dim++;
175 c++;
176 }
177
178 // Reference or primitive?
179 if (*c == 'L') {
180 // "[[La/b/C;" -> "a.b.C[][]".
181 c++; // Skip the 'L'.
182 } else {
183 // "[[B" -> "byte[][]".
184 // To make life easier, we make primitives look like unqualified
185 // reference types.
186 switch (*c) {
187 case 'B': c = "byte;"; break;
188 case 'C': c = "char;"; break;
189 case 'D': c = "double;"; break;
190 case 'F': c = "float;"; break;
191 case 'I': c = "int;"; break;
192 case 'J': c = "long;"; break;
193 case 'S': c = "short;"; break;
194 case 'Z': c = "boolean;"; break;
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700195 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700196 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700197 }
198 }
199
200 // At this point, 'c' is a string of the form "fully/qualified/Type;"
201 // or "primitive;". Rewrite the type with '.' instead of '/':
202 std::string result;
203 const char* p = c;
204 while (*p != ';') {
205 char ch = *p++;
206 if (ch == '/') {
207 ch = '.';
208 }
209 result.push_back(ch);
210 }
211 // ...and replace the semicolon with 'dim' "[]" pairs:
212 while (dim--) {
213 result += "[]";
214 }
215 return result;
216}
217
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700218std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800219 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700220 return PrettyDescriptor(descriptor_string);
221}
222
Elliott Hughes54e7df12011-09-16 11:47:04 -0700223std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700224 if (f == NULL) {
225 return "null";
226 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800227 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700228 std::string result;
229 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800230 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700231 result += ' ';
232 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800233 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700234 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800235 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700236 return result;
237}
238
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700239std::string PrettyArguments(const char* signature) {
240 std::string result;
241 result += '(';
242 CHECK_EQ(*signature, '(');
243 ++signature; // Skip the '('.
244 while (*signature != ')') {
245 size_t argument_length = 0;
246 while (signature[argument_length] == '[') {
247 ++argument_length;
248 }
249 if (signature[argument_length] == 'L') {
250 argument_length = (strchr(signature, ';') - signature + 1);
251 } else {
252 ++argument_length;
253 }
254 std::string argument_descriptor(signature, argument_length);
255 result += PrettyDescriptor(argument_descriptor);
256 if (signature[argument_length] != ')') {
257 result += ", ";
258 }
259 signature += argument_length;
260 }
261 CHECK_EQ(*signature, ')');
262 ++signature; // Skip the ')'.
263 result += ')';
264 return result;
265}
266
267std::string PrettyReturnType(const char* signature) {
268 const char* return_type = strchr(signature, ')');
269 CHECK(return_type != NULL);
270 ++return_type; // Skip ')'.
271 return PrettyDescriptor(return_type);
272}
273
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700274std::string PrettyMethod(const Method* m, bool with_signature) {
275 if (m == NULL) {
276 return "null";
277 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800278 MethodHelper mh(m);
279 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700280 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800281 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700282 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700283 std::string signature(mh.GetSignature());
Elliott Hughesf8c11932012-03-23 19:53:59 -0700284 if (signature == "<no signature>") {
285 return result + signature;
286 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700287 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700288 }
289 return result;
290}
291
Ian Rogers0571d352011-11-03 19:51:38 -0700292std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
293 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
294 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
295 result += '.';
296 result += dex_file.GetMethodName(method_id);
297 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700298 std::string signature(dex_file.GetMethodSignature(method_id));
Elliott Hughesf8c11932012-03-23 19:53:59 -0700299 if (signature == "<no signature>") {
300 return result + signature;
301 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700302 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700303 }
304 return result;
305}
306
Elliott Hughes54e7df12011-09-16 11:47:04 -0700307std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700308 if (obj == NULL) {
309 return "null";
310 }
311 if (obj->GetClass() == NULL) {
312 return "(raw)";
313 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800314 ClassHelper kh(obj->GetClass());
315 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700316 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800317 kh.ChangeClass(obj->AsClass());
318 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700319 }
320 return result;
321}
322
Elliott Hughes54e7df12011-09-16 11:47:04 -0700323std::string PrettyClass(const Class* c) {
324 if (c == NULL) {
325 return "null";
326 }
327 std::string result;
328 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800329 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700330 result += ">";
331 return result;
332}
333
Ian Rogersd81871c2011-10-03 13:57:23 -0700334std::string PrettyClassAndClassLoader(const Class* c) {
335 if (c == NULL) {
336 return "null";
337 }
338 std::string result;
339 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800340 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700341 result += ",";
342 result += PrettyTypeOf(c->GetClassLoader());
343 // TODO: add an identifying hash value for the loader
344 result += ">";
345 return result;
346}
347
Ian Rogers3bb17a62012-01-27 23:56:44 -0800348std::string PrettySize(size_t size_in_bytes) {
349 if ((size_in_bytes / GB) * GB == size_in_bytes) {
350 return StringPrintf("%zdGB", size_in_bytes / GB);
351 } else if ((size_in_bytes / MB) * MB == size_in_bytes) {
352 return StringPrintf("%zdMB", size_in_bytes / MB);
353 } else if ((size_in_bytes / KB) * KB == size_in_bytes) {
Elliott Hughes409d2732012-04-03 13:34:44 -0700354 return StringPrintf("%zdKB", size_in_bytes / KB);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800355 } else {
356 return StringPrintf("%zdB", size_in_bytes);
357 }
358}
359
360std::string PrettyDuration(uint64_t nano_duration) {
361 if (nano_duration == 0) {
362 return "0";
363 } else {
364 const uint64_t one_sec = 1000 * 1000 * 1000;
365 const uint64_t one_ms = 1000 * 1000;
366 const uint64_t one_us = 1000;
367 const char* unit;
368 uint64_t divisor;
369 uint32_t zero_fill;
370 if (nano_duration >= one_sec) {
371 unit = "s";
372 divisor = one_sec;
373 zero_fill = 9;
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700374 } else if (nano_duration >= one_ms) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800375 unit = "ms";
376 divisor = one_ms;
377 zero_fill = 6;
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700378 } else if (nano_duration >= one_us) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800379 unit = "us";
380 divisor = one_us;
381 zero_fill = 3;
382 } else {
383 unit = "ns";
384 divisor = 1;
385 zero_fill = 0;
386 }
387 uint64_t whole_part = nano_duration / divisor;
388 uint64_t fractional_part = nano_duration % divisor;
389 if (fractional_part == 0) {
390 return StringPrintf("%llu%s", whole_part, unit);
391 } else {
392 while ((fractional_part % 1000) == 0) {
393 zero_fill -= 3;
394 fractional_part /= 1000;
395 }
396 if (zero_fill == 3) {
397 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
398 } else if (zero_fill == 6) {
399 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
400 } else {
401 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
402 }
403 }
404 }
405}
406
Elliott Hughes82914b62012-04-09 15:56:29 -0700407std::string PrintableString(const std::string& utf) {
408 std::string result;
409 result += '"';
410 const char* p = utf.c_str();
411 size_t char_count = CountModifiedUtf8Chars(p);
412 for (size_t i = 0; i < char_count; ++i) {
413 uint16_t ch = GetUtf16FromUtf8(&p);
414 if (ch == '\\') {
415 result += "\\\\";
416 } else if (ch == '\n') {
417 result += "\\n";
418 } else if (ch == '\r') {
419 result += "\\r";
420 } else if (ch == '\t') {
421 result += "\\t";
422 } else if (NeedsEscaping(ch)) {
423 StringAppendF(&result, "\\u%04x", ch);
424 } else {
425 result += ch;
426 }
427 }
428 result += '"';
429 return result;
430}
431
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800432// 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 -0700433std::string MangleForJni(const std::string& s) {
434 std::string result;
435 size_t char_count = CountModifiedUtf8Chars(s.c_str());
436 const char* cp = &s[0];
437 for (size_t i = 0; i < char_count; ++i) {
438 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800439 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
440 result.push_back(ch);
441 } else if (ch == '.' || ch == '/') {
442 result += "_";
443 } else if (ch == '_') {
444 result += "_1";
445 } else if (ch == ';') {
446 result += "_2";
447 } else if (ch == '[') {
448 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700449 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800450 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700451 }
452 }
453 return result;
454}
455
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700456std::string DotToDescriptor(const char* class_name) {
457 std::string descriptor(class_name);
458 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
459 if (descriptor.length() > 0 && descriptor[0] != '[') {
460 descriptor = "L" + descriptor + ";";
461 }
462 return descriptor;
463}
464
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800465std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800466 size_t length = strlen(descriptor);
467 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
468 std::string result(descriptor + 1, length - 2);
469 std::replace(result.begin(), result.end(), '/', '.');
470 return result;
471 }
472 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800473}
474
475std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800476 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800477 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
478 std::string result(descriptor + 1, length - 2);
479 return result;
480 }
481 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700482}
483
Elliott Hughes79082e32011-08-25 12:07:32 -0700484std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800485 MethodHelper mh(m);
486 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700487 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700488 CHECK_EQ(class_name[0], 'L') << class_name;
489 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700490 class_name.erase(0, 1);
491 class_name.erase(class_name.size() - 1, 1);
492
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800493 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700494
495 std::string short_name;
496 short_name += "Java_";
497 short_name += MangleForJni(class_name);
498 short_name += "_";
499 short_name += MangleForJni(method_name);
500 return short_name;
501}
502
503std::string JniLongName(const Method* m) {
504 std::string long_name;
505 long_name += JniShortName(m);
506 long_name += "__";
507
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800508 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700509 signature.erase(0, 1);
510 signature.erase(signature.begin() + signature.find(')'), signature.end());
511
512 long_name += MangleForJni(signature);
513
514 return long_name;
515}
516
jeffhao10037c82012-01-23 15:06:23 -0800517// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700518uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
519 0x00000000, // 00..1f low control characters; nothing valid
520 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
521 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
522 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
523};
524
jeffhao10037c82012-01-23 15:06:23 -0800525// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
526bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700527 /*
528 * It's a multibyte encoded character. Decode it and analyze. We
529 * accept anything that isn't (a) an improperly encoded low value,
530 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
531 * control character, or (e) a high space, layout, or special
532 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
533 * U+fff0..U+ffff). This is all specified in the dex format
534 * document.
535 */
536
537 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
538
539 // Perform follow-up tests based on the high 8 bits.
540 switch (utf16 >> 8) {
541 case 0x00:
542 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
543 return (utf16 > 0x00a0);
544 case 0xd8:
545 case 0xd9:
546 case 0xda:
547 case 0xdb:
548 // It's a leading surrogate. Check to see that a trailing
549 // surrogate follows.
550 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
551 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
552 case 0xdc:
553 case 0xdd:
554 case 0xde:
555 case 0xdf:
556 // It's a trailing surrogate, which is not valid at this point.
557 return false;
558 case 0x20:
559 case 0xff:
560 // It's in the range that has spaces, controls, and specials.
561 switch (utf16 & 0xfff8) {
562 case 0x2000:
563 case 0x2008:
564 case 0x2028:
565 case 0xfff0:
566 case 0xfff8:
567 return false;
568 }
569 break;
570 }
571 return true;
572}
573
574/* Return whether the pointed-at modified-UTF-8 encoded character is
575 * valid as part of a member name, updating the pointer to point past
576 * the consumed character. This will consume two encoded UTF-16 code
577 * points if the character is encoded as a surrogate pair. Also, if
578 * this function returns false, then the given pointer may only have
579 * been partially advanced.
580 */
jeffhao10037c82012-01-23 15:06:23 -0800581bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700582 uint8_t c = (uint8_t) **pUtf8Ptr;
583 if (c <= 0x7f) {
584 // It's low-ascii, so check the table.
585 uint32_t wordIdx = c >> 5;
586 uint32_t bitIdx = c & 0x1f;
587 (*pUtf8Ptr)++;
588 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
589 }
590
591 // It's a multibyte encoded character. Call a non-inline function
592 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800593 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
594}
595
596bool IsValidMemberName(const char* s) {
597 bool angle_name = false;
598
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700599 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800600 case '\0':
601 // The empty string is not a valid name.
602 return false;
603 case '<':
604 angle_name = true;
605 s++;
606 break;
607 }
608
609 while (true) {
610 switch (*s) {
611 case '\0':
612 return !angle_name;
613 case '>':
614 return angle_name && s[1] == '\0';
615 }
616
617 if (!IsValidPartOfMemberNameUtf8(&s)) {
618 return false;
619 }
620 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700621}
622
Elliott Hughes906e6852011-10-28 14:52:10 -0700623enum ClassNameType { kName, kDescriptor };
624bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700625 int arrayCount = 0;
626 while (*s == '[') {
627 arrayCount++;
628 s++;
629 }
630
631 if (arrayCount > 255) {
632 // Arrays may have no more than 255 dimensions.
633 return false;
634 }
635
636 if (arrayCount != 0) {
637 /*
638 * If we're looking at an array of some sort, then it doesn't
639 * matter if what is being asked for is a class name; the
640 * format looks the same as a type descriptor in that case, so
641 * treat it as such.
642 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700643 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700644 }
645
Elliott Hughes906e6852011-10-28 14:52:10 -0700646 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700647 /*
648 * We are looking for a descriptor. Either validate it as a
649 * single-character primitive type, or continue on to check the
650 * embedded class name (bracketed by "L" and ";").
651 */
652 switch (*(s++)) {
653 case 'B':
654 case 'C':
655 case 'D':
656 case 'F':
657 case 'I':
658 case 'J':
659 case 'S':
660 case 'Z':
661 // These are all single-character descriptors for primitive types.
662 return (*s == '\0');
663 case 'V':
664 // Non-array void is valid, but you can't have an array of void.
665 return (arrayCount == 0) && (*s == '\0');
666 case 'L':
667 // Class name: Break out and continue below.
668 break;
669 default:
670 // Oddball descriptor character.
671 return false;
672 }
673 }
674
675 /*
676 * We just consumed the 'L' that introduces a class name as part
677 * of a type descriptor, or we are looking for an unadorned class
678 * name.
679 */
680
681 bool sepOrFirst = true; // first character or just encountered a separator.
682 for (;;) {
683 uint8_t c = (uint8_t) *s;
684 switch (c) {
685 case '\0':
686 /*
687 * Premature end for a type descriptor, but valid for
688 * a class name as long as we haven't encountered an
689 * empty component (including the degenerate case of
690 * the empty string "").
691 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700692 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700693 case ';':
694 /*
695 * Invalid character for a class name, but the
696 * legitimate end of a type descriptor. In the latter
697 * case, make sure that this is the end of the string
698 * and that it doesn't end with an empty component
699 * (including the degenerate case of "L;").
700 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700701 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700702 case '/':
703 case '.':
704 if (c != separator) {
705 // The wrong separator character.
706 return false;
707 }
708 if (sepOrFirst) {
709 // Separator at start or two separators in a row.
710 return false;
711 }
712 sepOrFirst = true;
713 s++;
714 break;
715 default:
jeffhao10037c82012-01-23 15:06:23 -0800716 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700717 return false;
718 }
719 sepOrFirst = false;
720 break;
721 }
722 }
723}
724
Elliott Hughes906e6852011-10-28 14:52:10 -0700725bool IsValidBinaryClassName(const char* s) {
726 return IsValidClassName(s, kName, '.');
727}
728
729bool IsValidJniClassName(const char* s) {
730 return IsValidClassName(s, kName, '/');
731}
732
733bool IsValidDescriptor(const char* s) {
734 return IsValidClassName(s, kDescriptor, '/');
735}
736
Elliott Hughes48436bb2012-02-07 15:23:28 -0800737void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700738 const char* p = s.data();
739 const char* end = p + s.size();
740 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800741 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700742 ++p;
743 } else {
744 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800745 while (++p != end && *p != separator) {
746 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700747 }
748 result.push_back(std::string(start, p - start));
749 }
750 }
751}
752
Elliott Hughes48436bb2012-02-07 15:23:28 -0800753template <typename StringT>
754std::string Join(std::vector<StringT>& strings, char separator) {
755 if (strings.empty()) {
756 return "";
757 }
758
759 std::string result(strings[0]);
760 for (size_t i = 1; i < strings.size(); ++i) {
761 result += separator;
762 result += strings[i];
763 }
764 return result;
765}
766
767// Explicit instantiations.
768template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
769template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
770template std::string Join<char*>(std::vector<char*>& strings, char separator);
771
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800772bool StartsWith(const std::string& s, const char* prefix) {
773 return s.compare(0, strlen(prefix), prefix) == 0;
774}
775
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700776bool EndsWith(const std::string& s, const char* suffix) {
777 size_t suffix_length = strlen(suffix);
778 size_t string_length = s.size();
779 if (suffix_length > string_length) {
780 return false;
781 }
782 size_t offset = string_length - suffix_length;
783 return s.compare(offset, suffix_length, suffix) == 0;
784}
785
Elliott Hughes22869a92012-03-27 14:08:24 -0700786void SetThreadName(const char* thread_name) {
787 ANNOTATE_THREAD_NAME(thread_name); // For tsan.
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800788
Elliott Hughesdcc24742011-09-07 14:02:44 -0700789 int hasAt = 0;
790 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700791 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700792 while (*s) {
793 if (*s == '.') {
794 hasDot = 1;
795 } else if (*s == '@') {
796 hasAt = 1;
797 }
798 s++;
799 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700800 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700801 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700802 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700803 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700804 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700805 }
806#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700807 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700808 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
809 strncpy(buf, s, sizeof(buf)-1);
810 buf[sizeof(buf)-1] = '\0';
811 errno = pthread_setname_np(pthread_self(), buf);
812 if (errno != 0) {
813 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
814 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700815#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700816 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700817#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700818 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700819#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700820 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700821#endif
822}
823
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700824void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
825 utime = stime = task_cpu = 0;
826 std::string stats;
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700827 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid).c_str(), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700828 return;
829 }
830 // Skip the command, which may contain spaces.
831 stats = stats.substr(stats.find(')') + 2);
832 // Extract the three fields we care about.
833 std::vector<std::string> fields;
834 Split(stats, ' ', fields);
835 utime = strtoull(fields[11].c_str(), NULL, 10);
836 stime = strtoull(fields[12].c_str(), NULL, 10);
837 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
838}
839
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700840std::string GetSchedulerGroupName(pid_t tid) {
841 // /proc/<pid>/cgroup looks like this:
842 // 2:devices:/
843 // 1:cpuacct,cpu:/
844 // We want the third field from the line whose second field contains the "cpu" token.
845 std::string cgroup_file;
846 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
847 return "";
848 }
849 std::vector<std::string> cgroup_lines;
850 Split(cgroup_file, '\n', cgroup_lines);
851 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
852 std::vector<std::string> cgroup_fields;
853 Split(cgroup_lines[i], ':', cgroup_fields);
854 std::vector<std::string> cgroups;
855 Split(cgroup_fields[1], ',', cgroups);
856 for (size_t i = 0; i < cgroups.size(); ++i) {
857 if (cgroups[i] == "cpu") {
858 return cgroup_fields[2].substr(1); // Skip the leading slash.
859 }
860 }
861 }
862 return "";
863}
864
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800865const char* GetAndroidRoot() {
866 const char* android_root = getenv("ANDROID_ROOT");
867 if (android_root == NULL) {
868 if (OS::DirectoryExists("/system")) {
869 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700870 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800871 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
872 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700873 }
874 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800875 if (!OS::DirectoryExists(android_root)) {
876 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700877 return "";
878 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800879 return android_root;
880}
Brian Carlstroma9f19782011-10-13 00:14:47 -0700881
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800882const char* GetAndroidData() {
883 const char* android_data = getenv("ANDROID_DATA");
884 if (android_data == NULL) {
885 if (OS::DirectoryExists("/data")) {
886 android_data = "/data";
887 } else {
888 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
889 return "";
890 }
891 }
892 if (!OS::DirectoryExists(android_data)) {
893 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
894 return "";
895 }
896 return android_data;
897}
898
899std::string GetArtCacheOrDie() {
900 std::string art_cache(StringPrintf("%s/art-cache", GetAndroidData()));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700901
902 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800903 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700904 int result = mkdir(art_cache.c_str(), 0700);
905 if (result != 0) {
906 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
907 return "";
908 }
909 } else {
910 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
911 return "";
912 }
913 }
914 return art_cache;
915}
916
jeffhao262bf462011-10-20 18:36:32 -0700917std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800918 std::string art_cache(GetArtCacheOrDie());
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800919 CHECK_EQ(location[0], '/') << location;
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700920 std::string cache_file(location, 1); // skip leading slash
921 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
922 return art_cache + "/" + cache_file;
923}
924
jeffhao262bf462011-10-20 18:36:32 -0700925bool IsValidZipFilename(const std::string& filename) {
926 if (filename.size() < 4) {
927 return false;
928 }
929 std::string suffix(filename.substr(filename.size() - 4));
930 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
931}
932
933bool IsValidDexFilename(const std::string& filename) {
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700934 return EndsWith(filename, ".dex");
935}
936
937bool IsValidOatFilename(const std::string& filename) {
938 return EndsWith(filename, ".oat");
jeffhao262bf462011-10-20 18:36:32 -0700939}
940
Elliott Hughes42ee1422011-09-06 12:33:32 -0700941} // namespace art