blob: 127c18fae59d7311211ef4513bebffc94acb3448 [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 Hughesd8c00d02012-01-30 14:08:31 -0800407// 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 -0700408std::string MangleForJni(const std::string& s) {
409 std::string result;
410 size_t char_count = CountModifiedUtf8Chars(s.c_str());
411 const char* cp = &s[0];
412 for (size_t i = 0; i < char_count; ++i) {
413 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800414 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
415 result.push_back(ch);
416 } else if (ch == '.' || ch == '/') {
417 result += "_";
418 } else if (ch == '_') {
419 result += "_1";
420 } else if (ch == ';') {
421 result += "_2";
422 } else if (ch == '[') {
423 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700424 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800425 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700426 }
427 }
428 return result;
429}
430
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700431std::string DotToDescriptor(const char* class_name) {
432 std::string descriptor(class_name);
433 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
434 if (descriptor.length() > 0 && descriptor[0] != '[') {
435 descriptor = "L" + descriptor + ";";
436 }
437 return descriptor;
438}
439
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800440std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800441 size_t length = strlen(descriptor);
442 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
443 std::string result(descriptor + 1, length - 2);
444 std::replace(result.begin(), result.end(), '/', '.');
445 return result;
446 }
447 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800448}
449
450std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800451 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800452 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
453 std::string result(descriptor + 1, length - 2);
454 return result;
455 }
456 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700457}
458
Elliott Hughes79082e32011-08-25 12:07:32 -0700459std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800460 MethodHelper mh(m);
461 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700462 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700463 CHECK_EQ(class_name[0], 'L') << class_name;
464 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700465 class_name.erase(0, 1);
466 class_name.erase(class_name.size() - 1, 1);
467
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800468 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700469
470 std::string short_name;
471 short_name += "Java_";
472 short_name += MangleForJni(class_name);
473 short_name += "_";
474 short_name += MangleForJni(method_name);
475 return short_name;
476}
477
478std::string JniLongName(const Method* m) {
479 std::string long_name;
480 long_name += JniShortName(m);
481 long_name += "__";
482
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800483 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700484 signature.erase(0, 1);
485 signature.erase(signature.begin() + signature.find(')'), signature.end());
486
487 long_name += MangleForJni(signature);
488
489 return long_name;
490}
491
jeffhao10037c82012-01-23 15:06:23 -0800492// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700493uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
494 0x00000000, // 00..1f low control characters; nothing valid
495 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
496 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
497 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
498};
499
jeffhao10037c82012-01-23 15:06:23 -0800500// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
501bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700502 /*
503 * It's a multibyte encoded character. Decode it and analyze. We
504 * accept anything that isn't (a) an improperly encoded low value,
505 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
506 * control character, or (e) a high space, layout, or special
507 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
508 * U+fff0..U+ffff). This is all specified in the dex format
509 * document.
510 */
511
512 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
513
514 // Perform follow-up tests based on the high 8 bits.
515 switch (utf16 >> 8) {
516 case 0x00:
517 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
518 return (utf16 > 0x00a0);
519 case 0xd8:
520 case 0xd9:
521 case 0xda:
522 case 0xdb:
523 // It's a leading surrogate. Check to see that a trailing
524 // surrogate follows.
525 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
526 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
527 case 0xdc:
528 case 0xdd:
529 case 0xde:
530 case 0xdf:
531 // It's a trailing surrogate, which is not valid at this point.
532 return false;
533 case 0x20:
534 case 0xff:
535 // It's in the range that has spaces, controls, and specials.
536 switch (utf16 & 0xfff8) {
537 case 0x2000:
538 case 0x2008:
539 case 0x2028:
540 case 0xfff0:
541 case 0xfff8:
542 return false;
543 }
544 break;
545 }
546 return true;
547}
548
549/* Return whether the pointed-at modified-UTF-8 encoded character is
550 * valid as part of a member name, updating the pointer to point past
551 * the consumed character. This will consume two encoded UTF-16 code
552 * points if the character is encoded as a surrogate pair. Also, if
553 * this function returns false, then the given pointer may only have
554 * been partially advanced.
555 */
jeffhao10037c82012-01-23 15:06:23 -0800556bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700557 uint8_t c = (uint8_t) **pUtf8Ptr;
558 if (c <= 0x7f) {
559 // It's low-ascii, so check the table.
560 uint32_t wordIdx = c >> 5;
561 uint32_t bitIdx = c & 0x1f;
562 (*pUtf8Ptr)++;
563 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
564 }
565
566 // It's a multibyte encoded character. Call a non-inline function
567 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800568 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
569}
570
571bool IsValidMemberName(const char* s) {
572 bool angle_name = false;
573
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700574 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800575 case '\0':
576 // The empty string is not a valid name.
577 return false;
578 case '<':
579 angle_name = true;
580 s++;
581 break;
582 }
583
584 while (true) {
585 switch (*s) {
586 case '\0':
587 return !angle_name;
588 case '>':
589 return angle_name && s[1] == '\0';
590 }
591
592 if (!IsValidPartOfMemberNameUtf8(&s)) {
593 return false;
594 }
595 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700596}
597
Elliott Hughes906e6852011-10-28 14:52:10 -0700598enum ClassNameType { kName, kDescriptor };
599bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700600 int arrayCount = 0;
601 while (*s == '[') {
602 arrayCount++;
603 s++;
604 }
605
606 if (arrayCount > 255) {
607 // Arrays may have no more than 255 dimensions.
608 return false;
609 }
610
611 if (arrayCount != 0) {
612 /*
613 * If we're looking at an array of some sort, then it doesn't
614 * matter if what is being asked for is a class name; the
615 * format looks the same as a type descriptor in that case, so
616 * treat it as such.
617 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700618 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700619 }
620
Elliott Hughes906e6852011-10-28 14:52:10 -0700621 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700622 /*
623 * We are looking for a descriptor. Either validate it as a
624 * single-character primitive type, or continue on to check the
625 * embedded class name (bracketed by "L" and ";").
626 */
627 switch (*(s++)) {
628 case 'B':
629 case 'C':
630 case 'D':
631 case 'F':
632 case 'I':
633 case 'J':
634 case 'S':
635 case 'Z':
636 // These are all single-character descriptors for primitive types.
637 return (*s == '\0');
638 case 'V':
639 // Non-array void is valid, but you can't have an array of void.
640 return (arrayCount == 0) && (*s == '\0');
641 case 'L':
642 // Class name: Break out and continue below.
643 break;
644 default:
645 // Oddball descriptor character.
646 return false;
647 }
648 }
649
650 /*
651 * We just consumed the 'L' that introduces a class name as part
652 * of a type descriptor, or we are looking for an unadorned class
653 * name.
654 */
655
656 bool sepOrFirst = true; // first character or just encountered a separator.
657 for (;;) {
658 uint8_t c = (uint8_t) *s;
659 switch (c) {
660 case '\0':
661 /*
662 * Premature end for a type descriptor, but valid for
663 * a class name as long as we haven't encountered an
664 * empty component (including the degenerate case of
665 * the empty string "").
666 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700667 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700668 case ';':
669 /*
670 * Invalid character for a class name, but the
671 * legitimate end of a type descriptor. In the latter
672 * case, make sure that this is the end of the string
673 * and that it doesn't end with an empty component
674 * (including the degenerate case of "L;").
675 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700676 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700677 case '/':
678 case '.':
679 if (c != separator) {
680 // The wrong separator character.
681 return false;
682 }
683 if (sepOrFirst) {
684 // Separator at start or two separators in a row.
685 return false;
686 }
687 sepOrFirst = true;
688 s++;
689 break;
690 default:
jeffhao10037c82012-01-23 15:06:23 -0800691 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700692 return false;
693 }
694 sepOrFirst = false;
695 break;
696 }
697 }
698}
699
Elliott Hughes906e6852011-10-28 14:52:10 -0700700bool IsValidBinaryClassName(const char* s) {
701 return IsValidClassName(s, kName, '.');
702}
703
704bool IsValidJniClassName(const char* s) {
705 return IsValidClassName(s, kName, '/');
706}
707
708bool IsValidDescriptor(const char* s) {
709 return IsValidClassName(s, kDescriptor, '/');
710}
711
Elliott Hughes48436bb2012-02-07 15:23:28 -0800712void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700713 const char* p = s.data();
714 const char* end = p + s.size();
715 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800716 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700717 ++p;
718 } else {
719 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800720 while (++p != end && *p != separator) {
721 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700722 }
723 result.push_back(std::string(start, p - start));
724 }
725 }
726}
727
Elliott Hughes48436bb2012-02-07 15:23:28 -0800728template <typename StringT>
729std::string Join(std::vector<StringT>& strings, char separator) {
730 if (strings.empty()) {
731 return "";
732 }
733
734 std::string result(strings[0]);
735 for (size_t i = 1; i < strings.size(); ++i) {
736 result += separator;
737 result += strings[i];
738 }
739 return result;
740}
741
742// Explicit instantiations.
743template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
744template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
745template std::string Join<char*>(std::vector<char*>& strings, char separator);
746
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800747bool StartsWith(const std::string& s, const char* prefix) {
748 return s.compare(0, strlen(prefix), prefix) == 0;
749}
750
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700751bool EndsWith(const std::string& s, const char* suffix) {
752 size_t suffix_length = strlen(suffix);
753 size_t string_length = s.size();
754 if (suffix_length > string_length) {
755 return false;
756 }
757 size_t offset = string_length - suffix_length;
758 return s.compare(offset, suffix_length, suffix) == 0;
759}
760
Elliott Hughes22869a92012-03-27 14:08:24 -0700761void SetThreadName(const char* thread_name) {
762 ANNOTATE_THREAD_NAME(thread_name); // For tsan.
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800763
Elliott Hughesdcc24742011-09-07 14:02:44 -0700764 int hasAt = 0;
765 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700766 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700767 while (*s) {
768 if (*s == '.') {
769 hasDot = 1;
770 } else if (*s == '@') {
771 hasAt = 1;
772 }
773 s++;
774 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700775 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700776 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700777 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700778 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700779 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700780 }
781#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700782 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700783 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
784 strncpy(buf, s, sizeof(buf)-1);
785 buf[sizeof(buf)-1] = '\0';
786 errno = pthread_setname_np(pthread_self(), buf);
787 if (errno != 0) {
788 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
789 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700790#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700791 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700792#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700793 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700794#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700795 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700796#endif
797}
798
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700799void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
800 utime = stime = task_cpu = 0;
801 std::string stats;
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700802 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid).c_str(), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700803 return;
804 }
805 // Skip the command, which may contain spaces.
806 stats = stats.substr(stats.find(')') + 2);
807 // Extract the three fields we care about.
808 std::vector<std::string> fields;
809 Split(stats, ' ', fields);
810 utime = strtoull(fields[11].c_str(), NULL, 10);
811 stime = strtoull(fields[12].c_str(), NULL, 10);
812 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
813}
814
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700815std::string GetSchedulerGroupName(pid_t tid) {
816 // /proc/<pid>/cgroup looks like this:
817 // 2:devices:/
818 // 1:cpuacct,cpu:/
819 // We want the third field from the line whose second field contains the "cpu" token.
820 std::string cgroup_file;
821 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
822 return "";
823 }
824 std::vector<std::string> cgroup_lines;
825 Split(cgroup_file, '\n', cgroup_lines);
826 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
827 std::vector<std::string> cgroup_fields;
828 Split(cgroup_lines[i], ':', cgroup_fields);
829 std::vector<std::string> cgroups;
830 Split(cgroup_fields[1], ',', cgroups);
831 for (size_t i = 0; i < cgroups.size(); ++i) {
832 if (cgroups[i] == "cpu") {
833 return cgroup_fields[2].substr(1); // Skip the leading slash.
834 }
835 }
836 }
837 return "";
838}
839
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800840const char* GetAndroidRoot() {
841 const char* android_root = getenv("ANDROID_ROOT");
842 if (android_root == NULL) {
843 if (OS::DirectoryExists("/system")) {
844 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700845 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800846 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
847 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700848 }
849 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800850 if (!OS::DirectoryExists(android_root)) {
851 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700852 return "";
853 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800854 return android_root;
855}
Brian Carlstroma9f19782011-10-13 00:14:47 -0700856
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800857const char* GetAndroidData() {
858 const char* android_data = getenv("ANDROID_DATA");
859 if (android_data == NULL) {
860 if (OS::DirectoryExists("/data")) {
861 android_data = "/data";
862 } else {
863 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
864 return "";
865 }
866 }
867 if (!OS::DirectoryExists(android_data)) {
868 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
869 return "";
870 }
871 return android_data;
872}
873
874std::string GetArtCacheOrDie() {
875 std::string art_cache(StringPrintf("%s/art-cache", GetAndroidData()));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700876
877 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800878 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700879 int result = mkdir(art_cache.c_str(), 0700);
880 if (result != 0) {
881 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
882 return "";
883 }
884 } else {
885 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
886 return "";
887 }
888 }
889 return art_cache;
890}
891
jeffhao262bf462011-10-20 18:36:32 -0700892std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800893 std::string art_cache(GetArtCacheOrDie());
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800894 CHECK_EQ(location[0], '/') << location;
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700895 std::string cache_file(location, 1); // skip leading slash
896 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
897 return art_cache + "/" + cache_file;
898}
899
jeffhao262bf462011-10-20 18:36:32 -0700900bool IsValidZipFilename(const std::string& filename) {
901 if (filename.size() < 4) {
902 return false;
903 }
904 std::string suffix(filename.substr(filename.size() - 4));
905 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
906}
907
908bool IsValidDexFilename(const std::string& filename) {
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700909 return EndsWith(filename, ".dex");
910}
911
912bool IsValidOatFilename(const std::string& filename) {
913 return EndsWith(filename, ".oat");
jeffhao262bf462011-10-20 18:36:32 -0700914}
915
Elliott Hughes42ee1422011-09-06 12:33:32 -0700916} // namespace art