## Overview Comprehensive troubleshooting guide for resolving common issues when developing with the DAP SDK. This guide covers installation problems, runtime errors, performance issues, debugging techniques, and provides systematic approaches to problem diagnosis and resolution. **What This Guide Covers:** - **Installation Issues** - Problems during SDK setup and configuration - **Runtime Errors** - Common application errors and their solutions - **Performance Problems** - Identifying and resolving performance bottlenecks - **Memory Issues** - Memory leaks, corruption, and allocation problems - **Network Problems** - Connectivity and protocol issues - **Module Integration** - Issues with module integration and dependencies - **Debugging Techniques** - Tools and methods for problem diagnosis ## Installation and Setup Issues ### SDK Installation Problems #### Problem: Package Not Found ```bash Error: Package 'dap-sdk' not found ``` **Possible Causes & Solutions:** 1. **Repository not added:** ```bash # Ubuntu/Debian curl -fsSL https://packages.demlabs.net/dap-sdk/gpg | sudo apt-key add - echo "deb https://packages.demlabs.net/dap-sdk/ubuntu $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/dap-sdk.list sudo apt update ``` 2. **Outdated package cache:** ```bash sudo apt update sudo dnf makecache # For CentOS/RHEL/Fedora ``` 3. **Incorrect distribution:** ```bash # Check your distribution lsb_release -cs # Ensure it matches supported versions ``` #### Problem: Compilation Errors During Build ```bash error: 'dap_common.h' file not found ``` **Solutions:** 1. **Missing development headers:** ```bash # Install development packages sudo apt install dap-sdk-dev libssl-dev sudo dnf install dap-sdk-devel openssl-devel ``` 2. **Incorrect PKG_CONFIG_PATH:** ```bash export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig:$PKG_CONFIG_PATH" pkg-config --exists dap-sdk && echo "Found" || echo "Not found" ``` 3. **CMake configuration issues:** ```bash # Clear cache and reconfigure rm -rf build/ mkdir build && cd build cmake -DCMAKE_VERBOSE_MAKEFILE=ON .. ``` #### Problem: Runtime Library Not Found ```bash error while loading shared libraries: libdap-core.so.1: cannot open shared object file ``` **Solutions:** 1. **Update library cache:** ```bash sudo ldconfig # Or on macOS sudo update_dyld_shared_cache ``` 2. **Set LD_LIBRARY_PATH:** ```bash export LD_LIBRARY_PATH="/usr/local/lib:$LD_LIBRARY_PATH" # Add to ~/.bashrc for persistence echo 'export LD_LIBRARY_PATH="/usr/local/lib:$LD_LIBRARY_PATH"' >> ~/.bashrc ``` 3. **Verify installation:** ```bash ldd your_application # Check for missing libraries ``` ### Build Configuration Issues #### Problem: CMake Cannot Find DAP SDK ```cmake CMake Error: Could not find a package configuration file provided by "dap-sdk" ``` **Solution:** ```cmake # Use pkg-config instead find_package(PkgConfig REQUIRED) pkg_check_modules(DAP_SDK REQUIRED dap-sdk) # Include directories and libraries include_directories(${DAP_SDK_INCLUDE_DIRS}) target_link_libraries(your_target ${DAP_SDK_LIBRARIES}) ``` #### Problem: Linker Errors ```bash undefined reference to `dap_common_init' ``` **Solutions:** 1. **Check linking order:** ```cmake # Correct order - dependent libraries first target_link_libraries(your_app dap-client dap-core dap-crypto) ``` 2. **Verify library installation:** ```bash pkg-config --libs dap-sdk nm -D /usr/local/lib/libdap-core.so | grep dap_common_init ``` ## Runtime Errors ### Initialization Failures #### Problem: DAP SDK Initialization Fails ```c if (dap_common_init("MyApp", NULL) != 0) { // This fails } ``` **Diagnostic Steps:** 1. **Check log output:** ```c // Enable debug logging dap_config_set_string("core", "log_level", "debug"); dap_common_init("MyApp", NULL); ``` 2. **Verify configuration:** ```c // Check configuration file if (access("dap.conf", R_OK) != 0) { log_it_warning("Configuration file not accessible"); } ``` 3. **Memory allocation check:** ```c // Check available memory dap_memory_stats_t stats; if (dap_memory_get_stats(&stats) == 0) { log_it_info("Available memory: %zu bytes", stats.bytes_available); } ``` **Common Solutions:** 1. **Insufficient permissions:** ```bash # Check file permissions ls -la dap.conf chmod 644 dap.conf ``` 2. **Memory constraints:** ```c // Reduce initial memory pool size dap_memory_pool_config_t config = { .initial_size = 1024 * 1024, // 1MB instead of default .max_size = 16 * 1024 * 1024 // 16MB max }; dap_memory_pool_init(&config); ``` #### Problem: Module Loading Failures ```bash Failed to load module: crypto ``` **Diagnostic Approach:** ```c // Check module dependencies const char *required_modules[] = {"core", "crypto", "io", NULL}; for (int i = 0; required_modules[i]; i++) { if (!dap_module_is_loaded(required_modules[i])) { log_it_error("Required module not loaded: %s", required_modules[i]); // Try to load explicitly if (dap_module_load(required_modules[i]) != 0) { log_it_error("Failed to load module: %s", required_modules[i]); // Check detailed error const char *error_msg = dap_module_get_last_error(); log_it_error("Module error: %s", error_msg); } } } ``` ### Memory Issues #### Problem: Memory Leaks **Detection:** ```bash # Using Valgrind valgrind --leak-check=full --show-leak-kinds=all ./your_app # Using AddressSanitizer gcc -fsanitize=address -g -o your_app_debug your_app.c $(pkg-config --cflags --libs dap-sdk) ./your_app_debug ``` **Built-in Detection:** ```c // Enable memory tracking dap_memory_enable_tracking(true); // Check for leaks before shutdown dap_memory_stats_t stats; dap_memory_get_stats(&stats); if (stats.bytes_allocated > 0) { log_it_warning("Memory leak detected: %zu bytes still allocated", stats.bytes_allocated); // Get detailed leak report dap_memory_dump_leaks(); } ``` **Common Fixes:** ```c // Always pair allocations with deallocations char *buffer = DAP_NEW_SIZE(char, 1024); if (buffer) { // Use buffer... DAP_DELETE(buffer); // Don't forget this! } // Use scope-based cleanup void function_with_cleanup(void) { char *temp = dap_strdup("temporary"); // Multiple exit points - use goto for cleanup if (some_condition) { goto cleanup; } if (another_condition) { goto cleanup; } // Normal processing... cleanup: DAP_DELETE(temp); } ``` #### Problem: Memory Corruption **Symptoms:** - Random crashes - Data corruption - Assertion failures **Detection:** ```c // Enable debug mode with canary values #ifdef DAP_DEBUG dap_memory_enable_canaries(true); dap_memory_enable_corruption_check(true); #endif // Check memory integrity periodically void periodic_memory_check(void) { if (dap_memory_check_integrity() != 0) { log_it_critical("Memory corruption detected!"); dap_memory_dump_corruption_info(); abort(); // Fail fast } } ``` **Prevention:** ```c // Always check bounds void safe_string_copy(char *dest, size_t dest_size, const char *src) { if (!dest || !src || dest_size == 0) { return; } size_t src_len = strlen(src); size_t copy_len = (src_len < dest_size - 1) ? src_len : dest_size - 1; memcpy(dest, src, copy_len); dest[copy_len] = '\0'; } // Use safe string functions int safe_concat(char *dest, size_t dest_size, const char *src) { size_t dest_len = strlen(dest); size_t remaining = dest_size - dest_len - 1; if (remaining > 0) { safe_string_copy(dest + dest_len, remaining + 1, src); return 0; } return -1; // Buffer too small } ``` ### Network Issues #### Problem: Connection Failures ```bash Failed to connect to server: Connection refused ``` **Diagnostic Steps:** 1. **Check network connectivity:** ```bash ping target_host telnet target_host target_port netstat -an | grep target_port ``` 2. **Verify DAP network configuration:** ```c // Enable network debug logging dap_config_set_string("network", "log_level", "debug"); // Check network interface status dap_net_interface_info_t *interfaces; int count = dap_net_get_interfaces(&interfaces); for (int i = 0; i < count; i++) { log_it_info("Interface %s: %s", interfaces[i].name, interfaces[i].is_up ? "UP" : "DOWN"); } ``` 3. **Test with minimal connection:** ```c // Simple connection test dap_socket_t *sock = dap_socket_create(DAP_SOCKET_TYPE_TCP); if (!sock) { log_it_error("Failed to create socket"); return -1; } dap_addr_t addr; if (dap_addr_from_string("127.0.0.1:8080", &addr) != 0) { log_it_error("Invalid address format"); dap_socket_close(sock); return -1; } if (dap_socket_connect(sock, &addr, 5000) != 0) { log_it_error("Connection failed: %s", dap_socket_get_error(sock)); dap_socket_close(sock); return -1; } log_it_info("Connection successful"); dap_socket_close(sock); ``` #### Problem: Slow Network Performance **Diagnostic Tools:** ```c // Measure network latency dap_time_t start_time, end_time; dap_time_now(&start_time); int result = dap_net_ping("target_host", 1000); // 1 second timeout dap_time_now(&end_time); dap_interval_t latency; dap_time_diff(&start_time, &end_time, &latency); log_it_info("Ping result: %d, latency: %lu.%06u ms", result, latency.seconds * 1000 + latency.nanoseconds / 1000000, latency.nanoseconds % 1000000); // Check network statistics dap_net_stats_t stats; if (dap_net_get_stats(&stats) == 0) { log_it_info("Bytes sent: %lu, received: %lu", stats.bytes_sent, stats.bytes_received); log_it_info("Packets sent: %lu, received: %lu", stats.packets_sent, stats.packets_received); log_it_info("Errors: %lu, drops: %lu", stats.errors, stats.drops); } ``` **Optimization Techniques:** ```c // Configure socket buffer sizes dap_socket_set_buffer_size(socket, DAP_SOCKET_BUFFER_SEND, 64 * 1024); dap_socket_set_buffer_size(socket, DAP_SOCKET_BUFFER_RECV, 64 * 1024); // Enable TCP_NODELAY for low latency dap_socket_set_option(socket, DAP_SOCKET_OPT_NO_DELAY, true); // Use connection pooling dap_connection_pool_t *pool = dap_connection_pool_create(10); // 10 connections dap_connection_t *conn = dap_connection_pool_acquire(pool, "target_host:8080"); ``` ### Cryptographic Issues #### Problem: Hash Verification Failures ```c // Hash mismatch errors if (memcmp(&computed_hash, &expected_hash, DAP_HASH_FAST_SIZE) != 0) { log_it_error("Hash verification failed"); } ``` **Debugging:** ```c // Enable crypto debug logging dap_config_set_string("crypto", "log_level", "debug"); // Verify input data log_it_debug("Input data size: %zu", data_size); DUMP_BUFFER(data, data_size); // Compute hash step by step dap_hash_fast_t hash; int result = dap_hash_fast(data, data_size, &hash); if (result != 0) { log_it_error("Hash computation failed: %d", result); } else { char hex_hash[DAP_HASH_FAST_SIZE * 2 + 1]; dap_bin2hex(hex_hash, hash.raw, DAP_HASH_FAST_SIZE); log_it_debug("Computed hash: %s", hex_hash); char expected_hex[DAP_HASH_FAST_SIZE * 2 + 1]; dap_bin2hex(expected_hex, expected_hash.raw, DAP_HASH_FAST_SIZE); log_it_debug("Expected hash: %s", expected_hex); } ``` #### Problem: Key Generation Failures ```c dap_enc_key_t *key = dap_enc_key_new_generate(key_type, NULL, 0, NULL, 0, 0); if (!key) { log_it_error("Key generation failed"); } ``` **Troubleshooting:** ```c // Check entropy source if (!dap_random_is_available()) { log_it_error("Random number generator not available"); // Initialize entropy source if (dap_random_init() != 0) { log_it_error("Failed to initialize RNG"); return -1; } } // Test random generation uint8_t test_bytes[32]; if (dap_random_bytes(test_bytes, sizeof(test_bytes)) != 0) { log_it_error("Random byte generation failed"); } else { log_it_debug("Random generation working"); DUMP_BUFFER(test_bytes, sizeof(test_bytes)); } // Check key type support if (!dap_enc_key_type_is_supported(key_type)) { log_it_error("Key type %d not supported", key_type); // List supported types const int *supported_types = dap_enc_key_get_supported_types(); log_it_info("Supported key types:"); for (int i = 0; supported_types[i] != -1; i++) { log_it_info(" Type %d: %s", supported_types[i], dap_enc_key_type_to_string(supported_types[i])); } } ``` ## Performance Issues ### High CPU Usage **Diagnosis:** ```bash # Profile with perf perf record -g ./your_app perf report # Profile with gprof gcc -pg -o your_app_profile your_app.c $(pkg-config --cflags --libs dap-sdk) ./your_app_profile gprof your_app_profile gmon.out > profile.txt ``` **Common Causes & Solutions:** 1. **Inefficient loops:** ```c // Bad: O(n²) complexity for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (expensive_comparison(data[i], data[j])) { // Process... } } } // Good: Use hash table for O(1) lookups dap_hash_table_t *lookup = dap_hash_table_new(1024, hash_func, compare_func); for (int i = 0; i < n; i++) { dap_hash_table_insert(lookup, &data[i], &data[i]); } for (int i = 0; i < n; i++) { if (dap_hash_table_lookup(lookup, &data[i])) { // Process... } } ``` 2. **Excessive memory allocations:** ```c // Bad: Allocate in loop for (int i = 0; i < 1000000; i++) { char *temp = DAP_NEW_SIZE(char, 1024); // Use temp... DAP_DELETE(temp); } // Good: Reuse buffer char *buffer = DAP_NEW_SIZE(char, 1024); for (int i = 0; i < 1000000; i++) { memset(buffer, 0, 1024); // Use buffer... } DAP_DELETE(buffer); // Better: Use memory pool dap_memory_pool_t *pool = dap_memory_pool_create(1024, 100); for (int i = 0; i < 1000000; i++) { char *temp = dap_memory_pool_acquire(pool); // Use temp... dap_memory_pool_release(pool, temp); } dap_memory_pool_destroy(pool); ``` ### High Memory Usage **Analysis:** ```c // Monitor memory usage void monitor_memory_usage(void) { static dap_time_t last_check = {0}; dap_time_t now; dap_time_now(&now); // Check every 10 seconds if (now.sec - last_check.sec >= 10) { dap_memory_stats_t stats; dap_memory_get_stats(&stats); log_it_info("Memory usage: %zu bytes (peak: %zu)", stats.bytes_allocated, stats.peak_allocated); log_it_info("Allocations: %zu, frees: %zu", stats.allocation_count, stats.free_count); log_it_info("Fragmentation: %.2f%%", stats.fragmentation_ratio * 100); last_check = now; } } ``` **Memory Optimization:** ```c // Use appropriate data structures typedef struct efficient_cache { dap_hash_table_t *index; // Fast lookups dap_list_t *lru_list; // LRU eviction size_t max_entries; size_t current_entries; } efficient_cache_t; // Implement cache with automatic cleanup int cache_insert(efficient_cache_t *cache, const char *key, void *value) { // Check if cache is full if (cache->current_entries >= cache->max_entries) { // Remove LRU entry dap_list_node_t *lru_node = dap_list_tail(cache->lru_list); if (lru_node) { cache_entry_t *entry = (cache_entry_t*)lru_node->data; dap_hash_table_remove(cache->index, entry->key); dap_list_remove(cache->lru_list, lru_node); cache_entry_destroy(entry); cache->current_entries--; } } // Insert new entry cache_entry_t *entry = cache_entry_create(key, value); dap_hash_table_insert(cache->index, key, entry); dap_list_prepend(cache->lru_list, entry); cache->current_entries++; return 0; } ``` ## Debugging Techniques ### Enabling Debug Output ```c // Compile-time debugging #ifdef DAP_DEBUG #define DBG_PRINT(fmt, ...) \ log_it_debug("[%s:%d] " fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__) #else #define DBG_PRINT(fmt, ...) #endif // Runtime debug level control void set_debug_level(int level) { switch (level) { case 0: // Minimal dap_config_set_string("core", "log_level", "error"); break; case 1: // Normal dap_config_set_string("core", "log_level", "info"); break; case 2: // Verbose dap_config_set_string("core", "log_level", "debug"); dap_config_set_bool("core", "enable_function_names", true); break; case 3: // Maximum dap_config_set_string("core", "log_level", "debug"); dap_config_set_bool("core", "enable_function_names", true); dap_config_set_bool("core", "enable_memory_tracking", true); dap_config_set_bool("core", "enable_trace", true); break; } } ``` ### Core Dumps and Crash Analysis ```bash # Enable core dumps ulimit -c unlimited echo "core.%e.%p" | sudo tee /proc/sys/kernel/core_pattern # Generate debug build cmake -DCMAKE_BUILD_TYPE=Debug -DDAP_ENABLE_DEBUG=ON .. make # Analyze crash gdb your_app core.your_app.12345 (gdb) bt full (gdb) info registers (gdb) examine memory around crash ``` ### Live Debugging ```bash # Attach to running process gdb -p $(pidof your_app) (gdb) bt (gdb) info threads (gdb) thread apply all bt # Set breakpoints (gdb) break dap_common_init (gdb) break main (gdb) condition 1 strcmp(app_name, "TestApp") == 0 ``` ## Advanced Diagnostics ### Performance Profiling ```c // Built-in profiling typedef struct profiler_data { const char *function_name; dap_time_t start_time; dap_time_t total_time; uint64_t call_count; } profiler_data_t; #ifdef DAP_PROFILING #define PROFILE_FUNCTION() \ static profiler_data_t prof_data = {__FUNCTION__, {0}, {0}, 0}; \ dap_time_t prof_start; \ dap_time_now(&prof_start); \ prof_data.call_count++; \ /* Function body here */ \ dap_time_t prof_end; \ dap_time_now(&prof_end); \ dap_interval_t prof_elapsed; \ dap_time_diff(&prof_start, &prof_end, &prof_elapsed); \ prof_data.total_time.sec += prof_elapsed.seconds; \ prof_data.total_time.nsec += prof_elapsed.nanoseconds; #else #define PROFILE_FUNCTION() #endif // Usage int expensive_function(void) { PROFILE_FUNCTION(); // Function implementation... return 0; } ``` ### Health Monitoring ```c // System health check typedef struct health_status { bool core_initialized; bool memory_healthy; bool network_available; double cpu_usage; size_t memory_usage; int active_connections; } health_status_t; health_status_t get_system_health(void) { health_status_t status = {0}; // Check core initialization status.core_initialized = dap_common_is_initialized(); // Check memory health dap_memory_stats_t mem_stats; if (dap_memory_get_stats(&mem_stats) == 0) { status.memory_healthy = mem_stats.fragmentation_ratio < 0.5; status.memory_usage = mem_stats.bytes_allocated; } // Check network availability status.network_available = dap_net_is_available(); // Check CPU usage (implementation specific) status.cpu_usage = get_cpu_usage(); // Check active connections status.active_connections = dap_net_get_connection_count(); return status; } void health_check_report(void) { health_status_t health = get_system_health(); log_it_info("=== System Health Report ==="); log_it_info("Core initialized: %s", health.core_initialized ? "YES" : "NO"); log_it_info("Memory healthy: %s", health.memory_healthy ? "YES" : "NO"); log_it_info("Network available: %s", health.network_available ? "YES" : "NO"); log_it_info("CPU usage: %.2f%%", health.cpu_usage); log_it_info("Memory usage: %zu bytes", health.memory_usage); log_it_info("Active connections: %d", health.active_connections); // Alert on issues if (!health.core_initialized) { log_it_critical("Core not initialized!"); } if (!health.memory_healthy) { log_it_warning("Memory fragmentation high!"); } if (health.cpu_usage > 80.0) { log_it_warning("High CPU usage detected!"); } } ``` ## Getting Help ### Documentation Resources - **[[Installation Guide|Installation Guide]]** - Complete setup instructions - **[[First Application|First Application]]** - Step-by-step tutorial - **[[Development Guide|Development Guide]]** - Best practices and patterns - **[[Architecture Overview|Architecture Overview]]** - System design and architecture - **[[Modules/Module Overview|Module Overview]]** - Detailed module documentation - **[[Glossary|Glossary]]** - Complete API reference ### Community Support - **Repository**: https://gitlab.demlabs.net/dap/dap-sdk/issues - **Forums**: https://forum.demlabs.net - **Documentation**: Complete DAP SDK documentation wiki - **Email Support**: [email protected] (for commercial users) ### Reporting Issues When reporting issues, include: 1. **Environment Information:** ```bash # System information uname -a cat /etc/os-release gcc --version cmake --version # DAP SDK information dap-sdk-config --version pkg-config --modversion dap-sdk ``` 2. **Minimal Reproduction Case:** ```c // Minimal code that reproduces the issue #include <dap/dap_common.h> int main() { if (dap_common_init("TestApp", NULL) != 0) { fprintf(stderr, "Initialization failed\n"); return 1; } // Code that triggers the issue... dap_common_deinit(); return 0; } ``` 3. **Error Messages and Logs:** - Complete error messages - Debug log output - Stack traces (if available) - Core dump analysis (if applicable) 4. **Expected vs. Actual Behavior:** - What you expected to happen - What actually happened - Steps to reproduce --- *Last updated: December 2024 | Version: 1.0 | Troubleshooting Guide for DAP SDK*