/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/*
*
* Copyright (C) 1991-1997, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains the JPEG system-independent memory management
* routines. This code is usable across a wide variety of machines; most
* of the system dependencies have been isolated in a separate file.
* The major functions provided here are:
* * pool-based allocation and freeing of memory;
* * policy decisions about how to divide available memory among the
* virtual arrays;
* * control logic for swapping virtual arrays between main memory and
* backing storage.
* The separate system-dependent file provides the actual backing-storage
* access code, and it contains the policy decision about how much total
* main memory to use.
* This file is system-dependent in the sense that some of its functions
* are unnecessary in some systems. For example, if there is enough virtual
* memory so that backing storage will never be used, much of the virtual
* array control logic could be removed. (Of course, if you have that much
* memory then you shouldn't care about a little bit of unused code...)
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
#include "jmemsys.h" /* import the system-dependent declarations */
#ifndef NO_GETENV
#ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
#endif
#endif
/*
* Some important notes:
* The allocation routines provided here must never return NULL.
* They should exit to error_exit if unsuccessful.
*
* It's not a good idea to try to merge the sarray and barray routines,
* even though they are textually almost the same, because samples are
* usually stored as bytes while coefficients are shorts or ints. Thus,
* in machines where byte pointers have a different representation from
* word pointers, the resulting machine code could not be the same.
*/
/*
* Many machines require storage alignment: longs must start on 4-byte
* boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
* always returns pointers that are multiples of the worst-case alignment
* requirement, and we had better do so too.
* There isn't any really portable way to determine the worst-case alignment
* requirement. This module assumes that the alignment requirement is
* multiples of sizeof(ALIGN_TYPE).
* By default, we define ALIGN_TYPE as double. This is necessary on some
* workstations (where doubles really do need 8-byte alignment) and will work
* fine on nearly everything. If your machine has lesser alignment needs,
* you can save a few bytes by making ALIGN_TYPE smaller.
* The only place I know of where this will NOT work is certain Macintosh
* 680x0 compilers that define double as a 10-byte IEEE extended float.
* Doing 10-byte alignment is counterproductive because longwords won't be
* aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
* such a compiler.
*/
#ifndef ALIGN_TYPE /* so can override from jconfig.h */
#define ALIGN_TYPE double
#endif
/*
* We allocate objects from "pools", where each pool is gotten with a single
* request to jpeg_get_small() or jpeg_get_large(). There is no per-object
* overhead within a pool, except for alignment padding. Each pool has a
* header with a link to the next pool of the same class.
* Small and large pool headers are identical except that the latter's
* link pointer must be FAR on 80x86 machines.
* Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
* field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
* of the alignment requirement of ALIGN_TYPE.
*/
typedef union small_pool_struct {
struct {
} hdr;
typedef union large_pool_struct {
struct {
} hdr;
/*
* Here is the full definition of a memory manager object.
*/
typedef struct {
/* Each pool identifier (lifetime class) names a linked list of pools. */
/* Since we only have one lifetime class of virtual arrays, only one
* linked list is necessary (for each datatype). Note that the virtual
* array control blocks being linked together are actually stored somewhere
* in the small-pool list.
*/
/* This counts total space obtained from jpeg_get_small/large */
/* alloc_sarray and alloc_barray set this value for use by virtual
* array routines.
*/
/*
* The control blocks for virtual arrays.
* Note that these blocks are allocated in the "small" pool area.
* System-dependent info for the associated backing store (if any) is hidden
* inside the backing_store_info struct.
*/
struct jvirt_sarray_control {
};
struct jvirt_barray_control {
};
#ifdef MEM_STATS /* optional extra stuff for statistics */
LOCAL(void)
{
/* Since this is only a debugging stub, we can cheat a little by using
* fprintf directly rather than going through the trace message code.
* This is helpful because message parm array can't handle longs.
*/
}
}
}
#endif /* MEM_STATS */
LOCAL(void)
/* Report an out-of-memory error and stop execution */
/* If we compiled MEM_STATS support, report alloc requests before dying */
{
#ifdef MEM_STATS
#endif
}
/*
* Allocation of "small" objects.
*
* For these, we use pooled storage. When a new pool must be created,
* we try to get enough space for the current request plus a "slop" factor,
* where the slop will be the amount of leftover space in the new pool.
* The speed vs. space tradeoff is largely determined by the slop values.
* A different slop value is provided for each pool class (lifetime),
* and we also distinguish the first pool of a class from later ones.
* NOTE: the values given work fairly well on both 16- and 32-bit-int
* machines, but may be too small if longs are 64 bits or more.
*/
{
1600, /* first PERMANENT pool */
16000 /* first IMAGE pool */
};
{
0, /* additional PERMANENT pools */
5000 /* additional IMAGE pools */
};
METHODDEF(void *)
/* Allocate a "small" object */
{
char * data_ptr;
/* Check for unsatisfiable request (do now to ensure no overflow below) */
/* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
if (odd_bytes > 0)
/* See if space is available in any existing pool */
prev_hdr_ptr = NULL;
break; /* found pool with enough space */
}
/* Time to make a new pool? */
/* min_request is what we need now, slop is what will be leftover */
else
/* Don't ask for more than MAX_ALLOC_CHUNK */
/* Try to get space, if fail reduce slop and try again */
for (;;) {
break;
slop /= 2;
}
/* Success, initialize the new pool header and add to end of list */
else
}
/* OK, allocate the object from the current pool */
return (void *) data_ptr;
}
/*
* Allocation of "large" objects.
*
* The external semantics of these are the same as "small" objects,
* except that FAR pointers are used on 80x86. However the pool
* management heuristics are quite different. We assume that each
* request is large enough that it may as well be passed directly to
* jpeg_get_large; the pool management just links everything together
* so that we can free it all on demand.
* Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
* structures. The routines that create these structures (see below)
* deliberately bunch rows together to ensure a large request size.
*/
/* Allocate a "large" object */
{
/* Check for unsatisfiable request (do now to ensure no overflow below) */
/* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
if (odd_bytes > 0)
/* Always make a new pool */
/* Success, initialize the new pool header and add to list */
/* We maintain space counts in each pool header for statistical purposes,
* even though they are not needed for allocation.
*/
}
/*
* Creation of 2-D sample arrays.
* The pointers are in near heap, the samples themselves in FAR heap.
*
* To minimize allocation overhead and to allow I/O of large contiguous
* blocks, we allocate the sample rows in groups of as many rows as possible
* without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
* NB: the virtual array control routines, later in this file, know about
* this chunking of rows. The rowsperchunk value is left in the mem manager
* object so that it can be saved away if this sarray is the workspace for
* a virtual array.
*/
/* Allocate a 2-D sample array */
{
long ltemp;
/* Calculate max # of rows allowed in one allocation chunk */
if (ltemp <= 0)
else
/* Get space for row pointers (small object) */
/* Get the rows themselves (large objects) */
currow = 0;
for (i = rowsperchunk; i > 0; i--) {
}
}
return result;
}
/*
* Creation of 2-D coefficient-block arrays.
* This is essentially the same as the code for sample arrays, above.
*/
/* Allocate a 2-D coefficient-block array */
{
long ltemp;
/* Calculate max # of rows allowed in one allocation chunk */
if (ltemp <= 0)
else
/* Get space for row pointers (small object) */
/* Get the rows themselves (large objects) */
currow = 0;
for (i = rowsperchunk; i > 0; i--) {
}
}
return result;
}
/*
* About virtual array management:
*
* The above "normal" array routines are only used to allocate strip buffers
* (as wide as the image, but just a few rows high). Full-image-sized buffers
* are handled as "virtual" arrays. The array is still accessed a strip at a
* time, but the memory manager must save the whole array for repeated
* accesses. The intended implementation is that there is a strip buffer in
* memory (as high as is possible given the desired memory limit), plus a
* backing file that holds the rest of the array.
*
* The request_virt_array routines are told the total size of the image and
* the maximum number of rows that will be accessed at once. The in-memory
* buffer must be at least as large as the maxaccess value.
*
* The request routines create control blocks but not the in-memory buffers.
* That is postponed until realize_virt_arrays is called. At that time the
* total amount of space needed is known (approximately, anyway), so free
* memory can be divided up fairly.
*
* The access_virt_array routines are responsible for making a specific strip
* area accessible (after reading or writing the backing file, if necessary).
* Note that the access routines are told whether the caller intends to modify
* the accessed strip; during a read-only pass this saves having to rewrite
* data to disk. The access routines are also responsible for pre-zeroing
* any newly accessed rows, if pre-zeroing was requested.
*
* In current usage, the access requests are usually for nonoverlapping
* strips; that is, successive access start_row numbers differ by exactly
* num_rows = maxaccess. This means we can get good performance with simple
* of the access height; then there will never be accesses across bufferload
* boundaries. The code will still work with overlapping access requests,
* but it doesn't handle bufferload overlaps very efficiently.
*/
/* Request a virtual 2-D sample array */
{
/* Only IMAGE-lifetime virtual arrays are currently supported */
if (pool_id != JPOOL_IMAGE)
/* get control block */
SIZEOF(struct jvirt_sarray_control));
return result;
}
/* Request a virtual 2-D coefficient-block array */
{
/* Only IMAGE-lifetime virtual arrays are currently supported */
if (pool_id != JPOOL_IMAGE)
/* get control block */
SIZEOF(struct jvirt_barray_control));
return result;
}
METHODDEF(void)
/* Allocate the in-memory buffers for any unrealized virtual arrays */
{
/* Compute the minimum space needed (maxaccess rows in each buffer)
* and the maximum space needed (full image height in each buffer).
* These may be of use to the system-dependent jpeg_mem_available routine.
*/
space_per_minheight = 0;
maximum_space = 0;
}
}
}
}
if (space_per_minheight <= 0)
return; /* no unrealized arrays, no work */
/* Determine amount of memory to actually use; this is system-dependent. */
/* If the maximum space needed is available, make all the buffers full
* height; otherwise parcel it out with the same number of minheights
* in each buffer.
*/
if (avail_mem >= maximum_space)
max_minheights = 1000000000L;
else {
/* If there doesn't seem to be enough space, try to get the minimum
* anyway. This allows a "stub" implementation of jpeg_mem_available().
*/
if (max_minheights <= 0)
max_minheights = 1;
}
/* Allocate the in-memory buffers and initialize backing store as needed. */
if (minheights <= max_minheights) {
/* This buffer fits in memory */
} else {
/* It doesn't fit in memory, create backing store. */
(long) sptr->rows_in_array *
(long) sptr->samplesperrow *
}
sptr->cur_start_row = 0;
sptr->first_undef_row = 0;
}
}
if (minheights <= max_minheights) {
/* This buffer fits in memory */
} else {
/* It doesn't fit in memory, create backing store. */
(long) bptr->rows_in_array *
(long) bptr->blocksperrow *
}
bptr->cur_start_row = 0;
bptr->first_undef_row = 0;
}
}
}
LOCAL(void)
/* Do backing store read or write of a virtual sample array */
{
/* Loop to read or write each allocation chunk in mem_buffer */
/* One chunk, but check for short chunk at end of buffer */
/* Transfer no more than is currently defined */
/* Transfer no more than fits in file */
if (rows <= 0) /* this chunk might be past end of file! */
break;
if (writing)
else
}
}
LOCAL(void)
/* Do backing store read or write of a virtual coefficient-block array */
{
/* Loop to read or write each allocation chunk in mem_buffer */
/* One chunk, but check for short chunk at end of buffer */
/* Transfer no more than is currently defined */
/* Transfer no more than fits in file */
if (rows <= 0) /* this chunk might be past end of file! */
break;
if (writing)
else
}
}
/* Access the part of a virtual sample array starting at start_row */
/* and extending for num_rows rows. writable is true if */
/* caller intends to modify the accessed area. */
{
/* debugging check */
/* Make the desired part of the virtual array accessible */
/* Flush old buffer contents if necessary */
}
/* Decide what part of virtual array to access.
* Algorithm: if target address > current window, assume forward scan,
* load starting at target address. If target address < current window,
* assume backward scan, load so that target area is top of window.
* Note that when switching from forward write to forward read, will have
* start_row = 0, so the limiting case applies and we load from 0 anyway.
*/
} else {
/* use long arithmetic here to avoid overflow & unsigned problems */
long ltemp;
if (ltemp < 0)
ltemp = 0; /* don't fall off front end of file */
}
/* Read in the selected part of the array.
* During the initial write pass, we will do no actual read
* because the selected part is all undefined.
*/
}
/* Ensure the accessed part of the array is defined; prezero if needed.
* To improve locality of access, we only prezero the part of the array
* that the caller is about to access, not the entire in-memory array.
*/
if (writable) /* writer skipped over a section of array */
} else {
}
if (writable)
undef_row++;
}
} else {
if (! writable) /* reader looking at undefined data */
}
}
/* Flag the buffer dirty if caller will write in it */
if (writable)
/* Return address of proper part of the buffer */
}
/* Access the part of a virtual block array starting at start_row */
/* and extending for num_rows rows. writable is true if */
/* caller intends to modify the accessed area. */
{
/* debugging check */
/* Make the desired part of the virtual array accessible */
/* Flush old buffer contents if necessary */
}
/* Decide what part of virtual array to access.
* Algorithm: if target address > current window, assume forward scan,
* load starting at target address. If target address < current window,
* assume backward scan, load so that target area is top of window.
* Note that when switching from forward write to forward read, will have
* start_row = 0, so the limiting case applies and we load from 0 anyway.
*/
} else {
/* use long arithmetic here to avoid overflow & unsigned problems */
long ltemp;
if (ltemp < 0)
ltemp = 0; /* don't fall off front end of file */
}
/* Read in the selected part of the array.
* During the initial write pass, we will do no actual read
* because the selected part is all undefined.
*/
}
/* Ensure the accessed part of the array is defined; prezero if needed.
* To improve locality of access, we only prezero the part of the array
* that the caller is about to access, not the entire in-memory array.
*/
if (writable) /* writer skipped over a section of array */
} else {
}
if (writable)
undef_row++;
}
} else {
if (! writable) /* reader looking at undefined data */
}
}
/* Flag the buffer dirty if caller will write in it */
if (writable)
/* Return address of proper part of the buffer */
}
/*
* Release all objects belonging to a specified pool.
*/
METHODDEF(void)
{
#ifdef MEM_STATS
#endif
/* If freeing IMAGE pool, close any virtual arrays first */
if (pool_id == JPOOL_IMAGE) {
}
}
}
}
}
/* Release large objects */
}
/* Release small objects */
}
}
/*
* Close up shop entirely.
* Note that this cannot be called unless cinfo->mem is non-NULL.
*/
METHODDEF(void)
{
int pool;
/* Close all backing store, release all memory.
* Releasing pools in reverse order might help avoid fragmentation
* with some (brain-damaged) malloc libraries.
*/
}
/* Release the memory manager control block too. */
}
/*
* Memory manager initialization.
* When this is called, only the error manager pointer is valid in cinfo!
*/
GLOBAL(void)
{
int pool;
/* Check for configuration errors.
* SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
* doesn't reflect any real hardware alignment requirement.
* The test is a little tricky: for X>0, X and X-1 have no one-bits
* in common if and only if X is a power of 2, ie has only one one-bit.
* Some compilers may give an "unreachable code" warning here; ignore it.
*/
/* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
* a multiple of SIZEOF(ALIGN_TYPE).
* Again, an "unreachable code" warning may be ignored here.
* But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
*/
if ((long) test_mac != MAX_ALLOC_CHUNK ||
/* Attempt to allocate memory manager's control block */
}
/* OK, fill in the method pointers */
/* Make MAX_ALLOC_CHUNK accessible to other modules */
/* Initialize working state */
}
/* Declare ourselves open for business */
/* Check for an environment variable JPEGMEM; if found, override the
* default max_memory setting from jpeg_mem_init. Note that the
* surrounding application may again override this value.
* If your system doesn't support getenv(), define NO_GETENV to disable
* this feature.
*/
#ifndef NO_GETENV
{ char * memenv;
unsigned int mem_max = 0u;
max_to_use *= 1000L;
}
}
}
#endif
}