## Overview The DAP Core module provides fundamental infrastructure and utilities that form the foundation of the entire DAP SDK ecosystem. This module implements essential data structures, memory management, logging systems, and cross-platform compatibility abstractions required by all other DAP SDK modules. **Based on:** `dap-sdk/core/include/dap_common.h`, `dap-sdk/core/src/dap_common.c` ## Document Structure - [[#Overview|Overview]] - [[#Module Structures|Module Structures]] - [[#dap_stream_node_addr_t|dap_stream_node_addr_t - Node Address Structure]] - [[#dap_log_level_t|dap_log_level_t - Logging Levels]] - [[#dap_memstat_rec_t|dap_memstat_rec_t - Memory Statistics]] - [[#dap_error_str_t|dap_error_str_t - Error String]] - [[#dap_maxint_str_t|dap_maxint_str_t - Integer String]] - [[#dap_node_addr_str_t|dap_node_addr_str_t - Node Address String]] - [[#DapAsciiType|DapAsciiType - ASCII Character Types]] - [[#iovec_t|iovec_t - I/O Vector]] - [[#Module Functions|Module Functions]] - [[#Core System Functions|System Initialization and Management]] - [[#Memory Management Functions|Advanced Memory Operations]] - [[#Logging Functions|Logging and Debugging]] - [[#String Utilities|String and Encoding Functions]] - [[#Timer Functions|Interval Timer Management]] - [[#Error Codes|Error Codes]] - [[#Typical Examples|Typical Examples]] ## Module Structures ### dap_stream_node_addr_t Node address structure for network identification and routing. ```c typedef union dap_stream_node_addr { uint64_t uint64; // 64-bit address representation uint16_t words[sizeof(uint64_t)/2]; // Word-based access uint8_t raw[sizeof(uint64_t)]; // Byte-level access } DAP_ALIGN_PACKED dap_stream_node_addr_t; ``` **Public Fields:** - `uint64` - Complete 64-bit node address for efficient operations - `words` - Array of 16-bit words for segmented address access - `raw` - Byte array for low-level address manipulation and serialization ### dap_log_level_t Enumeration defining logging severity levels and output control. ```c typedef enum dap_log_level { L_DEBUG = 0, // Debug information for development L_INFO = 1, // General information messages L_NOTICE = 2, // Important notices requiring attention L_MSG = 3, // Regular application messages L_DAP = 4, // DAP-specific protocol messages L_WARNING = 5, // Warning conditions that need review L_ATT = 6, // Attention-required events L_ERROR = 7, // Error conditions requiring action L_CRITICAL = 8, // Critical system failures L_TOTAL // Total number of log levels } dap_log_level_t; ``` **Log Levels:** - `L_DEBUG` - Detailed debugging information for development and troubleshooting - `L_INFO` - General operational information about system state - `L_NOTICE` - Important events that should be noted but don't indicate problems - `L_WARNING` - Potentially problematic situations that need attention - `L_ERROR` - Error conditions that affect functionality but allow continued operation - `L_CRITICAL` - Severe errors that may cause system instability or shutdown ### dap_memstat_rec_t Memory statistics record for debugging and performance monitoring. ```c typedef struct __dap_memstat_rec__ { unsigned char fac_len; // Length of facility name unsigned char fac_name[MEMSTAT$SZ_NAME + 1]; // Human readable facility name, ASCIC ssize_t alloc_sz; // Size of single allocations atomic_ullong alloc_nr; // Number of allocations performed atomic_ullong free_nr; // Number of deallocations performed } dap_memstat_rec_t; ``` **Statistics Fields:** - `fac_name` - Facility or module name for categorizing memory usage - `alloc_sz` - Standard allocation size for this facility - `alloc_nr` - Atomic counter tracking allocation operations - `free_nr` - Atomic counter tracking deallocation operations ### dap_error_str_t Error string union for error message handling. ```c typedef union dap_error_str { const char s[LAST_ERROR_MAX]; // Error message string buffer } dap_error_str_t; ``` **Fields:** - `s` - Fixed-size buffer for error message storage ### dap_maxint_str_t Maximum integer string union for number formatting. ```c typedef union dap_maxint_str { const char s[INT_DIGITS + 2]; // Integer string buffer } dap_maxint_str_t; ``` **Fields:** - `s` - Buffer for integer string representation ### dap_node_addr_str_t Node address string union for address formatting. ```c typedef union dap_node_addr_str { const char s[DAP_NODE_ADDR_LEN]; // Node address string buffer } dap_node_addr_str_t; ``` **Fields:** - `s` - Buffer for node address string representation ### DapAsciiType ASCII character classification flags for character type checking. ```c typedef enum { DAP_ASCII_ALNUM = 1 << 0, // Alphanumeric characters DAP_ASCII_ALPHA = 1 << 1, // Alphabetic characters DAP_ASCII_CNTRL = 1 << 2, // Control characters DAP_ASCII_DIGIT = 1 << 3, // Decimal digits DAP_ASCII_GRAPH = 1 << 4, // Graphic characters DAP_ASCII_LOWER = 1 << 5, // Lowercase letters DAP_ASCII_PRINT = 1 << 6, // Printable characters DAP_ASCII_PUNCT = 1 << 7, // Punctuation characters DAP_ASCII_SPACE = 1 << 8, // Whitespace characters DAP_ASCII_UPPER = 1 << 9, // Uppercase letters DAP_ASCII_XDIGIT = 1 << 10 // Hexadecimal digits } DapAsciiType; ``` **ASCII Types:** - `DAP_ASCII_ALNUM` - Alphanumeric characters (A-Z, a-z, 0-9) - `DAP_ASCII_ALPHA` - Alphabetic characters (A-Z, a-z) - `DAP_ASCII_CNTRL` - Control characters (ASCII 0-31, 127) - `DAP_ASCII_DIGIT` - Decimal digits (0-9) - `DAP_ASCII_GRAPH` - Graphic characters (printable except space) - `DAP_ASCII_LOWER` - Lowercase letters (a-z) - `DAP_ASCII_PRINT` - Printable characters (including space) - `DAP_ASCII_PUNCT` - Punctuation characters - `DAP_ASCII_SPACE` - Whitespace characters - `DAP_ASCII_UPPER` - Uppercase letters (A-Z) - `DAP_ASCII_XDIGIT` - Hexadecimal digits (0-9, A-F, a-f) ### iovec_t I/O vector structure for scatter-gather operations. ```c typedef struct iovec { void *iov_base; // Pointer to data buffer size_t iov_len; // Size of data buffer } iovec_t; ``` **I/O Fields:** - `iov_base` - Base pointer to data buffer for read/write operations - `iov_len` - Length of data buffer in bytes ## Module Functions ### Core System Functions #### `dap_common_init()` Initializes the DAP SDK core system with logging and basic infrastructure. ```c int dap_common_init(const char *console_title, const char *a_log_file); ``` **Parameters:** - `console_title` (const char*) - Application name for console display and logging - `a_log_file` (const char*) - Path to log file for persistent logging output **Returns:** - `0` - Initialization completed successfully - `-1` - Initialization failed due to system resource issues **Error Conditions:** - Returns -1 if logging system initialization fails - Returns -1 if memory management setup fails - Returns -1 if thread primitives initialization fails **Description:** Initializes core DAP SDK infrastructure including memory management, logging system, thread primitives, and platform-specific abstractions. Must be called before using any other DAP SDK functions. #### `wdap_common_init()` Windows-specific initialization with wide character log file support. ```c int wdap_common_init(const char *console_title, const wchar_t *a_wlog_file); ``` **Parameters:** - `console_title` (const char*) - Application name for console display - `a_wlog_file` (const wchar_t*) - Wide character path to log file **Returns:** - `0` - Initialization completed successfully - `-1` - Initialization failed **Description:** Windows-specific variant of dap_common_init() supporting wide character log file paths. #### `dap_common_deinit()` Cleanup and deinitialize the DAP SDK core system. ```c void dap_common_deinit(void); ``` **Parameters:** None **Returns:** None (void function) **Description:** Performs cleanup of all DAP SDK core resources including memory pools, logging system, thread resources, and platform-specific cleanup. Should be called before application termination. #### `dap_gettid()` Retrieves the current thread identifier for debugging and logging. ```c unsigned dap_gettid(void); ``` **Parameters:** None **Returns:** - `unsigned` - Current thread identifier **Description:** Cross-platform function to retrieve the current thread identifier for use in logging, debugging, and thread-specific operations. #### `dap_set_appname()` Sets the application name for logging and system identification. ```c void dap_set_appname(const char *a_appname); ``` **Parameters:** - `a_appname` (const char*) - Application name to set **Returns:** None (void function) **Description:** Sets the application name used in logging output and system identification. #### `dap_common_enable_cleaner_log()` Enables automatic log cleaning with specified parameters. ```c void dap_common_enable_cleaner_log(size_t a_timeout, size_t a_max_size); ``` **Parameters:** - `a_timeout` (size_t) - Timeout for log cleaning in seconds - `a_max_size` (size_t) - Maximum log size before cleaning **Returns:** None (void function) **Description:** Enables automatic log file cleaning to prevent excessive disk usage. ### Memory Management Functions #### `DAP_NEW()` Allocates memory for single object with type safety and debugging support. ```c #define DAP_NEW(type) ((type*)s_vm_get(__func__, __LINE__, sizeof(type))) ``` **Parameters:** - `type` - Data type to allocate memory for **Returns:** - `type*` - Pointer to allocated memory - `NULL` - Allocation failed **Error Conditions:** - Returns NULL if sizeof(type) is 0 - Returns NULL if system memory exhausted - Returns NULL if memory debugging structures cannot be allocated **Description:** Type-safe memory allocation macro that includes debugging information (function name and line number) for memory leak detection and debugging. #### `DAP_NEW_Z()` Allocates zero-initialized memory for single object. ```c #define DAP_NEW_Z(type) ((type*)s_vm_get_z(__func__, __LINE__, 1, sizeof(type))) ``` **Parameters:** - `type` - Data type to allocate and zero-initialize **Returns:** - `type*` - Pointer to zero-initialized memory - `NULL` - Allocation failed **Description:** Zero-initialized memory allocation with debugging support. Ensures all allocated memory is cleared to zero before returning. #### `DAP_DELETE()` Safely frees allocated memory and nullifies pointer to prevent double-free errors. ```c #define DAP_DELETE(ptr) s_vm_free(__func__, __LINE__, (void*)ptr) ``` **Parameters:** - `ptr` - Pointer to memory to free **Returns:** None (void macro) **Description:** Secure memory deallocation with debugging information. Includes safeguards against double-free errors and memory corruption. #### `dap_delete_multy()` Deletes multiple allocated objects with variable argument list. ```c void dap_delete_multy(size_t a_count, ...); ``` **Parameters:** - `a_count` (size_t) - Number of pointers to delete - `...` - Variable list of pointers to delete **Returns:** None (void function) **Description:** Safely deletes multiple allocated objects in a single call using variable arguments. #### `dap_serialize_multy()` Serializes multiple objects into a single buffer. ```c uint8_t* dap_serialize_multy(uint8_t *a_data, uint64_t a_size, ...); ``` **Parameters:** - `a_data` (uint8_t*) - Output buffer for serialized data - `a_size` (uint64_t) - Size of output buffer - `...` - Variable list of objects to serialize **Returns:** - `uint8_t*` - Pointer to next position in buffer - `NULL` - Serialization failed #### `dap_deserialize_multy()` Deserializes multiple objects from a buffer. ```c int dap_deserialize_multy(const uint8_t *a_data, uint64_t a_size, ...); ``` **Parameters:** - `a_data` (const uint8_t*) - Input buffer with serialized data - `a_size` (uint64_t) - Size of input buffer - `...` - Variable list of destination pointers **Returns:** - `0` - Deserialization successful - `-1` - Deserialization failed #### `dap_memstat_reg()` Registers memory statistics record for debugging. ```c int dap_memstat_reg(dap_memstat_rec_t *a_memstat_rec); ``` **Parameters:** - `a_memstat_rec` (dap_memstat_rec_t*) - Memory statistics record to register **Returns:** - `0` - Registration successful - `-1` - Registration failed #### `dap_memstat_show()` Displays comprehensive memory usage statistics for debugging. ```c void dap_memstat_show(void); ``` **Parameters:** None **Returns:** None (void function) **Description:** Outputs detailed memory usage statistics for all registered facilities, including allocation counts, sizes, and potential memory leaks. ### Logging Functions #### `dap_log_set_external_output()` Configures external logging output destination. ```c void dap_log_set_external_output(LOGGER_EXTERNAL_OUTPUT output, void *param); ``` **Parameters:** - `output` (LOGGER_EXTERNAL_OUTPUT) - Output destination type - `param` (void*) - Output-specific parameter **Returns:** None (void function) **Description:** Configures external logging output for custom logging destinations. #### `dap_log_set_max_item()` Sets maximum number of log items to retain in memory. ```c void dap_log_set_max_item(unsigned int a_max); ``` **Parameters:** - `a_max` (unsigned int) - Maximum number of log items **Returns:** None (void function) #### `dap_log_get_item()` Retrieves log items within specified time range. ```c char* dap_log_get_item(time_t a_start_time, int a_limit); ``` **Parameters:** - `a_start_time` (time_t) - Start time for log retrieval - `a_limit` (int) - Maximum number of items to retrieve **Returns:** - `char*` - Formatted log string - `NULL` - No log items found #### `dap_log_level_set()` Configures the minimum logging level for output filtering. ```c void dap_log_level_set(enum dap_log_level ll); ``` **Parameters:** - `ll` (enum dap_log_level) - Minimum log level to output **Returns:** None (void function) **Description:** Sets the global logging threshold. Messages below this level will be filtered out. #### `dap_log_level_get()` Retrieves the current logging level setting. ```c enum dap_log_level dap_log_level_get(void); ``` **Parameters:** None **Returns:** - `dap_log_level_t` - Current minimum logging level #### `dap_set_log_tag_width()` Sets the width for log tag formatting. ```c void dap_set_log_tag_width(size_t width); ``` **Parameters:** - `width` (size_t) - Tag width in characters **Returns:** None (void function) #### `dap_dump_hex()` Creates hexadecimal dump of binary data. ```c char* dap_dump_hex(byte_t *a_data, size_t a_size); ``` **Parameters:** - `a_data` (byte_t*) - Binary data to dump - `a_size` (size_t) - Size of data **Returns:** - `char*` - Hexadecimal string representation - `NULL` - Dump failed ### String Utilities #### `dap_random_string_create_alloc()` Creates a cryptographically random string for security applications. ```c char* dap_random_string_create_alloc(size_t a_length); ``` **Parameters:** - `a_length` (size_t) - Length of random string to generate **Returns:** - `char*` - Newly allocated random string - `NULL` - Generation failed **Error Conditions:** - Returns NULL if a_length is 0 - Returns NULL if memory allocation fails - Returns NULL if random number generation fails **Description:** Generates cryptographically secure random string suitable for tokens, keys, and other security-sensitive applications. #### `dap_random_string_fill()` Fills existing buffer with random string data. ```c void dap_random_string_fill(char *str, size_t length); ``` **Parameters:** - `str` (char*) - Buffer to fill with random data - `length` (size_t) - Length of buffer **Returns:** None (void function) #### `dap_hex2bin()` Converts hexadecimal string to binary data. ```c size_t dap_hex2bin(uint8_t *a_out, const char *a_in, size_t a_len); ``` **Parameters:** - `a_out` (uint8_t*) - Output buffer for binary data - `a_in` (const char*) - Input hexadecimal string - `a_len` (size_t) - Length of input string **Returns:** - `size_t` - Number of bytes converted - `0` - Conversion failed #### `dap_bin2hex()` Converts binary data to hexadecimal string representation. ```c size_t dap_bin2hex(char *a_out, const void *a_in, size_t a_len); ``` **Parameters:** - `a_out` (char*) - Output buffer for hexadecimal string - `a_in` (const void*) - Input binary data - `a_len` (size_t) - Length of input data **Returns:** - `size_t` - Number of characters written - `0` - Conversion failed #### `dap_is_hex_string()` Checks if string contains valid hexadecimal characters. ```c int dap_is_hex_string(const char *a_in, size_t a_len); ``` **Parameters:** - `a_in` (const char*) - String to check - `a_len` (size_t) - Length of string **Returns:** - `1` - String is valid hexadecimal - `0` - String is not valid hexadecimal #### `dap_digit_from_string()` Converts string representation to binary digits. ```c void dap_digit_from_string(const char *num_str, void *raw, size_t raw_len); ``` **Parameters:** - `num_str` (const char*) - String representation - `raw` (void*) - Output buffer for binary data - `raw_len` (size_t) - Size of output buffer **Returns:** None (void function) #### `dap_digit_from_string2()` Alternative string to binary conversion function. ```c void dap_digit_from_string2(const char *num_str, void *raw, size_t raw_len); ``` **Parameters:** - `num_str` (const char*) - String representation - `raw` (void*) - Output buffer for binary data - `raw_len` (size_t) - Size of output buffer **Returns:** None (void function) #### `dap_parse_items()` Parses string into array of items using delimiter. ```c char** dap_parse_items(const char *a_str, char a_delimiter, int *a_count, const int a_only_digit); ``` **Parameters:** - `a_str` (const char*) - String to parse - `a_delimiter` (char) - Delimiter character - `a_count` (int*) - Output: number of parsed items - `a_only_digit` (const int) - Flag to allow only digits **Returns:** - `char**` - Array of parsed strings - `NULL` - Parsing failed ### Timer Functions #### `dap_interval_timer_create()` Creates interval timer for periodic callback execution. ```c dap_interval_timer_t dap_interval_timer_create(unsigned int a_msec, dap_timer_callback_t a_callback, void *a_param); ``` **Parameters:** - `a_msec` (unsigned int) - Timer interval in milliseconds - `a_callback` (dap_timer_callback_t) - Function to call on timer expiration - `a_param` (void*) - Parameter to pass to callback function **Returns:** - `dap_interval_timer_t` - Timer handle for management operations - `NULL` - Timer creation failed **Error Conditions:** - Returns NULL if a_msec is 0 - Returns NULL if a_callback is NULL - Returns NULL if system timer resources exhausted #### `dap_interval_timer_delete()` Deletes interval timer and frees resources. ```c void dap_interval_timer_delete(dap_interval_timer_t a_timer); ``` **Parameters:** - `a_timer` (dap_interval_timer_t) - Timer handle to delete **Returns:** None (void function) #### `dap_interval_timer_disable()` Disables interval timer without deleting it. ```c int dap_interval_timer_disable(dap_interval_timer_t a_timer); ``` **Parameters:** - `a_timer` (dap_interval_timer_t) - Timer handle to disable **Returns:** - `0` - Timer disabled successfully - `-1` - Disable operation failed #### `dap_interval_timer_init()` Initializes the interval timer subsystem. ```c void dap_interval_timer_init(); ``` **Parameters:** None **Returns:** None (void function) #### `dap_interval_timer_deinit()` Deinitializes the interval timer subsystem. ```c void dap_interval_timer_deinit(); ``` **Parameters:** None **Returns:** None (void function) ### System Functions #### `dap_usleep()` Suspends execution for specified microseconds. ```c void dap_usleep(uint64_t a_microseconds); ``` **Parameters:** - `a_microseconds` (uint64_t) - Sleep duration in microseconds **Returns:** None (void function) #### `dap_time_to_str_rfc822()` Converts time to RFC822 string format. ```c int dap_time_to_str_rfc822(char *out, size_t out_size_max, dap_time_t a_time); ``` **Parameters:** - `out` (char*) - Output buffer for formatted string - `out_size_max` (size_t) - Maximum size of output buffer - `a_time` (dap_time_t) - Time to convert **Returns:** - `0` - Conversion successful - `-1` - Conversion failed #### `dap_time_from_str_rfc822()` Converts RFC822 string to time value. ```c dap_time_t dap_time_from_str_rfc822(const char *a_time_str); ``` **Parameters:** - `a_time_str` (const char*) - RFC822 formatted time string **Returns:** - `dap_time_t` - Converted time value #### `dap_nanotime_to_str_rfc822()` Converts nanotime to RFC822 string format. ```c int dap_nanotime_to_str_rfc822(char *a_out, size_t a_out_size_max, dap_nanotime_t a_chain_time); ``` **Parameters:** - `a_out` (char*) - Output buffer for formatted string - `a_out_size_max` (size_t) - Maximum size of output buffer - `a_chain_time` (dap_nanotime_t) - Nanotime to convert **Returns:** - `0` - Conversion successful - `-1` - Conversion failed #### `timespec_diff()` Calculates difference between two timespec structures. ```c int timespec_diff(struct timespec *a_start, struct timespec *a_stop, struct timespec *a_result); ``` **Parameters:** - `a_start` (struct timespec*) - Start time - `a_stop` (struct timespec*) - Stop time - `a_result` (struct timespec*) - Output: time difference **Returns:** - `0` - Calculation successful - `-1` - Calculation failed #### `dap_time_from_str_simplified()` Converts simplified time string to time value. ```c dap_time_t dap_time_from_str_simplified(const char *a_time_str); ``` **Parameters:** - `a_time_str` (const char*) - Simplified time string **Returns:** - `dap_time_t` - Converted time value #### `dap_time_from_str_custom()` Converts custom format time string to time value. ```c dap_time_t dap_time_from_str_custom(const char *a_time_str, const char *a_format_str); ``` **Parameters:** - `a_time_str` (const char*) - Time string to parse - `a_format_str` (const char*) - Custom format string **Returns:** - `dap_time_t` - Converted time value ### Error Handling Functions #### `dap_strerror_()` Converts error number to error string. ```c dap_error_str_t dap_strerror_(long long err); ``` **Parameters:** - `err` (long long) - Error number **Returns:** - `dap_error_str_t` - Error string representation #### `dap_str_ntstatus_()` Converts Windows NT status to error string. ```c dap_error_str_t dap_str_ntstatus_(DWORD err); ``` **Parameters:** - `err` (DWORD) - Windows NT status code **Returns:** - `dap_error_str_t` - Error string representation ### Utility Functions #### `dap_itoa_()` Converts integer to string representation. ```c dap_maxint_str_t dap_itoa_(long long i); ``` **Parameters:** - `i` (long long) - Integer to convert **Returns:** - `dap_maxint_str_t` - String representation #### `get_select_breaker()` Gets select breaker status. ```c int get_select_breaker(void); ``` **Parameters:** None **Returns:** - `int` - Select breaker status #### `send_select_break()` Sends select break signal. ```c int send_select_break(void); ``` **Parameters:** None **Returns:** - `0` - Signal sent successfully - `-1` - Signal failed #### `exec_with_ret()` Executes command with return value. ```c int exec_with_ret(char **argv, const char *cmd); ``` **Parameters:** - `argv` (char**) - Command arguments array - `cmd` (const char*) - Command to execute **Returns:** - `0` - Execution successful - `-1` - Execution failed #### `exec_silent()` Executes command silently without output. ```c int exec_silent(const char *a_cmd); ``` **Parameters:** - `a_cmd` (const char*) - Command to execute **Returns:** - `0` - Execution successful - `-1` - Execution failed ### Network Address Functions #### `dap_stream_node_addr_from_str()` Converts string address to node address structure. ```c static inline int dap_stream_node_addr_from_str(dap_stream_node_addr_t *a_addr, const char *a_addr_str); ``` **Parameters:** - `a_addr` (dap_stream_node_addr_t*) - Output node address structure - `a_addr_str` (const char*) - String representation of address **Returns:** - `0` - Conversion successful - `-1` - Conversion failed #### `dap_stream_node_addr_is_blank()` Checks if node address is blank/empty. ```c static inline bool dap_stream_node_addr_is_blank(dap_stream_node_addr_t *a_addr); ``` **Parameters:** - `a_addr` (dap_stream_node_addr_t*) - Node address to check **Returns:** - `true` - Address is blank - `false` - Address is not blank #### `dap_stream_node_addr_to_str_static_()` Converts node address to static string representation. ```c dap_node_addr_str_t dap_stream_node_addr_to_str_static_(dap_stream_node_addr_t a_address); ``` **Parameters:** - `a_address` (dap_stream_node_addr_t) - Node address to convert **Returns:** - `dap_node_addr_str_t` - Static string representation --- **See also:** [[Module DAP Crypto|Module DAP Crypto]], [[Module DAP IO|Module DAP IO]], [[ETC/Core Components|Core Components]] --- *Based on: `dap-sdk/core/include/dap_common.h`, `dap-sdk/core/src/dap_common.c`*