|
| 1 | +//go:build ignore || (darwin && cgo) |
| 2 | + |
| 3 | +#include <mach/mach_init.h> |
| 4 | +#include <mach/task.h> |
| 5 | +// Compiler warns shared_memory_server.h is deprecated, use this instead. |
| 6 | +// But this doesn't define SHARED_XXX_REGION_SIZE. |
| 7 | +//#include <mach/shared_region.h> |
| 8 | +#include <mach/shared_memory_server.h> // SHARED_DATA_REGION_SIZE, SHARED_TEXT_REGION_SIZE |
| 9 | +#include <mach/mach_vm.h> |
| 10 | +#include <stdio.h> |
| 11 | + |
| 12 | +int getmem (unsigned long long *rss, unsigned long long *vs) |
| 13 | +{ |
| 14 | + // https://github.com/apple-oss-distributions/adv_cmds/blob/8744084ea0ff41ca4bb96b0f9c22407d0e48e9b7/ps/tasks.c#L109 |
| 15 | + |
| 16 | + kern_return_t error; |
| 17 | + task_t task = MACH_PORT_NULL; |
| 18 | + struct task_basic_info t_info; |
| 19 | + mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT; |
| 20 | + |
| 21 | + error = task_info(mach_task_self(), |
| 22 | + TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count); |
| 23 | + |
| 24 | + if( error != KERN_SUCCESS ) |
| 25 | + { |
| 26 | + return error; |
| 27 | + } |
| 28 | + |
| 29 | + *rss = t_info.resident_size; |
| 30 | + *vs = t_info.virtual_size; |
| 31 | + |
| 32 | + { |
| 33 | + vm_region_basic_info_data_64_t b_info; |
| 34 | + mach_vm_address_t address = GLOBAL_SHARED_TEXT_SEGMENT; |
| 35 | + mach_vm_size_t size; |
| 36 | + mach_port_t object_name; |
| 37 | + |
| 38 | + /* |
| 39 | + * try to determine if this task has the split libraries |
| 40 | + * mapped in... if so, adjust its virtual size down by |
| 41 | + * the 2 segments that are used for split libraries |
| 42 | + */ |
| 43 | + t_info_count = VM_REGION_BASIC_INFO_COUNT_64; |
| 44 | + error = mach_vm_region(mach_task_self(), &address, &size, VM_REGION_BASIC_INFO, |
| 45 | + (vm_region_info_t)&b_info, &t_info_count, &object_name); |
| 46 | + |
| 47 | + if (error == KERN_SUCCESS) { |
| 48 | + if (b_info.reserved && size == (SHARED_TEXT_REGION_SIZE) && |
| 49 | + *vs > (SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE)) { |
| 50 | + *vs -= (SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + // `ps -o rss,vsize,command` prints values in KB |
| 56 | + printf("rss is %qd (%qd KB)\n", *rss, (unsigned long long) (*rss / 1024)); |
| 57 | + printf("vs is %qd (%qd KB)\n", *vs, (unsigned long long) (*vs / 1024)); |
| 58 | + |
| 59 | + return 0; |
| 60 | +} |
0 commit comments