1 /****************************************************************************
3 * Copyright (C) 2003-2009 Sourcefire, Inc.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License Version 2 as
7 * published by the Free Software Foundation. You may not use, modify or
8 * distribute this program under any other version of the GNU General
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 ****************************************************************************/
25 These functions wrap the alloc & free functions. They enforce a memory cap using
26 the MEMCAP structure. The MEMCAP structure tracks memory usage. Each allocation
27 has 4 bytes added to it so we can store the allocation size. This allows us to
28 free a block and accurately track how much memory was recovered.
39 * Set max # bytes & init other variables.
41 void sfmemcap_init( MEMCAP
* mc
, unsigned nbytes
)
49 * Create and Init a MEMCAP - use free to release it
51 MEMCAP
* sfmemcap_new( unsigned nbytes
)
55 mc
= (MEMCAP
*)calloc(1,sizeof(MEMCAP
));
57 if( mc
) sfmemcap_init( mc
, nbytes
);
63 * Release the memcap structure
65 void sfmemcap_delete( MEMCAP
* p
)
71 * Allocate some memory
73 void * sfmemcap_alloc( MEMCAP
* mc
, unsigned nbytes
)
77 //printf("sfmemcap_alloc: %d bytes requested, memcap=%d, used=%d\n",nbytes,mc->memcap,mc->memused);
79 nbytes
+= sizeof(long);
82 /* Check if we are limiting memory use */
85 /* Check if we've maxed out our memory - if we are tracking memory */
86 if( (mc
->memused
+ nbytes
) > mc
->memcap
)
92 //data = (long *) malloc( nbytes );
93 data
= (long *)calloc( nbytes
, sizeof(char));
100 *data
++ = (long)nbytes
;
102 mc
->memused
+= nbytes
;
111 void sfmemcap_free( MEMCAP
* mc
, void * p
)
117 mc
->memused
-= (unsigned)(*q
);
126 void sfmemcap_showmem( MEMCAP
* mc
)
128 fprintf(stderr
, "memcap: memcap = %u bytes,",mc
->memcap
);
129 fprintf(stderr
, " memused= %u bytes,",mc
->memused
);
130 fprintf(stderr
, " nblocks= %d blocks\n",mc
->nblocks
);
134 * String Dup Some memory.
136 char * sfmemcap_strdup( MEMCAP
* mc
, const char *str
)
141 data_size
= strlen(str
) + 1;
142 data
= (char *)sfmemcap_alloc(mc
, data_size
);
149 strncpy(data
, str
, data_size
);
157 void * sfmemcap_dupmem( MEMCAP
* mc
, void * src
, int n
)
159 void * data
= (char *)sfmemcap_alloc( mc
, n
);
165 memcpy( data
, src
, n
);