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
24static void nd_add_alloc_list(netdissect_options *, nd_mem_chunk_t *);
25
26/*
27 * nd_free_all() is intended to be used after a packet printing
28 */
29
30/* Add a memory chunk in allocation linked list */
31static void
32nd_add_alloc_list(netdissect_options *ndo, nd_mem_chunk_t *chunkp)
33{
34	if (ndo->ndo_last_mem_p == NULL)	/* first memory allocation */
35		chunkp->prev_mem_p = NULL;
36	else					/* previous memory allocation */
37		chunkp->prev_mem_p = ndo->ndo_last_mem_p;
38	ndo->ndo_last_mem_p = chunkp;
39}
40
41/* malloc replacement, with tracking in a linked list */
42void *
43nd_malloc(netdissect_options *ndo, size_t size)
44{
45	nd_mem_chunk_t *chunkp = malloc(sizeof(nd_mem_chunk_t) + size);
46	if (chunkp == NULL)
47		return NULL;
48	nd_add_alloc_list(ndo, chunkp);
49	return chunkp + 1;
50}
51
52/* Free chunks in allocation linked list from last to first */
53void
54nd_free_all(netdissect_options *ndo)
55{
56	nd_mem_chunk_t *current, *previous;
57	current = ndo->ndo_last_mem_p;
58	while (current != NULL) {
59		previous = current->prev_mem_p;
60		free(current);
61		current = previous;
62	}
63	ndo->ndo_last_mem_p = NULL;
64}
65