obgm / libcoap

A CoAP (RFC 7252) implementation in C
Other
790 stars 422 forks source link

Use Zephyr heap for Zephyr targets #1508

Closed pawszw2 closed 1 week ago

pawszw2 commented 2 weeks ago

Is your feature request related to a problem? Please describe.

Zephyr heap is efficient way to use memory on platforms using Zephyr OS and it isn't hard to introduce.

Describe the solution you would like

For Zephyr targets I'd like libcoap to use k_malloc, k_realloc and k_free instead of regular malloc, realloc and free. It would look like this:

--- a/src/coap_mem.c
+++ b/src/coap_mem.c
@@ -479,7 +479,65 @@ coap_realloc_type(coap_memory_tag_t type, void *p, size_t size) {
 }
 #else /* ! RIOT_VERSION && ! MODULE_MEMARRAY */

-#if defined(HAVE_MALLOC) || defined(__MINGW32__)
+#if defined(__ZEPHYR__)
+
+#include <zephyr/kernel.h>
+
+void
+coap_memory_init(void) {
+}
+
+void *
+coap_malloc_type(coap_memory_tag_t type, size_t size) {
+  void *ptr;
+
+  (void)type;
+  ptr = k_malloc(size);
+#if COAP_MEMORY_TYPE_TRACK
+  assert(type < COAP_MEM_TAG_LAST);
+  if (ptr) {
+    track_counts[type]++;
+    if (track_counts[type] > peak_counts[type])
+      peak_counts[type] = track_counts[type];
+  } else {
+    fail_counts[type]++;
+  }
+#endif /* COAP_MEMORY_TYPE_TRACK */
+  return ptr;
+}
+
+void *
+coap_realloc_type(coap_memory_tag_t type, void *p, size_t size) {
+  void *ptr;
+
+  (void)type;
+  ptr = k_realloc(p, size);
+#if COAP_MEMORY_TYPE_TRACK
+  if (ptr) {
+    assert(type < COAP_MEM_TAG_LAST);
+    if (!p)
+      track_counts[type]++;
+    if (track_counts[type] > peak_counts[type])
+      peak_counts[type] = track_counts[type];
+  } else {
+    fail_counts[type]++;
+  }
+#endif /* COAP_MEMORY_TYPE_TRACK */
+  return ptr;
+}
+
+void
+coap_free_type(coap_memory_tag_t type, void *p) {
+  (void)type;
+#if COAP_MEMORY_TYPE_TRACK
+  assert(type < COAP_MEM_TAG_LAST);
+  if (p)
+    track_counts[type]--;
+#endif /* COAP_MEMORY_TYPE_TRACK */
+  k_free(p);
+}
+
+#elif defined(HAVE_MALLOC) || defined(__MINGW32__)
 #include <stdlib.h>

 void
@@ -536,7 +594,7 @@ coap_free_type(coap_memory_tag_t type, void *p) {
   free(p);
 }

-#else /* ! HAVE_MALLOC  && !__MINGW32__ */
+#else /* ! HAVE_MALLOC  && !__MINGW32__ && !__ZEPHYR__*/

 #ifdef WITH_CONTIKI
 #include "lib/heapmem.h"

Describe alternatives you have considered

Another option is to make configurable, whether to use k_ functions or regular ones in terms of memory management.

mrdeep1 commented 2 weeks ago

This change looks perfectly reasonable to me as is. Can you please raise a PR for it?

mrdeep1 commented 1 week ago

Closed as now merged into the develop branch.