blob: b8c249f952f616f1d4ae645359a62129df58ce06 [file] [log] [blame]
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001/*
2 * Copyright (C) 2008 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 */
16/*
17 * Miscellaneous utility functions.
18 */
19#include "Dalvik.h"
20
21#include <stdlib.h>
22#include <stddef.h>
23#include <string.h>
Carl Shapiro10b0b7a2010-03-16 00:21:41 -070024#include <strings.h>
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080025#include <ctype.h>
26#include <time.h>
27#include <sys/time.h>
28#include <fcntl.h>
Barry Hayes6e5cf602010-06-22 12:32:59 -070029#include <cutils/ashmem.h>
30#include <sys/mman.h>
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080031
Barry Hayes6e5cf602010-06-22 12:32:59 -070032#define ALIGN_UP_TO_PAGE_SIZE(p) \
33 (((size_t)(p) + (SYSTEM_PAGE_SIZE - 1)) & ~(SYSTEM_PAGE_SIZE - 1))
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080034
35/*
36 * Print a hex dump in this format:
37 *
3801234567: 00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff 0123456789abcdef\n
39 *
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.
44 *
45 * "priority" and "tag" determine the values passed to the log calls.
46 *
47 * Does not use printf() or other string-formatting calls.
48 */
49void dvmPrintHexDumpEx(int priority, const char* tag, const void* vaddr,
50 size_t length, HexDumpMode mode)
51{
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 */
56 char* hex;
57 char* asc;
58 int gap;
59 //int trickle = 0;
60
61 if (mode == kHexDumpLocal)
62 offset = 0;
63 else
64 offset = (int) addr;
65
66 memset(out, ' ', sizeof(out)-1);
67 out[8] = ':';
68 out[sizeof(out)-2] = '\n';
69 out[sizeof(out)-1] = '\0';
70
71 gap = (int) offset & 0x0f;
72 while (length) {
73 unsigned int lineOffset = offset & ~0x0f;
74 int i, count;
75
76 hex = out;
77 asc = out + 59;
78
79 for (i = 0; i < 8; i++) {
80 *hex++ = gHexDigit[lineOffset >> 28];
81 lineOffset <<= 4;
82 }
83 hex++;
84 hex++;
85
86 count = ((int)length > 16-gap) ? 16-gap : (int)length; /* cap length */
87 assert(count != 0);
88 assert(count+gap <= 16);
89
90 if (gap) {
91 /* only on first line */
92 hex += gap * 3;
93 asc += gap;
94 }
95
96 for (i = gap ; i < count+gap; i++) {
97 *hex++ = gHexDigit[*addr >> 4];
98 *hex++ = gHexDigit[*addr & 0x0f];
99 hex++;
100 if (*addr >= 0x20 && *addr < 0x7f /*isprint(*addr)*/)
101 *asc++ = *addr;
102 else
103 *asc++ = '.';
104 addr++;
105 }
106 for ( ; i < 16; i++) {
107 /* erase extra stuff; only happens on last line */
108 *hex++ = ' ';
109 *hex++ = ' ';
110 hex++;
111 *asc++ = ' ';
112 }
113
114 LOG_PRI(priority, tag, "%s", out);
115#if 0 //def HAVE_ANDROID_OS
116 /*
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.
120 */
121 {
122 if (trickle++ == 8) {
123 trickle = 0;
124 usleep(20000);
125 }
126 }
127#endif
128
129 gap = 0;
130 length -= count;
131 offset += count;
132 }
133}
134
135
136/*
137 * Fill out a DebugOutputTarget, suitable for printing to the log.
138 */
139void dvmCreateLogOutputTarget(DebugOutputTarget* target, int priority,
140 const char* tag)
141{
142 assert(target != NULL);
143 assert(tag != NULL);
144
145 target->which = kDebugTargetLog;
146 target->data.log.priority = priority;
147 target->data.log.tag = tag;
148}
149
150/*
151 * Fill out a DebugOutputTarget suitable for printing to a file pointer.
152 */
153void dvmCreateFileOutputTarget(DebugOutputTarget* target, FILE* fp)
154{
155 assert(target != NULL);
156 assert(fp != NULL);
157
158 target->which = kDebugTargetFile;
159 target->data.file.fp = fp;
160}
161
162/*
163 * Free "target" and any associated data.
164 */
165void dvmFreeOutputTarget(DebugOutputTarget* target)
166{
167 free(target);
168}
169
170/*
171 * Print a debug message, to either a file or the log.
172 */
173void dvmPrintDebugMessage(const DebugOutputTarget* target, const char* format,
174 ...)
175{
176 va_list args;
177
178 va_start(args, format);
179
180 switch (target->which) {
181 case kDebugTargetLog:
182 LOG_PRI_VA(target->data.log.priority, target->data.log.tag,
183 format, args);
184 break;
185 case kDebugTargetFile:
186 vfprintf(target->data.file.fp, format, args);
187 break;
188 default:
189 LOGE("unexpected 'which' %d\n", target->which);
190 break;
191 }
192
193 va_end(args);
194}
195
196
197/*
198 * Allocate a bit vector with enough space to hold at least the specified
199 * number of bits.
200 */
201BitVector* dvmAllocBitVector(int startBits, bool expandable)
202{
203 BitVector* bv;
204 int count;
205
206 assert(sizeof(bv->storage[0]) == 4); /* assuming 32-bit units */
207 assert(startBits >= 0);
208
209 bv = (BitVector*) malloc(sizeof(BitVector));
210
211 count = (startBits + 31) >> 5;
212
213 bv->storageSize = count;
214 bv->expandable = expandable;
215 bv->storage = (u4*) malloc(count * sizeof(u4));
216 memset(bv->storage, 0x00, count * sizeof(u4));
217 return bv;
218}
219
220/*
221 * Free a BitVector.
222 */
223void dvmFreeBitVector(BitVector* pBits)
224{
225 if (pBits == NULL)
226 return;
227
228 free(pBits->storage);
229 free(pBits);
230}
231
232/*
233 * "Allocate" the first-available bit in the bitmap.
234 *
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.
238 */
239int dvmAllocBit(BitVector* pBits)
240{
241 int word, bit;
242
243retry:
244 for (word = 0; word < pBits->storageSize; word++) {
245 if (pBits->storage[word] != 0xffffffff) {
246 /*
247 * There are unallocated bits in this word. Return the first.
248 */
249 bit = ffs(~(pBits->storage[word])) -1;
250 assert(bit >= 0 && bit < 32);
251 pBits->storage[word] |= 1 << bit;
252 return (word << 5) | bit;
253 }
254 }
255
256 /*
257 * Ran out of space, allocate more if we're allowed to.
258 */
259 if (!pBits->expandable)
260 return -1;
261
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;
267 goto retry;
268}
269
270/*
271 * Mark the specified bit as "set".
272 *
273 * Returns "false" if the bit is outside the range of the vector and we're
274 * not allowed to expand.
275 */
276bool dvmSetBit(BitVector* pBits, int num)
277{
278 assert(num >= 0);
279 if (num >= pBits->storageSize * (int)sizeof(u4) * 8) {
280 if (!pBits->expandable)
281 return false;
282
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));
Andy McFadden01651b42009-08-19 10:32:01 -0700288 pBits->storageSize = newSize;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800289 }
290
291 pBits->storage[num >> 5] |= 1 << (num & 0x1f);
292 return true;
293}
294
295/*
296 * Mark the specified bit as "clear".
297 */
298void dvmClearBit(BitVector* pBits, int num)
299{
300 assert(num >= 0 && num < (int) pBits->storageSize * (int)sizeof(u4) * 8);
301
302 pBits->storage[num >> 5] &= ~(1 << (num & 0x1f));
303}
304
305/*
Ben Chenge9695e52009-06-16 16:11:47 -0700306 * Mark all bits bit as "clear".
307 */
308void dvmClearAllBits(BitVector* pBits)
309{
310 int count = pBits->storageSize;
311 memset(pBits->storage, 0, count * sizeof(u4));
312}
313
314/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800315 * Determine whether or not the specified bit is set.
316 */
317bool dvmIsBitSet(const BitVector* pBits, int num)
318{
319 assert(num >= 0 && num < (int) pBits->storageSize * (int)sizeof(u4) * 8);
320
321 int val = pBits->storage[num >> 5] & (1 << (num & 0x1f));
322 return (val != 0);
323}
324
325/*
326 * Count the number of bits that are set.
327 */
328int dvmCountSetBits(const BitVector* pBits)
329{
Carl Shapiroe3c01da2010-05-20 22:54:18 -0700330 int word;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800331 int count = 0;
332
333 for (word = 0; word < pBits->storageSize; word++) {
334 u4 val = pBits->storage[word];
335
336 if (val != 0) {
337 if (val == 0xffffffff) {
338 count += 32;
339 } else {
340 /* count the number of '1' bits */
341 while (val != 0) {
342 val &= val - 1;
343 count++;
344 }
345 }
346 }
347 }
348
349 return count;
350}
351
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800352/*
Ben Cheng4238ec22009-08-24 16:32:22 -0700353 * Copy a whole vector to the other. Only do that when the both vectors have
354 * the same size and attribute.
355 */
356bool dvmCopyBitVector(BitVector *dest, const BitVector *src)
357{
358 if (dest->storageSize != src->storageSize ||
359 dest->expandable != src->expandable)
360 return false;
361 memcpy(dest->storage, src->storage, sizeof(u4) * dest->storageSize);
362 return true;
363}
364
365/*
366 * Intersect two bit vectores and merge the result on top of the pre-existing
367 * value in the dest vector.
368 */
369bool dvmIntersectBitVectors(BitVector *dest, const BitVector *src1,
370 const BitVector *src2)
371{
372 if (dest->storageSize != src1->storageSize ||
373 dest->storageSize != src2->storageSize ||
374 dest->expandable != src1->expandable ||
375 dest->expandable != src2->expandable)
376 return false;
377
378 int i;
379 for (i = 0; i < dest->storageSize; i++) {
380 dest->storage[i] |= src1->storage[i] & src2->storage[i];
381 }
382 return true;
383}
384
385/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800386 * 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.
389 */
390char* dvmDotToSlash(const char* str)
391{
392 char* newStr = strdup(str);
393 char* cp = newStr;
394
Andy McFaddenf9058532009-09-03 14:48:10 -0700395 if (newStr == NULL)
396 return NULL;
397
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800398 while (*cp != '\0') {
399 if (*cp == '/') {
400 assert(false);
401 return NULL;
402 }
403 if (*cp == '.')
404 *cp = '/';
405 cp++;
406 }
407
408 return newStr;
409}
410
Elliott Hughes50169662010-11-22 13:14:23 -0800411char* dvmHumanReadableDescriptor(const char* descriptor)
412{
413 char *dotName = dvmDescriptorToDot(descriptor);
414 if (descriptor[0] == 'L') {
415 return dotName;
416 }
417
418 const char* c = dotName;
419 size_t dim = 0;
420 while (*c == '[') {
421 dim++;
422 c++;
423 }
424 if (*c == 'L') {
425 c++;
426 } else {
427 /* It's a primitive type; we should use a pretty name.
428 * Add semicolons to make all strings have the format
429 * of object class names.
430 */
431 switch (*c) {
432 case 'Z': c = "boolean;"; break;
433 case 'C': c = "char;"; break;
434 case 'F': c = "float;"; break;
435 case 'D': c = "double;"; break;
436 case 'B': c = "byte;"; break;
437 case 'S': c = "short;"; break;
438 case 'I': c = "int;"; break;
439 case 'J': c = "long;"; break;
440 default: assert(false); c = "UNKNOWN;"; break;
441 }
442 }
443
444 /* We have a string of the form "name;" and
445 * we want to replace the semicolon with as many
446 * "[]" pairs as is in dim.
447 */
448 size_t newLen = strlen(c)-1 + dim*2;
449 char* newName = malloc(newLen + 1);
450 if (newName == NULL) {
451 return NULL;
452 }
453 strcpy(newName, c);
454 newName[newLen] = '\0';
455
456 /* Point nc to the semicolon.
457 */
458 char* nc = newName + newLen - dim*2;
459 assert(*nc == ';');
460
461 while (dim--) {
462 *nc++ = '[';
463 *nc++ = ']';
464 }
465 assert(*nc == '\0');
466 free(dotName);
467 return newName;
468}
469
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800470/*
471 * Return a newly-allocated string for the "dot version" of the class
472 * name for the given type descriptor. That is, The initial "L" and
473 * final ";" (if any) have been removed and all occurrences of '/'
474 * have been changed to '.'.
Elliott Hughes50169662010-11-22 13:14:23 -0800475 *
476 * "Dot version" names are used in the class loading machinery.
477 * See also dvmHumanReadableDescriptor.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800478 */
479char* dvmDescriptorToDot(const char* str)
480{
481 size_t at = strlen(str);
482 char* newStr;
483
484 if ((at >= 2) && (str[0] == 'L') && (str[at - 1] == ';')) {
485 at -= 2; /* Two fewer chars to copy. */
486 str++; /* Skip the 'L'. */
487 }
488
489 newStr = malloc(at + 1); /* Add one for the '\0'. */
Andy McFaddenf9058532009-09-03 14:48:10 -0700490 if (newStr == NULL)
491 return NULL;
492
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800493 newStr[at] = '\0';
494
495 while (at > 0) {
496 at--;
497 newStr[at] = (str[at] == '/') ? '.' : str[at];
498 }
499
500 return newStr;
501}
502
503/*
504 * Return a newly-allocated string for the type descriptor
505 * corresponding to the "dot version" of the given class name. That
506 * is, non-array names are surrounded by "L" and ";", and all
Elliott Hughes50169662010-11-22 13:14:23 -0800507 * occurrences of '.' have been changed to '/'.
508 *
509 * "Dot version" names are used in the class loading machinery.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800510 */
511char* dvmDotToDescriptor(const char* str)
512{
513 size_t length = strlen(str);
514 int wrapElSemi = 0;
515 char* newStr;
516 char* at;
517
518 if (str[0] != '[') {
519 length += 2; /* for "L" and ";" */
520 wrapElSemi = 1;
521 }
522
523 newStr = at = malloc(length + 1); /* + 1 for the '\0' */
524
525 if (newStr == NULL) {
526 return NULL;
527 }
528
529 if (wrapElSemi) {
530 *(at++) = 'L';
531 }
532
533 while (*str) {
534 char c = *(str++);
535 if (c == '.') {
536 c = '/';
537 }
538 *(at++) = c;
539 }
540
541 if (wrapElSemi) {
542 *(at++) = ';';
543 }
544
545 *at = '\0';
546 return newStr;
547}
548
549/*
550 * Return a newly-allocated string for the internal-form class name for
551 * the given type descriptor. That is, the initial "L" and final ";" (if
552 * any) have been removed.
553 */
554char* dvmDescriptorToName(const char* str)
555{
556 if (str[0] == 'L') {
557 size_t length = strlen(str) - 1;
558 char* newStr = malloc(length);
559
560 if (newStr == NULL) {
561 return NULL;
562 }
563
564 strlcpy(newStr, str + 1, length);
565 return newStr;
566 }
567
568 return strdup(str);
569}
570
571/*
572 * Return a newly-allocated string for the type descriptor for the given
573 * internal-form class name. That is, a non-array class name will get
574 * surrounded by "L" and ";", while array names are left as-is.
575 */
576char* dvmNameToDescriptor(const char* str)
577{
578 if (str[0] != '[') {
579 size_t length = strlen(str);
580 char* descriptor = malloc(length + 3);
581
582 if (descriptor == NULL) {
583 return NULL;
584 }
585
586 descriptor[0] = 'L';
587 strcpy(descriptor + 1, str);
588 descriptor[length + 1] = ';';
589 descriptor[length + 2] = '\0';
590
591 return descriptor;
592 }
593
594 return strdup(str);
595}
596
597/*
598 * Get a notion of the current time, in nanoseconds. This is meant for
599 * computing durations (e.g. "operation X took 52nsec"), so the result
600 * should not be used to get the current date/time.
601 */
602u8 dvmGetRelativeTimeNsec(void)
603{
604#ifdef HAVE_POSIX_CLOCKS
605 struct timespec now;
606 clock_gettime(CLOCK_MONOTONIC, &now);
607 return (u8)now.tv_sec*1000000000LL + now.tv_nsec;
608#else
609 struct timeval now;
610 gettimeofday(&now, NULL);
611 return (u8)now.tv_sec*1000000000LL + now.tv_usec * 1000LL;
612#endif
613}
614
615/*
616 * Get the per-thread CPU time, in nanoseconds.
617 *
618 * Only useful for time deltas.
619 */
620u8 dvmGetThreadCpuTimeNsec(void)
621{
622#ifdef HAVE_POSIX_CLOCKS
623 struct timespec now;
624 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
625 return (u8)now.tv_sec*1000000000LL + now.tv_nsec;
626#else
627 return (u8) -1;
628#endif
629}
630
631/*
632 * Get the per-thread CPU time, in nanoseconds, for the specified thread.
633 */
634u8 dvmGetOtherThreadCpuTimeNsec(pthread_t thread)
635{
636#if 0 /*def HAVE_POSIX_CLOCKS*/
637 int clockId;
638
639 if (pthread_getcpuclockid(thread, &clockId) != 0)
640 return (u8) -1;
641
642 struct timespec now;
643 clock_gettime(clockId, &now);
644 return (u8)now.tv_sec*1000000000LL + now.tv_nsec;
645#else
646 return (u8) -1;
647#endif
648}
649
650
651/*
652 * Call this repeatedly, with successively higher values for "iteration",
653 * to sleep for a period of time not to exceed "maxTotalSleep".
654 *
655 * For example, when called with iteration==0 we will sleep for a very
656 * brief time. On the next call we will sleep for a longer time. When
657 * the sum total of all sleeps reaches "maxTotalSleep", this returns false.
658 *
659 * The initial start time value for "relStartTime" MUST come from the
660 * dvmGetRelativeTimeUsec call. On the device this must come from the
661 * monotonic clock source, not the wall clock.
662 *
663 * This should be used wherever you might be tempted to call sched_yield()
664 * in a loop. The problem with sched_yield is that, for a high-priority
665 * thread, the kernel might not actually transfer control elsewhere.
666 *
667 * Returns "false" if we were unable to sleep because our time was up.
668 */
669bool dvmIterativeSleep(int iteration, int maxTotalSleep, u8 relStartTime)
670{
671 const int minSleep = 10000;
672 u8 curTime;
673 int curDelay;
674
675 /*
676 * Get current time, and see if we've already exceeded the limit.
677 */
678 curTime = dvmGetRelativeTimeUsec();
679 if (curTime >= relStartTime + maxTotalSleep) {
680 LOGVV("exsl: sleep exceeded (start=%llu max=%d now=%llu)\n",
681 relStartTime, maxTotalSleep, curTime);
682 return false;
683 }
684
685 /*
686 * Compute current delay. We're bounded by "maxTotalSleep", so no
687 * real risk of overflow assuming "usleep" isn't returning early.
688 * (Besides, 2^30 usec is about 18 minutes by itself.)
689 *
690 * For iteration==0 we just call sched_yield(), so the first sleep
691 * at iteration==1 is actually (minSleep * 2).
692 */
693 curDelay = minSleep;
694 while (iteration-- > 0)
695 curDelay *= 2;
696 assert(curDelay > 0);
697
698 if (curTime + curDelay >= relStartTime + maxTotalSleep) {
699 LOGVV("exsl: reduced delay from %d to %d\n",
700 curDelay, (int) ((relStartTime + maxTotalSleep) - curTime));
701 curDelay = (int) ((relStartTime + maxTotalSleep) - curTime);
702 }
703
704 if (iteration == 0) {
705 LOGVV("exsl: yield\n");
706 sched_yield();
707 } else {
708 LOGVV("exsl: sleep for %d\n", curDelay);
709 usleep(curDelay);
710 }
711 return true;
712}
713
714
715/*
716 * Set the "close on exec" flag so we don't expose our file descriptors
717 * to processes launched by us.
718 */
719bool dvmSetCloseOnExec(int fd)
720{
721 int flags;
722
723 /*
724 * There's presently only one flag defined, so getting the previous
725 * value of the fd flags is probably unnecessary.
726 */
727 flags = fcntl(fd, F_GETFD);
728 if (flags < 0) {
729 LOGW("Unable to get fd flags for fd %d\n", fd);
730 return false;
731 }
732 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0) {
733 LOGW("Unable to set close-on-exec for fd %d\n", fd);
734 return false;
735 }
736 return true;
737}
738
739#if (!HAVE_STRLCPY)
740/* Implementation of strlcpy() for platforms that don't already have it. */
741size_t strlcpy(char *dst, const char *src, size_t size) {
742 size_t srcLength = strlen(src);
743 size_t copyLength = srcLength;
744
745 if (srcLength > (size - 1)) {
746 copyLength = size - 1;
747 }
748
749 if (size != 0) {
750 strncpy(dst, src, copyLength);
751 dst[copyLength] = '\0';
752 }
753
754 return srcLength;
755}
756#endif
Barry Hayes6e5cf602010-06-22 12:32:59 -0700757
758/*
759 * Allocates a memory region using ashmem and mmap, initialized to
760 * zero. Actual allocation rounded up to page multiple. Returns
761 * NULL on failure.
762 */
763void *dvmAllocRegion(size_t size, int prot, const char *name) {
764 void *base;
765 int fd, ret;
766
767 size = ALIGN_UP_TO_PAGE_SIZE(size);
768 fd = ashmem_create_region(name, size);
769 if (fd == -1) {
770 return NULL;
771 }
772 base = mmap(NULL, size, prot, MAP_PRIVATE, fd, 0);
773 ret = close(fd);
774 if (base == MAP_FAILED) {
775 return NULL;
776 }
777 if (ret == -1) {
778 return NULL;
779 }
780 return base;
781}
Andy McFadden0a3f6982010-08-31 13:50:08 -0700782
Andy McFadden0a3f6982010-08-31 13:50:08 -0700783/*
784 * Get some per-thread stats.
785 *
786 * This is currently generated by opening the appropriate "stat" file
787 * in /proc and reading the pile of stuff that comes out.
788 */
789bool dvmGetThreadStats(ProcStatData* pData, pid_t tid)
790{
791 /*
792 int pid;
793 char comm[128];
794 char state;
795 int ppid, pgrp, session, tty_nr, tpgid;
796 unsigned long flags, minflt, cminflt, majflt, cmajflt, utime, stime;
797 long cutime, cstime, priority, nice, zero, itrealvalue;
798 unsigned long starttime, vsize;
799 long rss;
800 unsigned long rlim, startcode, endcode, startstack, kstkesp, kstkeip;
801 unsigned long signal, blocked, sigignore, sigcatch, wchan, nswap, cnswap;
802 int exit_signal, processor;
803 unsigned long rt_priority, policy;
804
805 scanf("%d %s %c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %ld %ld %ld "
806 "%ld %ld %ld %lu %lu %ld %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu "
807 "%lu %lu %lu %d %d %lu %lu",
808 &pid, comm, &state, &ppid, &pgrp, &session, &tty_nr, &tpgid,
809 &flags, &minflt, &cminflt, &majflt, &cmajflt, &utime, &stime,
810 &cutime, &cstime, &priority, &nice, &zero, &itrealvalue,
811 &starttime, &vsize, &rss, &rlim, &startcode, &endcode,
812 &startstack, &kstkesp, &kstkeip, &signal, &blocked, &sigignore,
813 &sigcatch, &wchan, &nswap, &cnswap, &exit_signal, &processor,
814 &rt_priority, &policy);
815
816 (new: delayacct_blkio_ticks %llu (since Linux 2.6.18))
817 */
818
819 char nameBuf[64];
820 int i, fd;
821
822 /*
823 * Open and read the appropriate file. This is expected to work on
824 * Linux but will fail on other platforms (e.g. Mac sim).
825 */
826 sprintf(nameBuf, "/proc/self/task/%d/stat", (int) tid);
827 fd = open(nameBuf, O_RDONLY);
828 if (fd < 0) {
829 LOGV("Unable to open '%s': %s\n", nameBuf, strerror(errno));
830 return false;
831 }
832
833 char lineBuf[512]; /* > 2x typical */
834 int cc = read(fd, lineBuf, sizeof(lineBuf)-1);
835 if (cc <= 0) {
836 const char* msg = (cc == 0) ? "unexpected EOF" : strerror(errno);
837 LOGI("Unable to read '%s': %s\n", nameBuf, msg);
838 close(fd);
839 return false;
840 }
841 close(fd);
842 lineBuf[cc] = '\0';
843
844 /*
845 * Skip whitespace-separated tokens. For the most part we can assume
846 * that tokens do not contain spaces, and are separated by exactly one
847 * space character. The only exception is the second field ("comm")
848 * which may contain spaces but is surrounded by parenthesis.
849 */
850 char* cp = strchr(lineBuf, ')');
851 if (cp == NULL)
852 goto parse_fail;
853 cp++;
854 for (i = 2; i < 13; i++) {
855 cp = strchr(cp+1, ' ');
856 if (cp == NULL)
857 goto parse_fail;
858 }
859
860 /*
861 * Grab utime/stime.
862 */
863 char* endp;
864 pData->utime = strtoul(cp+1, &endp, 10);
865 if (endp == cp+1)
866 LOGI("Warning: strtoul failed on utime ('%.30s...')\n", cp);
867
868 cp = strchr(cp+1, ' ');
869 if (cp == NULL)
870 goto parse_fail;
871
872 pData->stime = strtoul(cp+1, &endp, 10);
873 if (endp == cp+1)
874 LOGI("Warning: strtoul failed on stime ('%.30s...')\n", cp);
875
876 /*
877 * Skip more stuff we don't care about.
878 */
879 for (i = 14; i < 38; i++) {
880 cp = strchr(cp+1, ' ');
881 if (cp == NULL)
882 goto parse_fail;
883 }
884
885 /*
886 * Grab processor number.
887 */
888 pData->processor = strtol(cp+1, &endp, 10);
889 if (endp == cp+1)
890 LOGI("Warning: strtoul failed on processor ('%.30s...')\n", cp);
891
892 return true;
893
894parse_fail:
895 LOGI("stat parse failed (%s)\n", lineBuf);
896 return false;
897}
Dan Bornsteinbbf9d732010-09-15 13:13:33 -0700898
Dan Bornstein32bc0782010-09-13 17:30:10 -0700899/* documented in header file */
900const char* dvmPathToAbsolutePortion(const char* path) {
901 if (path == NULL) {
902 return NULL;
903 }
904
905 if (path[0] == '/') {
906 /* It's a regular absolute path. Return it. */
907 return path;
908 }
909
910 const char* sentinel = strstr(path, "/./");
911
912 if (sentinel != NULL) {
913 /* It's got the sentinel. Return a pointer to the second slash. */
914 return sentinel + 2;
915 }
916
917 return NULL;
918}