blob: dc1ebffa2fd486c66c5c48882ba85709e3b2a229 [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);
Elliott Hughes7b9d9962012-04-20 18:48:18 -070090 tm tmbuf;
91 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -070092 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 Hughes7b9d9962012-04-20 18:48:18 -070099 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700100 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
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700103 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800104 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)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700111 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800112 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
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700115 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800116 gettimeofday(&now, NULL);
TDYa12754825032012-04-11 10:45:23 -0700117 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800118#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 Hughes7b9d9962012-04-20 18:48:18 -0700123 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700124 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
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700127 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800128 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)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700135 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800136 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)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700146 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700147 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
Elliott Hughesc967f782012-04-16 10:23:15 -0700348std::string PrettySize(size_t byte_count) {
349 // The byte thresholds at which we display amounts. A byte count is displayed
350 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
351 static const size_t kUnitThresholds[] = {
352 0, // B up to...
353 3*1024, // KB up to...
354 2*1024*1024, // MB up to...
355 1024*1024*1024 // GB from here.
356 };
357 static const size_t kBytesPerUnit[] = { 1, KB, MB, GB };
358 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
359
360 int i = arraysize(kUnitThresholds);
361 while (--i > 0) {
362 if (byte_count >= kUnitThresholds[i]) {
363 break;
364 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800365 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700366
367 return StringPrintf("%zd%s", byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800368}
369
370std::string PrettyDuration(uint64_t nano_duration) {
371 if (nano_duration == 0) {
372 return "0";
373 } else {
374 const uint64_t one_sec = 1000 * 1000 * 1000;
375 const uint64_t one_ms = 1000 * 1000;
376 const uint64_t one_us = 1000;
377 const char* unit;
378 uint64_t divisor;
379 uint32_t zero_fill;
380 if (nano_duration >= one_sec) {
381 unit = "s";
382 divisor = one_sec;
383 zero_fill = 9;
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700384 } else if (nano_duration >= one_ms) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800385 unit = "ms";
386 divisor = one_ms;
387 zero_fill = 6;
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700388 } else if (nano_duration >= one_us) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800389 unit = "us";
390 divisor = one_us;
391 zero_fill = 3;
392 } else {
393 unit = "ns";
394 divisor = 1;
395 zero_fill = 0;
396 }
397 uint64_t whole_part = nano_duration / divisor;
398 uint64_t fractional_part = nano_duration % divisor;
399 if (fractional_part == 0) {
400 return StringPrintf("%llu%s", whole_part, unit);
401 } else {
402 while ((fractional_part % 1000) == 0) {
403 zero_fill -= 3;
404 fractional_part /= 1000;
405 }
406 if (zero_fill == 3) {
407 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
408 } else if (zero_fill == 6) {
409 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
410 } else {
411 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
412 }
413 }
414 }
415}
416
Elliott Hughes82914b62012-04-09 15:56:29 -0700417std::string PrintableString(const std::string& utf) {
418 std::string result;
419 result += '"';
420 const char* p = utf.c_str();
421 size_t char_count = CountModifiedUtf8Chars(p);
422 for (size_t i = 0; i < char_count; ++i) {
423 uint16_t ch = GetUtf16FromUtf8(&p);
424 if (ch == '\\') {
425 result += "\\\\";
426 } else if (ch == '\n') {
427 result += "\\n";
428 } else if (ch == '\r') {
429 result += "\\r";
430 } else if (ch == '\t') {
431 result += "\\t";
432 } else if (NeedsEscaping(ch)) {
433 StringAppendF(&result, "\\u%04x", ch);
434 } else {
435 result += ch;
436 }
437 }
438 result += '"';
439 return result;
440}
441
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800442// 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 -0700443std::string MangleForJni(const std::string& s) {
444 std::string result;
445 size_t char_count = CountModifiedUtf8Chars(s.c_str());
446 const char* cp = &s[0];
447 for (size_t i = 0; i < char_count; ++i) {
448 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800449 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
450 result.push_back(ch);
451 } else if (ch == '.' || ch == '/') {
452 result += "_";
453 } else if (ch == '_') {
454 result += "_1";
455 } else if (ch == ';') {
456 result += "_2";
457 } else if (ch == '[') {
458 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700459 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800460 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700461 }
462 }
463 return result;
464}
465
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700466std::string DotToDescriptor(const char* class_name) {
467 std::string descriptor(class_name);
468 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
469 if (descriptor.length() > 0 && descriptor[0] != '[') {
470 descriptor = "L" + descriptor + ";";
471 }
472 return descriptor;
473}
474
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800475std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800476 size_t length = strlen(descriptor);
477 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
478 std::string result(descriptor + 1, length - 2);
479 std::replace(result.begin(), result.end(), '/', '.');
480 return result;
481 }
482 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800483}
484
485std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800486 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800487 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
488 std::string result(descriptor + 1, length - 2);
489 return result;
490 }
491 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700492}
493
Elliott Hughes79082e32011-08-25 12:07:32 -0700494std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800495 MethodHelper mh(m);
496 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700497 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700498 CHECK_EQ(class_name[0], 'L') << class_name;
499 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700500 class_name.erase(0, 1);
501 class_name.erase(class_name.size() - 1, 1);
502
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800503 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700504
505 std::string short_name;
506 short_name += "Java_";
507 short_name += MangleForJni(class_name);
508 short_name += "_";
509 short_name += MangleForJni(method_name);
510 return short_name;
511}
512
513std::string JniLongName(const Method* m) {
514 std::string long_name;
515 long_name += JniShortName(m);
516 long_name += "__";
517
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800518 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700519 signature.erase(0, 1);
520 signature.erase(signature.begin() + signature.find(')'), signature.end());
521
522 long_name += MangleForJni(signature);
523
524 return long_name;
525}
526
jeffhao10037c82012-01-23 15:06:23 -0800527// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700528uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
529 0x00000000, // 00..1f low control characters; nothing valid
530 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
531 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
532 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
533};
534
jeffhao10037c82012-01-23 15:06:23 -0800535// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
536bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700537 /*
538 * It's a multibyte encoded character. Decode it and analyze. We
539 * accept anything that isn't (a) an improperly encoded low value,
540 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
541 * control character, or (e) a high space, layout, or special
542 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
543 * U+fff0..U+ffff). This is all specified in the dex format
544 * document.
545 */
546
547 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
548
549 // Perform follow-up tests based on the high 8 bits.
550 switch (utf16 >> 8) {
551 case 0x00:
552 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
553 return (utf16 > 0x00a0);
554 case 0xd8:
555 case 0xd9:
556 case 0xda:
557 case 0xdb:
558 // It's a leading surrogate. Check to see that a trailing
559 // surrogate follows.
560 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
561 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
562 case 0xdc:
563 case 0xdd:
564 case 0xde:
565 case 0xdf:
566 // It's a trailing surrogate, which is not valid at this point.
567 return false;
568 case 0x20:
569 case 0xff:
570 // It's in the range that has spaces, controls, and specials.
571 switch (utf16 & 0xfff8) {
572 case 0x2000:
573 case 0x2008:
574 case 0x2028:
575 case 0xfff0:
576 case 0xfff8:
577 return false;
578 }
579 break;
580 }
581 return true;
582}
583
584/* Return whether the pointed-at modified-UTF-8 encoded character is
585 * valid as part of a member name, updating the pointer to point past
586 * the consumed character. This will consume two encoded UTF-16 code
587 * points if the character is encoded as a surrogate pair. Also, if
588 * this function returns false, then the given pointer may only have
589 * been partially advanced.
590 */
jeffhao10037c82012-01-23 15:06:23 -0800591bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700592 uint8_t c = (uint8_t) **pUtf8Ptr;
593 if (c <= 0x7f) {
594 // It's low-ascii, so check the table.
595 uint32_t wordIdx = c >> 5;
596 uint32_t bitIdx = c & 0x1f;
597 (*pUtf8Ptr)++;
598 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
599 }
600
601 // It's a multibyte encoded character. Call a non-inline function
602 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800603 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
604}
605
606bool IsValidMemberName(const char* s) {
607 bool angle_name = false;
608
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700609 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800610 case '\0':
611 // The empty string is not a valid name.
612 return false;
613 case '<':
614 angle_name = true;
615 s++;
616 break;
617 }
618
619 while (true) {
620 switch (*s) {
621 case '\0':
622 return !angle_name;
623 case '>':
624 return angle_name && s[1] == '\0';
625 }
626
627 if (!IsValidPartOfMemberNameUtf8(&s)) {
628 return false;
629 }
630 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700631}
632
Elliott Hughes906e6852011-10-28 14:52:10 -0700633enum ClassNameType { kName, kDescriptor };
634bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700635 int arrayCount = 0;
636 while (*s == '[') {
637 arrayCount++;
638 s++;
639 }
640
641 if (arrayCount > 255) {
642 // Arrays may have no more than 255 dimensions.
643 return false;
644 }
645
646 if (arrayCount != 0) {
647 /*
648 * If we're looking at an array of some sort, then it doesn't
649 * matter if what is being asked for is a class name; the
650 * format looks the same as a type descriptor in that case, so
651 * treat it as such.
652 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700653 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700654 }
655
Elliott Hughes906e6852011-10-28 14:52:10 -0700656 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700657 /*
658 * We are looking for a descriptor. Either validate it as a
659 * single-character primitive type, or continue on to check the
660 * embedded class name (bracketed by "L" and ";").
661 */
662 switch (*(s++)) {
663 case 'B':
664 case 'C':
665 case 'D':
666 case 'F':
667 case 'I':
668 case 'J':
669 case 'S':
670 case 'Z':
671 // These are all single-character descriptors for primitive types.
672 return (*s == '\0');
673 case 'V':
674 // Non-array void is valid, but you can't have an array of void.
675 return (arrayCount == 0) && (*s == '\0');
676 case 'L':
677 // Class name: Break out and continue below.
678 break;
679 default:
680 // Oddball descriptor character.
681 return false;
682 }
683 }
684
685 /*
686 * We just consumed the 'L' that introduces a class name as part
687 * of a type descriptor, or we are looking for an unadorned class
688 * name.
689 */
690
691 bool sepOrFirst = true; // first character or just encountered a separator.
692 for (;;) {
693 uint8_t c = (uint8_t) *s;
694 switch (c) {
695 case '\0':
696 /*
697 * Premature end for a type descriptor, but valid for
698 * a class name as long as we haven't encountered an
699 * empty component (including the degenerate case of
700 * the empty string "").
701 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700702 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700703 case ';':
704 /*
705 * Invalid character for a class name, but the
706 * legitimate end of a type descriptor. In the latter
707 * case, make sure that this is the end of the string
708 * and that it doesn't end with an empty component
709 * (including the degenerate case of "L;").
710 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700711 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700712 case '/':
713 case '.':
714 if (c != separator) {
715 // The wrong separator character.
716 return false;
717 }
718 if (sepOrFirst) {
719 // Separator at start or two separators in a row.
720 return false;
721 }
722 sepOrFirst = true;
723 s++;
724 break;
725 default:
jeffhao10037c82012-01-23 15:06:23 -0800726 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700727 return false;
728 }
729 sepOrFirst = false;
730 break;
731 }
732 }
733}
734
Elliott Hughes906e6852011-10-28 14:52:10 -0700735bool IsValidBinaryClassName(const char* s) {
736 return IsValidClassName(s, kName, '.');
737}
738
739bool IsValidJniClassName(const char* s) {
740 return IsValidClassName(s, kName, '/');
741}
742
743bool IsValidDescriptor(const char* s) {
744 return IsValidClassName(s, kDescriptor, '/');
745}
746
Elliott Hughes48436bb2012-02-07 15:23:28 -0800747void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700748 const char* p = s.data();
749 const char* end = p + s.size();
750 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800751 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700752 ++p;
753 } else {
754 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800755 while (++p != end && *p != separator) {
756 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700757 }
758 result.push_back(std::string(start, p - start));
759 }
760 }
761}
762
Elliott Hughes48436bb2012-02-07 15:23:28 -0800763template <typename StringT>
764std::string Join(std::vector<StringT>& strings, char separator) {
765 if (strings.empty()) {
766 return "";
767 }
768
769 std::string result(strings[0]);
770 for (size_t i = 1; i < strings.size(); ++i) {
771 result += separator;
772 result += strings[i];
773 }
774 return result;
775}
776
777// Explicit instantiations.
778template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
779template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
780template std::string Join<char*>(std::vector<char*>& strings, char separator);
781
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800782bool StartsWith(const std::string& s, const char* prefix) {
783 return s.compare(0, strlen(prefix), prefix) == 0;
784}
785
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700786bool EndsWith(const std::string& s, const char* suffix) {
787 size_t suffix_length = strlen(suffix);
788 size_t string_length = s.size();
789 if (suffix_length > string_length) {
790 return false;
791 }
792 size_t offset = string_length - suffix_length;
793 return s.compare(offset, suffix_length, suffix) == 0;
794}
795
Elliott Hughes22869a92012-03-27 14:08:24 -0700796void SetThreadName(const char* thread_name) {
797 ANNOTATE_THREAD_NAME(thread_name); // For tsan.
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800798
Elliott Hughesdcc24742011-09-07 14:02:44 -0700799 int hasAt = 0;
800 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700801 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700802 while (*s) {
803 if (*s == '.') {
804 hasDot = 1;
805 } else if (*s == '@') {
806 hasAt = 1;
807 }
808 s++;
809 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700810 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700811 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700812 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700813 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700814 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700815 }
816#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700817 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700818 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
819 strncpy(buf, s, sizeof(buf)-1);
820 buf[sizeof(buf)-1] = '\0';
821 errno = pthread_setname_np(pthread_self(), buf);
822 if (errno != 0) {
823 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
824 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700825#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700826 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700827#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700828 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700829#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700830 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700831#endif
832}
833
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700834void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
835 utime = stime = task_cpu = 0;
836 std::string stats;
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700837 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid).c_str(), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700838 return;
839 }
840 // Skip the command, which may contain spaces.
841 stats = stats.substr(stats.find(')') + 2);
842 // Extract the three fields we care about.
843 std::vector<std::string> fields;
844 Split(stats, ' ', fields);
845 utime = strtoull(fields[11].c_str(), NULL, 10);
846 stime = strtoull(fields[12].c_str(), NULL, 10);
847 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
848}
849
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700850std::string GetSchedulerGroupName(pid_t tid) {
851 // /proc/<pid>/cgroup looks like this:
852 // 2:devices:/
853 // 1:cpuacct,cpu:/
854 // We want the third field from the line whose second field contains the "cpu" token.
855 std::string cgroup_file;
856 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
857 return "";
858 }
859 std::vector<std::string> cgroup_lines;
860 Split(cgroup_file, '\n', cgroup_lines);
861 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
862 std::vector<std::string> cgroup_fields;
863 Split(cgroup_lines[i], ':', cgroup_fields);
864 std::vector<std::string> cgroups;
865 Split(cgroup_fields[1], ',', cgroups);
866 for (size_t i = 0; i < cgroups.size(); ++i) {
867 if (cgroups[i] == "cpu") {
868 return cgroup_fields[2].substr(1); // Skip the leading slash.
869 }
870 }
871 }
872 return "";
873}
874
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800875const char* GetAndroidRoot() {
876 const char* android_root = getenv("ANDROID_ROOT");
877 if (android_root == NULL) {
878 if (OS::DirectoryExists("/system")) {
879 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700880 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800881 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
882 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700883 }
884 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800885 if (!OS::DirectoryExists(android_root)) {
886 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700887 return "";
888 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800889 return android_root;
890}
Brian Carlstroma9f19782011-10-13 00:14:47 -0700891
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800892const char* GetAndroidData() {
893 const char* android_data = getenv("ANDROID_DATA");
894 if (android_data == NULL) {
895 if (OS::DirectoryExists("/data")) {
896 android_data = "/data";
897 } else {
898 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
899 return "";
900 }
901 }
902 if (!OS::DirectoryExists(android_data)) {
903 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
904 return "";
905 }
906 return android_data;
907}
908
909std::string GetArtCacheOrDie() {
910 std::string art_cache(StringPrintf("%s/art-cache", GetAndroidData()));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700911
912 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800913 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700914 int result = mkdir(art_cache.c_str(), 0700);
915 if (result != 0) {
916 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
917 return "";
918 }
919 } else {
920 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
921 return "";
922 }
923 }
924 return art_cache;
925}
926
jeffhao262bf462011-10-20 18:36:32 -0700927std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800928 std::string art_cache(GetArtCacheOrDie());
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800929 CHECK_EQ(location[0], '/') << location;
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700930 std::string cache_file(location, 1); // skip leading slash
931 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
932 return art_cache + "/" + cache_file;
933}
934
jeffhao262bf462011-10-20 18:36:32 -0700935bool IsValidZipFilename(const std::string& filename) {
936 if (filename.size() < 4) {
937 return false;
938 }
939 std::string suffix(filename.substr(filename.size() - 4));
940 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
941}
942
943bool IsValidDexFilename(const std::string& filename) {
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700944 return EndsWith(filename, ".dex");
945}
946
947bool IsValidOatFilename(const std::string& filename) {
948 return EndsWith(filename, ".oat");
jeffhao262bf462011-10-20 18:36:32 -0700949}
950
Elliott Hughes42ee1422011-09-06 12:33:32 -0700951} // namespace art