blob: 03b61725f9db2cf5915fcbe0c337b214866712db [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__)
42#include "AvailabilityMacros.h"
43#endif
44
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080045#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080046#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080047#endif
48
Elliott Hughes11e45072011-08-16 17:40:46 -070049namespace art {
50
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080051pid_t GetTid() {
52#if defined(__APPLE__)
53 // Mac OS doesn't have gettid(2).
54 return getpid();
55#else
56 // Neither bionic nor glibc exposes gettid(2).
57 return syscall(__NR_gettid);
58#endif
59}
60
Elliott Hughesd92bec42011-09-02 17:04:36 -070061bool ReadFileToString(const std::string& file_name, std::string* result) {
62 UniquePtr<File> file(OS::OpenFile(file_name.c_str(), false));
63 if (file.get() == NULL) {
64 return false;
65 }
buzbeec143c552011-08-20 17:38:58 -070066
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070067 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -070068 while (true) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070069 int64_t n = file->Read(&buf[0], buf.size());
Elliott Hughesd92bec42011-09-02 17:04:36 -070070 if (n == -1) {
71 return false;
buzbeec143c552011-08-20 17:38:58 -070072 }
Elliott Hughesd92bec42011-09-02 17:04:36 -070073 if (n == 0) {
74 return true;
75 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070076 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -070077 }
buzbeec143c552011-08-20 17:38:58 -070078}
79
Elliott Hughese27955c2011-08-26 15:21:24 -070080std::string GetIsoDate() {
81 time_t now = time(NULL);
82 struct tm tmbuf;
83 struct tm* ptm = localtime_r(&now, &tmbuf);
84 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
85 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
86 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
87}
88
Elliott Hughes7162ad92011-10-27 14:08:42 -070089uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -080090#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7162ad92011-10-27 14:08:42 -070091 struct timespec now;
92 clock_gettime(CLOCK_MONOTONIC, &now);
93 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -080094#else
95 struct timeval now;
96 gettimeofday(&now, NULL);
97 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
98#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -070099}
100
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800101uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800102#if defined(HAVE_POSIX_CLOCKS)
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800103 struct timespec now;
104 clock_gettime(CLOCK_MONOTONIC, &now);
105 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800106#else
107 struct timeval now;
108 gettimeofday(&now, NULL);
109 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec * 1000LL;
110#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800111}
112
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700113uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800114#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700115 struct timespec now;
116 clock_gettime(CLOCK_MONOTONIC, &now);
117 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800118#else
119 struct timeval now;
120 gettimeofday(&now, NULL);
121 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
122#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700123}
124
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800125uint64_t ThreadCpuMicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800126#if defined(HAVE_POSIX_CLOCKS)
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800127 struct timespec now;
128 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
129 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800130#else
131 UNIMPLEMENTED(WARNING);
132 return -1;
133#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800134}
135
Elliott Hughes0512f022012-03-15 22:10:52 -0700136uint64_t ThreadCpuNanoTime() {
137#if defined(HAVE_POSIX_CLOCKS)
138 struct timespec now;
139 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
140 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
141#else
142 UNIMPLEMENTED(WARNING);
143 return -1;
144#endif
145}
146
Elliott Hughes5174fe62011-08-23 15:12:35 -0700147std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700148 if (java_descriptor == NULL) {
149 return "null";
150 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700151 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
152}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700153
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800154std::string PrettyDescriptor(const Class* klass) {
155 if (klass == NULL) {
156 return "null";
157 }
158 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800159}
160
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700161std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700162 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700163 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700164 size_t dim = 0;
165 while (*c == '[') {
166 dim++;
167 c++;
168 }
169
170 // Reference or primitive?
171 if (*c == 'L') {
172 // "[[La/b/C;" -> "a.b.C[][]".
173 c++; // Skip the 'L'.
174 } else {
175 // "[[B" -> "byte[][]".
176 // To make life easier, we make primitives look like unqualified
177 // reference types.
178 switch (*c) {
179 case 'B': c = "byte;"; break;
180 case 'C': c = "char;"; break;
181 case 'D': c = "double;"; break;
182 case 'F': c = "float;"; break;
183 case 'I': c = "int;"; break;
184 case 'J': c = "long;"; break;
185 case 'S': c = "short;"; break;
186 case 'Z': c = "boolean;"; break;
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700187 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700188 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700189 }
190 }
191
192 // At this point, 'c' is a string of the form "fully/qualified/Type;"
193 // or "primitive;". Rewrite the type with '.' instead of '/':
194 std::string result;
195 const char* p = c;
196 while (*p != ';') {
197 char ch = *p++;
198 if (ch == '/') {
199 ch = '.';
200 }
201 result.push_back(ch);
202 }
203 // ...and replace the semicolon with 'dim' "[]" pairs:
204 while (dim--) {
205 result += "[]";
206 }
207 return result;
208}
209
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700210std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800211 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700212 return PrettyDescriptor(descriptor_string);
213}
214
Elliott Hughes54e7df12011-09-16 11:47:04 -0700215std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700216 if (f == NULL) {
217 return "null";
218 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800219 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700220 std::string result;
221 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800222 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700223 result += ' ';
224 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800225 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700226 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800227 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700228 return result;
229}
230
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700231std::string PrettyArguments(const char* signature) {
232 std::string result;
233 result += '(';
234 CHECK_EQ(*signature, '(');
235 ++signature; // Skip the '('.
236 while (*signature != ')') {
237 size_t argument_length = 0;
238 while (signature[argument_length] == '[') {
239 ++argument_length;
240 }
241 if (signature[argument_length] == 'L') {
242 argument_length = (strchr(signature, ';') - signature + 1);
243 } else {
244 ++argument_length;
245 }
246 std::string argument_descriptor(signature, argument_length);
247 result += PrettyDescriptor(argument_descriptor);
248 if (signature[argument_length] != ')') {
249 result += ", ";
250 }
251 signature += argument_length;
252 }
253 CHECK_EQ(*signature, ')');
254 ++signature; // Skip the ')'.
255 result += ')';
256 return result;
257}
258
259std::string PrettyReturnType(const char* signature) {
260 const char* return_type = strchr(signature, ')');
261 CHECK(return_type != NULL);
262 ++return_type; // Skip ')'.
263 return PrettyDescriptor(return_type);
264}
265
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700266std::string PrettyMethod(const Method* m, bool with_signature) {
267 if (m == NULL) {
268 return "null";
269 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800270 MethodHelper mh(m);
271 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700272 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800273 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700274 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700275 std::string signature(mh.GetSignature());
Elliott Hughesf8c11932012-03-23 19:53:59 -0700276 if (signature == "<no signature>") {
277 return result + signature;
278 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700279 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700280 }
281 return result;
282}
283
Ian Rogers0571d352011-11-03 19:51:38 -0700284std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
285 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
286 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
287 result += '.';
288 result += dex_file.GetMethodName(method_id);
289 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700290 std::string signature(dex_file.GetMethodSignature(method_id));
Elliott Hughesf8c11932012-03-23 19:53:59 -0700291 if (signature == "<no signature>") {
292 return result + signature;
293 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700294 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700295 }
296 return result;
297}
298
Elliott Hughes54e7df12011-09-16 11:47:04 -0700299std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700300 if (obj == NULL) {
301 return "null";
302 }
303 if (obj->GetClass() == NULL) {
304 return "(raw)";
305 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800306 ClassHelper kh(obj->GetClass());
307 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700308 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800309 kh.ChangeClass(obj->AsClass());
310 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700311 }
312 return result;
313}
314
Elliott Hughes54e7df12011-09-16 11:47:04 -0700315std::string PrettyClass(const Class* c) {
316 if (c == NULL) {
317 return "null";
318 }
319 std::string result;
320 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800321 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700322 result += ">";
323 return result;
324}
325
Ian Rogersd81871c2011-10-03 13:57:23 -0700326std::string PrettyClassAndClassLoader(const Class* c) {
327 if (c == NULL) {
328 return "null";
329 }
330 std::string result;
331 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800332 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700333 result += ",";
334 result += PrettyTypeOf(c->GetClassLoader());
335 // TODO: add an identifying hash value for the loader
336 result += ">";
337 return result;
338}
339
Ian Rogers3bb17a62012-01-27 23:56:44 -0800340std::string PrettySize(size_t size_in_bytes) {
341 if ((size_in_bytes / GB) * GB == size_in_bytes) {
342 return StringPrintf("%zdGB", size_in_bytes / GB);
343 } else if ((size_in_bytes / MB) * MB == size_in_bytes) {
344 return StringPrintf("%zdMB", size_in_bytes / MB);
345 } else if ((size_in_bytes / KB) * KB == size_in_bytes) {
346 return StringPrintf("%zdKiB", size_in_bytes / KB);
347 } else {
348 return StringPrintf("%zdB", size_in_bytes);
349 }
350}
351
352std::string PrettyDuration(uint64_t nano_duration) {
353 if (nano_duration == 0) {
354 return "0";
355 } else {
356 const uint64_t one_sec = 1000 * 1000 * 1000;
357 const uint64_t one_ms = 1000 * 1000;
358 const uint64_t one_us = 1000;
359 const char* unit;
360 uint64_t divisor;
361 uint32_t zero_fill;
362 if (nano_duration >= one_sec) {
363 unit = "s";
364 divisor = one_sec;
365 zero_fill = 9;
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700366 } else if (nano_duration >= one_ms) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800367 unit = "ms";
368 divisor = one_ms;
369 zero_fill = 6;
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700370 } else if (nano_duration >= one_us) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800371 unit = "us";
372 divisor = one_us;
373 zero_fill = 3;
374 } else {
375 unit = "ns";
376 divisor = 1;
377 zero_fill = 0;
378 }
379 uint64_t whole_part = nano_duration / divisor;
380 uint64_t fractional_part = nano_duration % divisor;
381 if (fractional_part == 0) {
382 return StringPrintf("%llu%s", whole_part, unit);
383 } else {
384 while ((fractional_part % 1000) == 0) {
385 zero_fill -= 3;
386 fractional_part /= 1000;
387 }
388 if (zero_fill == 3) {
389 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
390 } else if (zero_fill == 6) {
391 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
392 } else {
393 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
394 }
395 }
396 }
397}
398
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800399// 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 -0700400std::string MangleForJni(const std::string& s) {
401 std::string result;
402 size_t char_count = CountModifiedUtf8Chars(s.c_str());
403 const char* cp = &s[0];
404 for (size_t i = 0; i < char_count; ++i) {
405 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800406 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
407 result.push_back(ch);
408 } else if (ch == '.' || ch == '/') {
409 result += "_";
410 } else if (ch == '_') {
411 result += "_1";
412 } else if (ch == ';') {
413 result += "_2";
414 } else if (ch == '[') {
415 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700416 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800417 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700418 }
419 }
420 return result;
421}
422
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700423std::string DotToDescriptor(const char* class_name) {
424 std::string descriptor(class_name);
425 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
426 if (descriptor.length() > 0 && descriptor[0] != '[') {
427 descriptor = "L" + descriptor + ";";
428 }
429 return descriptor;
430}
431
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800432std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800433 size_t length = strlen(descriptor);
434 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
435 std::string result(descriptor + 1, length - 2);
436 std::replace(result.begin(), result.end(), '/', '.');
437 return result;
438 }
439 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800440}
441
442std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800443 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800444 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
445 std::string result(descriptor + 1, length - 2);
446 return result;
447 }
448 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700449}
450
Elliott Hughes79082e32011-08-25 12:07:32 -0700451std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800452 MethodHelper mh(m);
453 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700454 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700455 CHECK_EQ(class_name[0], 'L') << class_name;
456 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700457 class_name.erase(0, 1);
458 class_name.erase(class_name.size() - 1, 1);
459
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800460 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700461
462 std::string short_name;
463 short_name += "Java_";
464 short_name += MangleForJni(class_name);
465 short_name += "_";
466 short_name += MangleForJni(method_name);
467 return short_name;
468}
469
470std::string JniLongName(const Method* m) {
471 std::string long_name;
472 long_name += JniShortName(m);
473 long_name += "__";
474
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800475 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700476 signature.erase(0, 1);
477 signature.erase(signature.begin() + signature.find(')'), signature.end());
478
479 long_name += MangleForJni(signature);
480
481 return long_name;
482}
483
jeffhao10037c82012-01-23 15:06:23 -0800484// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700485uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
486 0x00000000, // 00..1f low control characters; nothing valid
487 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
488 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
489 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
490};
491
jeffhao10037c82012-01-23 15:06:23 -0800492// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
493bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700494 /*
495 * It's a multibyte encoded character. Decode it and analyze. We
496 * accept anything that isn't (a) an improperly encoded low value,
497 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
498 * control character, or (e) a high space, layout, or special
499 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
500 * U+fff0..U+ffff). This is all specified in the dex format
501 * document.
502 */
503
504 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
505
506 // Perform follow-up tests based on the high 8 bits.
507 switch (utf16 >> 8) {
508 case 0x00:
509 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
510 return (utf16 > 0x00a0);
511 case 0xd8:
512 case 0xd9:
513 case 0xda:
514 case 0xdb:
515 // It's a leading surrogate. Check to see that a trailing
516 // surrogate follows.
517 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
518 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
519 case 0xdc:
520 case 0xdd:
521 case 0xde:
522 case 0xdf:
523 // It's a trailing surrogate, which is not valid at this point.
524 return false;
525 case 0x20:
526 case 0xff:
527 // It's in the range that has spaces, controls, and specials.
528 switch (utf16 & 0xfff8) {
529 case 0x2000:
530 case 0x2008:
531 case 0x2028:
532 case 0xfff0:
533 case 0xfff8:
534 return false;
535 }
536 break;
537 }
538 return true;
539}
540
541/* Return whether the pointed-at modified-UTF-8 encoded character is
542 * valid as part of a member name, updating the pointer to point past
543 * the consumed character. This will consume two encoded UTF-16 code
544 * points if the character is encoded as a surrogate pair. Also, if
545 * this function returns false, then the given pointer may only have
546 * been partially advanced.
547 */
jeffhao10037c82012-01-23 15:06:23 -0800548bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700549 uint8_t c = (uint8_t) **pUtf8Ptr;
550 if (c <= 0x7f) {
551 // It's low-ascii, so check the table.
552 uint32_t wordIdx = c >> 5;
553 uint32_t bitIdx = c & 0x1f;
554 (*pUtf8Ptr)++;
555 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
556 }
557
558 // It's a multibyte encoded character. Call a non-inline function
559 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800560 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
561}
562
563bool IsValidMemberName(const char* s) {
564 bool angle_name = false;
565
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700566 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800567 case '\0':
568 // The empty string is not a valid name.
569 return false;
570 case '<':
571 angle_name = true;
572 s++;
573 break;
574 }
575
576 while (true) {
577 switch (*s) {
578 case '\0':
579 return !angle_name;
580 case '>':
581 return angle_name && s[1] == '\0';
582 }
583
584 if (!IsValidPartOfMemberNameUtf8(&s)) {
585 return false;
586 }
587 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700588}
589
Elliott Hughes906e6852011-10-28 14:52:10 -0700590enum ClassNameType { kName, kDescriptor };
591bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700592 int arrayCount = 0;
593 while (*s == '[') {
594 arrayCount++;
595 s++;
596 }
597
598 if (arrayCount > 255) {
599 // Arrays may have no more than 255 dimensions.
600 return false;
601 }
602
603 if (arrayCount != 0) {
604 /*
605 * If we're looking at an array of some sort, then it doesn't
606 * matter if what is being asked for is a class name; the
607 * format looks the same as a type descriptor in that case, so
608 * treat it as such.
609 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700610 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700611 }
612
Elliott Hughes906e6852011-10-28 14:52:10 -0700613 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700614 /*
615 * We are looking for a descriptor. Either validate it as a
616 * single-character primitive type, or continue on to check the
617 * embedded class name (bracketed by "L" and ";").
618 */
619 switch (*(s++)) {
620 case 'B':
621 case 'C':
622 case 'D':
623 case 'F':
624 case 'I':
625 case 'J':
626 case 'S':
627 case 'Z':
628 // These are all single-character descriptors for primitive types.
629 return (*s == '\0');
630 case 'V':
631 // Non-array void is valid, but you can't have an array of void.
632 return (arrayCount == 0) && (*s == '\0');
633 case 'L':
634 // Class name: Break out and continue below.
635 break;
636 default:
637 // Oddball descriptor character.
638 return false;
639 }
640 }
641
642 /*
643 * We just consumed the 'L' that introduces a class name as part
644 * of a type descriptor, or we are looking for an unadorned class
645 * name.
646 */
647
648 bool sepOrFirst = true; // first character or just encountered a separator.
649 for (;;) {
650 uint8_t c = (uint8_t) *s;
651 switch (c) {
652 case '\0':
653 /*
654 * Premature end for a type descriptor, but valid for
655 * a class name as long as we haven't encountered an
656 * empty component (including the degenerate case of
657 * the empty string "").
658 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700659 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700660 case ';':
661 /*
662 * Invalid character for a class name, but the
663 * legitimate end of a type descriptor. In the latter
664 * case, make sure that this is the end of the string
665 * and that it doesn't end with an empty component
666 * (including the degenerate case of "L;").
667 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700668 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700669 case '/':
670 case '.':
671 if (c != separator) {
672 // The wrong separator character.
673 return false;
674 }
675 if (sepOrFirst) {
676 // Separator at start or two separators in a row.
677 return false;
678 }
679 sepOrFirst = true;
680 s++;
681 break;
682 default:
jeffhao10037c82012-01-23 15:06:23 -0800683 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700684 return false;
685 }
686 sepOrFirst = false;
687 break;
688 }
689 }
690}
691
Elliott Hughes906e6852011-10-28 14:52:10 -0700692bool IsValidBinaryClassName(const char* s) {
693 return IsValidClassName(s, kName, '.');
694}
695
696bool IsValidJniClassName(const char* s) {
697 return IsValidClassName(s, kName, '/');
698}
699
700bool IsValidDescriptor(const char* s) {
701 return IsValidClassName(s, kDescriptor, '/');
702}
703
Elliott Hughes48436bb2012-02-07 15:23:28 -0800704void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700705 const char* p = s.data();
706 const char* end = p + s.size();
707 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800708 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700709 ++p;
710 } else {
711 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800712 while (++p != end && *p != separator) {
713 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700714 }
715 result.push_back(std::string(start, p - start));
716 }
717 }
718}
719
Elliott Hughes48436bb2012-02-07 15:23:28 -0800720template <typename StringT>
721std::string Join(std::vector<StringT>& strings, char separator) {
722 if (strings.empty()) {
723 return "";
724 }
725
726 std::string result(strings[0]);
727 for (size_t i = 1; i < strings.size(); ++i) {
728 result += separator;
729 result += strings[i];
730 }
731 return result;
732}
733
734// Explicit instantiations.
735template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
736template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
737template std::string Join<char*>(std::vector<char*>& strings, char separator);
738
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800739bool StartsWith(const std::string& s, const char* prefix) {
740 return s.compare(0, strlen(prefix), prefix) == 0;
741}
742
Elliott Hughes22869a92012-03-27 14:08:24 -0700743void SetThreadName(const char* thread_name) {
744 ANNOTATE_THREAD_NAME(thread_name); // For tsan.
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800745
Elliott Hughesdcc24742011-09-07 14:02:44 -0700746 int hasAt = 0;
747 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700748 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700749 while (*s) {
750 if (*s == '.') {
751 hasDot = 1;
752 } else if (*s == '@') {
753 hasAt = 1;
754 }
755 s++;
756 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700757 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700758 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700759 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700760 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700761 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700762 }
763#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700764 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700765 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
766 strncpy(buf, s, sizeof(buf)-1);
767 buf[sizeof(buf)-1] = '\0';
768 errno = pthread_setname_np(pthread_self(), buf);
769 if (errno != 0) {
770 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
771 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700772#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700773 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700774#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700775 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700776#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700777 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700778#endif
779}
780
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700781void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
782 utime = stime = task_cpu = 0;
783 std::string stats;
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700784 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid).c_str(), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700785 return;
786 }
787 // Skip the command, which may contain spaces.
788 stats = stats.substr(stats.find(')') + 2);
789 // Extract the three fields we care about.
790 std::vector<std::string> fields;
791 Split(stats, ' ', fields);
792 utime = strtoull(fields[11].c_str(), NULL, 10);
793 stime = strtoull(fields[12].c_str(), NULL, 10);
794 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
795}
796
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700797std::string GetSchedulerGroupName(pid_t tid) {
798 // /proc/<pid>/cgroup looks like this:
799 // 2:devices:/
800 // 1:cpuacct,cpu:/
801 // We want the third field from the line whose second field contains the "cpu" token.
802 std::string cgroup_file;
803 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
804 return "";
805 }
806 std::vector<std::string> cgroup_lines;
807 Split(cgroup_file, '\n', cgroup_lines);
808 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
809 std::vector<std::string> cgroup_fields;
810 Split(cgroup_lines[i], ':', cgroup_fields);
811 std::vector<std::string> cgroups;
812 Split(cgroup_fields[1], ',', cgroups);
813 for (size_t i = 0; i < cgroups.size(); ++i) {
814 if (cgroups[i] == "cpu") {
815 return cgroup_fields[2].substr(1); // Skip the leading slash.
816 }
817 }
818 }
819 return "";
820}
821
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800822const char* GetAndroidRoot() {
823 const char* android_root = getenv("ANDROID_ROOT");
824 if (android_root == NULL) {
825 if (OS::DirectoryExists("/system")) {
826 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700827 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800828 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
829 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700830 }
831 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800832 if (!OS::DirectoryExists(android_root)) {
833 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700834 return "";
835 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800836 return android_root;
837}
Brian Carlstroma9f19782011-10-13 00:14:47 -0700838
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800839const char* GetAndroidData() {
840 const char* android_data = getenv("ANDROID_DATA");
841 if (android_data == NULL) {
842 if (OS::DirectoryExists("/data")) {
843 android_data = "/data";
844 } else {
845 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
846 return "";
847 }
848 }
849 if (!OS::DirectoryExists(android_data)) {
850 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
851 return "";
852 }
853 return android_data;
854}
855
856std::string GetArtCacheOrDie() {
857 std::string art_cache(StringPrintf("%s/art-cache", GetAndroidData()));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700858
859 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800860 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700861 int result = mkdir(art_cache.c_str(), 0700);
862 if (result != 0) {
863 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
864 return "";
865 }
866 } else {
867 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
868 return "";
869 }
870 }
871 return art_cache;
872}
873
jeffhao262bf462011-10-20 18:36:32 -0700874std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800875 std::string art_cache(GetArtCacheOrDie());
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800876 CHECK_EQ(location[0], '/') << location;
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700877 std::string cache_file(location, 1); // skip leading slash
878 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
879 return art_cache + "/" + cache_file;
880}
881
jeffhao262bf462011-10-20 18:36:32 -0700882bool IsValidZipFilename(const std::string& filename) {
883 if (filename.size() < 4) {
884 return false;
885 }
886 std::string suffix(filename.substr(filename.size() - 4));
887 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
888}
889
890bool IsValidDexFilename(const std::string& filename) {
891 if (filename.size() < 4) {
892 return false;
893 }
894 std::string suffix(filename.substr(filename.size() - 4));
895 return (suffix == ".dex");
896}
897
Elliott Hughes42ee1422011-09-06 12:33:32 -0700898} // namespace art