thread_stack_pcs.c [plain text]
#include <pthread.h>
#include <mach/mach.h>
#include <mach/vm_statistics.h>
#include <stdlib.h>
#include "stack_logging.h"
#if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
#define FP_LINK_OFFSET 1
#elif defined(__ppc__) || defined(__ppc64__)
#define FP_LINK_OFFSET 2
#else
#error ********** Unimplemented architecture
#endif
#define INSTACK(a) ((a) >= stackbot && (a) <= stacktop)
#if defined(__ppc__) || defined(__ppc64__) || defined(__x86_64__)
#define ISALIGNED(a) ((((uintptr_t)(a)) & 0xf) == 0)
#elif defined(__arm__)
#define ISALIGNED(a) ((((uintptr_t)(a)) & 0x1) == 0)
#elif defined(__i386__)
#define ISALIGNED(a) ((((uintptr_t)(a)) & 0xf) == 8)
#endif
__private_extern__ __attribute__((noinline))
void
_thread_stack_pcs(vm_address_t *buffer, unsigned max, unsigned *nb, unsigned skip)
{
void *frame, *next;
pthread_t self = pthread_self();
void *stacktop = pthread_get_stackaddr_np(self);
void *stackbot = stacktop - pthread_get_stacksize_np(self);
*nb = 0;
stacktop -= (FP_LINK_OFFSET + 1) * sizeof(void *);
#if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
frame = __builtin_frame_address(0);
#elif defined(__ppc__) || defined(__ppc64__)
__asm__ volatile("mr %0, r1" : "=r" (frame));
#endif
if(!INSTACK(frame) || !ISALIGNED(frame))
return;
#if defined(__ppc__) || defined(__ppc64__)
next = *(void **)frame;
if(!INSTACK(next) || !ISALIGNED(next) || next <= frame)
return;
frame = next;
#endif
while (skip--) {
next = *(void **)frame;
if(!INSTACK(next) || !ISALIGNED(next) || next <= frame)
return;
frame = next;
}
while (max--) {
buffer[*nb] = *(vm_address_t *)(((void **)frame) + FP_LINK_OFFSET);
(*nb)++;
next = *(void **)frame;
if(!INSTACK(next) || !ISALIGNED(next) || next <= frame)
return;
frame = next;
}
}
void
thread_stack_pcs(vm_address_t *buffer, unsigned max, unsigned *nb)
{
_thread_stack_pcs(buffer, max, nb, 0);
__asm__ volatile("");
}