|
| 1 | +#include "vmprof_memory.h" |
| 2 | + |
| 3 | +#ifdef VMPROF_APPLE |
| 4 | +/* On OS X we can get RSS using the Mach API. */ |
| 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 | +#else |
| 12 | +#include <stdlib.h> |
| 13 | +#include <sys/types.h> |
| 14 | +#include <sys/stat.h> |
| 15 | +#include <fcntl.h> |
| 16 | +/* On '''normal''' Unices we can get RSS from '/proc/<pid>/status'. */ |
| 17 | +static int proc_file = -1; |
| 18 | +#endif |
| 19 | + |
| 20 | +int setup_rss(void) |
| 21 | +{ |
| 22 | +#ifdef VMPROF_LINUX |
| 23 | + char buf[128]; |
| 24 | + |
| 25 | + sprintf(buf, "/proc/%d/status", getpid()); |
| 26 | + proc_file = open(buf, O_RDONLY); |
| 27 | + return proc_file; |
| 28 | +#elif defined(VMPROF_APPLE) |
| 29 | + mach_task = mach_task_self(); |
| 30 | + return 0; |
| 31 | +#else |
| 32 | + return 0; |
| 33 | +#endif |
| 34 | +} |
| 35 | + |
| 36 | +int teardown_rss(void) |
| 37 | +{ |
| 38 | +#ifdef VMPROF_LINUX |
| 39 | + close(proc_file); |
| 40 | + proc_file = -1; |
| 41 | + return 0; |
| 42 | +#else |
| 43 | + return 0; |
| 44 | +#endif |
| 45 | +} |
| 46 | + |
| 47 | +long get_current_proc_rss(void) |
| 48 | +{ |
| 49 | +#ifdef VMPROF_LINUX |
| 50 | + char buf[1024]; |
| 51 | + int i = 0; |
| 52 | + |
| 53 | + if (lseek(proc_file, 0, SEEK_SET) == -1) |
| 54 | + return -1; |
| 55 | + if (read(proc_file, buf, 1024) == -1) |
| 56 | + return -1; |
| 57 | + while (i < 1020) { |
| 58 | + if (strncmp(buf + i, "VmRSS:\t", 7) == 0) { |
| 59 | + i += 7; |
| 60 | + return atoi(buf + i); |
| 61 | + } |
| 62 | + i++; |
| 63 | + } |
| 64 | + return -1; |
| 65 | +#elif defined(VMPROF_APPLE) |
| 66 | + mach_msg_type_number_t out_count = MACH_TASK_BASIC_INFO_COUNT; |
| 67 | + mach_task_basic_info_data_t taskinfo = { .resident_size = 0 }; |
| 68 | + |
| 69 | + kern_return_t error = task_info(mach_task, MACH_TASK_BASIC_INFO, (task_info_t)&taskinfo, &out_count); |
| 70 | + if (error == KERN_SUCCESS) { |
| 71 | + return (long)(taskinfo.resident_size / 1024); |
| 72 | + } else { |
| 73 | + return -1; |
| 74 | + } |
| 75 | +#else |
| 76 | + return -1; // not implemented |
| 77 | +#endif |
| 78 | +} |
0 commit comments