1 /*
2  * Copyright (c) 2018 The TCPDUMP project
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that: (1) source code
7  * distributions retain the above copyright notice and this paragraph
8  * in its entirety, and (2) distributions including binary code include
9  * the above copyright notice and this paragraph in its entirety in
10  * the documentation or other materials provided with the distribution.
11  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND
12  * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
13  * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
14  * FOR A PARTICULAR PURPOSE.
15  */
16 
17 #ifdef HAVE_CONFIG_H
18 #include <config.h>
19 #endif
20 
21 #include <stdlib.h>
22 #include "netdissect-alloc.h"
23 
24 /*
25  * nd_free_all() is intended to be used after a packet printing
26  */
27 
28 /* Add a memory chunk in allocation linked list */
29 void
nd_add_alloc_list(netdissect_options * ndo,nd_mem_chunk_t * chunkp)30 nd_add_alloc_list(netdissect_options *ndo, nd_mem_chunk_t *chunkp)
31 {
32 	if (ndo->ndo_last_mem_p == NULL)	/* first memory allocation */
33 		chunkp->prev_mem_p = NULL;
34 	else					/* previous memory allocation */
35 		chunkp->prev_mem_p = ndo->ndo_last_mem_p;
36 	ndo->ndo_last_mem_p = chunkp;
37 }
38 
39 /* malloc replacement, with tracking in a linked list */
40 void *
nd_malloc(netdissect_options * ndo,size_t size)41 nd_malloc(netdissect_options *ndo, size_t size)
42 {
43 	nd_mem_chunk_t *chunkp = malloc(sizeof(nd_mem_chunk_t) + size);
44 	if (chunkp == NULL)
45 		return NULL;
46 	nd_add_alloc_list(ndo, chunkp);
47 	return chunkp + 1;
48 }
49 
50 /* Free chunks in allocation linked list from last to first */
51 void
nd_free_all(netdissect_options * ndo)52 nd_free_all(netdissect_options *ndo)
53 {
54 	nd_mem_chunk_t *current, *previous;
55 	current = ndo->ndo_last_mem_p;
56 	while (current != NULL) {
57 		previous = current->prev_mem_p;
58 		free(current);
59 		current = previous;
60 	}
61 	ndo->ndo_last_mem_p = NULL;
62 }
63