Debian Codegraph @

prometheus/process_collector_mem_cgo_darwin.c

raw
1 // Copyright 2024 The Prometheus Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 //go:build darwin && !ios && cgo
15
16 #include <mach/mach_init.h>
17 #include <mach/task.h>
18 #include <mach/mach_vm.h>
19
20 // The compiler warns that mach/shared_memory_server.h is deprecated, and to use
21 // mach/shared_region.h instead. But that doesn't define
22 // SHARED_DATA_REGION_SIZE or SHARED_TEXT_REGION_SIZE, so redefine them here and
23 // avoid a warning message when running tests.
24 #define GLOBAL_SHARED_TEXT_SEGMENT 0x90000000U
25 #define SHARED_DATA_REGION_SIZE 0x10000000
26 #define SHARED_TEXT_REGION_SIZE 0x10000000
27
28
29 int get_memory_info(unsigned long long *rss, unsigned long long *vsize)
30 {
31 // This is lightly adapted from how ps(1) obtains its memory info.
32 // https://github.com/apple-oss-distributions/adv_cmds/blob/8744084ea0ff41ca4bb96b0f9c22407d0e48e9b7/ps/tasks.c#L109
33
34 kern_return_t error;
35 task_t task = MACH_PORT_NULL;
36 mach_task_basic_info_data_t info;
37 mach_msg_type_number_t info_count = MACH_TASK_BASIC_INFO_COUNT;
38
39 error = task_info(
40 mach_task_self(),
41 MACH_TASK_BASIC_INFO,
42 (task_info_t) &info,
43 &info_count );
44
45 if( error != KERN_SUCCESS )
46 {
47 return error;
48 }
49
50 *rss = info.resident_size;
51 *vsize = info.virtual_size;
52
53 {
54 vm_region_basic_info_data_64_t b_info;
55 mach_vm_address_t address = GLOBAL_SHARED_TEXT_SEGMENT;
56 mach_vm_size_t size;
57 mach_port_t object_name;
58
59 /*
60 * try to determine if this task has the split libraries
61 * mapped in... if so, adjust its virtual size down by
62 * the 2 segments that are used for split libraries
63 */
64 info_count = VM_REGION_BASIC_INFO_COUNT_64;
65
66 error = mach_vm_region(
67 mach_task_self(),
68 &address,
69 &size,
70 VM_REGION_BASIC_INFO_64,
71 (vm_region_info_t) &b_info,
72 &info_count,
73 &object_name);
74
75 if (error == KERN_SUCCESS) {
76 if (b_info.reserved && size == (SHARED_TEXT_REGION_SIZE) &&
77 *vsize > (SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE)) {
78 *vsize -= (SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE);
79 }
80 }
81 }
82
83 return 0;
84 }