thread_stack_pcs.c [plain text]
#include <pthread.h>
#include <mach/mach.h>
#include <mach/vm_statistics.h>
#include <stdlib.h>
#include <pthread/stack_np.h>
#include "stack_logging.h"
#define INSTACK(a) ((a) >= stackbot && (a) <= stacktop)
#if defined(__x86_64__)
#define ISALIGNED(a) ((((uintptr_t)(a)) & 0xf) == 0)
#elif defined(__i386__)
#define ISALIGNED(a) ((((uintptr_t)(a)) & 0xf) == 8)
#elif defined(__arm__) || defined(__arm64__)
#define ISALIGNED(a) ((((uintptr_t)(a)) & 0x1) == 0)
#endif
__attribute__((noinline))
static void
__thread_stack_pcs(vm_address_t *buffer, unsigned max, unsigned *nb,
unsigned skip, void *startfp)
{
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;
frame = __builtin_frame_address(0);
next = (void*)pthread_stack_frame_decode_np((uintptr_t)frame, NULL);
stacktop -= (next - frame);
if(!INSTACK(frame) || !ISALIGNED(frame))
return;
while (startfp || skip--) {
if (startfp && startfp < next) break;
if(!INSTACK(next) || !ISALIGNED(next) || next <= frame)
return;
frame = next;
next = (void*)pthread_stack_frame_decode_np((uintptr_t)frame, NULL);
}
while (max--) {
uintptr_t retaddr;
next = (void*)pthread_stack_frame_decode_np((uintptr_t)frame, &retaddr);
buffer[*nb] = retaddr;
(*nb)++;
if(!INSTACK(next) || !ISALIGNED(next) || next <= frame)
return;
frame = next;
}
}
__private_extern__ __attribute__((disable_tail_calls))
void
_thread_stack_pcs(vm_address_t *buffer, unsigned max, unsigned *nb,
unsigned skip, void *startfp)
{
__thread_stack_pcs(buffer, max, nb, skip + 1, startfp);
}
__attribute__((disable_tail_calls))
void
thread_stack_pcs(vm_address_t *buffer, unsigned max, unsigned *nb)
{
__thread_stack_pcs(buffer, max, nb, 0, NULL);
}