blob: 01fdac2df0cddcaeffb59c2c7916feff4fce6e47 [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"
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() {
53#if defined(__APPLE__)
Elliott Hughesf1498432012-03-28 19:34:27 -070054 // gettid(2) returns -1 on Darwin, but thread_selfid(2) works, and seems to be what their
55 // pthreads implementation uses.
56 return syscall(SYS_thread_selfid);
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080057#else
58 // Neither bionic nor glibc exposes gettid(2).
59 return syscall(__NR_gettid);
60#endif
61}
62
Elliott Hughesd92bec42011-09-02 17:04:36 -070063bool ReadFileToString(const std::string& file_name, std::string* result) {
64 UniquePtr<File> file(OS::OpenFile(file_name.c_str(), false));
65 if (file.get() == NULL) {
66 return false;
67 }
buzbeec143c552011-08-20 17:38:58 -070068
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070069 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -070070 while (true) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070071 int64_t n = file->Read(&buf[0], buf.size());
Elliott Hughesd92bec42011-09-02 17:04:36 -070072 if (n == -1) {
73 return false;
buzbeec143c552011-08-20 17:38:58 -070074 }
Elliott Hughesd92bec42011-09-02 17:04:36 -070075 if (n == 0) {
76 return true;
77 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070078 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -070079 }
buzbeec143c552011-08-20 17:38:58 -070080}
81
Elliott Hughese27955c2011-08-26 15:21:24 -070082std::string GetIsoDate() {
83 time_t now = time(NULL);
84 struct tm tmbuf;
85 struct tm* ptm = localtime_r(&now, &tmbuf);
86 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
87 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
88 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
89}
90
Elliott Hughes7162ad92011-10-27 14:08:42 -070091uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -080092#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7162ad92011-10-27 14:08:42 -070093 struct timespec now;
94 clock_gettime(CLOCK_MONOTONIC, &now);
95 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -080096#else
97 struct timeval now;
98 gettimeofday(&now, NULL);
99 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
100#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700101}
102
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800103uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800104#if defined(HAVE_POSIX_CLOCKS)
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800105 struct timespec now;
106 clock_gettime(CLOCK_MONOTONIC, &now);
107 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800108#else
109 struct timeval now;
110 gettimeofday(&now, NULL);
111 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec * 1000LL;
112#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800113}
114
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700115uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800116#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700117 struct timespec now;
118 clock_gettime(CLOCK_MONOTONIC, &now);
119 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800120#else
121 struct timeval now;
122 gettimeofday(&now, NULL);
123 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
124#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700125}
126
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800127uint64_t ThreadCpuMicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800128#if defined(HAVE_POSIX_CLOCKS)
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800129 struct timespec now;
130 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
131 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800132#else
133 UNIMPLEMENTED(WARNING);
134 return -1;
135#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800136}
137
Elliott Hughes0512f022012-03-15 22:10:52 -0700138uint64_t ThreadCpuNanoTime() {
139#if defined(HAVE_POSIX_CLOCKS)
140 struct timespec now;
141 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
142 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
143#else
144 UNIMPLEMENTED(WARNING);
145 return -1;
146#endif
147}
148
Elliott Hughes5174fe62011-08-23 15:12:35 -0700149std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700150 if (java_descriptor == NULL) {
151 return "null";
152 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700153 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
154}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700155
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800156std::string PrettyDescriptor(const Class* klass) {
157 if (klass == NULL) {
158 return "null";
159 }
160 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800161}
162
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700163std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700164 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700165 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700166 size_t dim = 0;
167 while (*c == '[') {
168 dim++;
169 c++;
170 }
171
172 // Reference or primitive?
173 if (*c == 'L') {
174 // "[[La/b/C;" -> "a.b.C[][]".
175 c++; // Skip the 'L'.
176 } else {
177 // "[[B" -> "byte[][]".
178 // To make life easier, we make primitives look like unqualified
179 // reference types.
180 switch (*c) {
181 case 'B': c = "byte;"; break;
182 case 'C': c = "char;"; break;
183 case 'D': c = "double;"; break;
184 case 'F': c = "float;"; break;
185 case 'I': c = "int;"; break;
186 case 'J': c = "long;"; break;
187 case 'S': c = "short;"; break;
188 case 'Z': c = "boolean;"; break;
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700189 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700190 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700191 }
192 }
193
194 // At this point, 'c' is a string of the form "fully/qualified/Type;"
195 // or "primitive;". Rewrite the type with '.' instead of '/':
196 std::string result;
197 const char* p = c;
198 while (*p != ';') {
199 char ch = *p++;
200 if (ch == '/') {
201 ch = '.';
202 }
203 result.push_back(ch);
204 }
205 // ...and replace the semicolon with 'dim' "[]" pairs:
206 while (dim--) {
207 result += "[]";
208 }
209 return result;
210}
211
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700212std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800213 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700214 return PrettyDescriptor(descriptor_string);
215}
216
Elliott Hughes54e7df12011-09-16 11:47:04 -0700217std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700218 if (f == NULL) {
219 return "null";
220 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800221 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700222 std::string result;
223 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800224 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700225 result += ' ';
226 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800227 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700228 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800229 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700230 return result;
231}
232
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700233std::string PrettyArguments(const char* signature) {
234 std::string result;
235 result += '(';
236 CHECK_EQ(*signature, '(');
237 ++signature; // Skip the '('.
238 while (*signature != ')') {
239 size_t argument_length = 0;
240 while (signature[argument_length] == '[') {
241 ++argument_length;
242 }
243 if (signature[argument_length] == 'L') {
244 argument_length = (strchr(signature, ';') - signature + 1);
245 } else {
246 ++argument_length;
247 }
248 std::string argument_descriptor(signature, argument_length);
249 result += PrettyDescriptor(argument_descriptor);
250 if (signature[argument_length] != ')') {
251 result += ", ";
252 }
253 signature += argument_length;
254 }
255 CHECK_EQ(*signature, ')');
256 ++signature; // Skip the ')'.
257 result += ')';
258 return result;
259}
260
261std::string PrettyReturnType(const char* signature) {
262 const char* return_type = strchr(signature, ')');
263 CHECK(return_type != NULL);
264 ++return_type; // Skip ')'.
265 return PrettyDescriptor(return_type);
266}
267
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700268std::string PrettyMethod(const Method* m, bool with_signature) {
269 if (m == NULL) {
270 return "null";
271 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800272 MethodHelper mh(m);
273 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700274 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800275 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700276 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700277 std::string signature(mh.GetSignature());
Elliott Hughesf8c11932012-03-23 19:53:59 -0700278 if (signature == "<no signature>") {
279 return result + signature;
280 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700281 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700282 }
283 return result;
284}
285
Ian Rogers0571d352011-11-03 19:51:38 -0700286std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
287 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
288 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
289 result += '.';
290 result += dex_file.GetMethodName(method_id);
291 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700292 std::string signature(dex_file.GetMethodSignature(method_id));
Elliott Hughesf8c11932012-03-23 19:53:59 -0700293 if (signature == "<no signature>") {
294 return result + signature;
295 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700296 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700297 }
298 return result;
299}
300
Elliott Hughes54e7df12011-09-16 11:47:04 -0700301std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700302 if (obj == NULL) {
303 return "null";
304 }
305 if (obj->GetClass() == NULL) {
306 return "(raw)";
307 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800308 ClassHelper kh(obj->GetClass());
309 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700310 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800311 kh.ChangeClass(obj->AsClass());
312 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700313 }
314 return result;
315}
316
Elliott Hughes54e7df12011-09-16 11:47:04 -0700317std::string PrettyClass(const Class* c) {
318 if (c == NULL) {
319 return "null";
320 }
321 std::string result;
322 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800323 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700324 result += ">";
325 return result;
326}
327
Ian Rogersd81871c2011-10-03 13:57:23 -0700328std::string PrettyClassAndClassLoader(const Class* c) {
329 if (c == NULL) {
330 return "null";
331 }
332 std::string result;
333 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800334 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700335 result += ",";
336 result += PrettyTypeOf(c->GetClassLoader());
337 // TODO: add an identifying hash value for the loader
338 result += ">";
339 return result;
340}
341
Ian Rogers3bb17a62012-01-27 23:56:44 -0800342std::string PrettySize(size_t size_in_bytes) {
343 if ((size_in_bytes / GB) * GB == size_in_bytes) {
344 return StringPrintf("%zdGB", size_in_bytes / GB);
345 } else if ((size_in_bytes / MB) * MB == size_in_bytes) {
346 return StringPrintf("%zdMB", size_in_bytes / MB);
347 } else if ((size_in_bytes / KB) * KB == size_in_bytes) {
348 return StringPrintf("%zdKiB", size_in_bytes / KB);
349 } else {
350 return StringPrintf("%zdB", size_in_bytes);
351 }
352}
353
354std::string PrettyDuration(uint64_t nano_duration) {
355 if (nano_duration == 0) {
356 return "0";
357 } else {
358 const uint64_t one_sec = 1000 * 1000 * 1000;
359 const uint64_t one_ms = 1000 * 1000;
360 const uint64_t one_us = 1000;
361 const char* unit;
362 uint64_t divisor;
363 uint32_t zero_fill;
364 if (nano_duration >= one_sec) {
365 unit = "s";
366 divisor = one_sec;
367 zero_fill = 9;
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700368 } else if (nano_duration >= one_ms) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800369 unit = "ms";
370 divisor = one_ms;
371 zero_fill = 6;
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700372 } else if (nano_duration >= one_us) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800373 unit = "us";
374 divisor = one_us;
375 zero_fill = 3;
376 } else {
377 unit = "ns";
378 divisor = 1;
379 zero_fill = 0;
380 }
381 uint64_t whole_part = nano_duration / divisor;
382 uint64_t fractional_part = nano_duration % divisor;
383 if (fractional_part == 0) {
384 return StringPrintf("%llu%s", whole_part, unit);
385 } else {
386 while ((fractional_part % 1000) == 0) {
387 zero_fill -= 3;
388 fractional_part /= 1000;
389 }
390 if (zero_fill == 3) {
391 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
392 } else if (zero_fill == 6) {
393 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
394 } else {
395 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
396 }
397 }
398 }
399}
400
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800401// 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 -0700402std::string MangleForJni(const std::string& s) {
403 std::string result;
404 size_t char_count = CountModifiedUtf8Chars(s.c_str());
405 const char* cp = &s[0];
406 for (size_t i = 0; i < char_count; ++i) {
407 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800408 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
409 result.push_back(ch);
410 } else if (ch == '.' || ch == '/') {
411 result += "_";
412 } else if (ch == '_') {
413 result += "_1";
414 } else if (ch == ';') {
415 result += "_2";
416 } else if (ch == '[') {
417 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700418 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800419 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700420 }
421 }
422 return result;
423}
424
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700425std::string DotToDescriptor(const char* class_name) {
426 std::string descriptor(class_name);
427 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
428 if (descriptor.length() > 0 && descriptor[0] != '[') {
429 descriptor = "L" + descriptor + ";";
430 }
431 return descriptor;
432}
433
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800434std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800435 size_t length = strlen(descriptor);
436 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
437 std::string result(descriptor + 1, length - 2);
438 std::replace(result.begin(), result.end(), '/', '.');
439 return result;
440 }
441 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800442}
443
444std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800445 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800446 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
447 std::string result(descriptor + 1, length - 2);
448 return result;
449 }
450 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700451}
452
Elliott Hughes79082e32011-08-25 12:07:32 -0700453std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800454 MethodHelper mh(m);
455 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700456 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700457 CHECK_EQ(class_name[0], 'L') << class_name;
458 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700459 class_name.erase(0, 1);
460 class_name.erase(class_name.size() - 1, 1);
461
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800462 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700463
464 std::string short_name;
465 short_name += "Java_";
466 short_name += MangleForJni(class_name);
467 short_name += "_";
468 short_name += MangleForJni(method_name);
469 return short_name;
470}
471
472std::string JniLongName(const Method* m) {
473 std::string long_name;
474 long_name += JniShortName(m);
475 long_name += "__";
476
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800477 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700478 signature.erase(0, 1);
479 signature.erase(signature.begin() + signature.find(')'), signature.end());
480
481 long_name += MangleForJni(signature);
482
483 return long_name;
484}
485
jeffhao10037c82012-01-23 15:06:23 -0800486// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700487uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
488 0x00000000, // 00..1f low control characters; nothing valid
489 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
490 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
491 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
492};
493
jeffhao10037c82012-01-23 15:06:23 -0800494// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
495bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700496 /*
497 * It's a multibyte encoded character. Decode it and analyze. We
498 * accept anything that isn't (a) an improperly encoded low value,
499 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
500 * control character, or (e) a high space, layout, or special
501 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
502 * U+fff0..U+ffff). This is all specified in the dex format
503 * document.
504 */
505
506 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
507
508 // Perform follow-up tests based on the high 8 bits.
509 switch (utf16 >> 8) {
510 case 0x00:
511 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
512 return (utf16 > 0x00a0);
513 case 0xd8:
514 case 0xd9:
515 case 0xda:
516 case 0xdb:
517 // It's a leading surrogate. Check to see that a trailing
518 // surrogate follows.
519 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
520 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
521 case 0xdc:
522 case 0xdd:
523 case 0xde:
524 case 0xdf:
525 // It's a trailing surrogate, which is not valid at this point.
526 return false;
527 case 0x20:
528 case 0xff:
529 // It's in the range that has spaces, controls, and specials.
530 switch (utf16 & 0xfff8) {
531 case 0x2000:
532 case 0x2008:
533 case 0x2028:
534 case 0xfff0:
535 case 0xfff8:
536 return false;
537 }
538 break;
539 }
540 return true;
541}
542
543/* Return whether the pointed-at modified-UTF-8 encoded character is
544 * valid as part of a member name, updating the pointer to point past
545 * the consumed character. This will consume two encoded UTF-16 code
546 * points if the character is encoded as a surrogate pair. Also, if
547 * this function returns false, then the given pointer may only have
548 * been partially advanced.
549 */
jeffhao10037c82012-01-23 15:06:23 -0800550bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700551 uint8_t c = (uint8_t) **pUtf8Ptr;
552 if (c <= 0x7f) {
553 // It's low-ascii, so check the table.
554 uint32_t wordIdx = c >> 5;
555 uint32_t bitIdx = c & 0x1f;
556 (*pUtf8Ptr)++;
557 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
558 }
559
560 // It's a multibyte encoded character. Call a non-inline function
561 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800562 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
563}
564
565bool IsValidMemberName(const char* s) {
566 bool angle_name = false;
567
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700568 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800569 case '\0':
570 // The empty string is not a valid name.
571 return false;
572 case '<':
573 angle_name = true;
574 s++;
575 break;
576 }
577
578 while (true) {
579 switch (*s) {
580 case '\0':
581 return !angle_name;
582 case '>':
583 return angle_name && s[1] == '\0';
584 }
585
586 if (!IsValidPartOfMemberNameUtf8(&s)) {
587 return false;
588 }
589 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700590}
591
Elliott Hughes906e6852011-10-28 14:52:10 -0700592enum ClassNameType { kName, kDescriptor };
593bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700594 int arrayCount = 0;
595 while (*s == '[') {
596 arrayCount++;
597 s++;
598 }
599
600 if (arrayCount > 255) {
601 // Arrays may have no more than 255 dimensions.
602 return false;
603 }
604
605 if (arrayCount != 0) {
606 /*
607 * If we're looking at an array of some sort, then it doesn't
608 * matter if what is being asked for is a class name; the
609 * format looks the same as a type descriptor in that case, so
610 * treat it as such.
611 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700612 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700613 }
614
Elliott Hughes906e6852011-10-28 14:52:10 -0700615 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700616 /*
617 * We are looking for a descriptor. Either validate it as a
618 * single-character primitive type, or continue on to check the
619 * embedded class name (bracketed by "L" and ";").
620 */
621 switch (*(s++)) {
622 case 'B':
623 case 'C':
624 case 'D':
625 case 'F':
626 case 'I':
627 case 'J':
628 case 'S':
629 case 'Z':
630 // These are all single-character descriptors for primitive types.
631 return (*s == '\0');
632 case 'V':
633 // Non-array void is valid, but you can't have an array of void.
634 return (arrayCount == 0) && (*s == '\0');
635 case 'L':
636 // Class name: Break out and continue below.
637 break;
638 default:
639 // Oddball descriptor character.
640 return false;
641 }
642 }
643
644 /*
645 * We just consumed the 'L' that introduces a class name as part
646 * of a type descriptor, or we are looking for an unadorned class
647 * name.
648 */
649
650 bool sepOrFirst = true; // first character or just encountered a separator.
651 for (;;) {
652 uint8_t c = (uint8_t) *s;
653 switch (c) {
654 case '\0':
655 /*
656 * Premature end for a type descriptor, but valid for
657 * a class name as long as we haven't encountered an
658 * empty component (including the degenerate case of
659 * the empty string "").
660 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700661 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700662 case ';':
663 /*
664 * Invalid character for a class name, but the
665 * legitimate end of a type descriptor. In the latter
666 * case, make sure that this is the end of the string
667 * and that it doesn't end with an empty component
668 * (including the degenerate case of "L;").
669 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700670 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700671 case '/':
672 case '.':
673 if (c != separator) {
674 // The wrong separator character.
675 return false;
676 }
677 if (sepOrFirst) {
678 // Separator at start or two separators in a row.
679 return false;
680 }
681 sepOrFirst = true;
682 s++;
683 break;
684 default:
jeffhao10037c82012-01-23 15:06:23 -0800685 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700686 return false;
687 }
688 sepOrFirst = false;
689 break;
690 }
691 }
692}
693
Elliott Hughes906e6852011-10-28 14:52:10 -0700694bool IsValidBinaryClassName(const char* s) {
695 return IsValidClassName(s, kName, '.');
696}
697
698bool IsValidJniClassName(const char* s) {
699 return IsValidClassName(s, kName, '/');
700}
701
702bool IsValidDescriptor(const char* s) {
703 return IsValidClassName(s, kDescriptor, '/');
704}
705
Elliott Hughes48436bb2012-02-07 15:23:28 -0800706void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700707 const char* p = s.data();
708 const char* end = p + s.size();
709 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800710 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700711 ++p;
712 } else {
713 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800714 while (++p != end && *p != separator) {
715 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700716 }
717 result.push_back(std::string(start, p - start));
718 }
719 }
720}
721
Elliott Hughes48436bb2012-02-07 15:23:28 -0800722template <typename StringT>
723std::string Join(std::vector<StringT>& strings, char separator) {
724 if (strings.empty()) {
725 return "";
726 }
727
728 std::string result(strings[0]);
729 for (size_t i = 1; i < strings.size(); ++i) {
730 result += separator;
731 result += strings[i];
732 }
733 return result;
734}
735
736// Explicit instantiations.
737template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
738template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
739template std::string Join<char*>(std::vector<char*>& strings, char separator);
740
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800741bool StartsWith(const std::string& s, const char* prefix) {
742 return s.compare(0, strlen(prefix), prefix) == 0;
743}
744
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700745bool EndsWith(const std::string& s, const char* suffix) {
746 size_t suffix_length = strlen(suffix);
747 size_t string_length = s.size();
748 if (suffix_length > string_length) {
749 return false;
750 }
751 size_t offset = string_length - suffix_length;
752 return s.compare(offset, suffix_length, suffix) == 0;
753}
754
Elliott Hughes22869a92012-03-27 14:08:24 -0700755void SetThreadName(const char* thread_name) {
756 ANNOTATE_THREAD_NAME(thread_name); // For tsan.
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800757
Elliott Hughesdcc24742011-09-07 14:02:44 -0700758 int hasAt = 0;
759 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700760 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700761 while (*s) {
762 if (*s == '.') {
763 hasDot = 1;
764 } else if (*s == '@') {
765 hasAt = 1;
766 }
767 s++;
768 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700769 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700770 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700771 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700772 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700773 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700774 }
775#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700776 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700777 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
778 strncpy(buf, s, sizeof(buf)-1);
779 buf[sizeof(buf)-1] = '\0';
780 errno = pthread_setname_np(pthread_self(), buf);
781 if (errno != 0) {
782 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
783 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700784#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700785 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700786#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700787 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700788#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700789 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700790#endif
791}
792
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700793void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
794 utime = stime = task_cpu = 0;
795 std::string stats;
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700796 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid).c_str(), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700797 return;
798 }
799 // Skip the command, which may contain spaces.
800 stats = stats.substr(stats.find(')') + 2);
801 // Extract the three fields we care about.
802 std::vector<std::string> fields;
803 Split(stats, ' ', fields);
804 utime = strtoull(fields[11].c_str(), NULL, 10);
805 stime = strtoull(fields[12].c_str(), NULL, 10);
806 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
807}
808
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700809std::string GetSchedulerGroupName(pid_t tid) {
810 // /proc/<pid>/cgroup looks like this:
811 // 2:devices:/
812 // 1:cpuacct,cpu:/
813 // We want the third field from the line whose second field contains the "cpu" token.
814 std::string cgroup_file;
815 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
816 return "";
817 }
818 std::vector<std::string> cgroup_lines;
819 Split(cgroup_file, '\n', cgroup_lines);
820 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
821 std::vector<std::string> cgroup_fields;
822 Split(cgroup_lines[i], ':', cgroup_fields);
823 std::vector<std::string> cgroups;
824 Split(cgroup_fields[1], ',', cgroups);
825 for (size_t i = 0; i < cgroups.size(); ++i) {
826 if (cgroups[i] == "cpu") {
827 return cgroup_fields[2].substr(1); // Skip the leading slash.
828 }
829 }
830 }
831 return "";
832}
833
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800834const char* GetAndroidRoot() {
835 const char* android_root = getenv("ANDROID_ROOT");
836 if (android_root == NULL) {
837 if (OS::DirectoryExists("/system")) {
838 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700839 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800840 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
841 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700842 }
843 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800844 if (!OS::DirectoryExists(android_root)) {
845 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700846 return "";
847 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800848 return android_root;
849}
Brian Carlstroma9f19782011-10-13 00:14:47 -0700850
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800851const char* GetAndroidData() {
852 const char* android_data = getenv("ANDROID_DATA");
853 if (android_data == NULL) {
854 if (OS::DirectoryExists("/data")) {
855 android_data = "/data";
856 } else {
857 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
858 return "";
859 }
860 }
861 if (!OS::DirectoryExists(android_data)) {
862 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
863 return "";
864 }
865 return android_data;
866}
867
868std::string GetArtCacheOrDie() {
869 std::string art_cache(StringPrintf("%s/art-cache", GetAndroidData()));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700870
871 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800872 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700873 int result = mkdir(art_cache.c_str(), 0700);
874 if (result != 0) {
875 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
876 return "";
877 }
878 } else {
879 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
880 return "";
881 }
882 }
883 return art_cache;
884}
885
jeffhao262bf462011-10-20 18:36:32 -0700886std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800887 std::string art_cache(GetArtCacheOrDie());
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800888 CHECK_EQ(location[0], '/') << location;
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700889 std::string cache_file(location, 1); // skip leading slash
890 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
891 return art_cache + "/" + cache_file;
892}
893
jeffhao262bf462011-10-20 18:36:32 -0700894bool IsValidZipFilename(const std::string& filename) {
895 if (filename.size() < 4) {
896 return false;
897 }
898 std::string suffix(filename.substr(filename.size() - 4));
899 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
900}
901
902bool IsValidDexFilename(const std::string& filename) {
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700903 return EndsWith(filename, ".dex");
904}
905
906bool IsValidOatFilename(const std::string& filename) {
907 return EndsWith(filename, ".oat");
jeffhao262bf462011-10-20 18:36:32 -0700908}
909
Elliott Hughes42ee1422011-09-06 12:33:32 -0700910} // namespace art