common.c 15 KB

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