1 /*
2  * jmemmgr.c
3  *
4  * Copyright (C) 1991-1994, 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 #include "jmemsys.h"		/* import the system-dependent declarations */
32 
33 #ifndef NO_GETENV
34 #ifndef HAVE_STDLIB_H		/* <stdlib.h> should declare getenv() */
35 extern char * getenv JPP((const char * name));
36 #endif
37 #endif
38 
39 
40 /*
41  * Some important notes:
42  *   The allocation routines provided here must never return NULL.
43  *   They should exit to error_exit if unsuccessful.
44  *
45  *   It's not a good idea to try to merge the sarray and barray routines,
46  *   even though they are textually almost the same, because samples are
47  *   usually stored as bytes while coefficients are shorts or ints.  Thus,
48  *   in machines where byte pointers have a different representation from
49  *   word pointers, the resulting machine code could not be the same.
50  */
51 
52 
53 /*
54  * Many machines require storage alignment: longs must start on 4-byte
55  * boundaries, doubles on 8-byte boundaries, etc.  On such machines, malloc()
56  * always returns pointers that are multiples of the worst-case alignment
57  * requirement, and we had better do so too.
58  * There isn't any really portable way to determine the worst-case alignment
59  * requirement.  This module assumes that the alignment requirement is
60  * multiples of sizeof(ALIGN_TYPE).
61  * By default, we define ALIGN_TYPE as double.  This is necessary on some
62  * workstations (where doubles really do need 8-byte alignment) and will work
63  * fine on nearly everything.  If your machine has lesser alignment needs,
64  * you can save a few bytes by making ALIGN_TYPE smaller.
65  * The only place I know of where this will NOT work is certain Macintosh
66  * 680x0 compilers that define double as a 10-byte IEEE extended float.
67  * Doing 10-byte alignment is counterproductive because longwords won't be
68  * aligned well.  Put "#define ALIGN_TYPE long" in jconfig.h if you have
69  * such a compiler.
70  */
71 
72 #ifndef ALIGN_TYPE		/* so can override from jconfig.h */
73 #define ALIGN_TYPE  double
74 #endif
75 
76 
77 /*
78  * We allocate objects from "pools", where each pool is gotten with a single
79  * request to jpeg_get_small() or jpeg_get_large().  There is no per-object
80  * overhead within a pool, except for alignment padding.  Each pool has a
81  * header with a link to the next pool of the same class.
82  * Small and large pool headers are identical except that the latter's
83  * link pointer must be FAR on 80x86 machines.
84  * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
85  * field.  This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
86  * of the alignment requirement of ALIGN_TYPE.
87  */
88 
89 typedef union small_pool_struct * small_pool_ptr;
90 
91 typedef union small_pool_struct {
92   struct {
93     small_pool_ptr next;	/* next in list of pools */
94     size_t bytes_used;		/* how many bytes already used within pool */
95     size_t bytes_left;		/* bytes still available in this pool */
96   } hdr;
97   ALIGN_TYPE dummy;		/* included in union to ensure alignment */
98 } small_pool_hdr;
99 
100 typedef union large_pool_struct FAR * large_pool_ptr;
101 
102 typedef union large_pool_struct {
103   struct {
104     large_pool_ptr next;	/* next in list of pools */
105     size_t bytes_used;		/* how many bytes already used within pool */
106     size_t bytes_left;		/* bytes still available in this pool */
107   } hdr;
108   ALIGN_TYPE dummy;		/* included in union to ensure alignment */
109 } large_pool_hdr;
110 
111 
112 /*
113  * Here is the full definition of a memory manager object.
114  */
115 
116 typedef struct {
117   struct jpeg_memory_mgr pub;	/* public fields */
118 
119   /* Each pool identifier (lifetime class) names a linked list of pools. */
120   small_pool_ptr small_list[JPOOL_NUMPOOLS];
121   large_pool_ptr large_list[JPOOL_NUMPOOLS];
122 
123   /* Since we only have one lifetime class of virtual arrays, only one
124    * linked list is necessary (for each datatype).  Note that the virtual
125    * array control blocks being linked together are actually stored somewhere
126    * in the small-pool list.
127    */
128   jvirt_sarray_ptr virt_sarray_list;
129   jvirt_barray_ptr virt_barray_list;
130 
131   /* This counts total space obtained from jpeg_get_small/large */
132   long total_space_allocated;
133 
134   /* alloc_sarray and alloc_barray set this value for use by virtual
135    * array routines.
136    */
137   JDIMENSION last_rowsperchunk;	/* from most recent alloc_sarray/barray */
138 } my_memory_mgr;
139 
140 typedef my_memory_mgr * my_mem_ptr;
141 
142 
143 /*
144  * The control blocks for virtual arrays.
145  * Note that these blocks are allocated in the "small" pool area.
146  * System-dependent info for the associated backing store (if any) is hidden
147  * inside the backing_store_info struct.
148  */
149 
150 struct jvirt_sarray_control {
151   JSAMPARRAY mem_buffer;	/* => the in-memory buffer */
152   JDIMENSION rows_in_array;	/* total virtual array height */
153   JDIMENSION samplesperrow;	/* width of array (and of memory buffer) */
154   JDIMENSION unitheight;	/* # of rows accessed by access_virt_sarray */
155   JDIMENSION rows_in_mem;	/* height of memory buffer */
156   JDIMENSION rowsperchunk;	/* allocation chunk size in mem_buffer */
157   JDIMENSION cur_start_row;	/* first logical row # in the buffer */
158   boolean dirty;		/* do current buffer contents need written? */
159   boolean b_s_open;		/* is backing-store data valid? */
160   jvirt_sarray_ptr next;	/* link to next virtual sarray control block */
161   backing_store_info b_s_info;	/* System-dependent control info */
162 };
163 
164 struct jvirt_barray_control {
165   JBLOCKARRAY mem_buffer;	/* => the in-memory buffer */
166   JDIMENSION rows_in_array;	/* total virtual array height */
167   JDIMENSION blocksperrow;	/* width of array (and of memory buffer) */
168   JDIMENSION unitheight;	/* # of rows accessed by access_virt_barray */
169   JDIMENSION rows_in_mem;	/* height of memory buffer */
170   JDIMENSION rowsperchunk;	/* allocation chunk size in mem_buffer */
171   JDIMENSION cur_start_row;	/* first logical row # in the buffer */
172   boolean dirty;		/* do current buffer contents need written? */
173   boolean b_s_open;		/* is backing-store data valid? */
174   jvirt_barray_ptr next;	/* link to next virtual barray control block */
175   backing_store_info b_s_info;	/* System-dependent control info */
176 };
177 
178 
179 #ifdef MEM_STATS		/* optional extra stuff for statistics */
180 
181 LOCAL void
print_mem_stats(j_common_ptr cinfo,int pool_id)182 print_mem_stats (j_common_ptr cinfo, int pool_id)
183 {
184   my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
185   small_pool_ptr shdr_ptr;
186   large_pool_ptr lhdr_ptr;
187 
188   /* Since this is only a debugging stub, we can cheat a little by using
189    * fprintf directly rather than going through the trace message code.
190    * This is helpful because message parm array can't handle longs.
191    */
192   fprintf(stderr, "Freeing pool %d, total space = %ld\n",
193 	  pool_id, mem->total_space_allocated);
194 
195   for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
196        lhdr_ptr = lhdr_ptr->hdr.next) {
197     fprintf(stderr, "  Large chunk used %ld\n",
198 	    (long) lhdr_ptr->hdr.bytes_used);
199   }
200 
201   for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
202        shdr_ptr = shdr_ptr->hdr.next) {
203     fprintf(stderr, "  Small chunk used %ld free %ld\n",
204 	    (long) shdr_ptr->hdr.bytes_used,
205 	    (long) shdr_ptr->hdr.bytes_left);
206   }
207 }
208 
209 #endif /* MEM_STATS */
210 
211 
212 LOCAL void
out_of_memory(j_common_ptr cinfo,int which)213 out_of_memory (j_common_ptr cinfo, int which)
214 /* Report an out-of-memory error and stop execution */
215 /* If we compiled MEM_STATS support, report alloc requests before dying */
216 {
217 #ifdef MEM_STATS
218   cinfo->err->trace_level = 2;	/* force self_destruct to report stats */
219 #endif
220   ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
221 }
222 
223 
224 /*
225  * Allocation of "small" objects.
226  *
227  * For these, we use pooled storage.  When a new pool must be created,
228  * we try to get enough space for the current request plus a "slop" factor,
229  * where the slop will be the amount of leftover space in the new pool.
230  * The speed vs. space tradeoff is largely determined by the slop values.
231  * A different slop value is provided for each pool class (lifetime),
232  * and we also distinguish the first pool of a class from later ones.
233  * NOTE: the values given work fairly well on both 16- and 32-bit-int
234  * machines, but may be too small if longs are 64 bits or more.
235  */
236 
237 static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
238 {
239 	1600,			/* first PERMANENT pool */
240 	16000			/* first IMAGE pool */
241 };
242 
243 static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
244 {
245 	0,			/* additional PERMANENT pools */
246 	5000			/* additional IMAGE pools */
247 };
248 
249 #define MIN_SLOP  50		/* greater than 0 to avoid futile looping */
250 
251 
252 METHODDEF void *
alloc_small(j_common_ptr cinfo,int pool_id,size_t sizeofobject)253 alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
254 /* Allocate a "small" object */
255 {
256   my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
257   small_pool_ptr hdr_ptr, prev_hdr_ptr;
258   char * data_ptr;
259   size_t odd_bytes, min_request, slop;
260 
261   /* Check for unsatisfiable request (do now to ensure no overflow below) */
262   if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
263     out_of_memory(cinfo, 1);	/* request exceeds malloc's ability */
264 
265   /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
266   odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
267   if (odd_bytes > 0)
268     sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
269 
270   /* See if space is available in any existing pool */
271   if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
272     ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
273   prev_hdr_ptr = NULL;
274   hdr_ptr = mem->small_list[pool_id];
275   while (hdr_ptr != NULL) {
276     if (hdr_ptr->hdr.bytes_left >= sizeofobject)
277       break;			/* found pool with enough space */
278     prev_hdr_ptr = hdr_ptr;
279     hdr_ptr = hdr_ptr->hdr.next;
280   }
281 
282   /* Time to make a new pool? */
283   if (hdr_ptr == NULL) {
284     /* min_request is what we need now, slop is what will be leftover */
285     min_request = sizeofobject + SIZEOF(small_pool_hdr);
286     if (prev_hdr_ptr == NULL)	/* first pool in class? */
287       slop = first_pool_slop[pool_id];
288     else
289       slop = extra_pool_slop[pool_id];
290     /* Don't ask for more than MAX_ALLOC_CHUNK */
291     if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
292       slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
293     /* Try to get space, if fail reduce slop and try again */
294     for (;;) {
295       hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
296       if (hdr_ptr != NULL)
297 	break;
298       slop /= 2;
299       if (slop < MIN_SLOP)	/* give up when it gets real small */
300 	out_of_memory(cinfo, 2); /* jpeg_get_small failed */
301     }
302     mem->total_space_allocated += min_request + slop;
303     /* Success, initialize the new pool header and add to end of list */
304     hdr_ptr->hdr.next = NULL;
305     hdr_ptr->hdr.bytes_used = 0;
306     hdr_ptr->hdr.bytes_left = sizeofobject + slop;
307     if (prev_hdr_ptr == NULL)	/* first pool in class? */
308       mem->small_list[pool_id] = hdr_ptr;
309     else
310       prev_hdr_ptr->hdr.next = hdr_ptr;
311   }
312 
313   /* OK, allocate the object from the current pool */
314   data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
315   data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
316   hdr_ptr->hdr.bytes_used += sizeofobject;
317   hdr_ptr->hdr.bytes_left -= sizeofobject;
318 
319   return (void *) data_ptr;
320 }
321 
322 
323 /*
324  * Allocation of "large" objects.
325  *
326  * The external semantics of these are the same as "small" objects,
327  * except that FAR pointers are used on 80x86.  However the pool
328  * management heuristics are quite different.  We assume that each
329  * request is large enough that it may as well be passed directly to
330  * jpeg_get_large; the pool management just links everything together
331  * so that we can free it all on demand.
332  * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
333  * structures.  The routines that create these structures (see below)
334  * deliberately bunch rows together to ensure a large request size.
335  */
336 
337 METHODDEF void FAR *
alloc_large(j_common_ptr cinfo,int pool_id,size_t sizeofobject)338 alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
339 /* Allocate a "large" object */
340 {
341   my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
342   large_pool_ptr hdr_ptr;
343   size_t odd_bytes;
344 
345   /* Check for unsatisfiable request (do now to ensure no overflow below) */
346   if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
347     out_of_memory(cinfo, 3);	/* request exceeds malloc's ability */
348 
349   /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
350   odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
351   if (odd_bytes > 0)
352     sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
353 
354   /* Always make a new pool */
355   if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
356     ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
357 
358   hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
359 					    SIZEOF(large_pool_hdr));
360   if (hdr_ptr == NULL)
361     out_of_memory(cinfo, 4);	/* jpeg_get_large failed */
362   mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
363 
364   /* Success, initialize the new pool header and add to list */
365   hdr_ptr->hdr.next = mem->large_list[pool_id];
366   /* We maintain space counts in each pool header for statistical purposes,
367    * even though they are not needed for allocation.
368    */
369   hdr_ptr->hdr.bytes_used = sizeofobject;
370   hdr_ptr->hdr.bytes_left = 0;
371   mem->large_list[pool_id] = hdr_ptr;
372 
373   return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
374 }
375 
376 
377 /*
378  * Creation of 2-D sample arrays.
379  * The pointers are in near heap, the samples themselves in FAR heap.
380  *
381  * To minimize allocation overhead and to allow I/O of large contiguous
382  * blocks, we allocate the sample rows in groups of as many rows as possible
383  * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
384  * NB: the virtual array control routines, later in this file, know about
385  * this chunking of rows.  The rowsperchunk value is left in the mem manager
386  * object so that it can be saved away if this sarray is the workspace for
387  * a virtual array.
388  */
389 
390 METHODDEF JSAMPARRAY
alloc_sarray(j_common_ptr cinfo,int pool_id,JDIMENSION samplesperrow,JDIMENSION numrows)391 alloc_sarray (j_common_ptr cinfo, int pool_id,
392 	      JDIMENSION samplesperrow, JDIMENSION numrows)
393 /* Allocate a 2-D sample array */
394 {
395   my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
396   JSAMPARRAY result;
397   JSAMPROW workspace;
398   JDIMENSION rowsperchunk, currow, i;
399   long ltemp;
400 
401   /* Calculate max # of rows allowed in one allocation chunk */
402   ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
403 	  ((long) samplesperrow * SIZEOF(JSAMPLE));
404   if (ltemp <= 0)
405     ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
406   if (ltemp < (long) numrows)
407     rowsperchunk = (JDIMENSION) ltemp;
408   else
409     rowsperchunk = numrows;
410   mem->last_rowsperchunk = rowsperchunk;
411 
412   /* Get space for row pointers (small object) */
413   result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
414 				    (size_t) (numrows * SIZEOF(JSAMPROW)));
415 
416   /* Get the rows themselves (large objects) */
417   currow = 0;
418   while (currow < numrows) {
419     rowsperchunk = MIN(rowsperchunk, numrows - currow);
420     workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
421 	(size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
422 		  * SIZEOF(JSAMPLE)));
423     for (i = rowsperchunk; i > 0; i--) {
424       result[currow++] = workspace;
425       workspace += samplesperrow;
426     }
427   }
428 
429   return result;
430 }
431 
432 
433 /*
434  * Creation of 2-D coefficient-block arrays.
435  * This is essentially the same as the code for sample arrays, above.
436  */
437 
438 METHODDEF JBLOCKARRAY
alloc_barray(j_common_ptr cinfo,int pool_id,JDIMENSION blocksperrow,JDIMENSION numrows)439 alloc_barray (j_common_ptr cinfo, int pool_id,
440 	      JDIMENSION blocksperrow, JDIMENSION numrows)
441 /* Allocate a 2-D coefficient-block array */
442 {
443   my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
444   JBLOCKARRAY result;
445   JBLOCKROW workspace;
446   JDIMENSION rowsperchunk, currow, i;
447   long ltemp;
448 
449   /* Calculate max # of rows allowed in one allocation chunk */
450   ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
451 	  ((long) blocksperrow * SIZEOF(JBLOCK));
452   if (ltemp <= 0)
453     ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
454   if (ltemp < (long) numrows)
455     rowsperchunk = (JDIMENSION) ltemp;
456   else
457     rowsperchunk = numrows;
458   mem->last_rowsperchunk = rowsperchunk;
459 
460   /* Get space for row pointers (small object) */
461   result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
462 				     (size_t) (numrows * SIZEOF(JBLOCKROW)));
463 
464   /* Get the rows themselves (large objects) */
465   currow = 0;
466   while (currow < numrows) {
467     rowsperchunk = MIN(rowsperchunk, numrows - currow);
468     workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
469 	(size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
470 		  * SIZEOF(JBLOCK)));
471     for (i = rowsperchunk; i > 0; i--) {
472       result[currow++] = workspace;
473       workspace += blocksperrow;
474     }
475   }
476 
477   return result;
478 }
479 
480 
481 /*
482  * About virtual array management:
483  *
484  * To allow machines with limited memory to handle large images, all
485  * processing in the JPEG system is done a few pixel or block rows at a time.
486  * The above "normal" array routines are only used to allocate strip buffers
487  * (as wide as the image, but just a few rows high).
488  * In some cases multiple passes must be made over the data.  In these
489  * cases the virtual array routines are used.  The array is still accessed
490  * a strip at a time, but the memory manager must save the whole array
491  * for repeated accesses.  The intended implementation is that there is
492  * a strip buffer in memory (as high as is possible given the desired memory
493  * limit), plus a backing file that holds the rest of the array.
494  *
495  * The request_virt_array routines are told the total size of the image and
496  * the unit height, which is the number of rows that will be accessed at once;
497  * the in-memory buffer should be made a multiple of this height for best
498  * efficiency.
499  *
500  * The request routines create control blocks but not the in-memory buffers.
501  * That is postponed until realize_virt_arrays is called.  At that time the
502  * total amount of space needed is known (approximately, anyway), so free
503  * memory can be divided up fairly.
504  *
505  * The access_virt_array routines are responsible for making a specific strip
506  * area accessible (after reading or writing the backing file, if necessary).
507  * Note that the access routines are told whether the caller intends to modify
508  * the accessed strip; during a read-only pass this saves having to rewrite
509  * data to disk.
510  *
511  * The typical access pattern is one top-to-bottom pass to write the data,
512  * followed by one or more read-only top-to-bottom passes.  However, other
513  * access patterns may occur while reading.  For example, translation of image
514  * formats that use bottom-to-top scan order will require bottom-to-top read
515  * passes.  The memory manager need not support multiple write passes nor
516  * funny write orders (meaning that rearranging rows must be handled while
517  * reading data out of the virtual array, not while putting it in).  THIS WILL
518  * PROBABLY NEED TO CHANGE ... will need multiple write passes for progressive
519  * JPEG decoding.
520  *
521  * In current usage, the access requests are always for nonoverlapping strips;
522  * that is, successive access start_row numbers always differ by exactly the
523  * unitheight.  This allows fairly simple buffer dump/reload logic if the
524  * in-memory buffer is made a multiple of the unitheight.  The code below
525  * would work with overlapping access requests, but not very efficiently.
526  */
527 
528 
529 METHODDEF jvirt_sarray_ptr
request_virt_sarray(j_common_ptr cinfo,int pool_id,JDIMENSION samplesperrow,JDIMENSION numrows,JDIMENSION unitheight)530 request_virt_sarray (j_common_ptr cinfo, int pool_id,
531 		     JDIMENSION samplesperrow, JDIMENSION numrows,
532 		     JDIMENSION unitheight)
533 /* Request a virtual 2-D sample array */
534 {
535   my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
536   jvirt_sarray_ptr result;
537 
538   /* Only IMAGE-lifetime virtual arrays are currently supported */
539   if (pool_id != JPOOL_IMAGE)
540     ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
541 
542   /* Round array size up to a multiple of unitheight */
543   numrows = (JDIMENSION) jround_up((long) numrows, (long) unitheight);
544 
545   /* get control block */
546   result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
547 					  SIZEOF(struct jvirt_sarray_control));
548 
549   result->mem_buffer = NULL;	/* marks array not yet realized */
550   result->rows_in_array = numrows;
551   result->samplesperrow = samplesperrow;
552   result->unitheight = unitheight;
553   result->b_s_open = FALSE;	/* no associated backing-store object */
554   result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
555   mem->virt_sarray_list = result;
556 
557   return result;
558 }
559 
560 
561 METHODDEF jvirt_barray_ptr
request_virt_barray(j_common_ptr cinfo,int pool_id,JDIMENSION blocksperrow,JDIMENSION numrows,JDIMENSION unitheight)562 request_virt_barray (j_common_ptr cinfo, int pool_id,
563 		     JDIMENSION blocksperrow, JDIMENSION numrows,
564 		     JDIMENSION unitheight)
565 /* Request a virtual 2-D coefficient-block array */
566 {
567   my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
568   jvirt_barray_ptr result;
569 
570   /* Only IMAGE-lifetime virtual arrays are currently supported */
571   if (pool_id != JPOOL_IMAGE)
572     ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
573 
574   /* Round array size up to a multiple of unitheight */
575   numrows = (JDIMENSION) jround_up((long) numrows, (long) unitheight);
576 
577   /* get control block */
578   result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
579 					  SIZEOF(struct jvirt_barray_control));
580 
581   result->mem_buffer = NULL;	/* marks array not yet realized */
582   result->rows_in_array = numrows;
583   result->blocksperrow = blocksperrow;
584   result->unitheight = unitheight;
585   result->b_s_open = FALSE;	/* no associated backing-store object */
586   result->next = mem->virt_barray_list; /* add to list of virtual arrays */
587   mem->virt_barray_list = result;
588 
589   return result;
590 }
591 
592 
593 METHODDEF void
realize_virt_arrays(j_common_ptr cinfo)594 realize_virt_arrays (j_common_ptr cinfo)
595 /* Allocate the in-memory buffers for any unrealized virtual arrays */
596 {
597   my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
598   long space_per_unitheight, maximum_space, avail_mem;
599   long unitheights, max_unitheights;
600   jvirt_sarray_ptr sptr;
601   jvirt_barray_ptr bptr;
602 
603   /* Compute the minimum space needed (unitheight rows in each buffer)
604    * and the maximum space needed (full image height in each buffer).
605    * These may be of use to the system-dependent jpeg_mem_available routine.
606    */
607   space_per_unitheight = 0;
608   maximum_space = 0;
609   for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
610     if (sptr->mem_buffer == NULL) { /* if not realized yet */
611       space_per_unitheight += (long) sptr->unitheight *
612 			      (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
613       maximum_space += (long) sptr->rows_in_array *
614 		       (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
615     }
616   }
617   for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
618     if (bptr->mem_buffer == NULL) { /* if not realized yet */
619       space_per_unitheight += (long) bptr->unitheight *
620 			      (long) bptr->blocksperrow * SIZEOF(JBLOCK);
621       maximum_space += (long) bptr->rows_in_array *
622 		       (long) bptr->blocksperrow * SIZEOF(JBLOCK);
623     }
624   }
625 
626   if (space_per_unitheight <= 0)
627     return;			/* no unrealized arrays, no work */
628 
629   /* Determine amount of memory to actually use; this is system-dependent. */
630   avail_mem = jpeg_mem_available(cinfo, space_per_unitheight, maximum_space,
631 				 mem->total_space_allocated);
632 
633   /* If the maximum space needed is available, make all the buffers full
634    * height; otherwise parcel it out with the same number of unitheights
635    * in each buffer.
636    */
637   if (avail_mem >= maximum_space)
638     max_unitheights = 1000000000L;
639   else {
640     max_unitheights = avail_mem / space_per_unitheight;
641     /* If there doesn't seem to be enough space, try to get the minimum
642      * anyway.  This allows a "stub" implementation of jpeg_mem_available().
643      */
644     if (max_unitheights <= 0)
645       max_unitheights = 1;
646   }
647 
648   /* Allocate the in-memory buffers and initialize backing store as needed. */
649 
650   for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
651     if (sptr->mem_buffer == NULL) { /* if not realized yet */
652       unitheights = ((long) sptr->rows_in_array - 1L) / sptr->unitheight + 1L;
653       if (unitheights <= max_unitheights) {
654 	/* This buffer fits in memory */
655 	sptr->rows_in_mem = sptr->rows_in_array;
656       } else {
657 	/* It doesn't fit in memory, create backing store. */
658 	sptr->rows_in_mem = (JDIMENSION) (max_unitheights * sptr->unitheight);
659 	jpeg_open_backing_store(cinfo, & sptr->b_s_info,
660 				(long) sptr->rows_in_array *
661 				(long) sptr->samplesperrow *
662 				(long) SIZEOF(JSAMPLE));
663 	sptr->b_s_open = TRUE;
664       }
665       sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
666 				      sptr->samplesperrow, sptr->rows_in_mem);
667       sptr->rowsperchunk = mem->last_rowsperchunk;
668       sptr->cur_start_row = 0;
669       sptr->dirty = FALSE;
670     }
671   }
672 
673   for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
674     if (bptr->mem_buffer == NULL) { /* if not realized yet */
675       unitheights = ((long) bptr->rows_in_array - 1L) / bptr->unitheight + 1L;
676       if (unitheights <= max_unitheights) {
677 	/* This buffer fits in memory */
678 	bptr->rows_in_mem = bptr->rows_in_array;
679       } else {
680 	/* It doesn't fit in memory, create backing store. */
681 	bptr->rows_in_mem = (JDIMENSION) (max_unitheights * bptr->unitheight);
682 	jpeg_open_backing_store(cinfo, & bptr->b_s_info,
683 				(long) bptr->rows_in_array *
684 				(long) bptr->blocksperrow *
685 				(long) SIZEOF(JBLOCK));
686 	bptr->b_s_open = TRUE;
687       }
688       bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
689 				      bptr->blocksperrow, bptr->rows_in_mem);
690       bptr->rowsperchunk = mem->last_rowsperchunk;
691       bptr->cur_start_row = 0;
692       bptr->dirty = FALSE;
693     }
694   }
695 }
696 
697 
698 LOCAL void
do_sarray_io(j_common_ptr cinfo,jvirt_sarray_ptr ptr,boolean writing)699 do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
700 /* Do backing store read or write of a virtual sample array */
701 {
702   long bytesperrow, file_offset, byte_count, rows, i;
703 
704   bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
705   file_offset = ptr->cur_start_row * bytesperrow;
706   /* Loop to read or write each allocation chunk in mem_buffer */
707   for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
708     /* One chunk, but check for short chunk at end of buffer */
709     rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
710     /* Transfer no more than fits in file */
711     rows = MIN(rows, (long) ptr->rows_in_array -
712 		    ((long) ptr->cur_start_row + i));
713     if (rows <= 0)		/* this chunk might be past end of file! */
714       break;
715     byte_count = rows * bytesperrow;
716     if (writing)
717       (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
718 					    (void FAR *) ptr->mem_buffer[i],
719 					    file_offset, byte_count);
720     else
721       (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
722 					   (void FAR *) ptr->mem_buffer[i],
723 					   file_offset, byte_count);
724     file_offset += byte_count;
725   }
726 }
727 
728 
729 LOCAL void
do_barray_io(j_common_ptr cinfo,jvirt_barray_ptr ptr,boolean writing)730 do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
731 /* Do backing store read or write of a virtual coefficient-block array */
732 {
733   long bytesperrow, file_offset, byte_count, rows, i;
734 
735   bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
736   file_offset = ptr->cur_start_row * bytesperrow;
737   /* Loop to read or write each allocation chunk in mem_buffer */
738   for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
739     /* One chunk, but check for short chunk at end of buffer */
740     rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
741     /* Transfer no more than fits in file */
742     rows = MIN(rows, (long) ptr->rows_in_array -
743 		    ((long) ptr->cur_start_row + i));
744     if (rows <= 0)		/* this chunk might be past end of file! */
745       break;
746     byte_count = rows * bytesperrow;
747     if (writing)
748       (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
749 					    (void FAR *) ptr->mem_buffer[i],
750 					    file_offset, byte_count);
751     else
752       (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
753 					   (void FAR *) ptr->mem_buffer[i],
754 					   file_offset, byte_count);
755     file_offset += byte_count;
756   }
757 }
758 
759 
760 METHODDEF JSAMPARRAY
access_virt_sarray(j_common_ptr cinfo,jvirt_sarray_ptr ptr,JDIMENSION start_row,boolean writable)761 access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
762 		    JDIMENSION start_row, boolean writable)
763 /* Access the part of a virtual sample array starting at start_row */
764 /* and extending for ptr->unitheight rows.  writable is true if  */
765 /* caller intends to modify the accessed area. */
766 {
767   /* debugging check */
768   if (start_row >= ptr->rows_in_array || ptr->mem_buffer == NULL)
769     ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
770 
771   /* Make the desired part of the virtual array accessible */
772   if (start_row < ptr->cur_start_row ||
773       start_row+ptr->unitheight > ptr->cur_start_row+ptr->rows_in_mem) {
774     if (! ptr->b_s_open)
775       ERREXIT(cinfo, JERR_VIRTUAL_BUG);
776     /* Flush old buffer contents if necessary */
777     if (ptr->dirty) {
778       do_sarray_io(cinfo, ptr, TRUE);
779       ptr->dirty = FALSE;
780     }
781     /* Decide what part of virtual array to access.
782      * Algorithm: if target address > current window, assume forward scan,
783      * load starting at target address.  If target address < current window,
784      * assume backward scan, load so that target area is top of window.
785      * Note that when switching from forward write to forward read, will have
786      * start_row = 0, so the limiting case applies and we load from 0 anyway.
787      */
788     if (start_row > ptr->cur_start_row) {
789       ptr->cur_start_row = start_row;
790     } else {
791       /* use long arithmetic here to avoid overflow & unsigned problems */
792       long ltemp;
793 
794       ltemp = (long) start_row + (long) ptr->unitheight -
795 	      (long) ptr->rows_in_mem;
796       if (ltemp < 0)
797 	ltemp = 0;		/* don't fall off front end of file */
798       ptr->cur_start_row = (JDIMENSION) ltemp;
799     }
800     /* If reading, read in the selected part of the array.
801      * If we are writing, we need not pre-read the selected portion,
802      * since the access sequence constraints ensure it would be garbage.
803      */
804     if (! writable) {
805       do_sarray_io(cinfo, ptr, FALSE);
806     }
807   }
808   /* Flag the buffer dirty if caller will write in it */
809   if (writable)
810     ptr->dirty = TRUE;
811   /* Return address of proper part of the buffer */
812   return ptr->mem_buffer + (start_row - ptr->cur_start_row);
813 }
814 
815 
816 METHODDEF JBLOCKARRAY
access_virt_barray(j_common_ptr cinfo,jvirt_barray_ptr ptr,JDIMENSION start_row,boolean writable)817 access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
818 		    JDIMENSION start_row, boolean writable)
819 /* Access the part of a virtual block array starting at start_row */
820 /* and extending for ptr->unitheight rows.  writable is true if  */
821 /* caller intends to modify the accessed area. */
822 {
823   /* debugging check */
824   if (start_row >= ptr->rows_in_array || ptr->mem_buffer == NULL)
825     ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
826 
827   /* Make the desired part of the virtual array accessible */
828   if (start_row < ptr->cur_start_row ||
829       start_row+ptr->unitheight > ptr->cur_start_row+ptr->rows_in_mem) {
830     if (! ptr->b_s_open)
831       ERREXIT(cinfo, JERR_VIRTUAL_BUG);
832     /* Flush old buffer contents if necessary */
833     if (ptr->dirty) {
834       do_barray_io(cinfo, ptr, TRUE);
835       ptr->dirty = FALSE;
836     }
837     /* Decide what part of virtual array to access.
838      * Algorithm: if target address > current window, assume forward scan,
839      * load starting at target address.  If target address < current window,
840      * assume backward scan, load so that target area is top of window.
841      * Note that when switching from forward write to forward read, will have
842      * start_row = 0, so the limiting case applies and we load from 0 anyway.
843      */
844     if (start_row > ptr->cur_start_row) {
845       ptr->cur_start_row = start_row;
846     } else {
847       /* use long arithmetic here to avoid overflow & unsigned problems */
848       long ltemp;
849 
850       ltemp = (long) start_row + (long) ptr->unitheight -
851 	      (long) ptr->rows_in_mem;
852       if (ltemp < 0)
853 	ltemp = 0;		/* don't fall off front end of file */
854       ptr->cur_start_row = (JDIMENSION) ltemp;
855     }
856     /* If reading, read in the selected part of the array.
857      * If we are writing, we need not pre-read the selected portion,
858      * since the access sequence constraints ensure it would be garbage.
859      */
860     if (! writable) {
861       do_barray_io(cinfo, ptr, FALSE);
862     }
863   }
864   /* Flag the buffer dirty if caller will write in it */
865   if (writable)
866     ptr->dirty = TRUE;
867   /* Return address of proper part of the buffer */
868   return ptr->mem_buffer + (start_row - ptr->cur_start_row);
869 }
870 
871 
872 /*
873  * Release all objects belonging to a specified pool.
874  */
875 
876 METHODDEF void
free_pool(j_common_ptr cinfo,int pool_id)877 free_pool (j_common_ptr cinfo, int pool_id)
878 {
879   my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
880   small_pool_ptr shdr_ptr;
881   large_pool_ptr lhdr_ptr;
882   size_t space_freed;
883 
884   if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
885     ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
886 
887 #ifdef MEM_STATS
888   if (cinfo->err->trace_level > 1)
889     print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
890 #endif
891 
892   /* If freeing IMAGE pool, close any virtual arrays first */
893   if (pool_id == JPOOL_IMAGE) {
894     jvirt_sarray_ptr sptr;
895     jvirt_barray_ptr bptr;
896 
897     for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
898       if (sptr->b_s_open) {	/* there may be no backing store */
899 	sptr->b_s_open = FALSE;	/* prevent recursive close if error */
900 	(*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
901       }
902     }
903     mem->virt_sarray_list = NULL;
904     for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
905       if (bptr->b_s_open) {	/* there may be no backing store */
906 	bptr->b_s_open = FALSE;	/* prevent recursive close if error */
907 	(*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
908       }
909     }
910     mem->virt_barray_list = NULL;
911   }
912 
913   /* Release large objects */
914   lhdr_ptr = mem->large_list[pool_id];
915   mem->large_list[pool_id] = NULL;
916 
917   while (lhdr_ptr != NULL) {
918     large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
919     space_freed = lhdr_ptr->hdr.bytes_used +
920 		  lhdr_ptr->hdr.bytes_left +
921 		  SIZEOF(large_pool_hdr);
922     jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
923     mem->total_space_allocated -= space_freed;
924     lhdr_ptr = next_lhdr_ptr;
925   }
926 
927   /* Release small objects */
928   shdr_ptr = mem->small_list[pool_id];
929   mem->small_list[pool_id] = NULL;
930 
931   while (shdr_ptr != NULL) {
932     small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
933     space_freed = shdr_ptr->hdr.bytes_used +
934 		  shdr_ptr->hdr.bytes_left +
935 		  SIZEOF(small_pool_hdr);
936     jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
937     mem->total_space_allocated -= space_freed;
938     shdr_ptr = next_shdr_ptr;
939   }
940 }
941 
942 
943 /*
944  * Close up shop entirely.
945  * Note that this cannot be called unless cinfo->mem is non-NULL.
946  */
947 
948 METHODDEF void
self_destruct(j_common_ptr cinfo)949 self_destruct (j_common_ptr cinfo)
950 {
951   int pool;
952 
953   /* Close all backing store, release all memory.
954    * Releasing pools in reverse order might help avoid fragmentation
955    * with some (brain-damaged) malloc libraries.
956    */
957   for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
958     free_pool(cinfo, pool);
959   }
960 
961   /* Release the memory manager control block too. */
962   jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
963   cinfo->mem = NULL;		/* ensures I will be called only once */
964 
965   jpeg_mem_term(cinfo);		/* system-dependent cleanup */
966 }
967 
968 
969 /*
970  * Memory manager initialization.
971  * When this is called, only the error manager pointer is valid in cinfo!
972  */
973 
974 GLOBAL void
jinit_memory_mgr(j_common_ptr cinfo)975 jinit_memory_mgr (j_common_ptr cinfo)
976 {
977   my_mem_ptr mem;
978   long max_to_use;
979   int pool;
980   size_t test_mac;
981 
982   cinfo->mem = NULL;		/* for safety if init fails */
983 
984   /* Check for configuration errors.
985    * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
986    * doesn't reflect any real hardware alignment requirement.
987    * The test is a little tricky: for X>0, X and X-1 have no one-bits
988    * in common if and only if X is a power of 2, ie has only one one-bit.
989    * Some compilers may give an "unreachable code" warning here; ignore it.
990    */
991   if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
992     ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
993   /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
994    * a multiple of SIZEOF(ALIGN_TYPE).
995    * Again, an "unreachable code" warning may be ignored here.
996    * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
997    */
998   test_mac = (size_t) MAX_ALLOC_CHUNK;
999   if ((long) test_mac != MAX_ALLOC_CHUNK ||
1000       (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
1001     ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
1002 
1003   max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
1004 
1005   /* Attempt to allocate memory manager's control block */
1006   mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
1007 
1008   if (mem == NULL) {
1009     jpeg_mem_term(cinfo);	/* system-dependent cleanup */
1010     ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
1011   }
1012 
1013   /* OK, fill in the method pointers */
1014   mem->pub.alloc_small = alloc_small;
1015   mem->pub.alloc_large = alloc_large;
1016   mem->pub.alloc_sarray = alloc_sarray;
1017   mem->pub.alloc_barray = alloc_barray;
1018   mem->pub.request_virt_sarray = request_virt_sarray;
1019   mem->pub.request_virt_barray = request_virt_barray;
1020   mem->pub.realize_virt_arrays = realize_virt_arrays;
1021   mem->pub.access_virt_sarray = access_virt_sarray;
1022   mem->pub.access_virt_barray = access_virt_barray;
1023   mem->pub.free_pool = free_pool;
1024   mem->pub.self_destruct = self_destruct;
1025 
1026   /* Initialize working state */
1027   mem->pub.max_memory_to_use = max_to_use;
1028 
1029   for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
1030     mem->small_list[pool] = NULL;
1031     mem->large_list[pool] = NULL;
1032   }
1033   mem->virt_sarray_list = NULL;
1034   mem->virt_barray_list = NULL;
1035 
1036   mem->total_space_allocated = SIZEOF(my_memory_mgr);
1037 
1038   /* Declare ourselves open for business */
1039   cinfo->mem = & mem->pub;
1040 
1041   /* Check for an environment variable JPEGMEM; if found, override the
1042    * default max_memory setting from jpeg_mem_init.  Note that the
1043    * surrounding application may again override this value.
1044    * If your system doesn't support getenv(), define NO_GETENV to disable
1045    * this feature.
1046    */
1047 #ifndef NO_GETENV
1048   { char * memenv;
1049 
1050     if ((memenv = getenv("JPEGMEM")) != NULL) {
1051       char ch = 'x';
1052 
1053       if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
1054 	if (ch == 'm' || ch == 'M')
1055 	  max_to_use *= 1000L;
1056 	mem->pub.max_memory_to_use = max_to_use * 1000L;
1057       }
1058     }
1059   }
1060 #endif
1061 
1062 }
1063