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.
17 * Miscellaneous utility functions.
29 #include <cutils/ashmem.h>
32 #define ALIGN_UP_TO_PAGE_SIZE(p) \
33 (((size_t)(p) + (SYSTEM_PAGE_SIZE - 1)) & ~(SYSTEM_PAGE_SIZE - 1))
36 * Print a hex dump in this format:
38 01234567: 00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff 0123456789abcdef\n
40 * If "mode" is kHexDumpLocal, we start at offset zero, and show a full
41 * 16 bytes on the first line. If it's kHexDumpMem, we make this look
42 * like a memory dump, using the actual address, outputting a partial line
43 * if "vaddr" isn't aligned on a 16-byte boundary.
45 * "priority" and "tag" determine the values passed to the log calls.
47 * Does not use printf() or other string-formatting calls.
49 void dvmPrintHexDumpEx(int priority, const char* tag, const void* vaddr,
50 size_t length, HexDumpMode mode)
52 static const char gHexDigit[] = "0123456789abcdef";
53 const unsigned char* addr = vaddr;
54 char out[77]; /* exact fit */
55 unsigned int offset; /* offset to show while printing */
61 if (mode == kHexDumpLocal)
66 memset(out, ' ', sizeof(out)-1);
68 out[sizeof(out)-2] = '\n';
69 out[sizeof(out)-1] = '\0';
71 gap = (int) offset & 0x0f;
73 unsigned int lineOffset = offset & ~0x0f;
79 for (i = 0; i < 8; i++) {
80 *hex++ = gHexDigit[lineOffset >> 28];
86 count = ((int)length > 16-gap) ? 16-gap : (int)length; /* cap length */
88 assert(count+gap <= 16);
91 /* only on first line */
96 for (i = gap ; i < count+gap; i++) {
97 *hex++ = gHexDigit[*addr >> 4];
98 *hex++ = gHexDigit[*addr & 0x0f];
100 if (*addr >= 0x20 && *addr < 0x7f /*isprint(*addr)*/)
106 for ( ; i < 16; i++) {
107 /* erase extra stuff; only happens on last line */
114 LOG_PRI(priority, tag, "%s", out);
115 #if 0 //def HAVE_ANDROID_OS
117 * We can overrun logcat easily by writing at full speed. On the
118 * other hand, we can make Eclipse time out if we're showing
119 * packet dumps while debugging JDWP.
122 if (trickle++ == 8) {
137 * Fill out a DebugOutputTarget, suitable for printing to the log.
139 void dvmCreateLogOutputTarget(DebugOutputTarget* target, int priority,
142 assert(target != NULL);
145 target->which = kDebugTargetLog;
146 target->data.log.priority = priority;
147 target->data.log.tag = tag;
151 * Fill out a DebugOutputTarget suitable for printing to a file pointer.
153 void dvmCreateFileOutputTarget(DebugOutputTarget* target, FILE* fp)
155 assert(target != NULL);
158 target->which = kDebugTargetFile;
159 target->data.file.fp = fp;
163 * Free "target" and any associated data.
165 void dvmFreeOutputTarget(DebugOutputTarget* target)
171 * Print a debug message, to either a file or the log.
173 void dvmPrintDebugMessage(const DebugOutputTarget* target, const char* format,
178 va_start(args, format);
180 switch (target->which) {
181 case kDebugTargetLog:
182 LOG_PRI_VA(target->data.log.priority, target->data.log.tag,
185 case kDebugTargetFile:
186 vfprintf(target->data.file.fp, format, args);
189 LOGE("unexpected 'which' %d\n", target->which);
198 * Allocate a bit vector with enough space to hold at least the specified
201 BitVector* dvmAllocBitVector(int startBits, bool expandable)
206 assert(sizeof(bv->storage[0]) == 4); /* assuming 32-bit units */
207 assert(startBits >= 0);
209 bv = (BitVector*) malloc(sizeof(BitVector));
211 count = (startBits + 31) >> 5;
213 bv->storageSize = count;
214 bv->expandable = expandable;
215 bv->storage = (u4*) malloc(count * sizeof(u4));
216 memset(bv->storage, 0x00, count * sizeof(u4));
223 void dvmFreeBitVector(BitVector* pBits)
228 free(pBits->storage);
233 * "Allocate" the first-available bit in the bitmap.
235 * This is not synchronized. The caller is expected to hold some sort of
236 * lock that prevents multiple threads from executing simultaneously in
237 * dvmAllocBit/dvmFreeBit.
239 int dvmAllocBit(BitVector* pBits)
244 for (word = 0; word < pBits->storageSize; word++) {
245 if (pBits->storage[word] != 0xffffffff) {
247 * There are unallocated bits in this word. Return the first.
249 bit = ffs(~(pBits->storage[word])) -1;
250 assert(bit >= 0 && bit < 32);
251 pBits->storage[word] |= 1 << bit;
252 return (word << 5) | bit;
257 * Ran out of space, allocate more if we're allowed to.
259 if (!pBits->expandable)
262 pBits->storage = realloc(pBits->storage,
263 (pBits->storageSize + kBitVectorGrowth) * sizeof(u4));
264 memset(&pBits->storage[pBits->storageSize], 0x00,
265 kBitVectorGrowth * sizeof(u4));
266 pBits->storageSize += kBitVectorGrowth;
271 * Mark the specified bit as "set".
273 * Returns "false" if the bit is outside the range of the vector and we're
274 * not allowed to expand.
276 bool dvmSetBit(BitVector* pBits, int num)
279 if (num >= pBits->storageSize * (int)sizeof(u4) * 8) {
280 if (!pBits->expandable)
283 int newSize = (num + 31) >> 5;
284 assert(newSize > pBits->storageSize);
285 pBits->storage = realloc(pBits->storage, newSize * sizeof(u4));
286 memset(&pBits->storage[pBits->storageSize], 0x00,
287 (newSize - pBits->storageSize) * sizeof(u4));
288 pBits->storageSize = newSize;
291 pBits->storage[num >> 5] |= 1 << (num & 0x1f);
296 * Mark the specified bit as "clear".
298 void dvmClearBit(BitVector* pBits, int num)
300 assert(num >= 0 && num < (int) pBits->storageSize * (int)sizeof(u4) * 8);
302 pBits->storage[num >> 5] &= ~(1 << (num & 0x1f));
306 * Mark all bits bit as "clear".
308 void dvmClearAllBits(BitVector* pBits)
310 int count = pBits->storageSize;
311 memset(pBits->storage, 0, count * sizeof(u4));
315 * Determine whether or not the specified bit is set.
317 bool dvmIsBitSet(const BitVector* pBits, int num)
319 assert(num >= 0 && num < (int) pBits->storageSize * (int)sizeof(u4) * 8);
321 int val = pBits->storage[num >> 5] & (1 << (num & 0x1f));
326 * Count the number of bits that are set.
328 int dvmCountSetBits(const BitVector* pBits)
333 for (word = 0; word < pBits->storageSize; word++) {
334 u4 val = pBits->storage[word];
337 if (val == 0xffffffff) {
340 /* count the number of '1' bits */
353 * Copy a whole vector to the other. Only do that when the both vectors have
354 * the same size and attribute.
356 bool dvmCopyBitVector(BitVector *dest, const BitVector *src)
358 if (dest->storageSize != src->storageSize ||
359 dest->expandable != src->expandable)
361 memcpy(dest->storage, src->storage, sizeof(u4) * dest->storageSize);
366 * Intersect two bit vectores and merge the result on top of the pre-existing
367 * value in the dest vector.
369 bool dvmIntersectBitVectors(BitVector *dest, const BitVector *src1,
370 const BitVector *src2)
372 if (dest->storageSize != src1->storageSize ||
373 dest->storageSize != src2->storageSize ||
374 dest->expandable != src1->expandable ||
375 dest->expandable != src2->expandable)
379 for (i = 0; i < dest->storageSize; i++) {
380 dest->storage[i] |= src1->storage[i] & src2->storage[i];
386 * Return a newly-allocated string in which all occurrences of '.' have
387 * been changed to '/'. If we find a '/' in the original string, NULL
388 * is returned to avoid ambiguity.
390 char* dvmDotToSlash(const char* str)
392 char* newStr = strdup(str);
398 while (*cp != '\0') {
412 * Return a newly-allocated string for the "dot version" of the class
413 * name for the given type descriptor. That is, The initial "L" and
414 * final ";" (if any) have been removed and all occurrences of '/'
415 * have been changed to '.'.
417 char* dvmDescriptorToDot(const char* str)
419 size_t at = strlen(str);
422 if ((at >= 2) && (str[0] == 'L') && (str[at - 1] == ';')) {
423 at -= 2; /* Two fewer chars to copy. */
424 str++; /* Skip the 'L'. */
427 newStr = malloc(at + 1); /* Add one for the '\0'. */
435 newStr[at] = (str[at] == '/') ? '.' : str[at];
442 * Return a newly-allocated string for the type descriptor
443 * corresponding to the "dot version" of the given class name. That
444 * is, non-array names are surrounded by "L" and ";", and all
445 * occurrences of '.' are changed to '/'.
447 char* dvmDotToDescriptor(const char* str)
449 size_t length = strlen(str);
455 length += 2; /* for "L" and ";" */
459 newStr = at = malloc(length + 1); /* + 1 for the '\0' */
461 if (newStr == NULL) {
486 * Return a newly-allocated string for the internal-form class name for
487 * the given type descriptor. That is, the initial "L" and final ";" (if
488 * any) have been removed.
490 char* dvmDescriptorToName(const char* str)
493 size_t length = strlen(str) - 1;
494 char* newStr = malloc(length);
496 if (newStr == NULL) {
500 strlcpy(newStr, str + 1, length);
508 * Return a newly-allocated string for the type descriptor for the given
509 * internal-form class name. That is, a non-array class name will get
510 * surrounded by "L" and ";", while array names are left as-is.
512 char* dvmNameToDescriptor(const char* str)
515 size_t length = strlen(str);
516 char* descriptor = malloc(length + 3);
518 if (descriptor == NULL) {
523 strcpy(descriptor + 1, str);
524 descriptor[length + 1] = ';';
525 descriptor[length + 2] = '\0';
534 * Get a notion of the current time, in nanoseconds. This is meant for
535 * computing durations (e.g. "operation X took 52nsec"), so the result
536 * should not be used to get the current date/time.
538 u8 dvmGetRelativeTimeNsec(void)
540 #ifdef HAVE_POSIX_CLOCKS
542 clock_gettime(CLOCK_MONOTONIC, &now);
543 return (u8)now.tv_sec*1000000000LL + now.tv_nsec;
546 gettimeofday(&now, NULL);
547 return (u8)now.tv_sec*1000000000LL + now.tv_usec * 1000LL;
552 * Get the per-thread CPU time, in nanoseconds.
554 * Only useful for time deltas.
556 u8 dvmGetThreadCpuTimeNsec(void)
558 #ifdef HAVE_POSIX_CLOCKS
560 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
561 return (u8)now.tv_sec*1000000000LL + now.tv_nsec;
568 * Get the per-thread CPU time, in nanoseconds, for the specified thread.
570 u8 dvmGetOtherThreadCpuTimeNsec(pthread_t thread)
572 #if 0 /*def HAVE_POSIX_CLOCKS*/
575 if (pthread_getcpuclockid(thread, &clockId) != 0)
579 clock_gettime(clockId, &now);
580 return (u8)now.tv_sec*1000000000LL + now.tv_nsec;
588 * Call this repeatedly, with successively higher values for "iteration",
589 * to sleep for a period of time not to exceed "maxTotalSleep".
591 * For example, when called with iteration==0 we will sleep for a very
592 * brief time. On the next call we will sleep for a longer time. When
593 * the sum total of all sleeps reaches "maxTotalSleep", this returns false.
595 * The initial start time value for "relStartTime" MUST come from the
596 * dvmGetRelativeTimeUsec call. On the device this must come from the
597 * monotonic clock source, not the wall clock.
599 * This should be used wherever you might be tempted to call sched_yield()
600 * in a loop. The problem with sched_yield is that, for a high-priority
601 * thread, the kernel might not actually transfer control elsewhere.
603 * Returns "false" if we were unable to sleep because our time was up.
605 bool dvmIterativeSleep(int iteration, int maxTotalSleep, u8 relStartTime)
607 const int minSleep = 10000;
612 * Get current time, and see if we've already exceeded the limit.
614 curTime = dvmGetRelativeTimeUsec();
615 if (curTime >= relStartTime + maxTotalSleep) {
616 LOGVV("exsl: sleep exceeded (start=%llu max=%d now=%llu)\n",
617 relStartTime, maxTotalSleep, curTime);
622 * Compute current delay. We're bounded by "maxTotalSleep", so no
623 * real risk of overflow assuming "usleep" isn't returning early.
624 * (Besides, 2^30 usec is about 18 minutes by itself.)
626 * For iteration==0 we just call sched_yield(), so the first sleep
627 * at iteration==1 is actually (minSleep * 2).
630 while (iteration-- > 0)
632 assert(curDelay > 0);
634 if (curTime + curDelay >= relStartTime + maxTotalSleep) {
635 LOGVV("exsl: reduced delay from %d to %d\n",
636 curDelay, (int) ((relStartTime + maxTotalSleep) - curTime));
637 curDelay = (int) ((relStartTime + maxTotalSleep) - curTime);
640 if (iteration == 0) {
641 LOGVV("exsl: yield\n");
644 LOGVV("exsl: sleep for %d\n", curDelay);
652 * Set the "close on exec" flag so we don't expose our file descriptors
653 * to processes launched by us.
655 bool dvmSetCloseOnExec(int fd)
660 * There's presently only one flag defined, so getting the previous
661 * value of the fd flags is probably unnecessary.
663 flags = fcntl(fd, F_GETFD);
665 LOGW("Unable to get fd flags for fd %d\n", fd);
668 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0) {
669 LOGW("Unable to set close-on-exec for fd %d\n", fd);
676 /* Implementation of strlcpy() for platforms that don't already have it. */
677 size_t strlcpy(char *dst, const char *src, size_t size) {
678 size_t srcLength = strlen(src);
679 size_t copyLength = srcLength;
681 if (srcLength > (size - 1)) {
682 copyLength = size - 1;
686 strncpy(dst, src, copyLength);
687 dst[copyLength] = '\0';
695 * Allocates a memory region using ashmem and mmap, initialized to
696 * zero. Actual allocation rounded up to page multiple. Returns
699 void *dvmAllocRegion(size_t size, int prot, const char *name) {
703 size = ALIGN_UP_TO_PAGE_SIZE(size);
704 fd = ashmem_create_region(name, size);
708 base = mmap(NULL, size, prot, MAP_PRIVATE, fd, 0);
710 if (base == MAP_FAILED) {
719 /* documented in header file */
720 const char* dvmPathToAbsolutePortion(const char* path) {
725 if (path[0] == '/') {
726 /* It's a regular absolute path. Return it. */
730 const char* sentinel = strstr(path, "/./");
732 if (sentinel != NULL) {
733 /* It's got the sentinel. Return a pointer to the second slash. */