blob: 389c280ed38985a04042f808e15a44941b10df20 [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());
276 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700277 }
278 return result;
279}
280
Ian Rogers0571d352011-11-03 19:51:38 -0700281std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
282 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
283 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
284 result += '.';
285 result += dex_file.GetMethodName(method_id);
286 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700287 std::string signature(dex_file.GetMethodSignature(method_id));
288 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700289 }
290 return result;
291}
292
Elliott Hughes54e7df12011-09-16 11:47:04 -0700293std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700294 if (obj == NULL) {
295 return "null";
296 }
297 if (obj->GetClass() == NULL) {
298 return "(raw)";
299 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800300 ClassHelper kh(obj->GetClass());
301 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700302 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800303 kh.ChangeClass(obj->AsClass());
304 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700305 }
306 return result;
307}
308
Elliott Hughes54e7df12011-09-16 11:47:04 -0700309std::string PrettyClass(const Class* c) {
310 if (c == NULL) {
311 return "null";
312 }
313 std::string result;
314 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800315 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700316 result += ">";
317 return result;
318}
319
Ian Rogersd81871c2011-10-03 13:57:23 -0700320std::string PrettyClassAndClassLoader(const Class* c) {
321 if (c == NULL) {
322 return "null";
323 }
324 std::string result;
325 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800326 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700327 result += ",";
328 result += PrettyTypeOf(c->GetClassLoader());
329 // TODO: add an identifying hash value for the loader
330 result += ">";
331 return result;
332}
333
Ian Rogers3bb17a62012-01-27 23:56:44 -0800334std::string PrettySize(size_t size_in_bytes) {
335 if ((size_in_bytes / GB) * GB == size_in_bytes) {
336 return StringPrintf("%zdGB", size_in_bytes / GB);
337 } else if ((size_in_bytes / MB) * MB == size_in_bytes) {
338 return StringPrintf("%zdMB", size_in_bytes / MB);
339 } else if ((size_in_bytes / KB) * KB == size_in_bytes) {
340 return StringPrintf("%zdKiB", size_in_bytes / KB);
341 } else {
342 return StringPrintf("%zdB", size_in_bytes);
343 }
344}
345
346std::string PrettyDuration(uint64_t nano_duration) {
347 if (nano_duration == 0) {
348 return "0";
349 } else {
350 const uint64_t one_sec = 1000 * 1000 * 1000;
351 const uint64_t one_ms = 1000 * 1000;
352 const uint64_t one_us = 1000;
353 const char* unit;
354 uint64_t divisor;
355 uint32_t zero_fill;
356 if (nano_duration >= one_sec) {
357 unit = "s";
358 divisor = one_sec;
359 zero_fill = 9;
360 } else if(nano_duration >= one_ms) {
361 unit = "ms";
362 divisor = one_ms;
363 zero_fill = 6;
364 } else if(nano_duration >= one_us) {
365 unit = "us";
366 divisor = one_us;
367 zero_fill = 3;
368 } else {
369 unit = "ns";
370 divisor = 1;
371 zero_fill = 0;
372 }
373 uint64_t whole_part = nano_duration / divisor;
374 uint64_t fractional_part = nano_duration % divisor;
375 if (fractional_part == 0) {
376 return StringPrintf("%llu%s", whole_part, unit);
377 } else {
378 while ((fractional_part % 1000) == 0) {
379 zero_fill -= 3;
380 fractional_part /= 1000;
381 }
382 if (zero_fill == 3) {
383 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
384 } else if (zero_fill == 6) {
385 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
386 } else {
387 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
388 }
389 }
390 }
391}
392
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800393// 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 -0700394std::string MangleForJni(const std::string& s) {
395 std::string result;
396 size_t char_count = CountModifiedUtf8Chars(s.c_str());
397 const char* cp = &s[0];
398 for (size_t i = 0; i < char_count; ++i) {
399 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800400 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
401 result.push_back(ch);
402 } else if (ch == '.' || ch == '/') {
403 result += "_";
404 } else if (ch == '_') {
405 result += "_1";
406 } else if (ch == ';') {
407 result += "_2";
408 } else if (ch == '[') {
409 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700410 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800411 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700412 }
413 }
414 return result;
415}
416
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700417std::string DotToDescriptor(const char* class_name) {
418 std::string descriptor(class_name);
419 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
420 if (descriptor.length() > 0 && descriptor[0] != '[') {
421 descriptor = "L" + descriptor + ";";
422 }
423 return descriptor;
424}
425
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800426std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800427 size_t length = strlen(descriptor);
428 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
429 std::string result(descriptor + 1, length - 2);
430 std::replace(result.begin(), result.end(), '/', '.');
431 return result;
432 }
433 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800434}
435
436std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800437 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800438 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
439 std::string result(descriptor + 1, length - 2);
440 return result;
441 }
442 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700443}
444
Elliott Hughes79082e32011-08-25 12:07:32 -0700445std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800446 MethodHelper mh(m);
447 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700448 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700449 CHECK_EQ(class_name[0], 'L') << class_name;
450 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700451 class_name.erase(0, 1);
452 class_name.erase(class_name.size() - 1, 1);
453
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800454 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700455
456 std::string short_name;
457 short_name += "Java_";
458 short_name += MangleForJni(class_name);
459 short_name += "_";
460 short_name += MangleForJni(method_name);
461 return short_name;
462}
463
464std::string JniLongName(const Method* m) {
465 std::string long_name;
466 long_name += JniShortName(m);
467 long_name += "__";
468
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800469 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700470 signature.erase(0, 1);
471 signature.erase(signature.begin() + signature.find(')'), signature.end());
472
473 long_name += MangleForJni(signature);
474
475 return long_name;
476}
477
jeffhao10037c82012-01-23 15:06:23 -0800478// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700479uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
480 0x00000000, // 00..1f low control characters; nothing valid
481 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
482 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
483 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
484};
485
jeffhao10037c82012-01-23 15:06:23 -0800486// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
487bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700488 /*
489 * It's a multibyte encoded character. Decode it and analyze. We
490 * accept anything that isn't (a) an improperly encoded low value,
491 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
492 * control character, or (e) a high space, layout, or special
493 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
494 * U+fff0..U+ffff). This is all specified in the dex format
495 * document.
496 */
497
498 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
499
500 // Perform follow-up tests based on the high 8 bits.
501 switch (utf16 >> 8) {
502 case 0x00:
503 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
504 return (utf16 > 0x00a0);
505 case 0xd8:
506 case 0xd9:
507 case 0xda:
508 case 0xdb:
509 // It's a leading surrogate. Check to see that a trailing
510 // surrogate follows.
511 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
512 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
513 case 0xdc:
514 case 0xdd:
515 case 0xde:
516 case 0xdf:
517 // It's a trailing surrogate, which is not valid at this point.
518 return false;
519 case 0x20:
520 case 0xff:
521 // It's in the range that has spaces, controls, and specials.
522 switch (utf16 & 0xfff8) {
523 case 0x2000:
524 case 0x2008:
525 case 0x2028:
526 case 0xfff0:
527 case 0xfff8:
528 return false;
529 }
530 break;
531 }
532 return true;
533}
534
535/* Return whether the pointed-at modified-UTF-8 encoded character is
536 * valid as part of a member name, updating the pointer to point past
537 * the consumed character. This will consume two encoded UTF-16 code
538 * points if the character is encoded as a surrogate pair. Also, if
539 * this function returns false, then the given pointer may only have
540 * been partially advanced.
541 */
jeffhao10037c82012-01-23 15:06:23 -0800542bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700543 uint8_t c = (uint8_t) **pUtf8Ptr;
544 if (c <= 0x7f) {
545 // It's low-ascii, so check the table.
546 uint32_t wordIdx = c >> 5;
547 uint32_t bitIdx = c & 0x1f;
548 (*pUtf8Ptr)++;
549 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
550 }
551
552 // It's a multibyte encoded character. Call a non-inline function
553 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800554 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
555}
556
557bool IsValidMemberName(const char* s) {
558 bool angle_name = false;
559
560 switch(*s) {
561 case '\0':
562 // The empty string is not a valid name.
563 return false;
564 case '<':
565 angle_name = true;
566 s++;
567 break;
568 }
569
570 while (true) {
571 switch (*s) {
572 case '\0':
573 return !angle_name;
574 case '>':
575 return angle_name && s[1] == '\0';
576 }
577
578 if (!IsValidPartOfMemberNameUtf8(&s)) {
579 return false;
580 }
581 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700582}
583
Elliott Hughes906e6852011-10-28 14:52:10 -0700584enum ClassNameType { kName, kDescriptor };
585bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700586 int arrayCount = 0;
587 while (*s == '[') {
588 arrayCount++;
589 s++;
590 }
591
592 if (arrayCount > 255) {
593 // Arrays may have no more than 255 dimensions.
594 return false;
595 }
596
597 if (arrayCount != 0) {
598 /*
599 * If we're looking at an array of some sort, then it doesn't
600 * matter if what is being asked for is a class name; the
601 * format looks the same as a type descriptor in that case, so
602 * treat it as such.
603 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700604 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700605 }
606
Elliott Hughes906e6852011-10-28 14:52:10 -0700607 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700608 /*
609 * We are looking for a descriptor. Either validate it as a
610 * single-character primitive type, or continue on to check the
611 * embedded class name (bracketed by "L" and ";").
612 */
613 switch (*(s++)) {
614 case 'B':
615 case 'C':
616 case 'D':
617 case 'F':
618 case 'I':
619 case 'J':
620 case 'S':
621 case 'Z':
622 // These are all single-character descriptors for primitive types.
623 return (*s == '\0');
624 case 'V':
625 // Non-array void is valid, but you can't have an array of void.
626 return (arrayCount == 0) && (*s == '\0');
627 case 'L':
628 // Class name: Break out and continue below.
629 break;
630 default:
631 // Oddball descriptor character.
632 return false;
633 }
634 }
635
636 /*
637 * We just consumed the 'L' that introduces a class name as part
638 * of a type descriptor, or we are looking for an unadorned class
639 * name.
640 */
641
642 bool sepOrFirst = true; // first character or just encountered a separator.
643 for (;;) {
644 uint8_t c = (uint8_t) *s;
645 switch (c) {
646 case '\0':
647 /*
648 * Premature end for a type descriptor, but valid for
649 * a class name as long as we haven't encountered an
650 * empty component (including the degenerate case of
651 * the empty string "").
652 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700653 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700654 case ';':
655 /*
656 * Invalid character for a class name, but the
657 * legitimate end of a type descriptor. In the latter
658 * case, make sure that this is the end of the string
659 * and that it doesn't end with an empty component
660 * (including the degenerate case of "L;").
661 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700662 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700663 case '/':
664 case '.':
665 if (c != separator) {
666 // The wrong separator character.
667 return false;
668 }
669 if (sepOrFirst) {
670 // Separator at start or two separators in a row.
671 return false;
672 }
673 sepOrFirst = true;
674 s++;
675 break;
676 default:
jeffhao10037c82012-01-23 15:06:23 -0800677 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700678 return false;
679 }
680 sepOrFirst = false;
681 break;
682 }
683 }
684}
685
Elliott Hughes906e6852011-10-28 14:52:10 -0700686bool IsValidBinaryClassName(const char* s) {
687 return IsValidClassName(s, kName, '.');
688}
689
690bool IsValidJniClassName(const char* s) {
691 return IsValidClassName(s, kName, '/');
692}
693
694bool IsValidDescriptor(const char* s) {
695 return IsValidClassName(s, kDescriptor, '/');
696}
697
Elliott Hughes48436bb2012-02-07 15:23:28 -0800698void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700699 const char* p = s.data();
700 const char* end = p + s.size();
701 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800702 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700703 ++p;
704 } else {
705 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800706 while (++p != end && *p != separator) {
707 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700708 }
709 result.push_back(std::string(start, p - start));
710 }
711 }
712}
713
Elliott Hughes48436bb2012-02-07 15:23:28 -0800714template <typename StringT>
715std::string Join(std::vector<StringT>& strings, char separator) {
716 if (strings.empty()) {
717 return "";
718 }
719
720 std::string result(strings[0]);
721 for (size_t i = 1; i < strings.size(); ++i) {
722 result += separator;
723 result += strings[i];
724 }
725 return result;
726}
727
728// Explicit instantiations.
729template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
730template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
731template std::string Join<char*>(std::vector<char*>& strings, char separator);
732
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800733bool StartsWith(const std::string& s, const char* prefix) {
734 return s.compare(0, strlen(prefix), prefix) == 0;
735}
736
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800737void SetThreadName(const char* threadName) {
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800738 ANNOTATE_THREAD_NAME(threadName); // For tsan.
739
Elliott Hughesdcc24742011-09-07 14:02:44 -0700740 int hasAt = 0;
741 int hasDot = 0;
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800742 const char* s = threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700743 while (*s) {
744 if (*s == '.') {
745 hasDot = 1;
746 } else if (*s == '@') {
747 hasAt = 1;
748 }
749 s++;
750 }
751 int len = s - threadName;
752 if (len < 15 || hasAt || !hasDot) {
753 s = threadName;
754 } else {
755 s = threadName + len - 15;
756 }
757#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700758 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700759 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
760 strncpy(buf, s, sizeof(buf)-1);
761 buf[sizeof(buf)-1] = '\0';
762 errno = pthread_setname_np(pthread_self(), buf);
763 if (errno != 0) {
764 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
765 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700766#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700767 pthread_setname_np(threadName);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700768#elif defined(HAVE_PRCTL)
769 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
770#else
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800771 UNIMPLEMENTED(WARNING) << threadName;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700772#endif
773}
774
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700775void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
776 utime = stime = task_cpu = 0;
777 std::string stats;
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700778 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid).c_str(), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700779 return;
780 }
781 // Skip the command, which may contain spaces.
782 stats = stats.substr(stats.find(')') + 2);
783 // Extract the three fields we care about.
784 std::vector<std::string> fields;
785 Split(stats, ' ', fields);
786 utime = strtoull(fields[11].c_str(), NULL, 10);
787 stime = strtoull(fields[12].c_str(), NULL, 10);
788 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
789}
790
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700791std::string GetSchedulerGroupName(pid_t tid) {
792 // /proc/<pid>/cgroup looks like this:
793 // 2:devices:/
794 // 1:cpuacct,cpu:/
795 // We want the third field from the line whose second field contains the "cpu" token.
796 std::string cgroup_file;
797 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
798 return "";
799 }
800 std::vector<std::string> cgroup_lines;
801 Split(cgroup_file, '\n', cgroup_lines);
802 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
803 std::vector<std::string> cgroup_fields;
804 Split(cgroup_lines[i], ':', cgroup_fields);
805 std::vector<std::string> cgroups;
806 Split(cgroup_fields[1], ',', cgroups);
807 for (size_t i = 0; i < cgroups.size(); ++i) {
808 if (cgroups[i] == "cpu") {
809 return cgroup_fields[2].substr(1); // Skip the leading slash.
810 }
811 }
812 }
813 return "";
814}
815
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800816const char* GetAndroidRoot() {
817 const char* android_root = getenv("ANDROID_ROOT");
818 if (android_root == NULL) {
819 if (OS::DirectoryExists("/system")) {
820 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700821 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800822 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
823 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700824 }
825 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800826 if (!OS::DirectoryExists(android_root)) {
827 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700828 return "";
829 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800830 return android_root;
831}
Brian Carlstroma9f19782011-10-13 00:14:47 -0700832
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800833const char* GetAndroidData() {
834 const char* android_data = getenv("ANDROID_DATA");
835 if (android_data == NULL) {
836 if (OS::DirectoryExists("/data")) {
837 android_data = "/data";
838 } else {
839 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
840 return "";
841 }
842 }
843 if (!OS::DirectoryExists(android_data)) {
844 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
845 return "";
846 }
847 return android_data;
848}
849
850std::string GetArtCacheOrDie() {
851 std::string art_cache(StringPrintf("%s/art-cache", GetAndroidData()));
Brian Carlstroma9f19782011-10-13 00:14:47 -0700852
853 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800854 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700855 int result = mkdir(art_cache.c_str(), 0700);
856 if (result != 0) {
857 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
858 return "";
859 }
860 } else {
861 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
862 return "";
863 }
864 }
865 return art_cache;
866}
867
jeffhao262bf462011-10-20 18:36:32 -0700868std::string GetArtCacheFilenameOrDie(const std::string& location) {
Elliott Hughes95572412011-12-13 18:14:20 -0800869 std::string art_cache(GetArtCacheOrDie());
Elliott Hughesc308a5d2012-02-16 17:12:06 -0800870 CHECK_EQ(location[0], '/') << location;
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700871 std::string cache_file(location, 1); // skip leading slash
872 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
873 return art_cache + "/" + cache_file;
874}
875
jeffhao262bf462011-10-20 18:36:32 -0700876bool IsValidZipFilename(const std::string& filename) {
877 if (filename.size() < 4) {
878 return false;
879 }
880 std::string suffix(filename.substr(filename.size() - 4));
881 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
882}
883
884bool IsValidDexFilename(const std::string& filename) {
885 if (filename.size() < 4) {
886 return false;
887 }
888 std::string suffix(filename.substr(filename.size() - 4));
889 return (suffix == ".dex");
890}
891
Elliott Hughes42ee1422011-09-06 12:33:32 -0700892} // namespace art