xref: /btstack/tool/btstack_memory_generator.py (revision c9207d20824cfe9695c51a231d0680f0f58d08ad)
1#!/usr/bin/env python3
2import os
3import sys
4
5import os
6import sys
7
8copyright = """/*
9 * Copyright (C) 2014 BlueKitchen GmbH
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 *
15 * 1. Redistributions of source code must retain the above copyright
16 *    notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 *    notice, this list of conditions and the following disclaimer in the
19 *    documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the copyright holders nor the names of
21 *    contributors may be used to endorse or promote products derived
22 *    from this software without specific prior written permission.
23 * 4. Any redistribution, use, or modification is done solely for
24 *    personal benefit and not for any commercial purpose or for
25 *    monetary gain.
26 *
27 * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
28 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
30 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
31 * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
33 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
34 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
35 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
36 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
37 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * SUCH DAMAGE.
39 *
40 * Please inquire about commercial licensing options at
41 * [email protected]
42 *
43 */
44"""
45
46hfile_header_begin = """
47
48/*
49 * btstack_memory.h
50 *
51 * @brief BTstack memory management using configurable memory pools
52 *
53 */
54
55#ifndef BTSTACK_MEMORY_H
56#define BTSTACK_MEMORY_H
57
58#if defined __cplusplus
59extern "C" {
60#endif
61
62#include "btstack_config.h"
63
64// Core
65#include "hci.h"
66#include "l2cap.h"
67
68// Classic
69#ifdef ENABLE_CLASSIC
70#include "classic/avdtp_sink.h"
71#include "classic/avdtp_source.h"
72#include "classic/avrcp.h"
73#include "classic/bnep.h"
74#include "classic/btstack_link_key_db.h"
75#include "classic/btstack_link_key_db_memory.h"
76#include "classic/goep_server.h"
77#include "classic/hfp.h"
78#include "classic/hid_host.h"
79#include "classic/rfcomm.h"
80#include "classic/sdp_server.h"
81#endif
82
83// BLE
84#ifdef ENABLE_BLE
85#include "ble/gatt-service/battery_service_client.h"
86#include "ble/gatt-service/hids_client.h"
87#include "ble/gatt-service/scan_parameters_service_client.h"
88#include "ble/gatt_client.h"
89#include "ble/sm.h"
90#endif
91
92#ifdef ENABLE_MESH
93#include "mesh/mesh_network.h"
94#include "mesh/mesh_keys.h"
95#include "mesh/mesh_virtual_addresses.h"
96#endif
97
98/* API_START */
99
100/**
101 * @brief Initializes BTstack memory pools.
102 */
103void btstack_memory_init(void);
104
105/**
106 * @brief Deinitialize BTstack memory pools
107 * @note if HAVE_MALLOC is defined, all previously allocated buffers are free'd
108 */
109void btstack_memory_deinit(void);
110
111/* API_END */
112"""
113
114hfile_header_end = """
115#if defined __cplusplus
116}
117#endif
118
119#endif // BTSTACK_MEMORY_H
120"""
121
122cfile_header_begin = """
123#define BTSTACK_FILE__ "btstack_memory.c"
124
125
126/*
127 *  btstack_memory.c
128 *
129 *  @brief BTstack memory management via configurable memory pools
130 *
131 *  @note code generated by tool/btstack_memory_generator.py
132 *  @note returnes buffers are initialized with 0
133 *
134 */
135
136#include "btstack_memory.h"
137#include "btstack_memory_pool.h"
138#include "btstack_debug.h"
139
140#include <stdlib.h>
141
142#ifdef ENABLE_MALLOC_TEST
143void * test_malloc(size_t size);
144#define malloc test_malloc
145#endif
146
147#ifdef HAVE_MALLOC
148typedef struct btstack_memory_buffer {
149    struct btstack_memory_buffer * next;
150    struct btstack_memory_buffer * prev;
151} btstack_memory_buffer_t;
152
153typedef struct {
154    btstack_memory_buffer_t tracking;
155    void * pointer;
156} test_buffer_t;
157
158static btstack_memory_buffer_t * btstack_memory_malloc_buffers;
159static uint32_t btstack_memory_malloc_counter;
160
161static void btstack_memory_tracking_add(btstack_memory_buffer_t * buffer){
162    btstack_assert(buffer != NULL);
163    if (btstack_memory_malloc_buffers != NULL) {
164        // let current first item prev point to new first item
165        btstack_memory_malloc_buffers->prev = buffer;
166    }
167    buffer->prev = NULL;
168    buffer->next = btstack_memory_malloc_buffers;
169    btstack_memory_malloc_buffers = buffer;
170
171    btstack_memory_malloc_counter++;
172}
173
174static void btstack_memory_tracking_remove(btstack_memory_buffer_t * buffer){
175    btstack_assert(buffer != NULL);
176    if (buffer->prev == NULL){
177        // first item
178        btstack_memory_malloc_buffers = buffer->next;
179    } else {
180        buffer->prev->next = buffer->next;
181    }
182    if (buffer->next != NULL){
183        buffer->next->prev = buffer->prev;
184    }
185
186    btstack_memory_malloc_counter--;
187}
188#endif
189
190void btstack_memory_deinit(void){
191#ifdef HAVE_MALLOC
192    while (btstack_memory_malloc_buffers != NULL){
193        btstack_memory_buffer_t * buffer = btstack_memory_malloc_buffers;
194        btstack_memory_malloc_buffers = buffer->next;
195        free(buffer);
196        btstack_memory_malloc_counter--;
197    }
198    btstack_assert(btstack_memory_malloc_counter == 0);
199#endif
200}
201"""
202
203header_template = """STRUCT_NAME_t * btstack_memory_STRUCT_NAME_get(void);
204void   btstack_memory_STRUCT_NAME_free(STRUCT_NAME_t *STRUCT_NAME);"""
205
206code_template = """
207// MARK: STRUCT_TYPE
208#if !defined(HAVE_MALLOC) && !defined(POOL_COUNT)
209    #if defined(POOL_COUNT_OLD_NO)
210        #error "Deprecated POOL_COUNT_OLD_NO defined instead of POOL_COUNT. Please update your btstack_config.h to use POOL_COUNT."
211    #else
212        #define POOL_COUNT 0
213    #endif
214#endif
215
216#ifdef POOL_COUNT
217#if POOL_COUNT > 0
218static STRUCT_TYPE STRUCT_NAME_storage[POOL_COUNT];
219static btstack_memory_pool_t STRUCT_NAME_pool;
220STRUCT_NAME_t * btstack_memory_STRUCT_NAME_get(void){
221    void * buffer = btstack_memory_pool_get(&STRUCT_NAME_pool);
222    if (buffer){
223        memset(buffer, 0, sizeof(STRUCT_TYPE));
224    }
225    return (STRUCT_NAME_t *) buffer;
226}
227void btstack_memory_STRUCT_NAME_free(STRUCT_NAME_t *STRUCT_NAME){
228    btstack_memory_pool_free(&STRUCT_NAME_pool, STRUCT_NAME);
229}
230#else
231STRUCT_NAME_t * btstack_memory_STRUCT_NAME_get(void){
232    return NULL;
233}
234void btstack_memory_STRUCT_NAME_free(STRUCT_NAME_t *STRUCT_NAME){
235    UNUSED(STRUCT_NAME);
236}
237#endif
238#elif defined(HAVE_MALLOC)
239
240typedef struct {
241    btstack_memory_buffer_t tracking;
242    STRUCT_NAME_t data;
243} btstack_memory_STRUCT_NAME_t;
244
245STRUCT_NAME_t * btstack_memory_STRUCT_NAME_get(void){
246    btstack_memory_STRUCT_NAME_t * buffer = (btstack_memory_STRUCT_NAME_t *) malloc(sizeof(btstack_memory_STRUCT_NAME_t));
247    if (buffer){
248        memset(buffer, 0, sizeof(btstack_memory_STRUCT_NAME_t));
249        btstack_memory_tracking_add(&buffer->tracking);
250        return &buffer->data;
251    } else {
252        return NULL;
253    }
254}
255void btstack_memory_STRUCT_NAME_free(STRUCT_NAME_t *STRUCT_NAME){
256    // reconstruct buffer start
257    btstack_memory_buffer_t * buffer = &((btstack_memory_buffer_t *) STRUCT_NAME)[-1];
258    btstack_memory_tracking_remove(buffer);
259    free(buffer);
260}
261#endif
262"""
263init_header = '''
264// init
265void btstack_memory_init(void){
266#ifdef HAVE_MALLOC
267    // assert that there is no unexpected padding for combined buffer
268    btstack_assert(sizeof(test_buffer_t) == sizeof(btstack_memory_buffer_t) + sizeof(void *));
269#endif
270
271'''
272
273init_template = """#if POOL_COUNT > 0
274    btstack_memory_pool_create(&STRUCT_NAME_pool, STRUCT_NAME_storage, POOL_COUNT, sizeof(STRUCT_TYPE));
275#endif"""
276
277list_of_structs = [
278    ["hci_connection"],
279    ["l2cap_service", "l2cap_channel"],
280]
281list_of_classic_structs = [
282    ["rfcomm_multiplexer", "rfcomm_service", "rfcomm_channel"],
283    ["btstack_link_key_db_memory_entry"],
284    ["bnep_service", "bnep_channel"],
285    ["goep_server_service", "goep_server_connection"],
286    ["hfp_connection"],
287    ["hid_host_connection"],
288    ["service_record_item"],
289    ["avdtp_stream_endpoint"],
290    ["avdtp_connection"],
291    ["avrcp_connection"],
292    ["avrcp_browsing_connection"],
293]
294list_of_le_structs = [
295    ["battery_service_client", "gatt_client", "hids_client", "scan_parameters_service_client", "sm_lookup_entry", "whitelist_entry", "periodic_advertiser_list_entry"],
296]
297list_of_mesh_structs = [
298    ['mesh_network_pdu', 'mesh_segmented_pdu', 'mesh_upper_transport_pdu', 'mesh_network_key', 'mesh_transport_key', 'mesh_virtual_address', 'mesh_subnet']
299]
300list_of_iso_structs = [
301    ['hci_iso_stream']
302]
303
304def writeln(f, data):
305    f.write(data + "\n")
306
307def replacePlaceholder(template, struct_name):
308    struct_type = struct_name + '_t'
309    if struct_name.endswith('try'):
310        pool_count = "MAX_NR_" + struct_name.upper()[:-3] + "TRIES"
311    else:
312        pool_count = "MAX_NR_" + struct_name.upper() + "S"
313    pool_count_old_no = pool_count.replace("MAX_NR_", "MAX_NO_")
314    snippet = template.replace("STRUCT_TYPE", struct_type).replace("STRUCT_NAME", struct_name).replace("POOL_COUNT_OLD_NO", pool_count_old_no).replace("POOL_COUNT", pool_count)
315    return snippet
316
317def add_struct(f, guard, template, structs):
318    if not guard == "":
319        writeln(f, "#ifdef " + guard)
320    for struct_names in structs:
321        # writeln(f, "// "+ ", ".join(struct_names))
322        for struct_name in struct_names:
323            writeln(f, replacePlaceholder(template, struct_name))
324        writeln(f, "")
325    if not guard == "":
326        writeln(f, "#endif")
327
328def add_structs(f, template):
329    add_struct(f, "",                               template, list_of_structs)
330    add_struct(f, "ENABLE_CLASSIC",                 template, list_of_classic_structs)
331    add_struct(f, "ENABLE_BLE",                     template, list_of_le_structs)
332    add_struct(f, "ENABLE_MESH",                    template, list_of_mesh_structs)
333    add_struct(f, "ENABLE_LE_ISOCHRONOUS_STREAMS",  template, list_of_iso_structs)
334
335btstack_root = os.path.abspath(os.path.dirname(sys.argv[0]) + '/..')
336file_name = btstack_root + "/src/btstack_memory"
337print ('Generating %s.[h|c]' % file_name)
338
339f = open(file_name+".h", "w")
340writeln(f, copyright)
341writeln(f, hfile_header_begin)
342add_structs(f, header_template)
343writeln(f, hfile_header_end)
344f.close();
345
346
347f = open(file_name+".c", "w")
348writeln(f, copyright)
349writeln(f, cfile_header_begin)
350add_structs(f, code_template)
351
352f.write(init_header)
353add_structs(f, init_template)
354writeln(f, "}")
355f.close();
356
357# also generate test code
358test_header = """
359#include <stdint.h>
360#include <stdio.h>
361#include <stdlib.h>
362#include <string.h>
363
364// malloc hook
365static int simulate_no_memory;
366extern "C" void * test_malloc(size_t size);
367void * test_malloc(size_t size){
368    if (simulate_no_memory) return NULL;
369    return malloc(size);
370}
371
372#include "btstack_config.h"
373
374#include "CppUTest/TestHarness.h"
375#include "CppUTest/CommandLineTestRunner.h"
376
377#include "bluetooth_data_types.h"
378#include "btstack_util.h"
379#include "btstack_memory.h"
380
381
382TEST_GROUP(btstack_memory){
383    void setup(void){
384        btstack_memory_init();
385        simulate_no_memory = 0;
386    }
387};
388
389#ifdef HAVE_MALLOC
390TEST(btstack_memory, deinit){
391    // alloc buffers 1,2,3
392    hci_connection_t * buffer_1 = btstack_memory_hci_connection_get();
393    hci_connection_t * buffer_2 = btstack_memory_hci_connection_get();
394    hci_connection_t * buffer_3 = btstack_memory_hci_connection_get();
395    // free first one in list
396    btstack_memory_hci_connection_free(buffer_3);
397    // free second one in list
398    btstack_memory_hci_connection_free(buffer_1);
399    // leave buffer in list
400    (void) buffer_2;
401    btstack_memory_deinit();
402}
403#endif
404
405"""
406
407test_template = """
408
409TEST(btstack_memory, STRUCT_NAME_GetAndFree){
410    STRUCT_NAME_t * context;
411#ifdef HAVE_MALLOC
412    context = btstack_memory_STRUCT_NAME_get();
413    CHECK(context != NULL);
414    btstack_memory_STRUCT_NAME_free(context);
415#else
416#ifdef POOL_COUNT
417    // single
418    context = btstack_memory_STRUCT_NAME_get();
419    CHECK(context != NULL);
420    btstack_memory_STRUCT_NAME_free(context);
421#else
422    // none
423    context = btstack_memory_STRUCT_NAME_get();
424    CHECK(context == NULL);
425    btstack_memory_STRUCT_NAME_free(context);
426#endif
427#endif
428}
429
430TEST(btstack_memory, STRUCT_NAME_NotEnoughBuffers){
431    STRUCT_NAME_t * context;
432#ifdef HAVE_MALLOC
433    simulate_no_memory = 1;
434#else
435#ifdef POOL_COUNT
436    int i;
437    // alloc all static buffers
438    for (i = 0; i < POOL_COUNT; i++){
439        context = btstack_memory_STRUCT_NAME_get();
440        CHECK(context != NULL);
441    }
442#endif
443#endif
444    // get one more
445    context = btstack_memory_STRUCT_NAME_get();
446    CHECK(context == NULL);
447}
448"""
449
450test_footer = """
451int main (int argc, const char * argv[]){
452    return CommandLineTestRunner::RunAllTests(argc, argv);
453}
454"""
455
456file_name = btstack_root + "/test/btstack_memory/btstack_memory_test.cpp"
457print ('Generating %s' % file_name)
458
459f = open(file_name, "w")
460writeln(f, copyright)
461writeln(f, test_header)
462add_structs(f, test_template)
463writeln(f, test_footer)
464