| 1 |
#include "vmprof_memory.h" |
| 2 |
|
| 3 |
#ifdef VMPROF_APPLE |
| 4 |
|
| 5 |
#include <mach/mach.h> |
| 6 |
#include <mach/message.h> |
| 7 |
#include <mach/kern_return.h> |
| 8 |
#include <mach/task_info.h> |
| 9 |
|
| 10 |
static mach_port_t mach_task; |
| 11 |
#elif defined(VMPROF_UNIX) |
| 12 |
#include <stdio.h> |
| 13 |
#include <stdlib.h> |
| 14 |
#include <sys/types.h> |
| 15 |
#include <sys/stat.h> |
| 16 |
#include <fcntl.h> |
| 17 |
#include <unistd.h> |
| 18 |
#include <string.h> |
| 19 |
|
| 20 |
static int proc_file = -1; |
| 21 |
#endif |
| 22 |
|
| 23 |
int setup_rss(void) |
| 24 |
{ |
| 25 |
#ifdef VMPROF_LINUX |
| 26 |
char buf[128]; |
| 27 |
|
| 28 |
sprintf(buf, "/proc/%d/status", getpid()); |
| 29 |
proc_file = open(buf, O_RDONLY); |
| 30 |
return proc_file; |
| 31 |
#elif defined(VMPROF_APPLE) |
| 32 |
mach_task = mach_task_self(); |
| 33 |
return 0; |
| 34 |
#else |
| 35 |
return 0; |
| 36 |
#endif |
| 37 |
} |
| 38 |
|
| 39 |
int teardown_rss(void) |
| 40 |
{ |
| 41 |
#ifdef VMPROF_LINUX |
| 42 |
close(proc_file); |
| 43 |
proc_file = -1; |
| 44 |
return 0; |
| 45 |
#else |
| 46 |
return 0; |
| 47 |
#endif |
| 48 |
} |
| 49 |
|
| 50 |
long get_current_proc_rss(void) |
| 51 |
{ |
| 52 |
#ifdef VMPROF_LINUX |
| 53 |
char buf[1024]; |
| 54 |
int i = 0; |
| 55 |
|
| 56 |
if (lseek(proc_file, 0, SEEK_SET) == -1) |
| 57 |
return -1; |
| 58 |
if (read(proc_file, buf, 1024) == -1) |
| 59 |
return -1; |
| 60 |
while (i < 1020) { |
| 61 |
if (strncmp(buf + i, "VmRSS:\t", 7) == 0) { |
| 62 |
i += 7; |
| 63 |
return atoi(buf + i); |
| 64 |
} |
| 65 |
i++; |
| 66 |
} |
| 67 |
return -1; |
| 68 |
#elif defined(VMPROF_APPLE) |
| 69 |
mach_msg_type_number_t out_count = MACH_TASK_BASIC_INFO_COUNT; |
| 70 |
mach_task_basic_info_data_t taskinfo = { .resident_size = 0 }; |
| 71 |
|
| 72 |
kern_return_t error = task_info(mach_task, MACH_TASK_BASIC_INFO, (task_info_t)&taskinfo, &out_count); |
| 73 |
if (error == KERN_SUCCESS) { |
| 74 |
return (long)(taskinfo.resident_size / 1024); |
| 75 |
} else { |
| 76 |
return -1; |
| 77 |
} |
| 78 |
#else |
| 79 |
return -1; |
| 80 |
#endif |
| 81 |
} |