Debian Codegraph @

crt/aws-c-common/source/common.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/common.h>
7 #include <aws/common/logging.h>
8 #include <aws/common/math.h>
9 #include <aws/common/private/dlloads.h>
10 #include <aws/common/private/external_module_impl.h>
11 #include <aws/common/private/thread_shared.h>
12
13 #include <stdarg.h>
14 #include <stdlib.h>
15
16 #ifdef _WIN32
17 # include <windows.h>
18 #else
19 # include <dlfcn.h>
20 #endif
21
22 #ifdef __MACH__
23 # include <CoreFoundation/CoreFoundation.h>
24 #endif
25
26 /* turn off unused named parameter warning on msvc.*/
27 #ifdef _MSC_VER
28 # pragma warning(push)
29 # pragma warning(disable : 4100)
30 #endif
31
32 long (*g_set_mempolicy_ptr)(int, const unsigned long *, unsigned long) = NULL;
33 int (*g_numa_available_ptr)(void) = NULL;
34 int (*g_numa_num_configured_nodes_ptr)(void) = NULL;
35 int (*g_numa_num_possible_cpus_ptr)(void) = NULL;
36 int (*g_numa_node_of_cpu_ptr)(int cpu) = NULL;
37
38 void *g_libnuma_handle = NULL;
39
40 void aws_secure_zero(void *pBuf, size_t bufsize) {
41 /* don't pass NULL to memset(), it's undefined behavior */
42 if (pBuf == NULL || bufsize == 0) {
43 AWS_ASSERT(bufsize == 0); /* if you believe your NULL buffer has a size, then you have issues */
44 return;
45 }
46
47 #if defined(_WIN32)
48 SecureZeroMemory(pBuf, bufsize);
49 #else
50 /* We cannot use memset_s, even on a C11 compiler, because that would require
51 * that __STDC_WANT_LIB_EXT1__ be defined before the _first_ inclusion of string.h.
52 *
53 * We'll try to work around this by using inline asm on GCC-like compilers,
54 * and by exposing the buffer pointer in a volatile local pointer elsewhere.
55 */
56 # if defined(__GNUC__) || defined(__clang__)
57 memset(pBuf, 0, bufsize);
58 /* This inline asm serves to convince the compiler that the buffer is (somehow) still
59 * used after the zero, and therefore that the optimizer can't eliminate the memset.
60 */
61 __asm__ __volatile__("" /* The asm doesn't actually do anything. */
62 : /* no outputs */
63 /* Tell the compiler that the asm code has access to the pointer to the buffer,
64 * and therefore it might be reading the (now-zeroed) buffer.
65 * Without this. clang/LLVM 9.0.0 optimizes away a memset of a stack buffer.
66 */
67 : "r"(pBuf)
68 /* Also clobber memory. While this seems like it might be unnecessary - after all,
69 * it's enough that the asm might read the buffer, right? - in practice GCC 7.3.0
70 * seems to optimize a zero of a stack buffer without it.
71 */
72 : "memory");
73 # else // not GCC/clang
74 /* We don't have access to inline asm, since we're on a non-GCC platform. Move the pointer
75 * through a volatile pointer in an attempt to confuse the optimizer.
76 */
77 volatile void *pVolBuf = pBuf;
78 memset(pVolBuf, 0, bufsize);
79 # endif // #else not GCC/clang
80 #endif // #else not windows
81 }
82
83 #define AWS_DEFINE_ERROR_INFO_COMMON(C, ES) [(C) - 0x0000] = AWS_DEFINE_ERROR_INFO(C, ES, "aws-c-common")
84 /* clang-format off */
85 static struct aws_error_info errors[] = {
86 AWS_DEFINE_ERROR_INFO_COMMON(
87 AWS_ERROR_SUCCESS,
88 "Success."),
89 AWS_DEFINE_ERROR_INFO_COMMON(
90 AWS_ERROR_OOM,
91 "Out of memory."),
92 AWS_DEFINE_ERROR_INFO_COMMON(
93 AWS_ERROR_NO_SPACE,
94 "Out of space on disk."),
95 AWS_DEFINE_ERROR_INFO_COMMON(
96 AWS_ERROR_UNKNOWN,
97 "Unknown error."),
98 AWS_DEFINE_ERROR_INFO_COMMON(
99 AWS_ERROR_SHORT_BUFFER,
100 "Buffer is not large enough to hold result."),
101 AWS_DEFINE_ERROR_INFO_COMMON(
102 AWS_ERROR_OVERFLOW_DETECTED,
103 "Fixed size value overflow was detected."),
104 AWS_DEFINE_ERROR_INFO_COMMON(
105 AWS_ERROR_UNSUPPORTED_OPERATION,
106 "Unsupported operation."),
107 AWS_DEFINE_ERROR_INFO_COMMON(
108 AWS_ERROR_INVALID_BUFFER_SIZE,
109 "Invalid buffer size."),
110 AWS_DEFINE_ERROR_INFO_COMMON(
111 AWS_ERROR_INVALID_HEX_STR,
112 "Invalid hex string."),
113 AWS_DEFINE_ERROR_INFO_COMMON(
114 AWS_ERROR_INVALID_BASE64_STR,
115 "Invalid base64 string."),
116 AWS_DEFINE_ERROR_INFO_COMMON(
117 AWS_ERROR_INVALID_INDEX,
118 "Invalid index for list access."),
119 AWS_DEFINE_ERROR_INFO_COMMON(
120 AWS_ERROR_THREAD_INVALID_SETTINGS,
121 "Invalid thread settings."),
122 AWS_DEFINE_ERROR_INFO_COMMON(
123 AWS_ERROR_THREAD_INSUFFICIENT_RESOURCE,
124 "Insufficent resources for thread."),
125 AWS_DEFINE_ERROR_INFO_COMMON(
126 AWS_ERROR_THREAD_NO_PERMISSIONS,
127 "Insufficient permissions for thread operation."),
128 AWS_DEFINE_ERROR_INFO_COMMON(
129 AWS_ERROR_THREAD_NOT_JOINABLE,
130 "Thread not joinable."),
131 AWS_DEFINE_ERROR_INFO_COMMON(
132 AWS_ERROR_THREAD_NO_SUCH_THREAD_ID,
133 "No such thread ID."),
134 AWS_DEFINE_ERROR_INFO_COMMON(
135 AWS_ERROR_THREAD_DEADLOCK_DETECTED,
136 "Deadlock detected in thread."),
137 AWS_DEFINE_ERROR_INFO_COMMON(
138 AWS_ERROR_MUTEX_NOT_INIT,
139 "Mutex not initialized."),
140 AWS_DEFINE_ERROR_INFO_COMMON(
141 AWS_ERROR_MUTEX_TIMEOUT,
142 "Mutex operation timed out."),
143 AWS_DEFINE_ERROR_INFO_COMMON(
144 AWS_ERROR_MUTEX_CALLER_NOT_OWNER,
145 "The caller of a mutex operation was not the owner."),
146 AWS_DEFINE_ERROR_INFO_COMMON(
147 AWS_ERROR_MUTEX_FAILED,
148 "Mutex operation failed."),
149 AWS_DEFINE_ERROR_INFO_COMMON(
150 AWS_ERROR_COND_VARIABLE_INIT_FAILED,
151 "Condition variable initialization failed."),
152 AWS_DEFINE_ERROR_INFO_COMMON(
153 AWS_ERROR_COND_VARIABLE_TIMED_OUT,
154 "Condition variable wait timed out."),
155 AWS_DEFINE_ERROR_INFO_COMMON(
156 AWS_ERROR_COND_VARIABLE_ERROR_UNKNOWN,
157 "Condition variable unknown error."),
158 AWS_DEFINE_ERROR_INFO_COMMON(
159 AWS_ERROR_CLOCK_FAILURE,
160 "Clock operation failed."),
161 AWS_DEFINE_ERROR_INFO_COMMON(
162 AWS_ERROR_LIST_EMPTY,
163 "Empty list."),
164 AWS_DEFINE_ERROR_INFO_COMMON(
165 AWS_ERROR_DEST_COPY_TOO_SMALL,
166 "Destination of copy is too small."),
167 AWS_DEFINE_ERROR_INFO_COMMON(
168 AWS_ERROR_LIST_EXCEEDS_MAX_SIZE,
169 "A requested operation on a list would exceed it's max size."),
170 AWS_DEFINE_ERROR_INFO_COMMON(
171 AWS_ERROR_LIST_STATIC_MODE_CANT_SHRINK,
172 "Attempt to shrink a list in static mode."),
173 AWS_DEFINE_ERROR_INFO_COMMON(
174 AWS_ERROR_PRIORITY_QUEUE_FULL,
175 "Attempt to add items to a full preallocated queue in static mode."),
176 AWS_DEFINE_ERROR_INFO_COMMON(
177 AWS_ERROR_PRIORITY_QUEUE_EMPTY,
178 "Attempt to pop an item from an empty queue."),
179 AWS_DEFINE_ERROR_INFO_COMMON(
180 AWS_ERROR_PRIORITY_QUEUE_BAD_NODE,
181 "Bad node handle passed to remove."),
182 AWS_DEFINE_ERROR_INFO_COMMON(
183 AWS_ERROR_HASHTBL_ITEM_NOT_FOUND,
184 "Item not found in hash table."),
185 AWS_DEFINE_ERROR_INFO_COMMON(
186 AWS_ERROR_INVALID_DATE_STR,
187 "Date string is invalid and cannot be parsed."
188 ),
189 AWS_DEFINE_ERROR_INFO_COMMON(
190 AWS_ERROR_INVALID_ARGUMENT,
191 "An invalid argument was passed to a function."
192 ),
193 AWS_DEFINE_ERROR_INFO_COMMON(
194 AWS_ERROR_RANDOM_GEN_FAILED,
195 "A call to the random number generator failed. Retry later."
196 ),
197 AWS_DEFINE_ERROR_INFO_COMMON(
198 AWS_ERROR_MALFORMED_INPUT_STRING,
199 "An input string was passed to a parser and the string was incorrectly formatted."
200 ),
201 AWS_DEFINE_ERROR_INFO_COMMON(
202 AWS_ERROR_UNIMPLEMENTED,
203 "A function was called, but is not implemented."
204 ),
205 AWS_DEFINE_ERROR_INFO_COMMON(
206 AWS_ERROR_INVALID_STATE,
207 "An invalid state was encountered."
208 ),
209 AWS_DEFINE_ERROR_INFO_COMMON(
210 AWS_ERROR_ENVIRONMENT_GET,
211 "System call failure when getting an environment variable."
212 ),
213 AWS_DEFINE_ERROR_INFO_COMMON(
214 AWS_ERROR_ENVIRONMENT_SET,
215 "System call failure when setting an environment variable."
216 ),
217 AWS_DEFINE_ERROR_INFO_COMMON(
218 AWS_ERROR_ENVIRONMENT_UNSET,
219 "System call failure when unsetting an environment variable."
220 ),
221 AWS_DEFINE_ERROR_INFO_COMMON(
222 AWS_ERROR_SYS_CALL_FAILURE,
223 "System call failure."),
224 AWS_DEFINE_ERROR_INFO_COMMON(
225 AWS_ERROR_FILE_INVALID_PATH,
226 "Invalid file path."),
227 AWS_DEFINE_ERROR_INFO_COMMON(
228 AWS_ERROR_MAX_FDS_EXCEEDED,
229 "The maximum number of fds has been exceeded."),
230 AWS_DEFINE_ERROR_INFO_COMMON(
231 AWS_ERROR_NO_PERMISSION,
232 "User does not have permission to perform the requested action."),
233 AWS_DEFINE_ERROR_INFO_COMMON(
234 AWS_ERROR_STREAM_UNSEEKABLE,
235 "Stream does not support seek operations."),
236 AWS_DEFINE_ERROR_INFO_COMMON(
237 AWS_ERROR_C_STRING_BUFFER_NOT_NULL_TERMINATED,
238 "A c-string like buffer was passed but a null terminator was not found within the bounds of the buffer."),
239 AWS_DEFINE_ERROR_INFO_COMMON(
240 AWS_ERROR_STRING_MATCH_NOT_FOUND,
241 "The specified substring was not present in the input string."),
242 AWS_DEFINE_ERROR_INFO_COMMON(
243 AWS_ERROR_DIVIDE_BY_ZERO,
244 "Attempt to divide a number by zero."),
245 AWS_DEFINE_ERROR_INFO_COMMON(
246 AWS_ERROR_INVALID_FILE_HANDLE,
247 "Invalid file handle."),
248 AWS_DEFINE_ERROR_INFO_COMMON(
249 AWS_ERROR_OPERATION_INTERUPTED,
250 "The operation was interrupted."
251 ),
252 AWS_DEFINE_ERROR_INFO_COMMON(
253 AWS_ERROR_DIRECTORY_NOT_EMPTY,
254 "An operation on a directory was attempted which is not allowed when the directory is not empty."
255 ),
256 AWS_DEFINE_ERROR_INFO_COMMON(
257 AWS_ERROR_PLATFORM_NOT_SUPPORTED,
258 "Feature not supported on this platform."),
259 AWS_DEFINE_ERROR_INFO_COMMON(
260 AWS_ERROR_INVALID_UTF8,
261 "Invalid UTF-8."),
262 AWS_DEFINE_ERROR_INFO_COMMON(
263 AWS_ERROR_GET_HOME_DIRECTORY_FAILED,
264 "Failed to get home directory."),
265 AWS_DEFINE_ERROR_INFO_COMMON(
266 AWS_ERROR_INVALID_XML,
267 "Invalid XML document."),
268 AWS_DEFINE_ERROR_INFO_COMMON(
269 AWS_ERROR_FILE_OPEN_FAILURE,
270 "Failed opening file."),
271 AWS_DEFINE_ERROR_INFO_COMMON(
272 AWS_ERROR_FILE_READ_FAILURE,
273 "Failed reading from file."),
274 AWS_DEFINE_ERROR_INFO_COMMON(
275 AWS_ERROR_FILE_WRITE_FAILURE,
276 "Failed writing to file."),
277 AWS_DEFINE_ERROR_INFO_COMMON(
278 AWS_ERROR_INVALID_CBOR,
279 "Malformed cbor data."),
280 AWS_DEFINE_ERROR_INFO_COMMON(
281 AWS_ERROR_CBOR_UNEXPECTED_TYPE,
282 "Unexpected cbor type encountered."),
283 AWS_DEFINE_ERROR_INFO_COMMON(
284 AWS_ERROR_CBOR_RESOURCE_LIMIT_EXCEEDED,
285 "Cbor decoder resource limit exceeded."),
286 };
287 /* clang-format on */
288
289 static struct aws_error_info_list s_list = {
290 .error_list = errors,
291 .count = AWS_ARRAY_SIZE(errors),
292 };
293
294 static struct aws_log_subject_info s_common_log_subject_infos[] = {
295 DEFINE_LOG_SUBJECT_INFO(
296 AWS_LS_COMMON_GENERAL,
297 "aws-c-common",
298 "Subject for aws-c-common logging that doesn't belong to any particular category"),
299 DEFINE_LOG_SUBJECT_INFO(
300 AWS_LS_COMMON_TASK_SCHEDULER,
301 "task-scheduler",
302 "Subject for task scheduler or task specific logging."),
303 DEFINE_LOG_SUBJECT_INFO(AWS_LS_COMMON_THREAD, "thread", "Subject for logging thread related functions."),
304 DEFINE_LOG_SUBJECT_INFO(AWS_LS_COMMON_MEMTRACE, "memtrace", "Output from the aws_mem_trace_dump function"),
305 DEFINE_LOG_SUBJECT_INFO(AWS_LS_COMMON_XML_PARSER, "xml-parser", "Subject for xml parser specific logging."),
306 DEFINE_LOG_SUBJECT_INFO(AWS_LS_COMMON_IO, "common-io", "Common IO utilities"),
307 DEFINE_LOG_SUBJECT_INFO(AWS_LS_COMMON_BUS, "bus", "Message bus"),
308 DEFINE_LOG_SUBJECT_INFO(AWS_LS_COMMON_TEST, "test", "Unit/integration testing"),
309 DEFINE_LOG_SUBJECT_INFO(AWS_LS_COMMON_JSON_PARSER, "json-parser", "Subject for json parser specific logging"),
310 DEFINE_LOG_SUBJECT_INFO(AWS_LS_COMMON_CBOR, "cbor", "Subject for CBOR encode and decode"),
311 };
312
313 static struct aws_log_subject_info_list s_common_log_subject_list = {
314 .subject_list = s_common_log_subject_infos,
315 .count = AWS_ARRAY_SIZE(s_common_log_subject_infos),
316 };
317
318 static bool s_common_library_initialized = false;
319
320 void aws_common_library_init(struct aws_allocator *allocator) {
321 (void)allocator;
322
323 if (!s_common_library_initialized) {
324 s_common_library_initialized = true;
325 aws_register_error_info(&s_list);
326 aws_register_log_subject_info_list(&s_common_log_subject_list);
327 aws_thread_initialize_thread_management();
328 aws_json_module_init(allocator);
329 aws_cbor_module_init(allocator);
330
331 /* NUMA is funky and we can't rely on libnuma.so being available. We also don't want to take a hard dependency on it,
332 * try and load it if we can. */
333 #ifdef AWS_OS_LINUX
334 /* libnuma defines set_mempolicy() as a WEAK symbol. Loading into the global symbol table overwrites symbols and
335 assumptions due to the way loaders and dlload are often implemented and those symbols are defined by things
336 like libpthread.so on some unix distros. Sorry about the memory usage here, but it's our only safe choice.
337 Also, please don't do numa configurations if memory is your economic bottleneck. */
338 g_libnuma_handle = dlopen("libnuma.so", RTLD_LAZY | RTLD_LOCAL);
339
340 /* turns out so versioning is really inconsistent these days */
341 if (!g_libnuma_handle) {
342 g_libnuma_handle = dlopen("libnuma.so.1", RTLD_LAZY | RTLD_LOCAL);
343 }
344
345 if (!g_libnuma_handle) {
346 g_libnuma_handle = dlopen("libnuma.so.2", RTLD_LAZY | RTLD_LOCAL);
347 }
348
349 if (g_libnuma_handle) {
350 AWS_LOGF_INFO(AWS_LS_COMMON_GENERAL, "static: libnuma.so loaded");
351 *(void **)(&g_set_mempolicy_ptr) = dlsym(g_libnuma_handle, "set_mempolicy");
352 if (g_set_mempolicy_ptr) {
353 AWS_LOGF_INFO(AWS_LS_COMMON_GENERAL, "static: set_mempolicy() loaded");
354 } else {
355 AWS_LOGF_INFO(AWS_LS_COMMON_GENERAL, "static: set_mempolicy() failed to load");
356 }
357
358 *(void **)(&g_numa_available_ptr) = dlsym(g_libnuma_handle, "numa_available");
359 if (g_numa_available_ptr) {
360 AWS_LOGF_INFO(AWS_LS_COMMON_GENERAL, "static: numa_available() loaded");
361 } else {
362 AWS_LOGF_INFO(AWS_LS_COMMON_GENERAL, "static: numa_available() failed to load");
363 }
364 if (g_numa_available_ptr() == -1) {
365 AWS_LOGF_INFO(
366 AWS_LS_COMMON_GENERAL,
367 "static: numa_available() returns -1, numa functions are not available. Skip loading the other "
368 "numa functions.");
369 } else {
370 *(void **)(&g_numa_num_configured_nodes_ptr) = dlsym(g_libnuma_handle, "numa_num_configured_nodes");
371 if (g_numa_num_configured_nodes_ptr) {
372 AWS_LOGF_INFO(AWS_LS_COMMON_GENERAL, "static: numa_num_configured_nodes() loaded");
373 } else {
374 AWS_LOGF_INFO(AWS_LS_COMMON_GENERAL, "static: numa_num_configured_nodes() failed to load");
375 }
376
377 *(void **)(&g_numa_num_possible_cpus_ptr) = dlsym(g_libnuma_handle, "numa_num_possible_cpus");
378 if (g_numa_num_possible_cpus_ptr) {
379 AWS_LOGF_INFO(AWS_LS_COMMON_GENERAL, "static: numa_num_possible_cpus() loaded");
380 } else {
381 AWS_LOGF_INFO(AWS_LS_COMMON_GENERAL, "static: numa_num_possible_cpus() failed to load");
382 }
383
384 *(void **)(&g_numa_node_of_cpu_ptr) = dlsym(g_libnuma_handle, "numa_node_of_cpu");
385 if (g_numa_node_of_cpu_ptr) {
386 AWS_LOGF_INFO(AWS_LS_COMMON_GENERAL, "static: numa_node_of_cpu() loaded");
387 } else {
388 AWS_LOGF_INFO(AWS_LS_COMMON_GENERAL, "static: numa_node_of_cpu() failed to load");
389 }
390 }
391
392 } else {
393 AWS_LOGF_INFO(AWS_LS_COMMON_GENERAL, "static: libnuma.so failed to load");
394 }
395 #endif
396 }
397 }
398
399 void aws_common_library_clean_up(void) {
400 if (s_common_library_initialized) {
401 s_common_library_initialized = false;
402 aws_thread_join_all_managed();
403 aws_unregister_error_info(&s_list);
404 aws_unregister_log_subject_info_list(&s_common_log_subject_list);
405 aws_json_module_cleanup();
406 aws_cbor_module_cleanup();
407 #ifdef AWS_OS_LINUX
408 if (g_libnuma_handle) {
409 dlclose(g_libnuma_handle);
410 }
411 #endif
412 }
413 }
414
415 void aws_common_fatal_assert_library_initialized(void) {
416 if (!s_common_library_initialized) {
417 fprintf(
418 stderr, "%s", "aws_common_library_init() must be called before using any functionality in aws-c-common.");
419
420 AWS_FATAL_ASSERT(s_common_library_initialized);
421 }
422 }
423
424 #ifdef _MSC_VER
425 # pragma warning(pop)
426 #endif