1 /*
2 * jmemmgr.c
3 *
4 * Copyright (C) 1991-1997, Thomas G. Lane.
5 * This file is part of the Independent JPEG Group's software.
6 * For conditions of distribution and use, see the accompanying README file.
7 *
8 * This file contains the JPEG system-independent memory management
9 * routines.  This code is usable across a wide variety of machines; most
10 * of the system dependencies have been isolated in a separate file.
11 * The major functions provided here are:
12 *   * pool-based allocation and freeing of memory;
13 *   * policy decisions about how to divide available memory among the
14 *     virtual arrays;
15 *   * control logic for swapping virtual arrays between main memory and
16 *     backing storage.
17 * The separate system-dependent file provides the actual backing-storage
18 * access code, and it contains the policy decision about how much total
19 * main memory to use.
20 * This file is system-dependent in the sense that some of its functions
21 * are unnecessary in some systems.  For example, if there is enough virtual
22 * memory so that backing storage will never be used, much of the virtual
23 * array control logic could be removed.  (Of course, if you have that much
24 * memory then you shouldn't care about a little bit of unused code...)
25 */
26 
27 #define JPEG_INTERNALS
28 #define AM_MEMORY_MANAGER	/* we define jvirt_Xarray_control structs */
29 #include "jinclude.h"
30 #include "jpeglib.h"
31 
32 
33 /*
34 * Some important notes:
35 *   The allocation routines provided here must never return NULL.
36 *   They should exit to error_exit if unsuccessful.
37 *
38 *   It's not a good idea to try to merge the sarray and barray routines,
39 *   even though they are textually almost the same, because samples are
40 *   usually stored as bytes while coefficients are shorts or ints.  Thus,
41 *   in machines where byte pointers have a different representation from
42 *   word pointers, the resulting machine code could not be the same.
43 */
44 
45 
46 /*
47 * Many machines require storage alignment: longs must start on 4-byte
48 * boundaries, doubles on 8-byte boundaries, etc.  On such machines, malloc()
49 * always returns pointers that are multiples of the worst-case alignment
50 * requirement, and we had better do so too.
51 * There isn't any really portable way to determine the worst-case alignment
52 * requirement.  This module assumes that the alignment requirement is
53 * multiples of sizeof(ALIGN_TYPE).
54 * By default, we define ALIGN_TYPE as double.  This is necessary on some
55 * workstations (where doubles really do need 8-byte alignment) and will work
56 * fine on nearly everything.  If your machine has lesser alignment needs,
57 * you can save a few bytes by making ALIGN_TYPE smaller.
58 * The only place I know of where this will NOT work is certain Macintosh
59 * 680x0 compilers that define double as a 10-byte IEEE extended float.
60 * Doing 10-byte alignment is counterproductive because longwords won't be
61 * aligned well.  Put "#define ALIGN_TYPE long" in jconfig.h if you have
62 * such a compiler.
63 */
64 
65 #ifndef ALIGN_TYPE		/* so can override from jconfig.h */
66 #define ALIGN_TYPE  double
67 #endif
68 
69 
70 /*
71 * We allocate objects from "pools", where each pool is gotten with a single
72 * request to jpeg_get_small() or jpeg_get_large().  There is no per-object
73 * overhead within a pool, except for alignment padding.  Each pool has a
74 * header with a link to the next pool of the same class.
75 * Small and large pool headers are identical except that the latter's
76 * link pointer must be FAR on 80x86 machines.
77 * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
78 * field.  This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
79 * of the alignment requirement of ALIGN_TYPE.
80 */
81 
82 typedef union small_pool_struct * small_pool_ptr;
83 
84 typedef union small_pool_struct {
85 	struct {
86 		small_pool_ptr next;	/* next in list of pools */
87 		size_t bytes_used;		/* how many bytes already used within pool */
88 		size_t bytes_left;		/* bytes still available in this pool */
89 	} hdr;
90 	ALIGN_TYPE dummy;		/* included in union to ensure alignment */
91 } small_pool_hdr;
92 
93 typedef union large_pool_struct * large_pool_ptr;
94 
95 typedef union large_pool_struct {
96 	struct {
97 		large_pool_ptr next;	/* next in list of pools */
98 		size_t bytes_used;		/* how many bytes already used within pool */
99 		size_t bytes_left;		/* bytes still available in this pool */
100 	} hdr;
101 	ALIGN_TYPE dummy;		/* included in union to ensure alignment */
102 } large_pool_hdr;
103 
104 
105 /*
106 * Here is the full definition of a memory manager object.
107 */
108 
109 typedef struct {
110 	struct jpeg_memory_mgr pub;	/* public fields */
111 
112 	/* Each pool identifier (lifetime class) names a linked list of pools. */
113 	small_pool_ptr small_list[JPOOL_NUMPOOLS];
114 	large_pool_ptr large_list[JPOOL_NUMPOOLS];
115 
116 	/* Since we only have one lifetime class of virtual arrays, only one
117 	* linked list is necessary (for each datatype).  Note that the virtual
118 	* array control blocks being linked together are actually stored somewhere
119 	* in the small-pool list.
120 	*/
121 	jvirt_barray_ptr virt_barray_list;
122 
123 	/* alloc_sarray and alloc_barray set this value for use by virtual
124 	* array routines.
125 	*/
126 	JDIMENSION last_rowsperchunk;	/* from most recent alloc_sarray/barray */
127 } my_memory_mgr;
128 
129 typedef my_memory_mgr * my_mem_ptr;
130 
131 
132 /*
133 * The control blocks for virtual arrays.
134 * Note that these blocks are allocated in the "small" pool area.
135 * System-dependent info for the associated backing store (if any) is hidden
136 * inside the backing_store_info struct.
137 */
138 
139 struct jvirt_barray_control {
140 	JBLOCKARRAY mem_buffer;	/* => the in-memory buffer */
141 	JDIMENSION rows_in_array;	/* total virtual array height */
142 	JDIMENSION blocksperrow;	/* width of array (and of memory buffer) */
143 	JDIMENSION maxaccess;		/* max rows accessed by access_virt_barray */
144 	JDIMENSION rows_in_mem;	/* height of memory buffer */
145 	JDIMENSION rowsperchunk;	/* allocation chunk size in mem_buffer */
146 	JDIMENSION cur_start_row;	/* first logical row # in the buffer */
147 	JDIMENSION first_undef_row;	/* row # of first uninitialized row */
148 	boolean pre_zero;		/* pre-zero mode requested? */
149 	boolean dirty;		/* do current buffer contents need written? */
150 	jvirt_barray_ptr next;	/* link to next virtual barray control block */
151 };
152 
153 
154 LOCAL(void)
out_of_memory(j_common_ptr cinfo,int which)155 out_of_memory (j_common_ptr cinfo, int which)
156 /* Report an out-of-memory error and stop execution */
157 {
158 	ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
159 }
160 
161 
162 /*
163 * Allocation of "small" objects.
164 *
165 * For these, we use pooled storage.  When a new pool must be created,
166 * we try to get enough space for the current request plus a "slop" factor,
167 * where the slop will be the amount of leftover space in the new pool.
168 * The speed vs. space tradeoff is largely determined by the slop values.
169 * A different slop value is provided for each pool class (lifetime),
170 * and we also distinguish the first pool of a class from later ones.
171 * NOTE: the values given work fairly well on both 16- and 32-bit-int
172 * machines, but may be too small if longs are 64 bits or more.
173 */
174 
175 static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
176 {
177 	1600,			/* first PERMANENT pool */
178 	16000			/* first IMAGE pool */
179 };
180 
181 static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
182 {
183 	0,			/* additional PERMANENT pools */
184 	5000			/* additional IMAGE pools */
185 };
186 
187 #define MIN_SLOP  50		/* greater than 0 to avoid futile looping */
188 
189 
190 METHODDEF(void *)
alloc_small(j_common_ptr cinfo,int pool_id,size_t sizeofobject)191 alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
192 /* Allocate a "small" object */
193 {
194 	my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
195 	small_pool_ptr hdr_ptr, prev_hdr_ptr;
196 	char * data_ptr;
197 	size_t odd_bytes, min_request, slop;
198 
199 	/* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
200 	odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
201 	if (odd_bytes > 0)
202 		sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
203 
204 	/* See if space is available in any existing pool */
205 	if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
206 		ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
207 	prev_hdr_ptr = NULL;
208 	hdr_ptr = mem->small_list[pool_id];
209 	while (hdr_ptr != NULL) {
210 		if (hdr_ptr->hdr.bytes_left >= sizeofobject)
211 			break;			/* found pool with enough space */
212 		prev_hdr_ptr = hdr_ptr;
213 		hdr_ptr = hdr_ptr->hdr.next;
214 	}
215 
216 	/* Time to make a new pool? */
217 	if (hdr_ptr == NULL) {
218 		/* min_request is what we need now, slop is what will be leftover */
219 		min_request = sizeofobject + SIZEOF(small_pool_hdr);
220 		if (prev_hdr_ptr == NULL)	/* first pool in class? */
221 			slop = first_pool_slop[pool_id];
222 		else
223 			slop = extra_pool_slop[pool_id];
224 		/* Try to get space, if fail reduce slop and try again */
225 		for (;;) {
226 			hdr_ptr = (small_pool_ptr) malloc(min_request + slop);
227 			if (hdr_ptr != NULL)
228 				break;
229 			slop /= 2;
230 			if (slop < MIN_SLOP)	/* give up when it gets real small */
231 				out_of_memory(cinfo, 2); /* jpeg_get_small failed */
232 		}
233 		/* Success, initialize the new pool header and add to end of list */
234 		hdr_ptr->hdr.next = NULL;
235 		hdr_ptr->hdr.bytes_used = 0;
236 		hdr_ptr->hdr.bytes_left = sizeofobject + slop;
237 		if (prev_hdr_ptr == NULL)	/* first pool in class? */
238 			mem->small_list[pool_id] = hdr_ptr;
239 		else
240 			prev_hdr_ptr->hdr.next = hdr_ptr;
241 	}
242 
243 	/* OK, allocate the object from the current pool */
244 	data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
245 	data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
246 	hdr_ptr->hdr.bytes_used += sizeofobject;
247 	hdr_ptr->hdr.bytes_left -= sizeofobject;
248 
249 	return (void *) data_ptr;
250 }
251 
252 
253 /*
254 * Allocation of "large" objects.
255 *
256 * The external semantics of these are the same as "small" objects,
257 * except that FAR pointers are used on 80x86.  However the pool
258 * management heuristics are quite different.  We assume that each
259 * request is large enough that it may as well be passed directly to
260 * jpeg_get_large; the pool management just links everything together
261 * so that we can free it all on demand.
262 * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
263 * structures.  The routines that create these structures (see below)
264 * deliberately bunch rows together to ensure a large request size.
265 */
266 
267 METHODDEF(void *)
alloc_large(j_common_ptr cinfo,int pool_id,size_t sizeofobject)268 alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
269 /* Allocate a "large" object */
270 {
271 	my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
272 	large_pool_ptr hdr_ptr;
273 	size_t odd_bytes;
274 
275 	/* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
276 	odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
277 	if (odd_bytes > 0)
278 		sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
279 
280 	/* Always make a new pool */
281 	if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
282 		ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
283 
284 	hdr_ptr = (large_pool_ptr) malloc(sizeofobject + SIZEOF(large_pool_hdr));
285 	if (hdr_ptr == NULL)
286 		out_of_memory(cinfo, 4);	/* jpeg_get_large failed */
287 
288 	/* Success, initialize the new pool header and add to list */
289 	hdr_ptr->hdr.next = mem->large_list[pool_id];
290 	/* We maintain space counts in each pool header for statistical purposes,
291 	* even though they are not needed for allocation.
292 	*/
293 	hdr_ptr->hdr.bytes_used = sizeofobject;
294 	hdr_ptr->hdr.bytes_left = 0;
295 	mem->large_list[pool_id] = hdr_ptr;
296 
297 	return (void *) (hdr_ptr + 1); /* point to first data byte in pool */
298 }
299 
300 
301 /*
302 * Creation of 2-D sample arrays.
303 * The pointers are in near heap, the samples themselves in FAR heap.
304 *
305 * To minimize allocation overhead and to allow I/O of large contiguous
306 * blocks, we allocate the sample rows in groups of as many rows as possible
307 * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
308 * NB: the virtual array control routines, later in this file, know about
309 * this chunking of rows.  The rowsperchunk value is left in the mem manager
310 * object so that it can be saved away if this sarray is the workspace for
311 * a virtual array.
312 */
313 
314 METHODDEF(JSAMPARRAY)
alloc_sarray(j_common_ptr cinfo,int pool_id,JDIMENSION samplesperrow,JDIMENSION numrows)315 alloc_sarray (j_common_ptr cinfo, int pool_id,
316 			  JDIMENSION samplesperrow, JDIMENSION numrows)
317 			  /* Allocate a 2-D sample array */
318 {
319 	my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
320 	JSAMPARRAY result;
321 	JSAMPROW workspace;
322 	JDIMENSION i;
323 
324 	/* Calculate max # of rows allowed in one allocation chunk */
325 	mem->last_rowsperchunk = numrows;
326 
327 	/* Get space for row pointers (small object) */
328 	result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
329 		(size_t) (numrows * SIZEOF(JSAMPROW)));
330 
331 	/* Get the rows themselves (large objects) */
332 	workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
333 		(size_t) ((size_t) numrows * (size_t) samplesperrow
334 		* SIZEOF(JSAMPLE)));
335 	for (i = 0; i < numrows; i++) {
336 		result[i] = workspace;
337 		workspace += samplesperrow;
338 	}
339 
340 	return result;
341 }
342 
343 
344 /*
345 * Creation of 2-D coefficient-block arrays.
346 * This is essentially the same as the code for sample arrays, above.
347 */
348 
349 METHODDEF(JBLOCKARRAY)
alloc_barray(j_common_ptr cinfo,int pool_id,JDIMENSION blocksperrow,JDIMENSION numrows)350 alloc_barray (j_common_ptr cinfo, int pool_id,
351 			  JDIMENSION blocksperrow, JDIMENSION numrows)
352 			  /* Allocate a 2-D coefficient-block array */
353 {
354 	my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
355 	JBLOCKARRAY result;
356 	JBLOCKROW workspace;
357 	JDIMENSION i;
358 
359 	/* Calculate max # of rows allowed in one allocation chunk */
360 	mem->last_rowsperchunk = numrows;
361 
362 	/* Get space for row pointers (small object) */
363 	result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
364 		(size_t) (numrows * SIZEOF(JBLOCKROW)));
365 
366 	/* Get the rows themselves (large objects) */
367 	workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
368 		(size_t) ((size_t) numrows * (size_t) blocksperrow
369 		* SIZEOF(JBLOCK)));
370 	for (i = 0; i < numrows; i++) {
371 		result[i] = workspace;
372 		workspace += blocksperrow;
373 	}
374 
375 	return result;
376 }
377 
378 
379 /*
380 * About virtual array management:
381 *
382 * The above "normal" array routines are only used to allocate strip buffers
383 * (as wide as the image, but just a few rows high).  Full-image-sized buffers
384 * are handled as "virtual" arrays.  The array is still accessed a strip at a
385 * time, but the memory manager must save the whole array for repeated
386 * accesses.  The intended implementation is that there is a strip buffer in
387 * memory (as high as is possible given the desired memory limit), plus a
388 * backing file that holds the rest of the array.
389 *
390 * The request_virt_array routines are told the total size of the image and
391 * the maximum number of rows that will be accessed at once.  The in-memory
392 * buffer must be at least as large as the maxaccess value.
393 *
394 * The request routines create control blocks but not the in-memory buffers.
395 * That is postponed until realize_virt_arrays is called.  At that time the
396 * total amount of space needed is known (approximately, anyway), so free
397 * memory can be divided up fairly.
398 *
399 * The access_virt_array routines are responsible for making a specific strip
400 * area accessible (after reading or writing the backing file, if necessary).
401 * Note that the access routines are told whether the caller intends to modify
402 * the accessed strip; during a read-only pass this saves having to rewrite
403 * data to disk.  The access routines are also responsible for pre-zeroing
404 * any newly accessed rows, if pre-zeroing was requested.
405 *
406 * In current usage, the access requests are usually for nonoverlapping
407 * strips; that is, successive access start_row numbers differ by exactly
408 * num_rows = maxaccess.  This means we can get good performance with simple
409 * buffer dump/reload logic, by making the in-memory buffer be a multiple
410 * of the access height; then there will never be accesses across bufferload
411 * boundaries.  The code will still work with overlapping access requests,
412 * but it doesn't handle bufferload overlaps very efficiently.
413 */
414 
415 
416 METHODDEF(jvirt_barray_ptr)
request_virt_barray(j_common_ptr cinfo,int pool_id,boolean pre_zero,JDIMENSION blocksperrow,JDIMENSION numrows,JDIMENSION maxaccess)417 request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
418 					 JDIMENSION blocksperrow, JDIMENSION numrows,
419 					 JDIMENSION maxaccess)
420 					 /* Request a virtual 2-D coefficient-block array */
421 {
422 	my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
423 	jvirt_barray_ptr result;
424 
425 	/* Only IMAGE-lifetime virtual arrays are currently supported */
426 	if (pool_id != JPOOL_IMAGE)
427 		ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
428 
429 	/* get control block */
430 	result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
431 		SIZEOF(struct jvirt_barray_control));
432 
433 	result->mem_buffer = NULL;	/* marks array not yet realized */
434 	result->rows_in_array = numrows;
435 	result->blocksperrow = blocksperrow;
436 	result->maxaccess = maxaccess;
437 	result->pre_zero = pre_zero;
438 	result->next = mem->virt_barray_list; /* add to list of virtual arrays */
439 	mem->virt_barray_list = result;
440 
441 	return result;
442 }
443 
444 
445 METHODDEF(void)
realize_virt_arrays(j_common_ptr cinfo)446 realize_virt_arrays (j_common_ptr cinfo)
447 /* Allocate the in-memory buffers for any unrealized virtual arrays */
448 {
449 	my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
450 	long space_per_minheight;
451 	long minheights;
452 	jvirt_barray_ptr bptr;
453 
454 	/* Compute the minimum space needed (maxaccess rows in each buffer)
455 	* and the maximum space needed (full image height in each buffer).
456 	* These may be of use to the system-dependent jpeg_mem_available routine.
457 	*/
458 	space_per_minheight = 0;
459 	for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
460 		if (bptr->mem_buffer == NULL) { /* if not realized yet */
461 			space_per_minheight += (long) bptr->maxaccess *
462 				(long) bptr->blocksperrow * SIZEOF(JBLOCK);
463 		}
464 	}
465 
466 	if (space_per_minheight <= 0)
467 		return;			/* no unrealized arrays, no work */
468 
469 	/* Allocate the in-memory buffers and initialize backing store as needed. */
470 
471 	for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
472 		if (bptr->mem_buffer == NULL) { /* if not realized yet */
473 			minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
474 			bptr->rows_in_mem = bptr->rows_in_array;
475 			bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
476 				bptr->blocksperrow, bptr->rows_in_mem);
477 			bptr->rowsperchunk = mem->last_rowsperchunk;
478 			bptr->cur_start_row = 0;
479 			bptr->first_undef_row = 0;
480 			bptr->dirty = FALSE;
481 		}
482 	}
483 }
484 
485 
486 
487 METHODDEF(JBLOCKARRAY)
access_virt_barray(j_common_ptr cinfo,jvirt_barray_ptr ptr,JDIMENSION start_row,JDIMENSION num_rows,boolean writable)488 access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
489 					JDIMENSION start_row, JDIMENSION num_rows,
490 					boolean writable)
491 					/* Access the part of a virtual block array starting at start_row */
492 					/* and extending for num_rows rows.  writable is true if  */
493 					/* caller intends to modify the accessed area. */
494 {
495 	JDIMENSION end_row = start_row + num_rows;
496 	JDIMENSION undef_row;
497 
498 	/* debugging check */
499 	if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
500 		ptr->mem_buffer == NULL)
501 		ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
502 
503 	/* Make the desired part of the virtual array accessible */
504 	if (start_row < ptr->cur_start_row || end_row > ptr->cur_start_row+ptr->rows_in_mem)
505 		ERREXIT(cinfo, JERR_VIRTUAL_BUG);
506 
507 	/* Ensure the accessed part of the array is defined; prezero if needed.
508 	* To improve locality of access, we only prezero the part of the array
509 	* that the caller is about to access, not the entire in-memory array.
510 	*/
511 	if (ptr->first_undef_row < end_row) {
512 		if (ptr->first_undef_row < start_row) {
513 			if (writable)		/* writer skipped over a section of array */
514 				ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
515 			undef_row = start_row;	/* but reader is allowed to read ahead */
516 		} else {
517 			undef_row = ptr->first_undef_row;
518 		}
519 		if (writable)
520 			ptr->first_undef_row = end_row;
521 		if (ptr->pre_zero) {
522 			size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
523 			undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
524 			end_row -= ptr->cur_start_row;
525 			while (undef_row < end_row) {
526 				MEMZERO((void *) ptr->mem_buffer[undef_row], bytesperrow);
527 				undef_row++;
528 			}
529 		} else {
530 			if (! writable)		/* reader looking at undefined data */
531 				ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
532 		}
533 	}
534 	/* Flag the buffer dirty if caller will write in it */
535 	if (writable)
536 		ptr->dirty = TRUE;
537 	/* Return address of proper part of the buffer */
538 	return ptr->mem_buffer + (start_row - ptr->cur_start_row);
539 }
540 
541 
542 /*
543 * Release all objects belonging to a specified pool.
544 */
545 
546 METHODDEF(void)
free_pool(j_common_ptr cinfo,int pool_id)547 free_pool (j_common_ptr cinfo, int pool_id)
548 {
549 	my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
550 	small_pool_ptr shdr_ptr;
551 	large_pool_ptr lhdr_ptr;
552 
553 	if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
554 		ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
555 
556 	/* Release large objects */
557 	lhdr_ptr = mem->large_list[pool_id];
558 	mem->large_list[pool_id] = NULL;
559 
560 	while (lhdr_ptr != NULL) {
561 		large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
562 		free(lhdr_ptr);
563 		lhdr_ptr = next_lhdr_ptr;
564 	}
565 
566 	/* Release small objects */
567 	shdr_ptr = mem->small_list[pool_id];
568 	mem->small_list[pool_id] = NULL;
569 
570 	while (shdr_ptr != NULL) {
571 		small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
572 		free(shdr_ptr);
573 		shdr_ptr = next_shdr_ptr;
574 	}
575 }
576 
577 
578 /*
579 * Close up shop entirely.
580 * Note that this cannot be called unless cinfo->mem is non-NULL.
581 */
582 
583 METHODDEF(void)
self_destruct(j_common_ptr cinfo)584 self_destruct (j_common_ptr cinfo)
585 {
586 	int pool;
587 
588 	/* Close all backing store, release all memory.
589 	* Releasing pools in reverse order might help avoid fragmentation
590 	* with some (brain-damaged) malloc libraries.
591 	*/
592 	for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
593 		free_pool(cinfo, pool);
594 	}
595 
596 	/* Release the memory manager control block too. */
597 	free(cinfo->mem);
598 	cinfo->mem = NULL;		/* ensures I will be called only once */
599 }
600 
601 
602 /*
603 * Memory manager initialization.
604 * When this is called, only the error manager pointer is valid in cinfo!
605 */
606 
607 GLOBAL(void)
jinit_memory_mgr(j_common_ptr cinfo)608 jinit_memory_mgr (j_common_ptr cinfo)
609 {
610 	my_mem_ptr mem;
611 	int pool;
612 
613 	cinfo->mem = NULL;		/* for safety if init fails */
614 
615 	/* Check for configuration errors.
616 	* SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
617 	* doesn't reflect any real hardware alignment requirement.
618 	* The test is a little tricky: for X>0, X and X-1 have no one-bits
619 	* in common if and only if X is a power of 2, ie has only one one-bit.
620 	* Some compilers may give an "unreachable code" warning here; ignore it.
621 	*/
622 	if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
623 		ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
624 
625 	/* Attempt to allocate memory manager's control block */
626 	mem = (my_mem_ptr) malloc(SIZEOF(my_memory_mgr));
627 
628 	if (mem == NULL) {
629 		ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
630 	}
631 
632 	/* OK, fill in the method pointers */
633 	mem->pub.alloc_small = alloc_small;
634 	mem->pub.alloc_large = alloc_large;
635 	mem->pub.alloc_sarray = alloc_sarray;
636 	mem->pub.alloc_barray = alloc_barray;
637 	mem->pub.request_virt_barray = request_virt_barray;
638 	mem->pub.realize_virt_arrays = realize_virt_arrays;
639 	mem->pub.access_virt_barray = access_virt_barray;
640 	mem->pub.free_pool = free_pool;
641 	mem->pub.self_destruct = self_destruct;
642 
643 	/* Initialize working state */
644 	for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
645 		mem->small_list[pool] = NULL;
646 		mem->large_list[pool] = NULL;
647 	}
648 	mem->virt_barray_list = NULL;
649 
650 	/* Declare ourselves open for business */
651 	cinfo->mem = & mem->pub;
652 }
653