Embedded Artistry libmemory
Memory library for embedded systems (malloc and friends)
malloc_threadx.c
Go to the documentation of this file.
1 /*
2  * Copyright © 2017 Embedded Artistry LLC.
3  * License: MIT. See LICENSE file for details.
4  */
5 
6 #include <assert.h>
7 #include <malloc.h>
8 #include <stdbool.h>
9 #include <stdint.h>
10 #include <threadx/tx_api.h>
11 
12 #pragma mark - Declarations -
13 
15 static TX_BYTE_POOL malloc_pool_;
16 
21 static volatile bool initialized_ = false;
22 
23 #pragma mark - APIs -
24 
25 __attribute__((weak)) void malloc_init(void)
26 {
27  // Unused here, override to specify your own init functin
28  // Which includes malloc_addblock calls
29 }
30 
36 void malloc_addblock(void* addr, size_t size)
37 {
38  assert(addr && (size > 0));
39 
40  unsigned r;
41 
42  /*
43  * tx_byte_pool_create is ThreadX's API to create a byte pool using a memory block.
44  * We are essentially just wrapping ThreadX APIs into a simpler form
45  */
46  r = tx_byte_pool_create(&malloc_pool_, "Heap Memory Pool", addr, size);
47  assert(r == TX_SUCCESS);
48 
49  // Signal to any threads waiting on do_malloc that we are done
50  initialized_ = true;
51 }
52 
53 void* malloc(size_t size)
54 {
55  void* ptr = NULL;
56 
62  while(!initialized_)
63  {
64  tx_thread_sleep(1);
65  }
66 
67  if(size > 0)
68  {
69  // We simply wrap the threadX call into a standard form
70  unsigned r = tx_byte_allocate(&malloc_pool_, &ptr, size, TX_WAIT_FOREVER);
71 
72  // I add the string to provide a more helpful error output. It's value is always true.
73  assert(r == TX_SUCCESS && "malloc failed");
74  } // else NULL if there was an error
75 
76  return ptr;
77 }
78 
79 void free(void* ptr)
80 {
82  assert(initialized_);
83 
84  if(ptr)
85  {
86  // We simply wrap the threadX call into a standard form
87  unsigned r = tx_byte_release(ptr);
88  assert(r == TX_SUCCESS);
89  }
90 }
__attribute__((weak))
static volatile bool initialized_
static TX_BYTE_POOL malloc_pool_
ThreadX internal memory pool stucture.
void * malloc(size_t size)
void free(void *ptr)
void malloc_init(void)
Initialize Malloc.
void malloc_addblock(void *addr, size_t size)
Assign blocks of memory for use by malloc().