xref: /btstack/tool/btstack_memory_generator.py (revision b149c1b9276b0e9d738e8038776af3dded42725e)
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 MATTHIAS
31 * RINGWALD 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 via 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/hfp.h"
77#include "classic/hid_host.h"
78#include "classic/rfcomm.h"
79#include "classic/sdp_server.h"
80#endif
81
82// BLE
83#ifdef ENABLE_BLE
84#include "ble/gatt-service/battery_service_client.h"
85#include "ble/gatt-service/hids_client.h"
86#include "ble/gatt-service/scan_parameters_service_client.h"
87#include "ble/gatt_client.h"
88#include "ble/sm.h"
89#endif
90
91#ifdef ENABLE_MESH
92#include "mesh/mesh_network.h"
93#include "mesh/mesh_keys.h"
94#include "mesh/mesh_virtual_addresses.h"
95#endif
96
97/* API_START */
98
99/**
100 * @brief Initializes BTstack memory pools.
101 */
102void btstack_memory_init(void);
103
104/**
105 * @brief Deinitialize BTstack memory pools
106 * @note if HAVE_MALLOC is defined, all previously allocated buffers are free'd
107 */
108void btstack_memory_deinit(void);
109
110/* API_END */
111"""
112
113hfile_header_end = """
114#if defined __cplusplus
115}
116#endif
117
118#endif // BTSTACK_MEMORY_H
119"""
120
121cfile_header_begin = """
122#define BTSTACK_FILE__ "btstack_memory.c"
123
124
125/*
126 *  btstack_memory.c
127 *
128 *  @brief BTstack memory management via configurable memory pools
129 *
130 *  @note code generated by tool/btstack_memory_generator.py
131 *  @note returnes buffers are initialized with 0
132 *
133 */
134
135#include "btstack_memory.h"
136#include "btstack_memory_pool.h"
137#include "btstack_debug.h"
138
139#include <stdlib.h>
140
141#ifdef ENABLE_MALLOC_TEST
142extern "C" void * test_malloc(size_t size);
143#define malloc test_malloc
144#endif
145
146#ifdef HAVE_MALLOC
147typedef struct btstack_memory_buffer {
148    struct btstack_memory_buffer * next;
149    struct btstack_memory_buffer * prev;
150} btstack_memory_buffer_t;
151
152typedef struct {
153    btstack_memory_buffer_t tracking;
154    void * pointer;
155} test_buffer_t;
156
157static btstack_memory_buffer_t * btstack_memory_malloc_buffers;
158static uint32_t btstack_memory_malloc_counter;
159
160static void btstack_memory_tracking_add(btstack_memory_buffer_t * buffer){
161    btstack_assert(buffer != NULL);
162    if (btstack_memory_malloc_buffers != NULL) {
163        // let current first item prev point to new first item
164        btstack_memory_malloc_buffers->prev = buffer;
165    }
166    buffer->prev = NULL;
167    buffer->next = btstack_memory_malloc_buffers;
168    btstack_memory_malloc_buffers = buffer;
169
170    btstack_memory_malloc_counter++;
171}
172
173static void btstack_memory_tracking_remove(btstack_memory_buffer_t * buffer){
174    btstack_assert(buffer != NULL);
175    if (buffer->prev == NULL){
176        // first item
177        btstack_memory_malloc_buffers = buffer->next;
178    } else {
179        buffer->prev->next = buffer->next;
180    }
181    if (buffer->next != NULL){
182        buffer->next->prev = buffer->prev;
183    }
184
185    btstack_memory_malloc_counter--;
186}
187#endif
188
189void btstack_memory_deinit(void){
190#ifdef HAVE_MALLOC
191    while (btstack_memory_malloc_buffers != NULL){
192        btstack_memory_buffer_t * buffer = btstack_memory_malloc_buffers;
193        btstack_memory_malloc_buffers = buffer->next;
194        free(buffer);
195    }
196    btstack_assert(btstack_memory_malloc_counter == 0);
197#endif
198}
199"""
200
201header_template = """STRUCT_NAME_t * btstack_memory_STRUCT_NAME_get(void);
202void   btstack_memory_STRUCT_NAME_free(STRUCT_NAME_t *STRUCT_NAME);"""
203
204code_template = """
205// MARK: STRUCT_TYPE
206#if !defined(HAVE_MALLOC) && !defined(POOL_COUNT)
207    #if defined(POOL_COUNT_OLD_NO)
208        #error "Deprecated POOL_COUNT_OLD_NO defined instead of POOL_COUNT. Please update your btstack_config.h to use POOL_COUNT."
209    #else
210        #define POOL_COUNT 0
211    #endif
212#endif
213
214#ifdef POOL_COUNT
215#if POOL_COUNT > 0
216static STRUCT_TYPE STRUCT_NAME_storage[POOL_COUNT];
217static btstack_memory_pool_t STRUCT_NAME_pool;
218STRUCT_NAME_t * btstack_memory_STRUCT_NAME_get(void){
219    void * buffer = btstack_memory_pool_get(&STRUCT_NAME_pool);
220    if (buffer){
221        memset(buffer, 0, sizeof(STRUCT_TYPE));
222    }
223    return (STRUCT_NAME_t *) buffer;
224}
225void btstack_memory_STRUCT_NAME_free(STRUCT_NAME_t *STRUCT_NAME){
226    btstack_memory_pool_free(&STRUCT_NAME_pool, STRUCT_NAME);
227}
228#else
229STRUCT_NAME_t * btstack_memory_STRUCT_NAME_get(void){
230    return NULL;
231}
232void btstack_memory_STRUCT_NAME_free(STRUCT_NAME_t *STRUCT_NAME){
233    UNUSED(STRUCT_NAME);
234};
235#endif
236#elif defined(HAVE_MALLOC)
237
238typedef struct {
239    btstack_memory_buffer_t tracking;
240    STRUCT_NAME_t data;
241} btstack_memory_STRUCT_NAME_t;
242
243STRUCT_NAME_t * btstack_memory_STRUCT_NAME_get(void){
244    btstack_memory_STRUCT_NAME_t * buffer = (btstack_memory_STRUCT_NAME_t *) malloc(sizeof(btstack_memory_STRUCT_NAME_t));
245    if (buffer){
246        memset(buffer, 0, sizeof(btstack_memory_STRUCT_NAME_t));
247        btstack_memory_tracking_add(&buffer->tracking);
248        return &buffer->data;
249    } else {
250        return NULL;
251    }
252}
253void btstack_memory_STRUCT_NAME_free(STRUCT_NAME_t *STRUCT_NAME){
254    // reconstruct buffer start
255    btstack_memory_buffer_t * buffer = &((btstack_memory_buffer_t *) STRUCT_NAME)[-1];
256    btstack_memory_tracking_remove(buffer);
257    free(buffer);
258}
259#endif
260"""
261init_header = '''
262// init
263void btstack_memory_init(void){
264#ifdef HAVE_MALLOC
265    // assert that there is no unexpected padding for combined buffer
266    btstack_assert(sizeof(test_buffer_t) == sizeof(btstack_memory_buffer_t) + sizeof(void *));
267#endif
268
269'''
270
271init_template = """#if POOL_COUNT > 0
272    btstack_memory_pool_create(&STRUCT_NAME_pool, STRUCT_NAME_storage, POOL_COUNT, sizeof(STRUCT_TYPE));
273#endif"""
274
275def writeln(f, data):
276    f.write(data + "\n")
277
278def replacePlaceholder(template, struct_name):
279    struct_type = struct_name + '_t'
280    if struct_name.endswith('try'):
281        pool_count = "MAX_NR_" + struct_name.upper()[:-3] + "TRIES"
282    else:
283        pool_count = "MAX_NR_" + struct_name.upper() + "S"
284    pool_count_old_no = pool_count.replace("MAX_NR_", "MAX_NO_")
285    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)
286    return snippet
287
288list_of_structs = [
289    ["hci_connection"],
290    ["l2cap_service", "l2cap_channel"],
291]
292list_of_classic_structs = [
293    ["rfcomm_multiplexer", "rfcomm_service", "rfcomm_channel"],
294    ["btstack_link_key_db_memory_entry"],
295    ["bnep_service", "bnep_channel"],
296    ["hfp_connection"],
297    ["hid_host_connection"],
298    ["service_record_item"],
299    ["avdtp_stream_endpoint"],
300    ["avdtp_connection"],
301    ["avrcp_connection"],
302    ["avrcp_browsing_connection"],
303]
304list_of_le_structs = [
305    ["battery_service_client", "gatt_client", "hids_client", "scan_parameters_service_client", "sm_lookup_entry", "whitelist_entry"],
306]
307list_of_mesh_structs = [
308    ['mesh_network_pdu', 'mesh_segmented_pdu', 'mesh_upper_transport_pdu', 'mesh_network_key', 'mesh_transport_key', 'mesh_virtual_address', 'mesh_subnet']
309]
310
311btstack_root = os.path.abspath(os.path.dirname(sys.argv[0]) + '/..')
312file_name = btstack_root + "/src/btstack_memory"
313print ('Generating %s.[h|c]' % file_name)
314
315f = open(file_name+".h", "w")
316writeln(f, copyright)
317writeln(f, hfile_header_begin)
318for struct_names in list_of_structs:
319    writeln(f, "// "+ ", ".join(struct_names))
320    for struct_name in struct_names:
321        writeln(f, replacePlaceholder(header_template, struct_name))
322    writeln(f, "")
323writeln(f, "#ifdef ENABLE_CLASSIC")
324for struct_names in list_of_classic_structs:
325    writeln(f, "// "+ ", ".join(struct_names))
326    for struct_name in struct_names:
327        writeln(f, replacePlaceholder(header_template, struct_name))
328    writeln(f, "")
329writeln(f, "#endif")
330writeln(f, "#ifdef ENABLE_BLE")
331for struct_names in list_of_le_structs:
332    writeln(f, "// "+ ", ".join(struct_names))
333    for struct_name in struct_names:
334        writeln(f, replacePlaceholder(header_template, struct_name))
335writeln(f, "#endif")
336writeln(f, "#ifdef ENABLE_MESH")
337for struct_names in list_of_mesh_structs:
338    writeln(f, "// "+ ", ".join(struct_names))
339    for struct_name in struct_names:
340        writeln(f, replacePlaceholder(header_template, struct_name))
341writeln(f, "#endif")
342writeln(f, hfile_header_end)
343f.close();
344
345
346f = open(file_name+".c", "w")
347writeln(f, copyright)
348writeln(f, cfile_header_begin)
349for struct_names in list_of_structs:
350    for struct_name in struct_names:
351        writeln(f, replacePlaceholder(code_template, struct_name))
352    writeln(f, "")
353writeln(f, "#ifdef ENABLE_CLASSIC")
354for struct_names in list_of_classic_structs:
355    for struct_name in struct_names:
356        writeln(f, replacePlaceholder(code_template, struct_name))
357    writeln(f, "")
358writeln(f, "#endif")
359writeln(f, "#ifdef ENABLE_BLE")
360for struct_names in list_of_le_structs:
361    for struct_name in struct_names:
362        writeln(f, replacePlaceholder(code_template, struct_name))
363    writeln(f, "")
364writeln(f, "#endif")
365writeln(f, "#ifdef ENABLE_MESH")
366for struct_names in list_of_mesh_structs:
367    for struct_name in struct_names:
368        writeln(f, replacePlaceholder(code_template, struct_name))
369    writeln(f, "")
370writeln(f, "#endif")
371
372f.write(init_header)
373for struct_names in list_of_structs:
374    for struct_name in struct_names:
375        writeln(f, replacePlaceholder(init_template, struct_name))
376writeln(f, "#ifdef ENABLE_CLASSIC")
377for struct_names in list_of_classic_structs:
378    for struct_name in struct_names:
379        writeln(f, replacePlaceholder(init_template, struct_name))
380writeln(f, "#endif")
381writeln(f, "#ifdef ENABLE_BLE")
382for struct_names in list_of_le_structs:
383    for struct_name in struct_names:
384        writeln(f, replacePlaceholder(init_template, struct_name))
385writeln(f, "#endif")
386writeln(f, "#ifdef ENABLE_MESH")
387for struct_names in list_of_mesh_structs:
388    for struct_name in struct_names:
389        writeln(f, replacePlaceholder(init_template, struct_name))
390writeln(f, "#endif")
391writeln(f, "}")
392f.close();
393
394# also generate test code
395test_header = """
396#include <stdint.h>
397#include <stdio.h>
398#include <stdlib.h>
399#include <string.h>
400
401// malloc hook
402static int simulate_no_memory;
403extern "C" void * test_malloc(size_t size);
404void * test_malloc(size_t size){
405    if (simulate_no_memory) return NULL;
406    return malloc(size);
407}
408
409#include "btstack_config.h"
410
411#include "CppUTest/TestHarness.h"
412#include "CppUTest/CommandLineTestRunner.h"
413
414#include "bluetooth_data_types.h"
415#include "btstack_util.h"
416#include "btstack_memory.h"
417
418
419TEST_GROUP(btstack_memory){
420    void setup(void){
421        btstack_memory_init();
422        simulate_no_memory = 0;
423    }
424};
425
426#ifdef HAVE_MALLOC
427TEST(btstack_memory, deinit){
428    // alloc buffers 1,2,3
429    hci_connection_t * buffer_1 = btstack_memory_hci_connection_get();
430    hci_connection_t * buffer_2 = btstack_memory_hci_connection_get();
431    hci_connection_t * buffer_3 = btstack_memory_hci_connection_get();
432    // free first one in list
433    btstack_memory_hci_connection_free(buffer_3);
434    // free second one in list
435    btstack_memory_hci_connection_free(buffer_1);
436    // leave buffer in list
437    (void) buffer_2;
438    btstack_memory_deinit();
439}
440#endif
441
442"""
443
444test_template = """
445
446TEST(btstack_memory, STRUCT_NAME_GetAndFree){
447    STRUCT_NAME_t * context;
448#ifdef HAVE_MALLOC
449    context = btstack_memory_STRUCT_NAME_get();
450    CHECK(context != NULL);
451    btstack_memory_STRUCT_NAME_free(context);
452#else
453#ifdef POOL_COUNT
454    // single
455    context = btstack_memory_STRUCT_NAME_get();
456    CHECK(context != NULL);
457    btstack_memory_STRUCT_NAME_free(context);
458#else
459    // none
460    context = btstack_memory_STRUCT_NAME_get();
461    CHECK(context == NULL);
462    btstack_memory_STRUCT_NAME_free(context);
463#endif
464#endif
465}
466
467TEST(btstack_memory, STRUCT_NAME_NotEnoughBuffers){
468    STRUCT_NAME_t * context;
469#ifdef HAVE_MALLOC
470    simulate_no_memory = 1;
471#else
472#ifdef POOL_COUNT
473    int i;
474    // alloc all static buffers
475    for (i = 0; i < POOL_COUNT; i++){
476        context = btstack_memory_STRUCT_NAME_get();
477        CHECK(context != NULL);
478    }
479#endif
480#endif
481    // get one more
482    context = btstack_memory_STRUCT_NAME_get();
483    CHECK(context == NULL);
484}
485"""
486
487test_footer = """
488int main (int argc, const char * argv[]){
489    return CommandLineTestRunner::RunAllTests(argc, argv);
490}
491"""
492
493file_name = btstack_root + "/test/btstack_memory/btstack_memory_test.c"
494print ('Generating %s' % file_name)
495
496f = open(file_name, "w")
497writeln(f, copyright)
498writeln(f, test_header)
499for struct_names in list_of_structs:
500    for struct_name in struct_names:
501        writeln(f, replacePlaceholder(test_template, struct_name))
502writeln(f, "#ifdef ENABLE_CLASSIC")
503for struct_names in list_of_classic_structs:
504    for struct_name in struct_names:
505        writeln(f, replacePlaceholder(test_template, struct_name))
506writeln(f, "#endif")
507writeln(f, "#ifdef ENABLE_BLE")
508for struct_names in list_of_le_structs:
509    for struct_name in struct_names:
510        writeln(f, replacePlaceholder(test_template, struct_name))
511writeln(f, "#endif")
512writeln(f, "#ifdef ENABLE_MESH")
513for struct_names in list_of_mesh_structs:
514    for struct_name in struct_names:
515        writeln(f, replacePlaceholder(test_template, struct_name))
516writeln(f, "#endif")
517writeln(f, test_footer)