2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * Miscellaneous utility functions.
30 #include <cutils/ashmem.h>
34 * Print a hex dump in this format:
36 01234567: 00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff 0123456789abcdef\n
38 * If "mode" is kHexDumpLocal, we start at offset zero, and show a full
39 * 16 bytes on the first line. If it's kHexDumpMem, we make this look
40 * like a memory dump, using the actual address, outputting a partial line
41 * if "vaddr" isn't aligned on a 16-byte boundary.
43 * "priority" and "tag" determine the values passed to the log calls.
45 * Does not use printf() or other string-formatting calls.
47 void dvmPrintHexDumpEx(int priority, const char* tag, const void* vaddr,
48 size_t length, HexDumpMode mode)
50 static const char gHexDigit[] = "0123456789abcdef";
51 const unsigned char* addr = (const unsigned char*)vaddr;
52 char out[77]; /* exact fit */
53 unsigned int offset; /* offset to show while printing */
59 if (mode == kHexDumpLocal)
64 memset(out, ' ', sizeof(out)-1);
66 out[sizeof(out)-2] = '\n';
67 out[sizeof(out)-1] = '\0';
69 gap = (int) offset & 0x0f;
71 unsigned int lineOffset = offset & ~0x0f;
77 for (i = 0; i < 8; i++) {
78 *hex++ = gHexDigit[lineOffset >> 28];
84 count = ((int)length > 16-gap) ? 16-gap : (int)length; /* cap length */
86 assert(count+gap <= 16);
89 /* only on first line */
94 for (i = gap ; i < count+gap; i++) {
95 *hex++ = gHexDigit[*addr >> 4];
96 *hex++ = gHexDigit[*addr & 0x0f];
98 if (*addr >= 0x20 && *addr < 0x7f /*isprint(*addr)*/)
104 for ( ; i < 16; i++) {
105 /* erase extra stuff; only happens on last line */
112 LOG_PRI(priority, tag, "%s", out);
113 #if 0 //def HAVE_ANDROID_OS
115 * We can overrun logcat easily by writing at full speed. On the
116 * other hand, we can make Eclipse time out if we're showing
117 * packet dumps while debugging JDWP.
120 if (trickle++ == 8) {
135 * Fill out a DebugOutputTarget, suitable for printing to the log.
137 void dvmCreateLogOutputTarget(DebugOutputTarget* target, int priority,
140 assert(target != NULL);
143 target->which = kDebugTargetLog;
144 target->data.log.priority = priority;
145 target->data.log.tag = tag;
149 * Fill out a DebugOutputTarget suitable for printing to a file pointer.
151 void dvmCreateFileOutputTarget(DebugOutputTarget* target, FILE* fp)
153 assert(target != NULL);
156 target->which = kDebugTargetFile;
157 target->data.file.fp = fp;
161 * Free "target" and any associated data.
163 void dvmFreeOutputTarget(DebugOutputTarget* target)
169 * Print a debug message, to either a file or the log.
171 void dvmPrintDebugMessage(const DebugOutputTarget* target, const char* format,
176 va_start(args, format);
178 switch (target->which) {
179 case kDebugTargetLog:
180 LOG_PRI_VA(target->data.log.priority, target->data.log.tag,
183 case kDebugTargetFile:
184 vfprintf(target->data.file.fp, format, args);
187 ALOGE("unexpected 'which' %d", target->which);
196 * Return a newly-allocated string in which all occurrences of '.' have
197 * been changed to '/'. If we find a '/' in the original string, NULL
198 * is returned to avoid ambiguity.
200 char* dvmDotToSlash(const char* str)
202 char* newStr = strdup(str);
208 while (*cp != '\0') {
221 std::string dvmHumanReadableDescriptor(const char* descriptor) {
222 // Count the number of '['s to get the dimensionality.
223 const char* c = descriptor;
230 // Reference or primitive?
232 // "[[La/b/C;" -> "a.b.C[][]".
233 c++; // Skip the 'L'.
235 // "[[B" -> "byte[][]".
236 // To make life easier, we make primitives look like unqualified
239 case 'B': c = "byte;"; break;
240 case 'C': c = "char;"; break;
241 case 'D': c = "double;"; break;
242 case 'F': c = "float;"; break;
243 case 'I': c = "int;"; break;
244 case 'J': c = "long;"; break;
245 case 'S': c = "short;"; break;
246 case 'Z': c = "boolean;"; break;
247 default: return descriptor;
251 // At this point, 'c' is a string of the form "fully/qualified/Type;"
252 // or "primitive;". Rewrite the type with '.' instead of '/':
260 result.push_back(ch);
262 // ...and replace the semicolon with 'dim' "[]" pairs:
269 std::string dvmHumanReadableType(const Object* obj)
274 if (obj->clazz == NULL) {
275 /* should only be possible right after a plain dvmMalloc() */
278 std::string result(dvmHumanReadableDescriptor(obj->clazz->descriptor));
279 if (dvmIsClassObject(obj)) {
280 const ClassObject* clazz = reinterpret_cast<const ClassObject*>(obj);
281 result += "<" + dvmHumanReadableDescriptor(clazz->descriptor) + ">";
286 std::string dvmHumanReadableField(const Field* field)
291 std::string result(dvmHumanReadableDescriptor(field->clazz->descriptor));
293 result += field->name;
297 std::string dvmHumanReadableMethod(const Method* method, bool withSignature)
299 if (method == NULL) {
302 std::string result(dvmHumanReadableDescriptor(method->clazz->descriptor));
304 result += method->name;
306 // TODO: the types in this aren't human readable!
307 char* signature = dexProtoCopyMethodDescriptor(&method->prototype);
315 * Return a newly-allocated string for the "dot version" of the class
316 * name for the given type descriptor. That is, The initial "L" and
317 * final ";" (if any) have been removed and all occurrences of '/'
318 * have been changed to '.'.
320 * "Dot version" names are used in the class loading machinery.
321 * See also dvmHumanReadableDescriptor.
323 char* dvmDescriptorToDot(const char* str)
325 size_t at = strlen(str);
328 if ((at >= 2) && (str[0] == 'L') && (str[at - 1] == ';')) {
329 at -= 2; /* Two fewer chars to copy. */
330 str++; /* Skip the 'L'. */
333 newStr = (char*)malloc(at + 1); /* Add one for the '\0'. */
341 newStr[at] = (str[at] == '/') ? '.' : str[at];
348 * Return a newly-allocated string for the type descriptor
349 * corresponding to the "dot version" of the given class name. That
350 * is, non-array names are surrounded by "L" and ";", and all
351 * occurrences of '.' have been changed to '/'.
353 * "Dot version" names are used in the class loading machinery.
355 char* dvmDotToDescriptor(const char* str)
357 size_t length = strlen(str);
363 length += 2; /* for "L" and ";" */
367 newStr = at = (char*)malloc(length + 1); /* + 1 for the '\0' */
369 if (newStr == NULL) {
394 * Return a newly-allocated string for the internal-form class name for
395 * the given type descriptor. That is, the initial "L" and final ";" (if
396 * any) have been removed.
398 char* dvmDescriptorToName(const char* str)
401 size_t length = strlen(str) - 1;
402 char* newStr = (char*)malloc(length);
404 if (newStr == NULL) {
408 strlcpy(newStr, str + 1, length);
416 * Return a newly-allocated string for the type descriptor for the given
417 * internal-form class name. That is, a non-array class name will get
418 * surrounded by "L" and ";", while array names are left as-is.
420 char* dvmNameToDescriptor(const char* str)
423 size_t length = strlen(str);
424 char* descriptor = (char*)malloc(length + 3);
426 if (descriptor == NULL) {
431 strcpy(descriptor + 1, str);
432 descriptor[length + 1] = ';';
433 descriptor[length + 2] = '\0';
442 * Get a notion of the current time, in nanoseconds. This is meant for
443 * computing durations (e.g. "operation X took 52nsec"), so the result
444 * should not be used to get the current date/time.
446 u8 dvmGetRelativeTimeNsec()
448 #ifdef HAVE_POSIX_CLOCKS
450 clock_gettime(CLOCK_MONOTONIC, &now);
451 return (u8)now.tv_sec*1000000000LL + now.tv_nsec;
454 gettimeofday(&now, NULL);
455 return (u8)now.tv_sec*1000000000LL + now.tv_usec * 1000LL;
460 * Get the per-thread CPU time, in nanoseconds.
462 * Only useful for time deltas.
464 u8 dvmGetThreadCpuTimeNsec()
466 #ifdef HAVE_POSIX_CLOCKS
468 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
469 return (u8)now.tv_sec*1000000000LL + now.tv_nsec;
476 * Get the per-thread CPU time, in nanoseconds, for the specified thread.
478 u8 dvmGetOtherThreadCpuTimeNsec(pthread_t thread)
480 #if 0 /*def HAVE_POSIX_CLOCKS*/
483 if (pthread_getcpuclockid(thread, &clockId) != 0)
487 clock_gettime(clockId, &now);
488 return (u8)now.tv_sec*1000000000LL + now.tv_nsec;
496 * Call this repeatedly, with successively higher values for "iteration",
497 * to sleep for a period of time not to exceed "maxTotalSleep".
499 * For example, when called with iteration==0 we will sleep for a very
500 * brief time. On the next call we will sleep for a longer time. When
501 * the sum total of all sleeps reaches "maxTotalSleep", this returns false.
503 * The initial start time value for "relStartTime" MUST come from the
504 * dvmGetRelativeTimeUsec call. On the device this must come from the
505 * monotonic clock source, not the wall clock.
507 * This should be used wherever you might be tempted to call sched_yield()
508 * in a loop. The problem with sched_yield is that, for a high-priority
509 * thread, the kernel might not actually transfer control elsewhere.
511 * Returns "false" if we were unable to sleep because our time was up.
513 bool dvmIterativeSleep(int iteration, int maxTotalSleep, u8 relStartTime)
516 * Minimum sleep is one millisecond, it is important to keep this value
517 * low to ensure short GC pauses since dvmSuspendAllThreads() uses this
520 const int minSleep = 1000;
525 * Get current time, and see if we've already exceeded the limit.
527 curTime = dvmGetRelativeTimeUsec();
528 if (curTime >= relStartTime + maxTotalSleep) {
529 LOGVV("exsl: sleep exceeded (start=%llu max=%d now=%llu)",
530 relStartTime, maxTotalSleep, curTime);
535 * Compute current delay. We're bounded by "maxTotalSleep", so no
536 * real risk of overflow assuming "usleep" isn't returning early.
537 * (Besides, 2^30 usec is about 18 minutes by itself.)
539 * For iteration==0 we just call sched_yield(), so the first sleep
540 * at iteration==1 is actually (minSleep * 2).
543 while (iteration-- > 0)
545 assert(curDelay > 0);
547 if (curTime + curDelay >= relStartTime + maxTotalSleep) {
548 LOGVV("exsl: reduced delay from %d to %d",
549 curDelay, (int) ((relStartTime + maxTotalSleep) - curTime));
550 curDelay = (int) ((relStartTime + maxTotalSleep) - curTime);
553 if (iteration == 0) {
554 LOGVV("exsl: yield");
557 LOGVV("exsl: sleep for %d", curDelay);
565 * Set the "close on exec" flag so we don't expose our file descriptors
566 * to processes launched by us.
568 bool dvmSetCloseOnExec(int fd)
573 * There's presently only one flag defined, so getting the previous
574 * value of the fd flags is probably unnecessary.
576 flags = fcntl(fd, F_GETFD);
578 ALOGW("Unable to get fd flags for fd %d", fd);
581 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0) {
582 ALOGW("Unable to set close-on-exec for fd %d", fd);
589 /* Implementation of strlcpy() for platforms that don't already have it. */
590 size_t strlcpy(char *dst, const char *src, size_t size) {
591 size_t srcLength = strlen(src);
592 size_t copyLength = srcLength;
594 if (srcLength > (size - 1)) {
595 copyLength = size - 1;
599 strncpy(dst, src, copyLength);
600 dst[copyLength] = '\0';
608 * Allocates a memory region using ashmem and mmap, initialized to
609 * zero. Actual allocation rounded up to page multiple. Returns
612 void *dvmAllocRegion(size_t byteCount, int prot, const char *name) {
616 byteCount = ALIGN_UP_TO_PAGE_SIZE(byteCount);
617 fd = ashmem_create_region(name, byteCount);
621 base = mmap(NULL, byteCount, prot, MAP_PRIVATE, fd, 0);
623 if (base == MAP_FAILED) {
627 munmap(base, byteCount);
634 * Get some per-thread stats.
636 * This is currently generated by opening the appropriate "stat" file
637 * in /proc and reading the pile of stuff that comes out.
639 bool dvmGetThreadStats(ProcStatData* pData, pid_t tid)
645 int ppid, pgrp, session, tty_nr, tpgid;
646 unsigned long flags, minflt, cminflt, majflt, cmajflt, utime, stime;
647 long cutime, cstime, priority, nice, zero, itrealvalue;
648 unsigned long starttime, vsize;
650 unsigned long rlim, startcode, endcode, startstack, kstkesp, kstkeip;
651 unsigned long signal, blocked, sigignore, sigcatch, wchan, nswap, cnswap;
652 int exit_signal, processor;
653 unsigned long rt_priority, policy;
655 scanf("%d %s %c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %ld %ld %ld "
656 "%ld %ld %ld %lu %lu %ld %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu "
657 "%lu %lu %lu %d %d %lu %lu",
658 &pid, comm, &state, &ppid, &pgrp, &session, &tty_nr, &tpgid,
659 &flags, &minflt, &cminflt, &majflt, &cmajflt, &utime, &stime,
660 &cutime, &cstime, &priority, &nice, &zero, &itrealvalue,
661 &starttime, &vsize, &rss, &rlim, &startcode, &endcode,
662 &startstack, &kstkesp, &kstkeip, &signal, &blocked, &sigignore,
663 &sigcatch, &wchan, &nswap, &cnswap, &exit_signal, &processor,
664 &rt_priority, &policy);
666 (new: delayacct_blkio_ticks %llu (since Linux 2.6.18))
673 * Open and read the appropriate file. This is expected to work on
674 * Linux but will fail on other platforms (e.g. Mac sim).
676 sprintf(nameBuf, "/proc/self/task/%d/stat", (int) tid);
677 fd = open(nameBuf, O_RDONLY);
679 ALOGV("Unable to open '%s': %s", nameBuf, strerror(errno));
683 char lineBuf[512]; /* > 2x typical */
684 int cc = read(fd, lineBuf, sizeof(lineBuf)-1);
686 const char* msg = (cc == 0) ? "unexpected EOF" : strerror(errno);
687 ALOGI("Unable to read '%s': %s", nameBuf, msg);
695 * Skip whitespace-separated tokens. For the most part we can assume
696 * that tokens do not contain spaces, and are separated by exactly one
697 * space character. The only exception is the second field ("comm")
698 * which may contain spaces but is surrounded by parenthesis.
700 char* cp = strchr(lineBuf, ')');
704 pData->state = *cp++;
706 for (i = 3; i < 13; i++) {
707 cp = strchr(cp+1, ' ');
716 pData->utime = strtoul(cp+1, &endp, 10);
718 ALOGI("Warning: strtoul failed on utime ('%.30s...')", cp);
720 cp = strchr(cp+1, ' ');
724 pData->stime = strtoul(cp+1, &endp, 10);
726 ALOGI("Warning: strtoul failed on stime ('%.30s...')", cp);
729 * Skip more stuff we don't care about.
731 for (i = 14; i < 38; i++) {
732 cp = strchr(cp+1, ' ');
738 * Grab processor number.
740 pData->processor = strtol(cp+1, &endp, 10);
742 ALOGI("Warning: strtoul failed on processor ('%.30s...')", cp);
747 ALOGI("stat parse failed (%s)", lineBuf);
751 /* documented in header file */
752 const char* dvmPathToAbsolutePortion(const char* path) {
757 if (path[0] == '/') {
758 /* It's a regular absolute path. Return it. */
762 const char* sentinel = strstr(path, "/./");
764 if (sentinel != NULL) {
765 /* It's got the sentinel. Return a pointer to the second slash. */
773 void StringAppendV(std::string* dst, const char* format, va_list ap) {
774 // First try with a small fixed size buffer
777 // It's possible for methods that use a va_list to invalidate
778 // the data in it upon use. The fix is to make a copy
779 // of the structure before using it and use that copy instead.
781 va_copy(backup_ap, ap);
782 int result = vsnprintf(space, sizeof(space), format, backup_ap);
785 if ((result >= 0) && ((size_t) result < sizeof(space))) {
787 dst->append(space, result);
791 // Repeatedly increase buffer size until it fits
792 int length = sizeof(space);
795 // Older behavior: just try doubling the buffer size
798 // We need exactly "result+1" characters
801 char* buf = new char[length];
803 // Restore the va_list before we use it again
804 va_copy(backup_ap, ap);
805 result = vsnprintf(buf, length, format, backup_ap);
808 if ((result >= 0) && (result < length)) {
810 dst->append(buf, result);
818 std::string StringPrintf(const char* fmt, ...) {
822 StringAppendV(&result, fmt, ap);
827 void StringAppendF(std::string* dst, const char* format, ...) {
829 va_start(ap, format);
830 StringAppendV(dst, format, ap);