Path: blob/master/src/java.desktop/share/native/libjavajpeg/jmemmgr.c
41149 views
/*1* reserved comment block2* DO NOT REMOVE OR ALTER!3*/4/*5* jmemmgr.c6*7* Copyright (C) 1991-1997, Thomas G. Lane.8* This file is part of the Independent JPEG Group's software.9* For conditions of distribution and use, see the accompanying README file.10*11* This file contains the JPEG system-independent memory management12* routines. This code is usable across a wide variety of machines; most13* of the system dependencies have been isolated in a separate file.14* The major functions provided here are:15* * pool-based allocation and freeing of memory;16* * policy decisions about how to divide available memory among the17* virtual arrays;18* * control logic for swapping virtual arrays between main memory and19* backing storage.20* The separate system-dependent file provides the actual backing-storage21* access code, and it contains the policy decision about how much total22* main memory to use.23* This file is system-dependent in the sense that some of its functions24* are unnecessary in some systems. For example, if there is enough virtual25* memory so that backing storage will never be used, much of the virtual26* array control logic could be removed. (Of course, if you have that much27* memory then you shouldn't care about a little bit of unused code...)28*/2930#define JPEG_INTERNALS31#define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */32#include "jinclude.h"33#include "jpeglib.h"34#include "jmemsys.h" /* import the system-dependent declarations */3536#ifndef NO_GETENV37#ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */38extern char * getenv JPP((const char * name));39#endif40#endif414243/*44* Some important notes:45* The allocation routines provided here must never return NULL.46* They should exit to error_exit if unsuccessful.47*48* It's not a good idea to try to merge the sarray and barray routines,49* even though they are textually almost the same, because samples are50* usually stored as bytes while coefficients are shorts or ints. Thus,51* in machines where byte pointers have a different representation from52* word pointers, the resulting machine code could not be the same.53*/545556/*57* Many machines require storage alignment: longs must start on 4-byte58* boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()59* always returns pointers that are multiples of the worst-case alignment60* requirement, and we had better do so too.61* There isn't any really portable way to determine the worst-case alignment62* requirement. This module assumes that the alignment requirement is63* multiples of sizeof(ALIGN_TYPE).64* By default, we define ALIGN_TYPE as double. This is necessary on some65* workstations (where doubles really do need 8-byte alignment) and will work66* fine on nearly everything. If your machine has lesser alignment needs,67* you can save a few bytes by making ALIGN_TYPE smaller.68* The only place I know of where this will NOT work is certain Macintosh69* 680x0 compilers that define double as a 10-byte IEEE extended float.70* Doing 10-byte alignment is counterproductive because longwords won't be71* aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have72* such a compiler.73*/7475#ifndef ALIGN_TYPE /* so can override from jconfig.h */76#define ALIGN_TYPE double77#endif787980/*81* We allocate objects from "pools", where each pool is gotten with a single82* request to jpeg_get_small() or jpeg_get_large(). There is no per-object83* overhead within a pool, except for alignment padding. Each pool has a84* header with a link to the next pool of the same class.85* Small and large pool headers are identical except that the latter's86* link pointer must be FAR on 80x86 machines.87* Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE88* field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple89* of the alignment requirement of ALIGN_TYPE.90*/9192typedef union small_pool_struct * small_pool_ptr;9394typedef union small_pool_struct {95struct {96small_pool_ptr next; /* next in list of pools */97size_t bytes_used; /* how many bytes already used within pool */98size_t bytes_left; /* bytes still available in this pool */99} hdr;100ALIGN_TYPE dummy; /* included in union to ensure alignment */101} small_pool_hdr;102103typedef union large_pool_struct FAR * large_pool_ptr;104105typedef union large_pool_struct {106struct {107large_pool_ptr next; /* next in list of pools */108size_t bytes_used; /* how many bytes already used within pool */109size_t bytes_left; /* bytes still available in this pool */110} hdr;111ALIGN_TYPE dummy; /* included in union to ensure alignment */112} large_pool_hdr;113114115/*116* Here is the full definition of a memory manager object.117*/118119typedef struct {120struct jpeg_memory_mgr pub; /* public fields */121122/* Each pool identifier (lifetime class) names a linked list of pools. */123small_pool_ptr small_list[JPOOL_NUMPOOLS];124large_pool_ptr large_list[JPOOL_NUMPOOLS];125126/* Since we only have one lifetime class of virtual arrays, only one127* linked list is necessary (for each datatype). Note that the virtual128* array control blocks being linked together are actually stored somewhere129* in the small-pool list.130*/131jvirt_sarray_ptr virt_sarray_list;132jvirt_barray_ptr virt_barray_list;133134/* This counts total space obtained from jpeg_get_small/large */135size_t total_space_allocated;136137/* alloc_sarray and alloc_barray set this value for use by virtual138* array routines.139*/140JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */141} my_memory_mgr;142143typedef my_memory_mgr * my_mem_ptr;144145146/*147* The control blocks for virtual arrays.148* Note that these blocks are allocated in the "small" pool area.149* System-dependent info for the associated backing store (if any) is hidden150* inside the backing_store_info struct.151*/152153struct jvirt_sarray_control {154JSAMPARRAY mem_buffer; /* => the in-memory buffer */155JDIMENSION rows_in_array; /* total virtual array height */156JDIMENSION samplesperrow; /* width of array (and of memory buffer) */157JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */158JDIMENSION rows_in_mem; /* height of memory buffer */159JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */160JDIMENSION cur_start_row; /* first logical row # in the buffer */161JDIMENSION first_undef_row; /* row # of first uninitialized row */162boolean pre_zero; /* pre-zero mode requested? */163boolean dirty; /* do current buffer contents need written? */164boolean b_s_open; /* is backing-store data valid? */165jvirt_sarray_ptr next; /* link to next virtual sarray control block */166backing_store_info b_s_info; /* System-dependent control info */167};168169struct jvirt_barray_control {170JBLOCKARRAY mem_buffer; /* => the in-memory buffer */171JDIMENSION rows_in_array; /* total virtual array height */172JDIMENSION blocksperrow; /* width of array (and of memory buffer) */173JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */174JDIMENSION rows_in_mem; /* height of memory buffer */175JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */176JDIMENSION cur_start_row; /* first logical row # in the buffer */177JDIMENSION first_undef_row; /* row # of first uninitialized row */178boolean pre_zero; /* pre-zero mode requested? */179boolean dirty; /* do current buffer contents need written? */180boolean b_s_open; /* is backing-store data valid? */181jvirt_barray_ptr next; /* link to next virtual barray control block */182backing_store_info b_s_info; /* System-dependent control info */183};184185186#ifdef MEM_STATS /* optional extra stuff for statistics */187188LOCAL(void)189print_mem_stats (j_common_ptr cinfo, int pool_id)190{191my_mem_ptr mem = (my_mem_ptr) cinfo->mem;192small_pool_ptr shdr_ptr;193large_pool_ptr lhdr_ptr;194195/* Since this is only a debugging stub, we can cheat a little by using196* fprintf directly rather than going through the trace message code.197* This is helpful because message parm array can't handle longs.198*/199fprintf(stderr, "Freeing pool %d, total space = %ld\n",200pool_id, mem->total_space_allocated);201202for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;203lhdr_ptr = lhdr_ptr->hdr.next) {204fprintf(stderr, " Large chunk used %ld\n",205(long) lhdr_ptr->hdr.bytes_used);206}207208for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;209shdr_ptr = shdr_ptr->hdr.next) {210fprintf(stderr, " Small chunk used %ld free %ld\n",211(long) shdr_ptr->hdr.bytes_used,212(long) shdr_ptr->hdr.bytes_left);213}214}215216#endif /* MEM_STATS */217218219LOCAL(void)220out_of_memory (j_common_ptr cinfo, int which)221/* Report an out-of-memory error and stop execution */222/* If we compiled MEM_STATS support, report alloc requests before dying */223{224#ifdef MEM_STATS225cinfo->err->trace_level = 2; /* force self_destruct to report stats */226#endif227ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);228}229230231/*232* Allocation of "small" objects.233*234* For these, we use pooled storage. When a new pool must be created,235* we try to get enough space for the current request plus a "slop" factor,236* where the slop will be the amount of leftover space in the new pool.237* The speed vs. space tradeoff is largely determined by the slop values.238* A different slop value is provided for each pool class (lifetime),239* and we also distinguish the first pool of a class from later ones.240* NOTE: the values given work fairly well on both 16- and 32-bit-int241* machines, but may be too small if longs are 64 bits or more.242*/243244static const size_t first_pool_slop[JPOOL_NUMPOOLS] =245{2461600, /* first PERMANENT pool */24716000 /* first IMAGE pool */248};249250static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =251{2520, /* additional PERMANENT pools */2535000 /* additional IMAGE pools */254};255256#define MIN_SLOP 50 /* greater than 0 to avoid futile looping */257258259METHODDEF(void *)260alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)261/* Allocate a "small" object */262{263my_mem_ptr mem = (my_mem_ptr) cinfo->mem;264small_pool_ptr hdr_ptr, prev_hdr_ptr;265char * data_ptr;266size_t odd_bytes, min_request, slop;267268/* Check for unsatisfiable request (do now to ensure no overflow below) */269if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))270out_of_memory(cinfo, 1); /* request exceeds malloc's ability */271272/* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */273odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);274if (odd_bytes > 0)275sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;276277/* See if space is available in any existing pool */278if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)279ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */280prev_hdr_ptr = NULL;281hdr_ptr = mem->small_list[pool_id];282while (hdr_ptr != NULL) {283if (hdr_ptr->hdr.bytes_left >= sizeofobject)284break; /* found pool with enough space */285prev_hdr_ptr = hdr_ptr;286hdr_ptr = hdr_ptr->hdr.next;287}288289/* Time to make a new pool? */290if (hdr_ptr == NULL) {291/* min_request is what we need now, slop is what will be leftover */292min_request = sizeofobject + SIZEOF(small_pool_hdr);293if (prev_hdr_ptr == NULL) /* first pool in class? */294slop = first_pool_slop[pool_id];295else296slop = extra_pool_slop[pool_id];297/* Don't ask for more than MAX_ALLOC_CHUNK */298if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))299slop = (size_t) (MAX_ALLOC_CHUNK-min_request);300/* Try to get space, if fail reduce slop and try again */301for (;;) {302hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);303if (hdr_ptr != NULL)304break;305slop /= 2;306if (slop < MIN_SLOP) /* give up when it gets real small */307out_of_memory(cinfo, 2); /* jpeg_get_small failed */308}309mem->total_space_allocated += min_request + slop;310/* Success, initialize the new pool header and add to end of list */311hdr_ptr->hdr.next = NULL;312hdr_ptr->hdr.bytes_used = 0;313hdr_ptr->hdr.bytes_left = sizeofobject + slop;314if (prev_hdr_ptr == NULL) /* first pool in class? */315mem->small_list[pool_id] = hdr_ptr;316else317prev_hdr_ptr->hdr.next = hdr_ptr;318}319320/* OK, allocate the object from the current pool */321data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */322data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */323hdr_ptr->hdr.bytes_used += sizeofobject;324hdr_ptr->hdr.bytes_left -= sizeofobject;325326return (void *) data_ptr;327}328329330/*331* Allocation of "large" objects.332*333* The external semantics of these are the same as "small" objects,334* except that FAR pointers are used on 80x86. However the pool335* management heuristics are quite different. We assume that each336* request is large enough that it may as well be passed directly to337* jpeg_get_large; the pool management just links everything together338* so that we can free it all on demand.339* Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY340* structures. The routines that create these structures (see below)341* deliberately bunch rows together to ensure a large request size.342*/343344METHODDEF(void FAR *)345alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)346/* Allocate a "large" object */347{348my_mem_ptr mem = (my_mem_ptr) cinfo->mem;349large_pool_ptr hdr_ptr;350size_t odd_bytes;351352/* Check for unsatisfiable request (do now to ensure no overflow below) */353if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))354out_of_memory(cinfo, 3); /* request exceeds malloc's ability */355356/* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */357odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);358if (odd_bytes > 0)359sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;360361/* Always make a new pool */362if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)363ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */364365hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +366SIZEOF(large_pool_hdr));367if (hdr_ptr == NULL)368out_of_memory(cinfo, 4); /* jpeg_get_large failed */369mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);370371/* Success, initialize the new pool header and add to list */372hdr_ptr->hdr.next = mem->large_list[pool_id];373/* We maintain space counts in each pool header for statistical purposes,374* even though they are not needed for allocation.375*/376hdr_ptr->hdr.bytes_used = sizeofobject;377hdr_ptr->hdr.bytes_left = 0;378mem->large_list[pool_id] = hdr_ptr;379380return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */381}382383384/*385* Creation of 2-D sample arrays.386* The pointers are in near heap, the samples themselves in FAR heap.387*388* To minimize allocation overhead and to allow I/O of large contiguous389* blocks, we allocate the sample rows in groups of as many rows as possible390* without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.391* NB: the virtual array control routines, later in this file, know about392* this chunking of rows. The rowsperchunk value is left in the mem manager393* object so that it can be saved away if this sarray is the workspace for394* a virtual array.395*/396397METHODDEF(JSAMPARRAY)398alloc_sarray (j_common_ptr cinfo, int pool_id,399JDIMENSION samplesperrow, JDIMENSION numrows)400/* Allocate a 2-D sample array */401{402my_mem_ptr mem = (my_mem_ptr) cinfo->mem;403JSAMPARRAY result;404JSAMPROW workspace;405JDIMENSION rowsperchunk, currow, i;406long ltemp;407408if (samplesperrow == 0) {409ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);410}411/* Calculate max # of rows allowed in one allocation chunk */412ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /413((long) samplesperrow * SIZEOF(JSAMPLE));414if (ltemp <= 0)415ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);416if (ltemp < (long) numrows)417rowsperchunk = (JDIMENSION) ltemp;418else419rowsperchunk = numrows;420mem->last_rowsperchunk = rowsperchunk;421422/* Get space for row pointers (small object) */423result = (JSAMPARRAY) alloc_small(cinfo, pool_id,424(size_t) (numrows * SIZEOF(JSAMPROW)));425426/* Get the rows themselves (large objects) */427currow = 0;428while (currow < numrows) {429rowsperchunk = MIN(rowsperchunk, numrows - currow);430workspace = (JSAMPROW) alloc_large(cinfo, pool_id,431(size_t) ((size_t) rowsperchunk * (size_t) samplesperrow432* SIZEOF(JSAMPLE)));433for (i = rowsperchunk; i > 0; i--) {434result[currow++] = workspace;435workspace += samplesperrow;436}437}438439return result;440}441442443/*444* Creation of 2-D coefficient-block arrays.445* This is essentially the same as the code for sample arrays, above.446*/447448METHODDEF(JBLOCKARRAY)449alloc_barray (j_common_ptr cinfo, int pool_id,450JDIMENSION blocksperrow, JDIMENSION numrows)451/* Allocate a 2-D coefficient-block array */452{453my_mem_ptr mem = (my_mem_ptr) cinfo->mem;454JBLOCKARRAY result;455JBLOCKROW workspace;456JDIMENSION rowsperchunk, currow, i;457long ltemp;458459if (blocksperrow == 0) {460ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);461}462463/* Calculate max # of rows allowed in one allocation chunk */464ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /465((long) blocksperrow * SIZEOF(JBLOCK));466if (ltemp <= 0)467ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);468if (ltemp < (long) numrows)469rowsperchunk = (JDIMENSION) ltemp;470else471rowsperchunk = numrows;472mem->last_rowsperchunk = rowsperchunk;473474/* Get space for row pointers (small object) */475result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,476(size_t) (numrows * SIZEOF(JBLOCKROW)));477478/* Get the rows themselves (large objects) */479currow = 0;480while (currow < numrows) {481rowsperchunk = MIN(rowsperchunk, numrows - currow);482workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,483(size_t) ((size_t) rowsperchunk * (size_t) blocksperrow484* SIZEOF(JBLOCK)));485for (i = rowsperchunk; i > 0; i--) {486result[currow++] = workspace;487workspace += blocksperrow;488}489}490491return result;492}493494495/*496* About virtual array management:497*498* The above "normal" array routines are only used to allocate strip buffers499* (as wide as the image, but just a few rows high). Full-image-sized buffers500* are handled as "virtual" arrays. The array is still accessed a strip at a501* time, but the memory manager must save the whole array for repeated502* accesses. The intended implementation is that there is a strip buffer in503* memory (as high as is possible given the desired memory limit), plus a504* backing file that holds the rest of the array.505*506* The request_virt_array routines are told the total size of the image and507* the maximum number of rows that will be accessed at once. The in-memory508* buffer must be at least as large as the maxaccess value.509*510* The request routines create control blocks but not the in-memory buffers.511* That is postponed until realize_virt_arrays is called. At that time the512* total amount of space needed is known (approximately, anyway), so free513* memory can be divided up fairly.514*515* The access_virt_array routines are responsible for making a specific strip516* area accessible (after reading or writing the backing file, if necessary).517* Note that the access routines are told whether the caller intends to modify518* the accessed strip; during a read-only pass this saves having to rewrite519* data to disk. The access routines are also responsible for pre-zeroing520* any newly accessed rows, if pre-zeroing was requested.521*522* In current usage, the access requests are usually for nonoverlapping523* strips; that is, successive access start_row numbers differ by exactly524* num_rows = maxaccess. This means we can get good performance with simple525* buffer dump/reload logic, by making the in-memory buffer be a multiple526* of the access height; then there will never be accesses across bufferload527* boundaries. The code will still work with overlapping access requests,528* but it doesn't handle bufferload overlaps very efficiently.529*/530531532METHODDEF(jvirt_sarray_ptr)533request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,534JDIMENSION samplesperrow, JDIMENSION numrows,535JDIMENSION maxaccess)536/* Request a virtual 2-D sample array */537{538my_mem_ptr mem = (my_mem_ptr) cinfo->mem;539jvirt_sarray_ptr result;540541/* Only IMAGE-lifetime virtual arrays are currently supported */542if (pool_id != JPOOL_IMAGE)543ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */544545/* get control block */546result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,547SIZEOF(struct jvirt_sarray_control));548549result->mem_buffer = NULL; /* marks array not yet realized */550result->rows_in_array = numrows;551result->samplesperrow = samplesperrow;552result->maxaccess = maxaccess;553result->pre_zero = pre_zero;554result->b_s_open = FALSE; /* no associated backing-store object */555result->next = mem->virt_sarray_list; /* add to list of virtual arrays */556mem->virt_sarray_list = result;557558return result;559}560561562METHODDEF(jvirt_barray_ptr)563request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,564JDIMENSION blocksperrow, JDIMENSION numrows,565JDIMENSION maxaccess)566/* Request a virtual 2-D coefficient-block array */567{568my_mem_ptr mem = (my_mem_ptr) cinfo->mem;569jvirt_barray_ptr result;570571/* Only IMAGE-lifetime virtual arrays are currently supported */572if (pool_id != JPOOL_IMAGE)573ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */574575/* get control block */576result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,577SIZEOF(struct jvirt_barray_control));578579result->mem_buffer = NULL; /* marks array not yet realized */580result->rows_in_array = numrows;581result->blocksperrow = blocksperrow;582result->maxaccess = maxaccess;583result->pre_zero = pre_zero;584result->b_s_open = FALSE; /* no associated backing-store object */585result->next = mem->virt_barray_list; /* add to list of virtual arrays */586mem->virt_barray_list = result;587588return result;589}590591592METHODDEF(void)593realize_virt_arrays (j_common_ptr cinfo)594/* Allocate the in-memory buffers for any unrealized virtual arrays */595{596my_mem_ptr mem = (my_mem_ptr) cinfo->mem;597size_t space_per_minheight, maximum_space, avail_mem;598size_t minheights, max_minheights;599jvirt_sarray_ptr sptr;600jvirt_barray_ptr bptr;601602/* Compute the minimum space needed (maxaccess rows in each buffer)603* and the maximum space needed (full image height in each buffer).604* These may be of use to the system-dependent jpeg_mem_available routine.605*/606space_per_minheight = 0;607maximum_space = 0;608for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {609if (sptr->mem_buffer == NULL) { /* if not realized yet */610space_per_minheight += (long) sptr->maxaccess *611(long) sptr->samplesperrow * SIZEOF(JSAMPLE);612maximum_space += (long) sptr->rows_in_array *613(long) sptr->samplesperrow * SIZEOF(JSAMPLE);614}615}616for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {617if (bptr->mem_buffer == NULL) { /* if not realized yet */618space_per_minheight += (long) bptr->maxaccess *619(long) bptr->blocksperrow * SIZEOF(JBLOCK);620maximum_space += (long) bptr->rows_in_array *621(long) bptr->blocksperrow * SIZEOF(JBLOCK);622}623}624625if (space_per_minheight <= 0)626return; /* no unrealized arrays, no work */627628/* Determine amount of memory to actually use; this is system-dependent. */629avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,630mem->total_space_allocated);631632/* If the maximum space needed is available, make all the buffers full633* height; otherwise parcel it out with the same number of minheights634* in each buffer.635*/636if (avail_mem >= maximum_space)637max_minheights = 1000000000L;638else {639max_minheights = avail_mem / space_per_minheight;640/* If there doesn't seem to be enough space, try to get the minimum641* anyway. This allows a "stub" implementation of jpeg_mem_available().642*/643if (max_minheights <= 0)644max_minheights = 1;645}646647/* Allocate the in-memory buffers and initialize backing store as needed. */648649for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {650if (sptr->mem_buffer == NULL) { /* if not realized yet */651minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;652if (minheights <= max_minheights) {653/* This buffer fits in memory */654sptr->rows_in_mem = sptr->rows_in_array;655} else {656/* It doesn't fit in memory, create backing store. */657sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);658jpeg_open_backing_store(cinfo, & sptr->b_s_info,659(long) sptr->rows_in_array *660(long) sptr->samplesperrow *661(long) SIZEOF(JSAMPLE));662sptr->b_s_open = TRUE;663}664sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,665sptr->samplesperrow, sptr->rows_in_mem);666sptr->rowsperchunk = mem->last_rowsperchunk;667sptr->cur_start_row = 0;668sptr->first_undef_row = 0;669sptr->dirty = FALSE;670}671}672673for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {674if (bptr->mem_buffer == NULL) { /* if not realized yet */675minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;676if (minheights <= max_minheights) {677/* This buffer fits in memory */678bptr->rows_in_mem = bptr->rows_in_array;679} else {680/* It doesn't fit in memory, create backing store. */681bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);682jpeg_open_backing_store(cinfo, & bptr->b_s_info,683(long) bptr->rows_in_array *684(long) bptr->blocksperrow *685(long) SIZEOF(JBLOCK));686bptr->b_s_open = TRUE;687}688bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,689bptr->blocksperrow, bptr->rows_in_mem);690bptr->rowsperchunk = mem->last_rowsperchunk;691bptr->cur_start_row = 0;692bptr->first_undef_row = 0;693bptr->dirty = FALSE;694}695}696}697698699LOCAL(void)700do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)701/* Do backing store read or write of a virtual sample array */702{703long bytesperrow, file_offset, byte_count, rows, thisrow, i;704705bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);706file_offset = ptr->cur_start_row * bytesperrow;707/* Loop to read or write each allocation chunk in mem_buffer */708for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {709/* One chunk, but check for short chunk at end of buffer */710rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);711/* Transfer no more than is currently defined */712thisrow = (long) ptr->cur_start_row + i;713rows = MIN(rows, (long) ptr->first_undef_row - thisrow);714/* Transfer no more than fits in file */715rows = MIN(rows, (long) ptr->rows_in_array - thisrow);716if (rows <= 0) /* this chunk might be past end of file! */717break;718byte_count = rows * bytesperrow;719if (writing)720(*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,721(void FAR *) ptr->mem_buffer[i],722file_offset, byte_count);723else724(*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,725(void FAR *) ptr->mem_buffer[i],726file_offset, byte_count);727file_offset += byte_count;728}729}730731732LOCAL(void)733do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)734/* Do backing store read or write of a virtual coefficient-block array */735{736long bytesperrow, file_offset, byte_count, rows, thisrow, i;737738bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);739file_offset = ptr->cur_start_row * bytesperrow;740/* Loop to read or write each allocation chunk in mem_buffer */741for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {742/* One chunk, but check for short chunk at end of buffer */743rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);744/* Transfer no more than is currently defined */745thisrow = (long) ptr->cur_start_row + i;746rows = MIN(rows, (long) ptr->first_undef_row - thisrow);747/* Transfer no more than fits in file */748rows = MIN(rows, (long) ptr->rows_in_array - thisrow);749if (rows <= 0) /* this chunk might be past end of file! */750break;751byte_count = rows * bytesperrow;752if (writing)753(*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,754(void FAR *) ptr->mem_buffer[i],755file_offset, byte_count);756else757(*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,758(void FAR *) ptr->mem_buffer[i],759file_offset, byte_count);760file_offset += byte_count;761}762}763764765METHODDEF(JSAMPARRAY)766access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,767JDIMENSION start_row, JDIMENSION num_rows,768boolean writable)769/* Access the part of a virtual sample array starting at start_row */770/* and extending for num_rows rows. writable is true if */771/* caller intends to modify the accessed area. */772{773JDIMENSION end_row = start_row + num_rows;774JDIMENSION undef_row;775776/* debugging check */777if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||778ptr->mem_buffer == NULL)779ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);780781/* Make the desired part of the virtual array accessible */782if (start_row < ptr->cur_start_row ||783end_row > ptr->cur_start_row+ptr->rows_in_mem) {784if (! ptr->b_s_open)785ERREXIT(cinfo, JERR_VIRTUAL_BUG);786/* Flush old buffer contents if necessary */787if (ptr->dirty) {788do_sarray_io(cinfo, ptr, TRUE);789ptr->dirty = FALSE;790}791/* Decide what part of virtual array to access.792* Algorithm: if target address > current window, assume forward scan,793* load starting at target address. If target address < current window,794* assume backward scan, load so that target area is top of window.795* Note that when switching from forward write to forward read, will have796* start_row = 0, so the limiting case applies and we load from 0 anyway.797*/798if (start_row > ptr->cur_start_row) {799ptr->cur_start_row = start_row;800} else {801/* use long arithmetic here to avoid overflow & unsigned problems */802long ltemp;803804ltemp = (long) end_row - (long) ptr->rows_in_mem;805if (ltemp < 0)806ltemp = 0; /* don't fall off front end of file */807ptr->cur_start_row = (JDIMENSION) ltemp;808}809/* Read in the selected part of the array.810* During the initial write pass, we will do no actual read811* because the selected part is all undefined.812*/813do_sarray_io(cinfo, ptr, FALSE);814}815/* Ensure the accessed part of the array is defined; prezero if needed.816* To improve locality of access, we only prezero the part of the array817* that the caller is about to access, not the entire in-memory array.818*/819if (ptr->first_undef_row < end_row) {820if (ptr->first_undef_row < start_row) {821if (writable) /* writer skipped over a section of array */822ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);823undef_row = start_row; /* but reader is allowed to read ahead */824} else {825undef_row = ptr->first_undef_row;826}827if (writable)828ptr->first_undef_row = end_row;829if (ptr->pre_zero) {830size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);831undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */832end_row -= ptr->cur_start_row;833while (undef_row < end_row) {834jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);835undef_row++;836}837} else {838if (! writable) /* reader looking at undefined data */839ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);840}841}842/* Flag the buffer dirty if caller will write in it */843if (writable)844ptr->dirty = TRUE;845/* Return address of proper part of the buffer */846return ptr->mem_buffer + (start_row - ptr->cur_start_row);847}848849850METHODDEF(JBLOCKARRAY)851access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,852JDIMENSION start_row, JDIMENSION num_rows,853boolean writable)854/* Access the part of a virtual block array starting at start_row */855/* and extending for num_rows rows. writable is true if */856/* caller intends to modify the accessed area. */857{858JDIMENSION end_row = start_row + num_rows;859JDIMENSION undef_row;860861/* debugging check */862if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||863ptr->mem_buffer == NULL)864ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);865866/* Make the desired part of the virtual array accessible */867if (start_row < ptr->cur_start_row ||868end_row > ptr->cur_start_row+ptr->rows_in_mem) {869if (! ptr->b_s_open)870ERREXIT(cinfo, JERR_VIRTUAL_BUG);871/* Flush old buffer contents if necessary */872if (ptr->dirty) {873do_barray_io(cinfo, ptr, TRUE);874ptr->dirty = FALSE;875}876/* Decide what part of virtual array to access.877* Algorithm: if target address > current window, assume forward scan,878* load starting at target address. If target address < current window,879* assume backward scan, load so that target area is top of window.880* Note that when switching from forward write to forward read, will have881* start_row = 0, so the limiting case applies and we load from 0 anyway.882*/883if (start_row > ptr->cur_start_row) {884ptr->cur_start_row = start_row;885} else {886/* use long arithmetic here to avoid overflow & unsigned problems */887long ltemp;888889ltemp = (long) end_row - (long) ptr->rows_in_mem;890if (ltemp < 0)891ltemp = 0; /* don't fall off front end of file */892ptr->cur_start_row = (JDIMENSION) ltemp;893}894/* Read in the selected part of the array.895* During the initial write pass, we will do no actual read896* because the selected part is all undefined.897*/898do_barray_io(cinfo, ptr, FALSE);899}900/* Ensure the accessed part of the array is defined; prezero if needed.901* To improve locality of access, we only prezero the part of the array902* that the caller is about to access, not the entire in-memory array.903*/904if (ptr->first_undef_row < end_row) {905if (ptr->first_undef_row < start_row) {906if (writable) /* writer skipped over a section of array */907ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);908undef_row = start_row; /* but reader is allowed to read ahead */909} else {910undef_row = ptr->first_undef_row;911}912if (writable)913ptr->first_undef_row = end_row;914if (ptr->pre_zero) {915size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);916undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */917end_row -= ptr->cur_start_row;918while (undef_row < end_row) {919jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);920undef_row++;921}922} else {923if (! writable) /* reader looking at undefined data */924ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);925}926}927/* Flag the buffer dirty if caller will write in it */928if (writable)929ptr->dirty = TRUE;930/* Return address of proper part of the buffer */931return ptr->mem_buffer + (start_row - ptr->cur_start_row);932}933934935/*936* Release all objects belonging to a specified pool.937*/938939METHODDEF(void)940free_pool (j_common_ptr cinfo, int pool_id)941{942my_mem_ptr mem = (my_mem_ptr) cinfo->mem;943small_pool_ptr shdr_ptr;944large_pool_ptr lhdr_ptr;945size_t space_freed;946947if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)948ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */949950#ifdef MEM_STATS951if (cinfo->err->trace_level > 1)952print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */953#endif954955/* If freeing IMAGE pool, close any virtual arrays first */956if (pool_id == JPOOL_IMAGE) {957jvirt_sarray_ptr sptr;958jvirt_barray_ptr bptr;959960for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {961if (sptr->b_s_open) { /* there may be no backing store */962sptr->b_s_open = FALSE; /* prevent recursive close if error */963(*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);964}965}966mem->virt_sarray_list = NULL;967for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {968if (bptr->b_s_open) { /* there may be no backing store */969bptr->b_s_open = FALSE; /* prevent recursive close if error */970(*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);971}972}973mem->virt_barray_list = NULL;974}975976/* Release large objects */977lhdr_ptr = mem->large_list[pool_id];978mem->large_list[pool_id] = NULL;979980while (lhdr_ptr != NULL) {981large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;982space_freed = lhdr_ptr->hdr.bytes_used +983lhdr_ptr->hdr.bytes_left +984SIZEOF(large_pool_hdr);985jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);986mem->total_space_allocated -= space_freed;987lhdr_ptr = next_lhdr_ptr;988}989990/* Release small objects */991shdr_ptr = mem->small_list[pool_id];992mem->small_list[pool_id] = NULL;993994while (shdr_ptr != NULL) {995small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;996space_freed = shdr_ptr->hdr.bytes_used +997shdr_ptr->hdr.bytes_left +998SIZEOF(small_pool_hdr);999jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);1000mem->total_space_allocated -= space_freed;1001shdr_ptr = next_shdr_ptr;1002}1003}100410051006/*1007* Close up shop entirely.1008* Note that this cannot be called unless cinfo->mem is non-NULL.1009*/10101011METHODDEF(void)1012self_destruct (j_common_ptr cinfo)1013{1014int pool;10151016/* Close all backing store, release all memory.1017* Releasing pools in reverse order might help avoid fragmentation1018* with some (brain-damaged) malloc libraries.1019*/1020for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {1021free_pool(cinfo, pool);1022}10231024/* Release the memory manager control block too. */1025jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));1026cinfo->mem = NULL; /* ensures I will be called only once */10271028jpeg_mem_term(cinfo); /* system-dependent cleanup */1029}103010311032/*1033* Memory manager initialization.1034* When this is called, only the error manager pointer is valid in cinfo!1035*/10361037GLOBAL(void)1038jinit_memory_mgr (j_common_ptr cinfo)1039{1040my_mem_ptr mem;1041size_t max_to_use;1042int pool;1043size_t test_mac;10441045cinfo->mem = NULL; /* for safety if init fails */10461047/* Check for configuration errors.1048* SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably1049* doesn't reflect any real hardware alignment requirement.1050* The test is a little tricky: for X>0, X and X-1 have no one-bits1051* in common if and only if X is a power of 2, ie has only one one-bit.1052* Some compilers may give an "unreachable code" warning here; ignore it.1053*/1054if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)1055ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);1056/* MAX_ALLOC_CHUNK must be representable as type size_t, and must be1057* a multiple of SIZEOF(ALIGN_TYPE).1058* Again, an "unreachable code" warning may be ignored here.1059* But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.1060*/1061test_mac = (size_t) MAX_ALLOC_CHUNK;1062if ((long) test_mac != MAX_ALLOC_CHUNK ||1063(MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)1064ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);10651066max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */10671068/* Attempt to allocate memory manager's control block */1069mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));10701071if (mem == NULL) {1072jpeg_mem_term(cinfo); /* system-dependent cleanup */1073ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);1074}10751076/* OK, fill in the method pointers */1077mem->pub.alloc_small = alloc_small;1078mem->pub.alloc_large = alloc_large;1079mem->pub.alloc_sarray = alloc_sarray;1080mem->pub.alloc_barray = alloc_barray;1081mem->pub.request_virt_sarray = request_virt_sarray;1082mem->pub.request_virt_barray = request_virt_barray;1083mem->pub.realize_virt_arrays = realize_virt_arrays;1084mem->pub.access_virt_sarray = access_virt_sarray;1085mem->pub.access_virt_barray = access_virt_barray;1086mem->pub.free_pool = free_pool;1087mem->pub.self_destruct = self_destruct;10881089/* Make MAX_ALLOC_CHUNK accessible to other modules */1090mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;10911092/* Initialize working state */1093mem->pub.max_memory_to_use = max_to_use;10941095for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {1096mem->small_list[pool] = NULL;1097mem->large_list[pool] = NULL;1098}1099mem->virt_sarray_list = NULL;1100mem->virt_barray_list = NULL;11011102mem->total_space_allocated = SIZEOF(my_memory_mgr);11031104/* Declare ourselves open for business */1105cinfo->mem = & mem->pub;11061107/* Check for an environment variable JPEGMEM; if found, override the1108* default max_memory setting from jpeg_mem_init. Note that the1109* surrounding application may again override this value.1110* If your system doesn't support getenv(), define NO_GETENV to disable1111* this feature.1112*/1113#ifndef NO_GETENV1114{ char * memenv;11151116if ((memenv = getenv("JPEGMEM")) != NULL) {1117char ch = 'x';1118unsigned int mem_max = 0u;11191120if (sscanf(memenv, "%u%c", &mem_max, &ch) > 0) {1121max_to_use = (size_t)mem_max;1122if (ch == 'm' || ch == 'M')1123max_to_use *= 1000L;1124mem->pub.max_memory_to_use = max_to_use * 1000L;1125}1126}1127}1128#endif11291130}113111321133