Debian Codegraph @

crt/aws-c-common/source/posix/system_info.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5
6 #include <aws/common/system_info.h>
7
8 #include <aws/common/byte_buf.h>
9 #include <aws/common/logging.h>
10 #include <aws/common/platform.h>
11 #include <aws/common/private/dlloads.h>
12
13 #if defined(__FreeBSD__) || defined(__NetBSD__)
14 # define __BSD_VISIBLE 1
15 #endif
16
17 #if defined(__linux__)
18 # include <sys/sysinfo.h>
19 #endif
20
21 #if defined(__linux__) || defined(__unix__)
22 # include <sys/types.h>
23 #endif
24
25 #include <unistd.h>
26
27 #if defined(HAVE_SYSCONF)
28 size_t aws_system_info_processor_count(void) {
29 long nprocs = sysconf(_SC_NPROCESSORS_ONLN);
30 if (AWS_LIKELY(nprocs >= 0)) {
31 return (size_t)nprocs;
32 }
33
34 AWS_FATAL_POSTCONDITION(nprocs >= 0);
35 return 0;
36 }
37
38 size_t aws_system_info_page_size(void) {
39 long page_size = sysconf(_SC_PAGESIZE);
40 if (AWS_LIKELY(page_size >= 0)) {
41 return (size_t)page_size;
42 }
43
44 AWS_FATAL_POSTCONDITION(page_size >= 0);
45 return 0;
46 }
47 #else
48 size_t aws_system_info_processor_count(void) {
49 # if defined(AWS_NUM_CPU_CORES)
50 AWS_FATAL_PRECONDITION(AWS_NUM_CPU_CORES > 0);
51 return AWS_NUM_CPU_CORES;
52 # else
53 return 1;
54 # endif
55 }
56
57 size_t aws_system_info_page_size(void) {
58 # if defined(AWS_PAGE_SIZE)
59 AWS_FATAL_PRECONDITION(AWS_PAGE_SIZE > 0);
60 return AWS_PAGE_SIZE;
61 # else
62 /* Default page size fallback - most systems use 4KiB pages */
63 AWS_LOGF(AWS_LL_INFO, AWS_LS_COMMON_GENERAL, "No page size found, fallback to 4KiB");
64 return 4096;
65 # endif
66 }
67 #endif
68
69 #include <ctype.h>
70 #include <fcntl.h>
71
72 uint16_t aws_get_cpu_group_count(void) {
73 if (g_numa_num_configured_nodes_ptr) {
74 return aws_max_u16(1, (uint16_t)g_numa_num_configured_nodes_ptr());
75 }
76
77 return 1U;
78 }
79
80 size_t aws_get_cpu_count_for_group(uint16_t group_idx) {
81 if (g_numa_node_of_cpu_ptr) {
82 size_t total_cpus = aws_system_info_processor_count();
83
84 uint16_t cpu_count = 0;
85 for (size_t i = 0; i < total_cpus; ++i) {
86 if (group_idx == g_numa_node_of_cpu_ptr((int)i)) {
87 cpu_count++;
88 }
89 }
90 return cpu_count;
91 }
92
93 return aws_system_info_processor_count();
94 }
95
96 void aws_get_cpu_ids_for_group(uint16_t group_idx, struct aws_cpu_info *cpu_ids_array, size_t cpu_ids_array_length) {
97 AWS_PRECONDITION(cpu_ids_array);
98
99 if (!cpu_ids_array_length) {
100 return;
101 }
102
103 /* go ahead and initialize everything. */
104 for (size_t i = 0; i < cpu_ids_array_length; ++i) {
105 cpu_ids_array[i].cpu_id = -1;
106 cpu_ids_array[i].suspected_hyper_thread = false;
107 }
108
109 if (g_numa_node_of_cpu_ptr) {
110 size_t total_cpus = aws_system_info_processor_count();
111 size_t current_array_idx = 0;
112 for (size_t i = 0; i < total_cpus && current_array_idx < cpu_ids_array_length; ++i) {
113 if ((int)group_idx == g_numa_node_of_cpu_ptr((int)i)) {
114 cpu_ids_array[current_array_idx].cpu_id = (int32_t)i;
115
116 /* looking for an index jump is a more reliable way to find these. If they're in the group and then
117 * the index jumps, say from 17 to 36, we're most-likely in hyper-thread land. Also, inside a node,
118 * once we find the first hyper-thread, the remaining cores are also likely hyper threads. */
119 if (current_array_idx > 0 && (cpu_ids_array[current_array_idx - 1].suspected_hyper_thread ||
120 cpu_ids_array[current_array_idx - 1].cpu_id < ((int)i - 1))) {
121 cpu_ids_array[current_array_idx].suspected_hyper_thread = true;
122 }
123 current_array_idx += 1;
124 }
125 }
126
127 return;
128 }
129
130 /* a crude hint, but hyper-threads are numbered as the second half of the cpu id listing. The assumption if you
131 * hit here is that this is just listing all cpus on the system. */
132 size_t hyper_thread_hint = cpu_ids_array_length / 2 - 1;
133
134 for (size_t i = 0; i < cpu_ids_array_length; ++i) {
135 cpu_ids_array[i].cpu_id = (int32_t)i;
136 cpu_ids_array[i].suspected_hyper_thread = i > hyper_thread_hint;
137 }
138 }
139
140 bool aws_is_debugger_present(void) {
141 /* Open the status file */
142 const int status_fd = open("/proc/self/status", O_RDONLY);
143 if (status_fd == -1) {
144 return false;
145 }
146
147 /* Read its contents */
148 char buf[4096];
149 const ssize_t num_read = read(status_fd, buf, sizeof(buf) - 1);
150 close(status_fd);
151 if (num_read <= 0) {
152 return false;
153 }
154 buf[num_read] = '\0';
155
156 /* Search for the TracerPid field, which will indicate the debugger process */
157 const char tracerPidString[] = "TracerPid:";
158 const char *tracer_pid = strstr(buf, tracerPidString);
159 if (!tracer_pid) {
160 return false;
161 }
162
163 /* If it's not 0, then there's a debugger */
164 for (const char *cur = tracer_pid + sizeof(tracerPidString) - 1; cur <= buf + num_read; ++cur) {
165 if (!aws_isspace(*cur)) {
166 return aws_isdigit(*cur) && *cur != '0';
167 }
168 }
169
170 return false;
171 }
172
173 #include <signal.h>
174
175 #ifndef __has_builtin
176 # define __has_builtin(x) 0
177 #endif
178
179 void aws_debug_break(void) {
180 #ifdef DEBUG_BUILD
181 if (aws_is_debugger_present()) {
182 # if __has_builtin(__builtin_debugtrap)
183 __builtin_debugtrap();
184 # else
185 raise(SIGTRAP);
186 # endif
187 }
188 #endif /* DEBUG_BUILD */
189 }
190
191 #if defined(AWS_HAVE_EXECINFO)
192 # include <execinfo.h>
193 # include <limits.h>
194
195 # define AWS_BACKTRACE_DEPTH 128
196
197 struct aws_stack_frame_info {
198 char exe[PATH_MAX];
199 char addr[32];
200 char base[32]; /* base addr for dylib/exe */
201 char function[128];
202 };
203
204 /* Ensure only safe characters in a path buffer in case someone tries to
205 rename the exe and trigger shell execution via the sub commands used to
206 resolve symbols */
207 char *s_whitelist_chars(char *path) {
208 char *cur = path;
209 while (*cur) {
210 bool whitelisted = aws_isalnum(*cur) || aws_isspace(*cur) || *cur == '/' || *cur == '_' || *cur == '.' ||
211 (cur > path && *cur == '-');
212 if (!whitelisted) {
213 *cur = '_';
214 }
215 ++cur;
216 }
217 return path;
218 }
219
220 # if defined(__APPLE__)
221 # include <ctype.h>
222 # include <dlfcn.h>
223 # include <mach-o/dyld.h>
224 static char s_exe_path[PATH_MAX];
225 static const char *s_get_executable_path(void) {
226 static const char *s_exe = NULL;
227 if (AWS_LIKELY(s_exe)) {
228 return s_exe;
229 }
230 uint32_t len = sizeof(s_exe_path);
231 if (!_NSGetExecutablePath(s_exe_path, &len)) {
232 s_exe = s_exe_path;
233 }
234 return s_exe;
235 }
236 int s_parse_symbol(const char *symbol, void *addr, struct aws_stack_frame_info *frame) {
237 /* symbols look like: <frame_idx> <exe-or-shared-lib> <addr> <function> + <offset>
238 */
239 const char *current_exe = s_get_executable_path();
240 /* parse exe/shared lib */
241 const char *exe_start = strstr(symbol, " ");
242 while (aws_isspace(*exe_start)) {
243 ++exe_start;
244 }
245 const char *exe_end = strstr(exe_start, " ");
246 strncpy(frame->exe, exe_start, exe_end - exe_start);
247 /* executables get basename'd, so restore the path */
248 if (strstr(current_exe, frame->exe)) {
249 strncpy(frame->exe, current_exe, strlen(current_exe));
250 }
251 s_whitelist_chars(frame->exe);
252
253 /* parse addr */
254 const char *addr_start = strstr(exe_end, "0x");
255 const char *addr_end = strstr(addr_start, " ");
256 strncpy(frame->addr, addr_start, addr_end - addr_start);
257
258 /* parse function */
259 const char *function_start = strstr(addr_end, " ") + 1;
260 const char *function_end = strstr(function_start, " ");
261 /* truncate function name if needed */
262 size_t function_len = function_end - function_start;
263 if (function_len >= (sizeof(frame->function) - 1)) {
264 function_len = sizeof(frame->function) - 1;
265 }
266 strncpy(frame->function, function_start, function_len);
267
268 /* find base addr for library/exe */
269 Dl_info addr_info;
270 dladdr(addr, &addr_info);
271 snprintf(frame->base, sizeof(frame->base), "0x%p", addr_info.dli_fbase);
272
273 return AWS_OP_SUCCESS;
274 }
275
276 void s_resolve_cmd(char *cmd, size_t len, struct aws_stack_frame_info *frame) {
277 snprintf(cmd, len, "atos -o %s -l %s %s", frame->exe, frame->base, frame->addr);
278 }
279 # else
280 int s_parse_symbol(const char *symbol, void *addr, struct aws_stack_frame_info *frame) {
281 /* symbols look like: <exe-or-shared-lib>(<function>+<addr>) [0x<addr>]
282 * or: <exe-or-shared-lib> [0x<addr>]
283 * or: [0x<addr>]
284 */
285 (void)addr;
286 const char *open_paren = strstr(symbol, "(");
287 const char *close_paren = strstr(symbol, ")");
288 const char *exe_end = open_paren;
289 /* there may not be a function in parens, or parens at all */
290 if (open_paren == NULL || close_paren == NULL) {
291 exe_end = strstr(symbol, "[");
292 if (!exe_end) {
293 return AWS_OP_ERR;
294 }
295 /* if exe_end == symbol, there's no exe */
296 if (exe_end != symbol) {
297 exe_end -= 1;
298 }
299 }
300
301 ptrdiff_t exe_len = exe_end - symbol;
302 if (exe_len > 0) {
303 strncpy(frame->exe, symbol, exe_len);
304 }
305 s_whitelist_chars(frame->exe);
306
307 long function_len = (open_paren && close_paren) ? close_paren - open_paren - 1 : 0;
308 if (function_len > 0) { /* dynamic symbol was found */
309 /* there might be (<function>+<addr>) or just (<function>) */
310 const char *function_start = open_paren + 1;
311 const char *plus = strstr(function_start, "+");
312 const char *function_end = (plus) ? plus : close_paren;
313 if (function_end > function_start) {
314 function_len = function_end - function_start;
315 strncpy(frame->function, function_start, function_len);
316 } else if (plus) {
317 long addr_len = close_paren - plus - 1;
318 strncpy(frame->addr, plus + 1, addr_len);
319 }
320 }
321 if (frame->addr[0] == 0) {
322 /* use the address in []'s, since it's all we have */
323 const char *addr_start = strstr(exe_end, "[") + 1;
324 char *addr_end = strstr(addr_start, "]");
325 if (!addr_end) {
326 return AWS_OP_ERR;
327 }
328 strncpy(frame->addr, addr_start, addr_end - addr_start);
329 }
330
331 return AWS_OP_SUCCESS;
332 }
333 void s_resolve_cmd(char *cmd, size_t len, struct aws_stack_frame_info *frame) {
334 snprintf(cmd, len, "addr2line -afips -e %s %s", frame->exe, frame->addr);
335 }
336 # endif
337
338 size_t aws_backtrace(void **stack_frames, size_t num_frames) {
339 return backtrace(stack_frames, (int)aws_min_size(num_frames, INT_MAX));
340 }
341
342 char **aws_backtrace_symbols(void *const *stack_frames, size_t stack_depth) {
343 return backtrace_symbols(stack_frames, (int)aws_min_size(stack_depth, INT_MAX));
344 }
345
346 char **aws_backtrace_addr2line(void *const *stack_frames, size_t stack_depth) {
347 char **symbols = aws_backtrace_symbols(stack_frames, stack_depth);
348 AWS_FATAL_ASSERT(symbols);
349 struct aws_byte_buf lines;
350 aws_byte_buf_init(&lines, aws_default_allocator(), stack_depth * 256);
351
352 /* insert pointers for each stack entry */
353 memset(lines.buffer, 0, stack_depth * sizeof(void *));
354 lines.len += stack_depth * sizeof(void *);
355
356 /* symbols look like: <exe-or-shared-lib>(<function>+<addr>) [0x<addr>]
357 * or: <exe-or-shared-lib> [0x<addr>]
358 * start at 1 to skip the current frame (this function) */
359 for (size_t frame_idx = 0; frame_idx < stack_depth; ++frame_idx) {
360 struct aws_stack_frame_info frame;
361 AWS_ZERO_STRUCT(frame);
362 const char *symbol = symbols[frame_idx];
363 if (s_parse_symbol(symbol, stack_frames[frame_idx], &frame)) {
364 goto parse_failed;
365 }
366
367 /* TODO: Emulate libunwind */
368 char cmd[sizeof(struct aws_stack_frame_info)] = {0};
369 s_resolve_cmd(cmd, sizeof(cmd), &frame);
370 FILE *out = popen(cmd, "r");
371 if (!out) {
372 goto parse_failed;
373 }
374 char output[1024];
375 if (fgets(output, sizeof(output), out)) {
376 /* if addr2line or atos don't know what to do with an address, they just echo it */
377 /* if there are spaces in the output, then they resolved something */
378 if (strstr(output, " ")) {
379 symbol = output;
380 }
381 }
382 pclose(out);
383
384 parse_failed:
385 /* record the pointer to where the symbol will be */
386 *((char **)&lines.buffer[frame_idx * sizeof(void *)]) = (char *)lines.buffer + lines.len;
387 struct aws_byte_cursor line_cursor = aws_byte_cursor_from_c_str(symbol);
388 line_cursor.len += 1; /* strings must be null terminated, make sure we copy the null */
389 aws_byte_buf_append_dynamic(&lines, &line_cursor);
390 }
391 free(symbols);
392 return (char **)lines.buffer; /* caller is responsible for freeing */
393 }
394
395 void aws_backtrace_print(FILE *fp, void *call_site_data) {
396 siginfo_t *siginfo = call_site_data;
397 if (siginfo) {
398 fprintf(fp, "Signal received: %d, errno: %d\n", siginfo->si_signo, siginfo->si_errno);
399 if (siginfo->si_signo == SIGSEGV) {
400 fprintf(fp, " SIGSEGV @ 0x%p\n", siginfo->si_addr);
401 }
402 }
403
404 void *stack_frames[AWS_BACKTRACE_DEPTH];
405 size_t stack_depth = aws_backtrace(stack_frames, AWS_BACKTRACE_DEPTH);
406 char **symbols = aws_backtrace_symbols(stack_frames, stack_depth);
407 if (symbols == NULL) {
408 fprintf(fp, "Unable to decode backtrace via backtrace_symbols\n");
409 return;
410 }
411
412 fprintf(fp, "################################################################################\n");
413 fprintf(fp, "Stack trace:\n");
414 fprintf(fp, "################################################################################\n");
415 for (size_t frame_idx = 1; frame_idx < stack_depth; ++frame_idx) {
416 const char *symbol = symbols[frame_idx];
417 fprintf(fp, "%s\n", symbol);
418 }
419 fflush(fp);
420
421 free(symbols);
422 }
423
424 void aws_backtrace_log(int log_level) {
425 void *stack_frames[AWS_BACKTRACE_DEPTH];
426 size_t num_frames = aws_backtrace(stack_frames, AWS_BACKTRACE_DEPTH);
427 if (!num_frames) {
428 AWS_LOGF(log_level, AWS_LS_COMMON_GENERAL, "Unable to capture backtrace");
429 return;
430 }
431 char **symbols = aws_backtrace_symbols(stack_frames, num_frames);
432 for (size_t line = 0; line < num_frames; ++line) {
433 const char *symbol = symbols[line];
434 AWS_LOGF(log_level, AWS_LS_COMMON_GENERAL, "%s", symbol);
435 }
436 free(symbols);
437 }
438
439 #else
440 void aws_backtrace_print(FILE *fp, void *call_site_data) {
441 (void)call_site_data;
442 fprintf(fp, "No call stack information available\n");
443 }
444
445 size_t aws_backtrace(void **stack_frames, size_t num_frames) {
446 (void)stack_frames;
447 (void)num_frames;
448 return 0;
449 }
450
451 char **aws_backtrace_symbols(void *const *stack_frames, size_t stack_depth) {
452 (void)stack_frames;
453 (void)stack_depth;
454 return NULL;
455 }
456
457 char **aws_backtrace_addr2line(void *const *stack_frames, size_t stack_depth) {
458 (void)stack_frames;
459 (void)stack_depth;
460 return NULL;
461 }
462
463 void aws_backtrace_log(int log_level) {
464 AWS_LOGF(log_level, AWS_LS_COMMON_GENERAL, "aws_backtrace_log: no execinfo compatible backtrace API available");
465 }
466 #endif /* AWS_HAVE_EXECINFO */
467
468 enum aws_platform_os aws_get_platform_build_os(void) {
469 #if defined(AWS_OS_MACOS)
470 return AWS_PLATFORM_OS_MAC;
471 // Other Apple platforms will be reported as iOS
472 #elif defined(AWS_OS_APPLE)
473 return AWS_PLATFORM_OS_IOS;
474 #elif defined(AWS_OS_ANDROID)
475 return AWS_PLATFORM_OS_ANDROID;
476 #else
477 return AWS_PLATFORM_OS_UNIX;
478 #endif
479 }