blob: bfa0c4f5070c2410842a58ea38a0ed064e2f8b72 [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 Hughese1884192012-04-23 12:38:15 -070069void GetThreadStack(void*& stack_base, size_t& stack_size) {
70#if defined(__APPLE__)
71 stack_size = pthread_get_stacksize_np(pthread_self());
72 void* stack_addr = pthread_get_stackaddr_np(pthread_self());
73
74 // Check whether stack_addr is the base or end of the stack.
75 // (On Mac OS 10.7, it's the end.)
76 int stack_variable;
77 if (stack_addr > &stack_variable) {
78 stack_base = reinterpret_cast<byte*>(stack_addr) - stack_size;
79 } else {
80 stack_base = stack_addr;
81 }
82#else
83 pthread_attr_t attributes;
84 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_self(), &attributes), __FUNCTION__);
85 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
86 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
87#endif
88}
89
Elliott Hughesd92bec42011-09-02 17:04:36 -070090bool ReadFileToString(const std::string& file_name, std::string* result) {
91 UniquePtr<File> file(OS::OpenFile(file_name.c_str(), false));
92 if (file.get() == NULL) {
93 return false;
94 }
buzbeec143c552011-08-20 17:38:58 -070095
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070096 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -070097 while (true) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070098 int64_t n = file->Read(&buf[0], buf.size());
Elliott Hughesd92bec42011-09-02 17:04:36 -070099 if (n == -1) {
100 return false;
buzbeec143c552011-08-20 17:38:58 -0700101 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700102 if (n == 0) {
103 return true;
104 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700105 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700106 }
buzbeec143c552011-08-20 17:38:58 -0700107}
108
Elliott Hughese27955c2011-08-26 15:21:24 -0700109std::string GetIsoDate() {
110 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700111 tm tmbuf;
112 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700113 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
114 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
115 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
116}
117
Elliott Hughes7162ad92011-10-27 14:08:42 -0700118uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800119#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700120 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700121 clock_gettime(CLOCK_MONOTONIC, &now);
122 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800123#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700124 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800125 gettimeofday(&now, NULL);
126 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
127#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700128}
129
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800130uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800131#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700132 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800133 clock_gettime(CLOCK_MONOTONIC, &now);
134 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800135#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700136 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800137 gettimeofday(&now, NULL);
TDYa12754825032012-04-11 10:45:23 -0700138 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800139#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800140}
141
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700142uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800143#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700144 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700145 clock_gettime(CLOCK_MONOTONIC, &now);
146 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800147#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700148 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800149 gettimeofday(&now, NULL);
150 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
151#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700152}
153
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800154uint64_t ThreadCpuMicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800155#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700156 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800157 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
158 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800159#else
160 UNIMPLEMENTED(WARNING);
161 return -1;
162#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800163}
164
Elliott Hughes0512f022012-03-15 22:10:52 -0700165uint64_t ThreadCpuNanoTime() {
166#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700167 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700168 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
169 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
170#else
171 UNIMPLEMENTED(WARNING);
172 return -1;
173#endif
174}
175
Elliott Hughes5174fe62011-08-23 15:12:35 -0700176std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700177 if (java_descriptor == NULL) {
178 return "null";
179 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700180 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
181}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700182
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800183std::string PrettyDescriptor(const Class* klass) {
184 if (klass == NULL) {
185 return "null";
186 }
187 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800188}
189
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700190std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700191 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700192 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700193 size_t dim = 0;
194 while (*c == '[') {
195 dim++;
196 c++;
197 }
198
199 // Reference or primitive?
200 if (*c == 'L') {
201 // "[[La/b/C;" -> "a.b.C[][]".
202 c++; // Skip the 'L'.
203 } else {
204 // "[[B" -> "byte[][]".
205 // To make life easier, we make primitives look like unqualified
206 // reference types.
207 switch (*c) {
208 case 'B': c = "byte;"; break;
209 case 'C': c = "char;"; break;
210 case 'D': c = "double;"; break;
211 case 'F': c = "float;"; break;
212 case 'I': c = "int;"; break;
213 case 'J': c = "long;"; break;
214 case 'S': c = "short;"; break;
215 case 'Z': c = "boolean;"; break;
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700216 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700217 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700218 }
219 }
220
221 // At this point, 'c' is a string of the form "fully/qualified/Type;"
222 // or "primitive;". Rewrite the type with '.' instead of '/':
223 std::string result;
224 const char* p = c;
225 while (*p != ';') {
226 char ch = *p++;
227 if (ch == '/') {
228 ch = '.';
229 }
230 result.push_back(ch);
231 }
232 // ...and replace the semicolon with 'dim' "[]" pairs:
233 while (dim--) {
234 result += "[]";
235 }
236 return result;
237}
238
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700239std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800240 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700241 return PrettyDescriptor(descriptor_string);
242}
243
Elliott Hughes54e7df12011-09-16 11:47:04 -0700244std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700245 if (f == NULL) {
246 return "null";
247 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800248 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700249 std::string result;
250 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800251 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700252 result += ' ';
253 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800254 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700255 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800256 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700257 return result;
258}
259
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700260std::string PrettyArguments(const char* signature) {
261 std::string result;
262 result += '(';
263 CHECK_EQ(*signature, '(');
264 ++signature; // Skip the '('.
265 while (*signature != ')') {
266 size_t argument_length = 0;
267 while (signature[argument_length] == '[') {
268 ++argument_length;
269 }
270 if (signature[argument_length] == 'L') {
271 argument_length = (strchr(signature, ';') - signature + 1);
272 } else {
273 ++argument_length;
274 }
275 std::string argument_descriptor(signature, argument_length);
276 result += PrettyDescriptor(argument_descriptor);
277 if (signature[argument_length] != ')') {
278 result += ", ";
279 }
280 signature += argument_length;
281 }
282 CHECK_EQ(*signature, ')');
283 ++signature; // Skip the ')'.
284 result += ')';
285 return result;
286}
287
288std::string PrettyReturnType(const char* signature) {
289 const char* return_type = strchr(signature, ')');
290 CHECK(return_type != NULL);
291 ++return_type; // Skip ')'.
292 return PrettyDescriptor(return_type);
293}
294
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700295std::string PrettyMethod(const Method* m, bool with_signature) {
296 if (m == NULL) {
297 return "null";
298 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800299 MethodHelper mh(m);
300 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700301 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800302 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700303 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700304 std::string signature(mh.GetSignature());
Elliott Hughesf8c11932012-03-23 19:53:59 -0700305 if (signature == "<no signature>") {
306 return result + signature;
307 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700308 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700309 }
310 return result;
311}
312
Ian Rogers0571d352011-11-03 19:51:38 -0700313std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
314 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
315 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
316 result += '.';
317 result += dex_file.GetMethodName(method_id);
318 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700319 std::string signature(dex_file.GetMethodSignature(method_id));
Elliott Hughesf8c11932012-03-23 19:53:59 -0700320 if (signature == "<no signature>") {
321 return result + signature;
322 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700323 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700324 }
325 return result;
326}
327
Elliott Hughes54e7df12011-09-16 11:47:04 -0700328std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700329 if (obj == NULL) {
330 return "null";
331 }
332 if (obj->GetClass() == NULL) {
333 return "(raw)";
334 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800335 ClassHelper kh(obj->GetClass());
336 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700337 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800338 kh.ChangeClass(obj->AsClass());
339 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700340 }
341 return result;
342}
343
Elliott Hughes54e7df12011-09-16 11:47:04 -0700344std::string PrettyClass(const Class* c) {
345 if (c == NULL) {
346 return "null";
347 }
348 std::string result;
349 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800350 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700351 result += ">";
352 return result;
353}
354
Ian Rogersd81871c2011-10-03 13:57:23 -0700355std::string PrettyClassAndClassLoader(const Class* c) {
356 if (c == NULL) {
357 return "null";
358 }
359 std::string result;
360 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800361 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700362 result += ",";
363 result += PrettyTypeOf(c->GetClassLoader());
364 // TODO: add an identifying hash value for the loader
365 result += ">";
366 return result;
367}
368
Elliott Hughesc967f782012-04-16 10:23:15 -0700369std::string PrettySize(size_t byte_count) {
370 // The byte thresholds at which we display amounts. A byte count is displayed
371 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
372 static const size_t kUnitThresholds[] = {
373 0, // B up to...
374 3*1024, // KB up to...
375 2*1024*1024, // MB up to...
376 1024*1024*1024 // GB from here.
377 };
378 static const size_t kBytesPerUnit[] = { 1, KB, MB, GB };
379 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
380
381 int i = arraysize(kUnitThresholds);
382 while (--i > 0) {
383 if (byte_count >= kUnitThresholds[i]) {
384 break;
385 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800386 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700387
388 return StringPrintf("%zd%s", byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800389}
390
391std::string PrettyDuration(uint64_t nano_duration) {
392 if (nano_duration == 0) {
393 return "0";
394 } else {
395 const uint64_t one_sec = 1000 * 1000 * 1000;
396 const uint64_t one_ms = 1000 * 1000;
397 const uint64_t one_us = 1000;
398 const char* unit;
399 uint64_t divisor;
400 uint32_t zero_fill;
401 if (nano_duration >= one_sec) {
402 unit = "s";
403 divisor = one_sec;
404 zero_fill = 9;
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700405 } else if (nano_duration >= one_ms) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800406 unit = "ms";
407 divisor = one_ms;
408 zero_fill = 6;
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700409 } else if (nano_duration >= one_us) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800410 unit = "us";
411 divisor = one_us;
412 zero_fill = 3;
413 } else {
414 unit = "ns";
415 divisor = 1;
416 zero_fill = 0;
417 }
418 uint64_t whole_part = nano_duration / divisor;
419 uint64_t fractional_part = nano_duration % divisor;
420 if (fractional_part == 0) {
421 return StringPrintf("%llu%s", whole_part, unit);
422 } else {
423 while ((fractional_part % 1000) == 0) {
424 zero_fill -= 3;
425 fractional_part /= 1000;
426 }
427 if (zero_fill == 3) {
428 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
429 } else if (zero_fill == 6) {
430 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
431 } else {
432 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
433 }
434 }
435 }
436}
437
Elliott Hughes82914b62012-04-09 15:56:29 -0700438std::string PrintableString(const std::string& utf) {
439 std::string result;
440 result += '"';
441 const char* p = utf.c_str();
442 size_t char_count = CountModifiedUtf8Chars(p);
443 for (size_t i = 0; i < char_count; ++i) {
444 uint16_t ch = GetUtf16FromUtf8(&p);
445 if (ch == '\\') {
446 result += "\\\\";
447 } else if (ch == '\n') {
448 result += "\\n";
449 } else if (ch == '\r') {
450 result += "\\r";
451 } else if (ch == '\t') {
452 result += "\\t";
453 } else if (NeedsEscaping(ch)) {
454 StringAppendF(&result, "\\u%04x", ch);
455 } else {
456 result += ch;
457 }
458 }
459 result += '"';
460 return result;
461}
462
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800463// 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 -0700464std::string MangleForJni(const std::string& s) {
465 std::string result;
466 size_t char_count = CountModifiedUtf8Chars(s.c_str());
467 const char* cp = &s[0];
468 for (size_t i = 0; i < char_count; ++i) {
469 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800470 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
471 result.push_back(ch);
472 } else if (ch == '.' || ch == '/') {
473 result += "_";
474 } else if (ch == '_') {
475 result += "_1";
476 } else if (ch == ';') {
477 result += "_2";
478 } else if (ch == '[') {
479 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700480 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800481 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700482 }
483 }
484 return result;
485}
486
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700487std::string DotToDescriptor(const char* class_name) {
488 std::string descriptor(class_name);
489 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
490 if (descriptor.length() > 0 && descriptor[0] != '[') {
491 descriptor = "L" + descriptor + ";";
492 }
493 return descriptor;
494}
495
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800496std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800497 size_t length = strlen(descriptor);
498 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
499 std::string result(descriptor + 1, length - 2);
500 std::replace(result.begin(), result.end(), '/', '.');
501 return result;
502 }
503 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800504}
505
506std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800507 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800508 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
509 std::string result(descriptor + 1, length - 2);
510 return result;
511 }
512 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700513}
514
Elliott Hughes79082e32011-08-25 12:07:32 -0700515std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800516 MethodHelper mh(m);
517 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700518 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700519 CHECK_EQ(class_name[0], 'L') << class_name;
520 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700521 class_name.erase(0, 1);
522 class_name.erase(class_name.size() - 1, 1);
523
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800524 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700525
526 std::string short_name;
527 short_name += "Java_";
528 short_name += MangleForJni(class_name);
529 short_name += "_";
530 short_name += MangleForJni(method_name);
531 return short_name;
532}
533
534std::string JniLongName(const Method* m) {
535 std::string long_name;
536 long_name += JniShortName(m);
537 long_name += "__";
538
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800539 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700540 signature.erase(0, 1);
541 signature.erase(signature.begin() + signature.find(')'), signature.end());
542
543 long_name += MangleForJni(signature);
544
545 return long_name;
546}
547
jeffhao10037c82012-01-23 15:06:23 -0800548// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700549uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
550 0x00000000, // 00..1f low control characters; nothing valid
551 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
552 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
553 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
554};
555
jeffhao10037c82012-01-23 15:06:23 -0800556// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
557bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700558 /*
559 * It's a multibyte encoded character. Decode it and analyze. We
560 * accept anything that isn't (a) an improperly encoded low value,
561 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
562 * control character, or (e) a high space, layout, or special
563 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
564 * U+fff0..U+ffff). This is all specified in the dex format
565 * document.
566 */
567
568 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
569
570 // Perform follow-up tests based on the high 8 bits.
571 switch (utf16 >> 8) {
572 case 0x00:
573 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
574 return (utf16 > 0x00a0);
575 case 0xd8:
576 case 0xd9:
577 case 0xda:
578 case 0xdb:
579 // It's a leading surrogate. Check to see that a trailing
580 // surrogate follows.
581 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
582 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
583 case 0xdc:
584 case 0xdd:
585 case 0xde:
586 case 0xdf:
587 // It's a trailing surrogate, which is not valid at this point.
588 return false;
589 case 0x20:
590 case 0xff:
591 // It's in the range that has spaces, controls, and specials.
592 switch (utf16 & 0xfff8) {
593 case 0x2000:
594 case 0x2008:
595 case 0x2028:
596 case 0xfff0:
597 case 0xfff8:
598 return false;
599 }
600 break;
601 }
602 return true;
603}
604
605/* Return whether the pointed-at modified-UTF-8 encoded character is
606 * valid as part of a member name, updating the pointer to point past
607 * the consumed character. This will consume two encoded UTF-16 code
608 * points if the character is encoded as a surrogate pair. Also, if
609 * this function returns false, then the given pointer may only have
610 * been partially advanced.
611 */
jeffhao10037c82012-01-23 15:06:23 -0800612bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700613 uint8_t c = (uint8_t) **pUtf8Ptr;
614 if (c <= 0x7f) {
615 // It's low-ascii, so check the table.
616 uint32_t wordIdx = c >> 5;
617 uint32_t bitIdx = c & 0x1f;
618 (*pUtf8Ptr)++;
619 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
620 }
621
622 // It's a multibyte encoded character. Call a non-inline function
623 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800624 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
625}
626
627bool IsValidMemberName(const char* s) {
628 bool angle_name = false;
629
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700630 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800631 case '\0':
632 // The empty string is not a valid name.
633 return false;
634 case '<':
635 angle_name = true;
636 s++;
637 break;
638 }
639
640 while (true) {
641 switch (*s) {
642 case '\0':
643 return !angle_name;
644 case '>':
645 return angle_name && s[1] == '\0';
646 }
647
648 if (!IsValidPartOfMemberNameUtf8(&s)) {
649 return false;
650 }
651 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700652}
653
Elliott Hughes906e6852011-10-28 14:52:10 -0700654enum ClassNameType { kName, kDescriptor };
655bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700656 int arrayCount = 0;
657 while (*s == '[') {
658 arrayCount++;
659 s++;
660 }
661
662 if (arrayCount > 255) {
663 // Arrays may have no more than 255 dimensions.
664 return false;
665 }
666
667 if (arrayCount != 0) {
668 /*
669 * If we're looking at an array of some sort, then it doesn't
670 * matter if what is being asked for is a class name; the
671 * format looks the same as a type descriptor in that case, so
672 * treat it as such.
673 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700674 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700675 }
676
Elliott Hughes906e6852011-10-28 14:52:10 -0700677 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700678 /*
679 * We are looking for a descriptor. Either validate it as a
680 * single-character primitive type, or continue on to check the
681 * embedded class name (bracketed by "L" and ";").
682 */
683 switch (*(s++)) {
684 case 'B':
685 case 'C':
686 case 'D':
687 case 'F':
688 case 'I':
689 case 'J':
690 case 'S':
691 case 'Z':
692 // These are all single-character descriptors for primitive types.
693 return (*s == '\0');
694 case 'V':
695 // Non-array void is valid, but you can't have an array of void.
696 return (arrayCount == 0) && (*s == '\0');
697 case 'L':
698 // Class name: Break out and continue below.
699 break;
700 default:
701 // Oddball descriptor character.
702 return false;
703 }
704 }
705
706 /*
707 * We just consumed the 'L' that introduces a class name as part
708 * of a type descriptor, or we are looking for an unadorned class
709 * name.
710 */
711
712 bool sepOrFirst = true; // first character or just encountered a separator.
713 for (;;) {
714 uint8_t c = (uint8_t) *s;
715 switch (c) {
716 case '\0':
717 /*
718 * Premature end for a type descriptor, but valid for
719 * a class name as long as we haven't encountered an
720 * empty component (including the degenerate case of
721 * the empty string "").
722 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700723 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700724 case ';':
725 /*
726 * Invalid character for a class name, but the
727 * legitimate end of a type descriptor. In the latter
728 * case, make sure that this is the end of the string
729 * and that it doesn't end with an empty component
730 * (including the degenerate case of "L;").
731 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700732 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700733 case '/':
734 case '.':
735 if (c != separator) {
736 // The wrong separator character.
737 return false;
738 }
739 if (sepOrFirst) {
740 // Separator at start or two separators in a row.
741 return false;
742 }
743 sepOrFirst = true;
744 s++;
745 break;
746 default:
jeffhao10037c82012-01-23 15:06:23 -0800747 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700748 return false;
749 }
750 sepOrFirst = false;
751 break;
752 }
753 }
754}
755
Elliott Hughes906e6852011-10-28 14:52:10 -0700756bool IsValidBinaryClassName(const char* s) {
757 return IsValidClassName(s, kName, '.');
758}
759
760bool IsValidJniClassName(const char* s) {
761 return IsValidClassName(s, kName, '/');
762}
763
764bool IsValidDescriptor(const char* s) {
765 return IsValidClassName(s, kDescriptor, '/');
766}
767
Elliott Hughes48436bb2012-02-07 15:23:28 -0800768void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700769 const char* p = s.data();
770 const char* end = p + s.size();
771 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800772 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700773 ++p;
774 } else {
775 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800776 while (++p != end && *p != separator) {
777 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700778 }
779 result.push_back(std::string(start, p - start));
780 }
781 }
782}
783
Elliott Hughes48436bb2012-02-07 15:23:28 -0800784template <typename StringT>
785std::string Join(std::vector<StringT>& strings, char separator) {
786 if (strings.empty()) {
787 return "";
788 }
789
790 std::string result(strings[0]);
791 for (size_t i = 1; i < strings.size(); ++i) {
792 result += separator;
793 result += strings[i];
794 }
795 return result;
796}
797
798// Explicit instantiations.
799template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
800template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
801template std::string Join<char*>(std::vector<char*>& strings, char separator);
802
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800803bool StartsWith(const std::string& s, const char* prefix) {
804 return s.compare(0, strlen(prefix), prefix) == 0;
805}
806
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700807bool EndsWith(const std::string& s, const char* suffix) {
808 size_t suffix_length = strlen(suffix);
809 size_t string_length = s.size();
810 if (suffix_length > string_length) {
811 return false;
812 }
813 size_t offset = string_length - suffix_length;
814 return s.compare(offset, suffix_length, suffix) == 0;
815}
816
Elliott Hughes22869a92012-03-27 14:08:24 -0700817void SetThreadName(const char* thread_name) {
818 ANNOTATE_THREAD_NAME(thread_name); // For tsan.
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800819
Elliott Hughesdcc24742011-09-07 14:02:44 -0700820 int hasAt = 0;
821 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700822 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700823 while (*s) {
824 if (*s == '.') {
825 hasDot = 1;
826 } else if (*s == '@') {
827 hasAt = 1;
828 }
829 s++;
830 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700831 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700832 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700833 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700834 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700835 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700836 }
837#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700838 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700839 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
840 strncpy(buf, s, sizeof(buf)-1);
841 buf[sizeof(buf)-1] = '\0';
842 errno = pthread_setname_np(pthread_self(), buf);
843 if (errno != 0) {
844 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
845 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700846#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700847 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700848#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700849 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700850#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700851 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700852#endif
853}
854
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700855void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
856 utime = stime = task_cpu = 0;
857 std::string stats;
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700858 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid).c_str(), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700859 return;
860 }
861 // Skip the command, which may contain spaces.
862 stats = stats.substr(stats.find(')') + 2);
863 // Extract the three fields we care about.
864 std::vector<std::string> fields;
865 Split(stats, ' ', fields);
866 utime = strtoull(fields[11].c_str(), NULL, 10);
867 stime = strtoull(fields[12].c_str(), NULL, 10);
868 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
869}
870
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700871std::string GetSchedulerGroupName(pid_t tid) {
872 // /proc/<pid>/cgroup looks like this:
873 // 2:devices:/
874 // 1:cpuacct,cpu:/
875 // We want the third field from the line whose second field contains the "cpu" token.
876 std::string cgroup_file;
877 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
878 return "";
879 }
880 std::vector<std::string> cgroup_lines;
881 Split(cgroup_file, '\n', cgroup_lines);
882 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
883 std::vector<std::string> cgroup_fields;
884 Split(cgroup_lines[i], ':', cgroup_fields);
885 std::vector<std::string> cgroups;
886 Split(cgroup_fields[1], ',', cgroups);
887 for (size_t i = 0; i < cgroups.size(); ++i) {
888 if (cgroups[i] == "cpu") {
889 return cgroup_fields[2].substr(1); // Skip the leading slash.
890 }
891 }
892 }
893 return "";
894}
895
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800896const char* GetAndroidRoot() {
897 const char* android_root = getenv("ANDROID_ROOT");
898 if (android_root == NULL) {
899 if (OS::DirectoryExists("/system")) {
900 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700901 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800902 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
903 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700904 }
905 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800906 if (!OS::DirectoryExists(android_root)) {
907 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700908 return "";
909 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800910 return android_root;
911}
Brian Carlstroma9f19782011-10-13 00:14:47 -0700912
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800913const char* GetAndroidData() {
914 const char* android_data = getenv("ANDROID_DATA");
915 if (android_data == NULL) {
916 if (OS::DirectoryExists("/data")) {
917 android_data = "/data";
918 } else {
919 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
920 return "";
921 }
922 }
923 if (!OS::DirectoryExists(android_data)) {
924 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
925 return "";
926 }
927 return android_data;
928}
929
Shih-wei Liao795e3302012-04-21 00:20:57 -0700930std::string GetArtCacheOrDie(const char* android_data) {
931 std::string art_cache(StringPrintf("%s/art-cache", android_data));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700932
933 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800934 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700935 int result = mkdir(art_cache.c_str(), 0700);
936 if (result != 0) {
937 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
938 return "";
939 }
940 } else {
941 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
942 return "";
943 }
944 }
945 return art_cache;
946}
947
jeffhao262bf462011-10-20 18:36:32 -0700948std::string GetArtCacheFilenameOrDie(const std::string& location) {
Shih-wei Liao795e3302012-04-21 00:20:57 -0700949 std::string art_cache(GetArtCacheOrDie(GetAndroidData()));
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800950 CHECK_EQ(location[0], '/') << location;
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700951 std::string cache_file(location, 1); // skip leading slash
952 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
953 return art_cache + "/" + cache_file;
954}
955
jeffhao262bf462011-10-20 18:36:32 -0700956bool IsValidZipFilename(const std::string& filename) {
957 if (filename.size() < 4) {
958 return false;
959 }
960 std::string suffix(filename.substr(filename.size() - 4));
961 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
962}
963
964bool IsValidDexFilename(const std::string& filename) {
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700965 return EndsWith(filename, ".dex");
966}
967
968bool IsValidOatFilename(const std::string& filename) {
969 return EndsWith(filename, ".oat");
jeffhao262bf462011-10-20 18:36:32 -0700970}
971
Elliott Hughes42ee1422011-09-06 12:33:32 -0700972} // namespace art