Bug Summary

File:jdk/src/java.desktop/share/native/libjavajpeg/jmemmgr.c
Warning:line 413, column 52
Division by zero

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name jmemmgr.c -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 2 -mthread-model posix -fno-delete-null-pointer-checks -mframe-pointer=all -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -I /home/daniel/Projects/java/jdk/build/linux-x86_64-server-fastdebug/support/modules_include/java.base -I /home/daniel/Projects/java/jdk/build/linux-x86_64-server-fastdebug/support/modules_include/java.base/linux -I /home/daniel/Projects/java/jdk/src/java.base/share/native/libjava -I /home/daniel/Projects/java/jdk/src/java.base/unix/native/libjava -I /home/daniel/Projects/java/jdk/src/hotspot/share/include -I /home/daniel/Projects/java/jdk/src/hotspot/os/posix/include -D LIBC=gnu -D _GNU_SOURCE -D _REENTRANT -D _LARGEFILE64_SOURCE -D LINUX -D DEBUG -D _LITTLE_ENDIAN -D ARCH="amd64" -D amd64 -D _LP64=1 -I /home/daniel/Projects/java/jdk/src/java.desktop/share/native/libjavajpeg -I /home/daniel/Projects/java/jdk/build/linux-x86_64-server-fastdebug/support/headers/java.desktop -D _FORTIFY_SOURCE=2 -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O3 -Wno-unused-parameter -Wno-unused -Wno-clobbered -Wno-implicit-fallthrough -Wno-shift-negative-value -Wno-array-bounds -std=c99 -fdebug-compilation-dir /home/daniel/Projects/java/jdk/make -ferror-limit 19 -fmessage-length 0 -fvisibility hidden -stack-protector 1 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -faddrsig -o /home/daniel/Projects/java/scan/2021-12-21-193737-8510-1 -x c /home/daniel/Projects/java/jdk/src/java.desktop/share/native/libjavajpeg/jmemmgr.c
1/*
2 * reserved comment block
3 * DO NOT REMOVE OR ALTER!
4 */
5/*
6 * jmemmgr.c
7 *
8 * Copyright (C) 1991-1997, Thomas G. Lane.
9 * This file is part of the Independent JPEG Group's software.
10 * For conditions of distribution and use, see the accompanying README file.
11 *
12 * This file contains the JPEG system-independent memory management
13 * routines. This code is usable across a wide variety of machines; most
14 * of the system dependencies have been isolated in a separate file.
15 * The major functions provided here are:
16 * * pool-based allocation and freeing of memory;
17 * * policy decisions about how to divide available memory among the
18 * virtual arrays;
19 * * control logic for swapping virtual arrays between main memory and
20 * backing storage.
21 * The separate system-dependent file provides the actual backing-storage
22 * access code, and it contains the policy decision about how much total
23 * main memory to use.
24 * This file is system-dependent in the sense that some of its functions
25 * are unnecessary in some systems. For example, if there is enough virtual
26 * memory so that backing storage will never be used, much of the virtual
27 * array control logic could be removed. (Of course, if you have that much
28 * memory then you shouldn't care about a little bit of unused code...)
29 */
30
31#define JPEG_INTERNALS
32#define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
33#include "jinclude.h"
34#include "jpeglib.h"
35#include "jmemsys.h" /* import the system-dependent declarations */
36
37#ifndef NO_GETENV
38#ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
39extern char * getenv JPP((const char * name))(const char * name);
40#endif
41#endif
42
43
44/*
45 * Some important notes:
46 * The allocation routines provided here must never return NULL.
47 * They should exit to error_exit if unsuccessful.
48 *
49 * It's not a good idea to try to merge the sarray and barray routines,
50 * even though they are textually almost the same, because samples are
51 * usually stored as bytes while coefficients are shorts or ints. Thus,
52 * in machines where byte pointers have a different representation from
53 * word pointers, the resulting machine code could not be the same.
54 */
55
56
57/*
58 * Many machines require storage alignment: longs must start on 4-byte
59 * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
60 * always returns pointers that are multiples of the worst-case alignment
61 * requirement, and we had better do so too.
62 * There isn't any really portable way to determine the worst-case alignment
63 * requirement. This module assumes that the alignment requirement is
64 * multiples of sizeof(ALIGN_TYPE).
65 * By default, we define ALIGN_TYPE as double. This is necessary on some
66 * workstations (where doubles really do need 8-byte alignment) and will work
67 * fine on nearly everything. If your machine has lesser alignment needs,
68 * you can save a few bytes by making ALIGN_TYPE smaller.
69 * The only place I know of where this will NOT work is certain Macintosh
70 * 680x0 compilers that define double as a 10-byte IEEE extended float.
71 * Doing 10-byte alignment is counterproductive because longwords won't be
72 * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
73 * such a compiler.
74 */
75
76#ifndef ALIGN_TYPEdouble /* so can override from jconfig.h */
77#define ALIGN_TYPEdouble double
78#endif
79
80
81/*
82 * We allocate objects from "pools", where each pool is gotten with a single
83 * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
84 * overhead within a pool, except for alignment padding. Each pool has a
85 * header with a link to the next pool of the same class.
86 * Small and large pool headers are identical except that the latter's
87 * link pointer must be FAR on 80x86 machines.
88 * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
89 * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
90 * of the alignment requirement of ALIGN_TYPE.
91 */
92
93typedef union small_pool_struct * small_pool_ptr;
94
95typedef union small_pool_struct {
96 struct {
97 small_pool_ptr next; /* next in list of pools */
98 size_t bytes_used; /* how many bytes already used within pool */
99 size_t bytes_left; /* bytes still available in this pool */
100 } hdr;
101 ALIGN_TYPEdouble dummy; /* included in union to ensure alignment */
102} small_pool_hdr;
103
104typedef union large_pool_struct FAR * large_pool_ptr;
105
106typedef union large_pool_struct {
107 struct {
108 large_pool_ptr next; /* next in list of pools */
109 size_t bytes_used; /* how many bytes already used within pool */
110 size_t bytes_left; /* bytes still available in this pool */
111 } hdr;
112 ALIGN_TYPEdouble dummy; /* included in union to ensure alignment */
113} large_pool_hdr;
114
115
116/*
117 * Here is the full definition of a memory manager object.
118 */
119
120typedef struct {
121 struct jpeg_memory_mgr pub; /* public fields */
122
123 /* Each pool identifier (lifetime class) names a linked list of pools. */
124 small_pool_ptr small_list[JPOOL_NUMPOOLS2];
125 large_pool_ptr large_list[JPOOL_NUMPOOLS2];
126
127 /* Since we only have one lifetime class of virtual arrays, only one
128 * linked list is necessary (for each datatype). Note that the virtual
129 * array control blocks being linked together are actually stored somewhere
130 * in the small-pool list.
131 */
132 jvirt_sarray_ptr virt_sarray_list;
133 jvirt_barray_ptr virt_barray_list;
134
135 /* This counts total space obtained from jpeg_get_small/large */
136 size_t total_space_allocated;
137
138 /* alloc_sarray and alloc_barray set this value for use by virtual
139 * array routines.
140 */
141 JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
142} my_memory_mgr;
143
144typedef my_memory_mgr * my_mem_ptr;
145
146
147/*
148 * The control blocks for virtual arrays.
149 * Note that these blocks are allocated in the "small" pool area.
150 * System-dependent info for the associated backing store (if any) is hidden
151 * inside the backing_store_info struct.
152 */
153
154struct jvirt_sarray_control {
155 JSAMPARRAY mem_buffer; /* => the in-memory buffer */
156 JDIMENSION rows_in_array; /* total virtual array height */
157 JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
158 JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
159 JDIMENSION rows_in_mem; /* height of memory buffer */
160 JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
161 JDIMENSION cur_start_row; /* first logical row # in the buffer */
162 JDIMENSION first_undef_row; /* row # of first uninitialized row */
163 boolean pre_zero; /* pre-zero mode requested? */
164 boolean dirty; /* do current buffer contents need written? */
165 boolean b_s_open; /* is backing-store data valid? */
166 jvirt_sarray_ptr next; /* link to next virtual sarray control block */
167 backing_store_info b_s_info; /* System-dependent control info */
168};
169
170struct jvirt_barray_control {
171 JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
172 JDIMENSION rows_in_array; /* total virtual array height */
173 JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
174 JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
175 JDIMENSION rows_in_mem; /* height of memory buffer */
176 JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
177 JDIMENSION cur_start_row; /* first logical row # in the buffer */
178 JDIMENSION first_undef_row; /* row # of first uninitialized row */
179 boolean pre_zero; /* pre-zero mode requested? */
180 boolean dirty; /* do current buffer contents need written? */
181 boolean b_s_open; /* is backing-store data valid? */
182 jvirt_barray_ptr next; /* link to next virtual barray control block */
183 backing_store_info b_s_info; /* System-dependent control info */
184};
185
186
187#ifdef MEM_STATS /* optional extra stuff for statistics */
188
189LOCAL(void)static void
190print_mem_stats (j_common_ptr cinfo, int pool_id)
191{
192 my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
193 small_pool_ptr shdr_ptr;
194 large_pool_ptr lhdr_ptr;
195
196 /* Since this is only a debugging stub, we can cheat a little by using
197 * fprintf directly rather than going through the trace message code.
198 * This is helpful because message parm array can't handle longs.
199 */
200 fprintf(stderr, "Freeing pool %d, total space = %ld\n",__fprintf_chk (stderr, 2 - 1, "Freeing pool %d, total space = %ld\n"
, pool_id, mem->total_space_allocated)
201 pool_id, mem->total_space_allocated)__fprintf_chk (stderr, 2 - 1, "Freeing pool %d, total space = %ld\n"
, pool_id, mem->total_space_allocated)
;
202
203 for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL((void*)0);
204 lhdr_ptr = lhdr_ptr->hdr.next) {
205 fprintf(stderr, " Large chunk used %ld\n",__fprintf_chk (stderr, 2 - 1, " Large chunk used %ld\n", (long
) lhdr_ptr->hdr.bytes_used)
206 (long) lhdr_ptr->hdr.bytes_used)__fprintf_chk (stderr, 2 - 1, " Large chunk used %ld\n", (long
) lhdr_ptr->hdr.bytes_used)
;
207 }
208
209 for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL((void*)0);
210 shdr_ptr = shdr_ptr->hdr.next) {
211 fprintf(stderr, " Small chunk used %ld free %ld\n",__fprintf_chk (stderr, 2 - 1, " Small chunk used %ld free %ld\n"
, (long) shdr_ptr->hdr.bytes_used, (long) shdr_ptr->hdr
.bytes_left)
212 (long) shdr_ptr->hdr.bytes_used,__fprintf_chk (stderr, 2 - 1, " Small chunk used %ld free %ld\n"
, (long) shdr_ptr->hdr.bytes_used, (long) shdr_ptr->hdr
.bytes_left)
213 (long) shdr_ptr->hdr.bytes_left)__fprintf_chk (stderr, 2 - 1, " Small chunk used %ld free %ld\n"
, (long) shdr_ptr->hdr.bytes_used, (long) shdr_ptr->hdr
.bytes_left)
;
214 }
215}
216
217#endif /* MEM_STATS */
218
219
220LOCAL(void)static void
221out_of_memory (j_common_ptr cinfo, int which)
222/* Report an out-of-memory error and stop execution */
223/* If we compiled MEM_STATS support, report alloc requests before dying */
224{
225#ifdef MEM_STATS
226 cinfo->err->trace_level = 2; /* force self_destruct to report stats */
227#endif
228 ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which)((cinfo)->err->msg_code = (JERR_OUT_OF_MEMORY), (cinfo)
->err->msg_parm.i[0] = (which), (*(cinfo)->err->error_exit
) ((j_common_ptr) (cinfo)))
;
229}
230
231
232/*
233 * Allocation of "small" objects.
234 *
235 * For these, we use pooled storage. When a new pool must be created,
236 * we try to get enough space for the current request plus a "slop" factor,
237 * where the slop will be the amount of leftover space in the new pool.
238 * The speed vs. space tradeoff is largely determined by the slop values.
239 * A different slop value is provided for each pool class (lifetime),
240 * and we also distinguish the first pool of a class from later ones.
241 * NOTE: the values given work fairly well on both 16- and 32-bit-int
242 * machines, but may be too small if longs are 64 bits or more.
243 */
244
245static const size_t first_pool_slop[JPOOL_NUMPOOLS2] =
246{
247 1600, /* first PERMANENT pool */
248 16000 /* first IMAGE pool */
249};
250
251static const size_t extra_pool_slop[JPOOL_NUMPOOLS2] =
252{
253 0, /* additional PERMANENT pools */
254 5000 /* additional IMAGE pools */
255};
256
257#define MIN_SLOP50 50 /* greater than 0 to avoid futile looping */
258
259
260METHODDEF(void *)static void *
261alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
262/* Allocate a "small" object */
263{
264 my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
265 small_pool_ptr hdr_ptr, prev_hdr_ptr;
266 char * data_ptr;
267 size_t odd_bytes, min_request, slop;
268
269 /* Check for unsatisfiable request (do now to ensure no overflow below) */
270 if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK1000000000L-SIZEOF(small_pool_hdr)((size_t) sizeof(small_pool_hdr))))
271 out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
272
273 /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
274 odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE)((size_t) sizeof(double));
275 if (odd_bytes > 0)
276 sizeofobject += SIZEOF(ALIGN_TYPE)((size_t) sizeof(double)) - odd_bytes;
277
278 /* See if space is available in any existing pool */
279 if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS2)
280 ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id)((cinfo)->err->msg_code = (JERR_BAD_POOL_ID), (cinfo)->
err->msg_parm.i[0] = (pool_id), (*(cinfo)->err->error_exit
) ((j_common_ptr) (cinfo)))
; /* safety check */
281 prev_hdr_ptr = NULL((void*)0);
282 hdr_ptr = mem->small_list[pool_id];
283 while (hdr_ptr != NULL((void*)0)) {
284 if (hdr_ptr->hdr.bytes_left >= sizeofobject)
285 break; /* found pool with enough space */
286 prev_hdr_ptr = hdr_ptr;
287 hdr_ptr = hdr_ptr->hdr.next;
288 }
289
290 /* Time to make a new pool? */
291 if (hdr_ptr == NULL((void*)0)) {
292 /* min_request is what we need now, slop is what will be leftover */
293 min_request = sizeofobject + SIZEOF(small_pool_hdr)((size_t) sizeof(small_pool_hdr));
294 if (prev_hdr_ptr == NULL((void*)0)) /* first pool in class? */
295 slop = first_pool_slop[pool_id];
296 else
297 slop = extra_pool_slop[pool_id];
298 /* Don't ask for more than MAX_ALLOC_CHUNK */
299 if (slop > (size_t) (MAX_ALLOC_CHUNK1000000000L-min_request))
300 slop = (size_t) (MAX_ALLOC_CHUNK1000000000L-min_request);
301 /* Try to get space, if fail reduce slop and try again */
302 for (;;) {
303 hdr_ptr = (small_pool_ptr) jpeg_get_smalljGetSmall(cinfo, min_request + slop);
304 if (hdr_ptr != NULL((void*)0))
305 break;
306 slop /= 2;
307 if (slop < MIN_SLOP50) /* give up when it gets real small */
308 out_of_memory(cinfo, 2); /* jpeg_get_small failed */
309 }
310 mem->total_space_allocated += min_request + slop;
311 /* Success, initialize the new pool header and add to end of list */
312 hdr_ptr->hdr.next = NULL((void*)0);
313 hdr_ptr->hdr.bytes_used = 0;
314 hdr_ptr->hdr.bytes_left = sizeofobject + slop;
315 if (prev_hdr_ptr == NULL((void*)0)) /* first pool in class? */
316 mem->small_list[pool_id] = hdr_ptr;
317 else
318 prev_hdr_ptr->hdr.next = hdr_ptr;
319 }
320
321 /* OK, allocate the object from the current pool */
322 data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
323 data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
324 hdr_ptr->hdr.bytes_used += sizeofobject;
325 hdr_ptr->hdr.bytes_left -= sizeofobject;
326
327 return (void *) data_ptr;
328}
329
330
331/*
332 * Allocation of "large" objects.
333 *
334 * The external semantics of these are the same as "small" objects,
335 * except that FAR pointers are used on 80x86. However the pool
336 * management heuristics are quite different. We assume that each
337 * request is large enough that it may as well be passed directly to
338 * jpeg_get_large; the pool management just links everything together
339 * so that we can free it all on demand.
340 * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
341 * structures. The routines that create these structures (see below)
342 * deliberately bunch rows together to ensure a large request size.
343 */
344
345METHODDEF(void FAR *)static void *
346alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
347/* Allocate a "large" object */
348{
349 my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
350 large_pool_ptr hdr_ptr;
351 size_t odd_bytes;
352
353 /* Check for unsatisfiable request (do now to ensure no overflow below) */
354 if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK1000000000L-SIZEOF(large_pool_hdr)((size_t) sizeof(large_pool_hdr))))
355 out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
356
357 /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
358 odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE)((size_t) sizeof(double));
359 if (odd_bytes > 0)
360 sizeofobject += SIZEOF(ALIGN_TYPE)((size_t) sizeof(double)) - odd_bytes;
361
362 /* Always make a new pool */
363 if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS2)
364 ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id)((cinfo)->err->msg_code = (JERR_BAD_POOL_ID), (cinfo)->
err->msg_parm.i[0] = (pool_id), (*(cinfo)->err->error_exit
) ((j_common_ptr) (cinfo)))
; /* safety check */
365
366 hdr_ptr = (large_pool_ptr) jpeg_get_largejGetLarge(cinfo, sizeofobject +
367 SIZEOF(large_pool_hdr)((size_t) sizeof(large_pool_hdr)));
368 if (hdr_ptr == NULL((void*)0))
369 out_of_memory(cinfo, 4); /* jpeg_get_large failed */
370 mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr)((size_t) sizeof(large_pool_hdr));
371
372 /* Success, initialize the new pool header and add to list */
373 hdr_ptr->hdr.next = mem->large_list[pool_id];
374 /* We maintain space counts in each pool header for statistical purposes,
375 * even though they are not needed for allocation.
376 */
377 hdr_ptr->hdr.bytes_used = sizeofobject;
378 hdr_ptr->hdr.bytes_left = 0;
379 mem->large_list[pool_id] = hdr_ptr;
380
381 return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
382}
383
384
385/*
386 * Creation of 2-D sample arrays.
387 * The pointers are in near heap, the samples themselves in FAR heap.
388 *
389 * To minimize allocation overhead and to allow I/O of large contiguous
390 * blocks, we allocate the sample rows in groups of as many rows as possible
391 * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
392 * NB: the virtual array control routines, later in this file, know about
393 * this chunking of rows. The rowsperchunk value is left in the mem manager
394 * object so that it can be saved away if this sarray is the workspace for
395 * a virtual array.
396 */
397
398METHODDEF(JSAMPARRAY)static JSAMPARRAY
399alloc_sarray (j_common_ptr cinfo, int pool_id,
400 JDIMENSION samplesperrow, JDIMENSION numrows)
401/* Allocate a 2-D sample array */
402{
403 my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
404 JSAMPARRAY result;
405 JSAMPROW workspace;
406 JDIMENSION rowsperchunk, currow, i;
407 long ltemp;
408
409 if (samplesperrow == 0) {
18
Assuming 'samplesperrow' is equal to 0
19
Taking true branch
410 ERREXIT(cinfo, JERR_WIDTH_OVERFLOW)((cinfo)->err->msg_code = (JERR_WIDTH_OVERFLOW), (*(cinfo
)->err->error_exit) ((j_common_ptr) (cinfo)))
;
411 }
412 /* Calculate max # of rows allowed in one allocation chunk */
413 ltemp = (MAX_ALLOC_CHUNK1000000000L-SIZEOF(large_pool_hdr)((size_t) sizeof(large_pool_hdr))) /
20
Division by zero
414 ((long) samplesperrow * SIZEOF(JSAMPLE)((size_t) sizeof(JSAMPLE)));
415 if (ltemp <= 0)
416 ERREXIT(cinfo, JERR_WIDTH_OVERFLOW)((cinfo)->err->msg_code = (JERR_WIDTH_OVERFLOW), (*(cinfo
)->err->error_exit) ((j_common_ptr) (cinfo)))
;
417 if (ltemp < (long) numrows)
418 rowsperchunk = (JDIMENSION) ltemp;
419 else
420 rowsperchunk = numrows;
421 mem->last_rowsperchunk = rowsperchunk;
422
423 /* Get space for row pointers (small object) */
424 result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
425 (size_t) (numrows * SIZEOF(JSAMPROW)((size_t) sizeof(JSAMPROW))));
426
427 /* Get the rows themselves (large objects) */
428 currow = 0;
429 while (currow < numrows) {
430 rowsperchunk = MIN(rowsperchunk, numrows - currow)((rowsperchunk) < (numrows - currow) ? (rowsperchunk) : (numrows
- currow))
;
431 workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
432 (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
433 * SIZEOF(JSAMPLE)((size_t) sizeof(JSAMPLE))));
434 for (i = rowsperchunk; i > 0; i--) {
435 result[currow++] = workspace;
436 workspace += samplesperrow;
437 }
438 }
439
440 return result;
441}
442
443
444/*
445 * Creation of 2-D coefficient-block arrays.
446 * This is essentially the same as the code for sample arrays, above.
447 */
448
449METHODDEF(JBLOCKARRAY)static JBLOCKARRAY
450alloc_barray (j_common_ptr cinfo, int pool_id,
451 JDIMENSION blocksperrow, JDIMENSION numrows)
452/* Allocate a 2-D coefficient-block array */
453{
454 my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
455 JBLOCKARRAY result;
456 JBLOCKROW workspace;
457 JDIMENSION rowsperchunk, currow, i;
458 long ltemp;
459
460 if (blocksperrow == 0) {
461 ERREXIT(cinfo, JERR_WIDTH_OVERFLOW)((cinfo)->err->msg_code = (JERR_WIDTH_OVERFLOW), (*(cinfo
)->err->error_exit) ((j_common_ptr) (cinfo)))
;
462 }
463
464 /* Calculate max # of rows allowed in one allocation chunk */
465 ltemp = (MAX_ALLOC_CHUNK1000000000L-SIZEOF(large_pool_hdr)((size_t) sizeof(large_pool_hdr))) /
466 ((long) blocksperrow * SIZEOF(JBLOCK)((size_t) sizeof(JBLOCK)));
467 if (ltemp <= 0)
468 ERREXIT(cinfo, JERR_WIDTH_OVERFLOW)((cinfo)->err->msg_code = (JERR_WIDTH_OVERFLOW), (*(cinfo
)->err->error_exit) ((j_common_ptr) (cinfo)))
;
469 if (ltemp < (long) numrows)
470 rowsperchunk = (JDIMENSION) ltemp;
471 else
472 rowsperchunk = numrows;
473 mem->last_rowsperchunk = rowsperchunk;
474
475 /* Get space for row pointers (small object) */
476 result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
477 (size_t) (numrows * SIZEOF(JBLOCKROW)((size_t) sizeof(JBLOCKROW))));
478
479 /* Get the rows themselves (large objects) */
480 currow = 0;
481 while (currow < numrows) {
482 rowsperchunk = MIN(rowsperchunk, numrows - currow)((rowsperchunk) < (numrows - currow) ? (rowsperchunk) : (numrows
- currow))
;
483 workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
484 (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
485 * SIZEOF(JBLOCK)((size_t) sizeof(JBLOCK))));
486 for (i = rowsperchunk; i > 0; i--) {
487 result[currow++] = workspace;
488 workspace += blocksperrow;
489 }
490 }
491
492 return result;
493}
494
495
496/*
497 * About virtual array management:
498 *
499 * The above "normal" array routines are only used to allocate strip buffers
500 * (as wide as the image, but just a few rows high). Full-image-sized buffers
501 * are handled as "virtual" arrays. The array is still accessed a strip at a
502 * time, but the memory manager must save the whole array for repeated
503 * accesses. The intended implementation is that there is a strip buffer in
504 * memory (as high as is possible given the desired memory limit), plus a
505 * backing file that holds the rest of the array.
506 *
507 * The request_virt_array routines are told the total size of the image and
508 * the maximum number of rows that will be accessed at once. The in-memory
509 * buffer must be at least as large as the maxaccess value.
510 *
511 * The request routines create control blocks but not the in-memory buffers.
512 * That is postponed until realize_virt_arrays is called. At that time the
513 * total amount of space needed is known (approximately, anyway), so free
514 * memory can be divided up fairly.
515 *
516 * The access_virt_array routines are responsible for making a specific strip
517 * area accessible (after reading or writing the backing file, if necessary).
518 * Note that the access routines are told whether the caller intends to modify
519 * the accessed strip; during a read-only pass this saves having to rewrite
520 * data to disk. The access routines are also responsible for pre-zeroing
521 * any newly accessed rows, if pre-zeroing was requested.
522 *
523 * In current usage, the access requests are usually for nonoverlapping
524 * strips; that is, successive access start_row numbers differ by exactly
525 * num_rows = maxaccess. This means we can get good performance with simple
526 * buffer dump/reload logic, by making the in-memory buffer be a multiple
527 * of the access height; then there will never be accesses across bufferload
528 * boundaries. The code will still work with overlapping access requests,
529 * but it doesn't handle bufferload overlaps very efficiently.
530 */
531
532
533METHODDEF(jvirt_sarray_ptr)static jvirt_sarray_ptr
534request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
535 JDIMENSION samplesperrow, JDIMENSION numrows,
536 JDIMENSION maxaccess)
537/* Request a virtual 2-D sample array */
538{
539 my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
540 jvirt_sarray_ptr result;
541
542 /* Only IMAGE-lifetime virtual arrays are currently supported */
543 if (pool_id != JPOOL_IMAGE1)
544 ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id)((cinfo)->err->msg_code = (JERR_BAD_POOL_ID), (cinfo)->
err->msg_parm.i[0] = (pool_id), (*(cinfo)->err->error_exit
) ((j_common_ptr) (cinfo)))
; /* safety check */
545
546 /* get control block */
547 result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
548 SIZEOF(struct jvirt_sarray_control)((size_t) sizeof(struct jvirt_sarray_control)));
549
550 result->mem_buffer = NULL((void*)0); /* marks array not yet realized */
551 result->rows_in_array = numrows;
552 result->samplesperrow = samplesperrow;
553 result->maxaccess = maxaccess;
554 result->pre_zero = pre_zero;
555 result->b_s_open = FALSE0; /* no associated backing-store object */
556 result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
557 mem->virt_sarray_list = result;
558
559 return result;
560}
561
562
563METHODDEF(jvirt_barray_ptr)static jvirt_barray_ptr
564request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
565 JDIMENSION blocksperrow, JDIMENSION numrows,
566 JDIMENSION maxaccess)
567/* Request a virtual 2-D coefficient-block array */
568{
569 my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
570 jvirt_barray_ptr result;
571
572 /* Only IMAGE-lifetime virtual arrays are currently supported */
573 if (pool_id != JPOOL_IMAGE1)
574 ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id)((cinfo)->err->msg_code = (JERR_BAD_POOL_ID), (cinfo)->
err->msg_parm.i[0] = (pool_id), (*(cinfo)->err->error_exit
) ((j_common_ptr) (cinfo)))
; /* safety check */
575
576 /* get control block */
577 result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
578 SIZEOF(struct jvirt_barray_control)((size_t) sizeof(struct jvirt_barray_control)));
579
580 result->mem_buffer = NULL((void*)0); /* marks array not yet realized */
581 result->rows_in_array = numrows;
582 result->blocksperrow = blocksperrow;
583 result->maxaccess = maxaccess;
584 result->pre_zero = pre_zero;
585 result->b_s_open = FALSE0; /* 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
593METHODDEF(void)static void
594realize_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 size_t space_per_minheight, maximum_space, avail_mem;
599 size_t minheights, max_minheights;
600 jvirt_sarray_ptr sptr;
601 jvirt_barray_ptr bptr;
602
603 /* Compute the minimum space needed (maxaccess 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_minheight = 0;
608 maximum_space = 0;
609 for (sptr = mem->virt_sarray_list; sptr != NULL((void*)0); sptr = sptr->next) {
1
Assuming 'sptr' is not equal to NULL
2
Loop condition is true. Entering loop body
5
Assuming 'sptr' is equal to NULL
6
Loop condition is false. Execution continues on line 617
610 if (sptr->mem_buffer == NULL((void*)0)) { /* if not realized yet */
3
Assuming field 'mem_buffer' is equal to NULL
4
Taking true branch
611 space_per_minheight += (long) sptr->maxaccess *
612 (long) sptr->samplesperrow * SIZEOF(JSAMPLE)((size_t) sizeof(JSAMPLE));
613 maximum_space += (long) sptr->rows_in_array *
614 (long) sptr->samplesperrow * SIZEOF(JSAMPLE)((size_t) sizeof(JSAMPLE));
615 }
616 }
617 for (bptr = mem->virt_barray_list; bptr != NULL((void*)0); bptr = bptr->next) {
7
Assuming 'bptr' is equal to NULL
8
Loop condition is false. Execution continues on line 626
618 if (bptr->mem_buffer == NULL((void*)0)) { /* if not realized yet */
619 space_per_minheight += (long) bptr->maxaccess *
620 (long) bptr->blocksperrow * SIZEOF(JBLOCK)((size_t) sizeof(JBLOCK));
621 maximum_space += (long) bptr->rows_in_array *
622 (long) bptr->blocksperrow * SIZEOF(JBLOCK)((size_t) sizeof(JBLOCK));
623 }
624 }
625
626 if (space_per_minheight <= 0)
9
Assuming 'space_per_minheight' is > 0
10
Taking false branch
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_availablejMemAvail(cinfo, space_per_minheight, 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 minheights
635 * in each buffer.
636 */
637 if (avail_mem >= maximum_space)
11
Assuming 'avail_mem' is >= 'maximum_space'
12
Taking true branch
638 max_minheights = 1000000000L;
639 else {
640 max_minheights = avail_mem / space_per_minheight;
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_minheights <= 0)
645 max_minheights = 1;
646 }
647
648 /* Allocate the in-memory buffers and initialize backing store as needed. */
649
650 for (sptr = mem->virt_sarray_list; sptr
12.1
'sptr' is not equal to NULL
!= NULL((void*)0); sptr = sptr->next) {
13
Loop condition is true. Entering loop body
651 if (sptr->mem_buffer
13.1
Field 'mem_buffer' is equal to NULL
== NULL((void*)0)) { /* if not realized yet */
14
Taking true branch
652 minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
653 if (minheights <= max_minheights) {
15
Assuming 'minheights' is <= 'max_minheights'
16
Taking true branch
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_minheights * sptr->maxaccess);
659 jpeg_open_backing_storejOpenBackStore(cinfo, & sptr->b_s_info,
660 (long) sptr->rows_in_array *
661 (long) sptr->samplesperrow *
662 (long) SIZEOF(JSAMPLE)((size_t) sizeof(JSAMPLE)));
663 sptr->b_s_open = TRUE1;
664 }
665 sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE1,
17
Calling 'alloc_sarray'
666 sptr->samplesperrow, sptr->rows_in_mem);
667 sptr->rowsperchunk = mem->last_rowsperchunk;
668 sptr->cur_start_row = 0;
669 sptr->first_undef_row = 0;
670 sptr->dirty = FALSE0;
671 }
672 }
673
674 for (bptr = mem->virt_barray_list; bptr != NULL((void*)0); bptr = bptr->next) {
675 if (bptr->mem_buffer == NULL((void*)0)) { /* if not realized yet */
676 minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
677 if (minheights <= max_minheights) {
678 /* This buffer fits in memory */
679 bptr->rows_in_mem = bptr->rows_in_array;
680 } else {
681 /* It doesn't fit in memory, create backing store. */
682 bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
683 jpeg_open_backing_storejOpenBackStore(cinfo, & bptr->b_s_info,
684 (long) bptr->rows_in_array *
685 (long) bptr->blocksperrow *
686 (long) SIZEOF(JBLOCK)((size_t) sizeof(JBLOCK)));
687 bptr->b_s_open = TRUE1;
688 }
689 bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE1,
690 bptr->blocksperrow, bptr->rows_in_mem);
691 bptr->rowsperchunk = mem->last_rowsperchunk;
692 bptr->cur_start_row = 0;
693 bptr->first_undef_row = 0;
694 bptr->dirty = FALSE0;
695 }
696 }
697}
698
699
700LOCAL(void)static void
701do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
702/* Do backing store read or write of a virtual sample array */
703{
704 long bytesperrow, file_offset, byte_count, rows, thisrow, i;
705
706 bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE)((size_t) sizeof(JSAMPLE));
707 file_offset = ptr->cur_start_row * bytesperrow;
708 /* Loop to read or write each allocation chunk in mem_buffer */
709 for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
710 /* One chunk, but check for short chunk at end of buffer */
711 rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i)(((long) ptr->rowsperchunk) < ((long) ptr->rows_in_mem
- i) ? ((long) ptr->rowsperchunk) : ((long) ptr->rows_in_mem
- i))
;
712 /* Transfer no more than is currently defined */
713 thisrow = (long) ptr->cur_start_row + i;
714 rows = MIN(rows, (long) ptr->first_undef_row - thisrow)((rows) < ((long) ptr->first_undef_row - thisrow) ? (rows
) : ((long) ptr->first_undef_row - thisrow))
;
715 /* Transfer no more than fits in file */
716 rows = MIN(rows, (long) ptr->rows_in_array - thisrow)((rows) < ((long) ptr->rows_in_array - thisrow) ? (rows
) : ((long) ptr->rows_in_array - thisrow))
;
717 if (rows <= 0) /* this chunk might be past end of file! */
718 break;
719 byte_count = rows * bytesperrow;
720 if (writing)
721 (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
722 (void FAR *) ptr->mem_buffer[i],
723 file_offset, byte_count);
724 else
725 (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
726 (void FAR *) ptr->mem_buffer[i],
727 file_offset, byte_count);
728 file_offset += byte_count;
729 }
730}
731
732
733LOCAL(void)static void
734do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
735/* Do backing store read or write of a virtual coefficient-block array */
736{
737 long bytesperrow, file_offset, byte_count, rows, thisrow, i;
738
739 bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK)((size_t) sizeof(JBLOCK));
740 file_offset = ptr->cur_start_row * bytesperrow;
741 /* Loop to read or write each allocation chunk in mem_buffer */
742 for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
743 /* One chunk, but check for short chunk at end of buffer */
744 rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i)(((long) ptr->rowsperchunk) < ((long) ptr->rows_in_mem
- i) ? ((long) ptr->rowsperchunk) : ((long) ptr->rows_in_mem
- i))
;
745 /* Transfer no more than is currently defined */
746 thisrow = (long) ptr->cur_start_row + i;
747 rows = MIN(rows, (long) ptr->first_undef_row - thisrow)((rows) < ((long) ptr->first_undef_row - thisrow) ? (rows
) : ((long) ptr->first_undef_row - thisrow))
;
748 /* Transfer no more than fits in file */
749 rows = MIN(rows, (long) ptr->rows_in_array - thisrow)((rows) < ((long) ptr->rows_in_array - thisrow) ? (rows
) : ((long) ptr->rows_in_array - thisrow))
;
750 if (rows <= 0) /* this chunk might be past end of file! */
751 break;
752 byte_count = rows * bytesperrow;
753 if (writing)
754 (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
755 (void FAR *) ptr->mem_buffer[i],
756 file_offset, byte_count);
757 else
758 (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
759 (void FAR *) ptr->mem_buffer[i],
760 file_offset, byte_count);
761 file_offset += byte_count;
762 }
763}
764
765
766METHODDEF(JSAMPARRAY)static JSAMPARRAY
767access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
768 JDIMENSION start_row, JDIMENSION num_rows,
769 boolean writable)
770/* Access the part of a virtual sample array starting at start_row */
771/* and extending for num_rows rows. writable is true if */
772/* caller intends to modify the accessed area. */
773{
774 JDIMENSION end_row = start_row + num_rows;
775 JDIMENSION undef_row;
776
777 /* debugging check */
778 if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
779 ptr->mem_buffer == NULL((void*)0))
780 ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS)((cinfo)->err->msg_code = (JERR_BAD_VIRTUAL_ACCESS), (*
(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
;
781
782 /* Make the desired part of the virtual array accessible */
783 if (start_row < ptr->cur_start_row ||
784 end_row > ptr->cur_start_row+ptr->rows_in_mem) {
785 if (! ptr->b_s_open)
786 ERREXIT(cinfo, JERR_VIRTUAL_BUG)((cinfo)->err->msg_code = (JERR_VIRTUAL_BUG), (*(cinfo)
->err->error_exit) ((j_common_ptr) (cinfo)))
;
787 /* Flush old buffer contents if necessary */
788 if (ptr->dirty) {
789 do_sarray_io(cinfo, ptr, TRUE1);
790 ptr->dirty = FALSE0;
791 }
792 /* Decide what part of virtual array to access.
793 * Algorithm: if target address > current window, assume forward scan,
794 * load starting at target address. If target address < current window,
795 * assume backward scan, load so that target area is top of window.
796 * Note that when switching from forward write to forward read, will have
797 * start_row = 0, so the limiting case applies and we load from 0 anyway.
798 */
799 if (start_row > ptr->cur_start_row) {
800 ptr->cur_start_row = start_row;
801 } else {
802 /* use long arithmetic here to avoid overflow & unsigned problems */
803 long ltemp;
804
805 ltemp = (long) end_row - (long) ptr->rows_in_mem;
806 if (ltemp < 0)
807 ltemp = 0; /* don't fall off front end of file */
808 ptr->cur_start_row = (JDIMENSION) ltemp;
809 }
810 /* Read in the selected part of the array.
811 * During the initial write pass, we will do no actual read
812 * because the selected part is all undefined.
813 */
814 do_sarray_io(cinfo, ptr, FALSE0);
815 }
816 /* Ensure the accessed part of the array is defined; prezero if needed.
817 * To improve locality of access, we only prezero the part of the array
818 * that the caller is about to access, not the entire in-memory array.
819 */
820 if (ptr->first_undef_row < end_row) {
821 if (ptr->first_undef_row < start_row) {
822 if (writable) /* writer skipped over a section of array */
823 ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS)((cinfo)->err->msg_code = (JERR_BAD_VIRTUAL_ACCESS), (*
(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
;
824 undef_row = start_row; /* but reader is allowed to read ahead */
825 } else {
826 undef_row = ptr->first_undef_row;
827 }
828 if (writable)
829 ptr->first_undef_row = end_row;
830 if (ptr->pre_zero) {
831 size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE)((size_t) sizeof(JSAMPLE));
832 undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
833 end_row -= ptr->cur_start_row;
834 while (undef_row < end_row) {
835 jzero_farjZeroFar((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
836 undef_row++;
837 }
838 } else {
839 if (! writable) /* reader looking at undefined data */
840 ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS)((cinfo)->err->msg_code = (JERR_BAD_VIRTUAL_ACCESS), (*
(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
;
841 }
842 }
843 /* Flag the buffer dirty if caller will write in it */
844 if (writable)
845 ptr->dirty = TRUE1;
846 /* Return address of proper part of the buffer */
847 return ptr->mem_buffer + (start_row - ptr->cur_start_row);
848}
849
850
851METHODDEF(JBLOCKARRAY)static JBLOCKARRAY
852access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
853 JDIMENSION start_row, JDIMENSION num_rows,
854 boolean writable)
855/* Access the part of a virtual block array starting at start_row */
856/* and extending for num_rows rows. writable is true if */
857/* caller intends to modify the accessed area. */
858{
859 JDIMENSION end_row = start_row + num_rows;
860 JDIMENSION undef_row;
861
862 /* debugging check */
863 if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
864 ptr->mem_buffer == NULL((void*)0))
865 ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS)((cinfo)->err->msg_code = (JERR_BAD_VIRTUAL_ACCESS), (*
(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
;
866
867 /* Make the desired part of the virtual array accessible */
868 if (start_row < ptr->cur_start_row ||
869 end_row > ptr->cur_start_row+ptr->rows_in_mem) {
870 if (! ptr->b_s_open)
871 ERREXIT(cinfo, JERR_VIRTUAL_BUG)((cinfo)->err->msg_code = (JERR_VIRTUAL_BUG), (*(cinfo)
->err->error_exit) ((j_common_ptr) (cinfo)))
;
872 /* Flush old buffer contents if necessary */
873 if (ptr->dirty) {
874 do_barray_io(cinfo, ptr, TRUE1);
875 ptr->dirty = FALSE0;
876 }
877 /* Decide what part of virtual array to access.
878 * Algorithm: if target address > current window, assume forward scan,
879 * load starting at target address. If target address < current window,
880 * assume backward scan, load so that target area is top of window.
881 * Note that when switching from forward write to forward read, will have
882 * start_row = 0, so the limiting case applies and we load from 0 anyway.
883 */
884 if (start_row > ptr->cur_start_row) {
885 ptr->cur_start_row = start_row;
886 } else {
887 /* use long arithmetic here to avoid overflow & unsigned problems */
888 long ltemp;
889
890 ltemp = (long) end_row - (long) ptr->rows_in_mem;
891 if (ltemp < 0)
892 ltemp = 0; /* don't fall off front end of file */
893 ptr->cur_start_row = (JDIMENSION) ltemp;
894 }
895 /* Read in the selected part of the array.
896 * During the initial write pass, we will do no actual read
897 * because the selected part is all undefined.
898 */
899 do_barray_io(cinfo, ptr, FALSE0);
900 }
901 /* Ensure the accessed part of the array is defined; prezero if needed.
902 * To improve locality of access, we only prezero the part of the array
903 * that the caller is about to access, not the entire in-memory array.
904 */
905 if (ptr->first_undef_row < end_row) {
906 if (ptr->first_undef_row < start_row) {
907 if (writable) /* writer skipped over a section of array */
908 ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS)((cinfo)->err->msg_code = (JERR_BAD_VIRTUAL_ACCESS), (*
(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
;
909 undef_row = start_row; /* but reader is allowed to read ahead */
910 } else {
911 undef_row = ptr->first_undef_row;
912 }
913 if (writable)
914 ptr->first_undef_row = end_row;
915 if (ptr->pre_zero) {
916 size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK)((size_t) sizeof(JBLOCK));
917 undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
918 end_row -= ptr->cur_start_row;
919 while (undef_row < end_row) {
920 jzero_farjZeroFar((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
921 undef_row++;
922 }
923 } else {
924 if (! writable) /* reader looking at undefined data */
925 ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS)((cinfo)->err->msg_code = (JERR_BAD_VIRTUAL_ACCESS), (*
(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
;
926 }
927 }
928 /* Flag the buffer dirty if caller will write in it */
929 if (writable)
930 ptr->dirty = TRUE1;
931 /* Return address of proper part of the buffer */
932 return ptr->mem_buffer + (start_row - ptr->cur_start_row);
933}
934
935
936/*
937 * Release all objects belonging to a specified pool.
938 */
939
940METHODDEF(void)static void
941free_pool (j_common_ptr cinfo, int pool_id)
942{
943 my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
944 small_pool_ptr shdr_ptr;
945 large_pool_ptr lhdr_ptr;
946 size_t space_freed;
947
948 if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS2)
949 ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id)((cinfo)->err->msg_code = (JERR_BAD_POOL_ID), (cinfo)->
err->msg_parm.i[0] = (pool_id), (*(cinfo)->err->error_exit
) ((j_common_ptr) (cinfo)))
; /* safety check */
950
951#ifdef MEM_STATS
952 if (cinfo->err->trace_level > 1)
953 print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
954#endif
955
956 /* If freeing IMAGE pool, close any virtual arrays first */
957 if (pool_id == JPOOL_IMAGE1) {
958 jvirt_sarray_ptr sptr;
959 jvirt_barray_ptr bptr;
960
961 for (sptr = mem->virt_sarray_list; sptr != NULL((void*)0); sptr = sptr->next) {
962 if (sptr->b_s_open) { /* there may be no backing store */
963 sptr->b_s_open = FALSE0; /* prevent recursive close if error */
964 (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
965 }
966 }
967 mem->virt_sarray_list = NULL((void*)0);
968 for (bptr = mem->virt_barray_list; bptr != NULL((void*)0); bptr = bptr->next) {
969 if (bptr->b_s_open) { /* there may be no backing store */
970 bptr->b_s_open = FALSE0; /* prevent recursive close if error */
971 (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
972 }
973 }
974 mem->virt_barray_list = NULL((void*)0);
975 }
976
977 /* Release large objects */
978 lhdr_ptr = mem->large_list[pool_id];
979 mem->large_list[pool_id] = NULL((void*)0);
980
981 while (lhdr_ptr != NULL((void*)0)) {
982 large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
983 space_freed = lhdr_ptr->hdr.bytes_used +
984 lhdr_ptr->hdr.bytes_left +
985 SIZEOF(large_pool_hdr)((size_t) sizeof(large_pool_hdr));
986 jpeg_free_largejFreeLarge(cinfo, (void FAR *) lhdr_ptr, space_freed);
987 mem->total_space_allocated -= space_freed;
988 lhdr_ptr = next_lhdr_ptr;
989 }
990
991 /* Release small objects */
992 shdr_ptr = mem->small_list[pool_id];
993 mem->small_list[pool_id] = NULL((void*)0);
994
995 while (shdr_ptr != NULL((void*)0)) {
996 small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
997 space_freed = shdr_ptr->hdr.bytes_used +
998 shdr_ptr->hdr.bytes_left +
999 SIZEOF(small_pool_hdr)((size_t) sizeof(small_pool_hdr));
1000 jpeg_free_smalljFreeSmall(cinfo, (void *) shdr_ptr, space_freed);
1001 mem->total_space_allocated -= space_freed;
1002 shdr_ptr = next_shdr_ptr;
1003 }
1004}
1005
1006
1007/*
1008 * Close up shop entirely.
1009 * Note that this cannot be called unless cinfo->mem is non-NULL.
1010 */
1011
1012METHODDEF(void)static void
1013self_destruct (j_common_ptr cinfo)
1014{
1015 int pool;
1016
1017 /* Close all backing store, release all memory.
1018 * Releasing pools in reverse order might help avoid fragmentation
1019 * with some (brain-damaged) malloc libraries.
1020 */
1021 for (pool = JPOOL_NUMPOOLS2-1; pool >= JPOOL_PERMANENT0; pool--) {
1022 free_pool(cinfo, pool);
1023 }
1024
1025 /* Release the memory manager control block too. */
1026 jpeg_free_smalljFreeSmall(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr)((size_t) sizeof(my_memory_mgr)));
1027 cinfo->mem = NULL((void*)0); /* ensures I will be called only once */
1028
1029 jpeg_mem_termjMemTerm(cinfo); /* system-dependent cleanup */
1030}
1031
1032
1033/*
1034 * Memory manager initialization.
1035 * When this is called, only the error manager pointer is valid in cinfo!
1036 */
1037
1038GLOBAL(void)void
1039jinit_memory_mgrjIMemMgr (j_common_ptr cinfo)
1040{
1041 my_mem_ptr mem;
1042 size_t max_to_use;
1043 int pool;
1044 size_t test_mac;
1045
1046 cinfo->mem = NULL((void*)0); /* for safety if init fails */
1047
1048 /* Check for configuration errors.
1049 * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
1050 * doesn't reflect any real hardware alignment requirement.
1051 * The test is a little tricky: for X>0, X and X-1 have no one-bits
1052 * in common if and only if X is a power of 2, ie has only one one-bit.
1053 * Some compilers may give an "unreachable code" warning here; ignore it.
1054 */
1055 if ((SIZEOF(ALIGN_TYPE)((size_t) sizeof(double)) & (SIZEOF(ALIGN_TYPE)((size_t) sizeof(double))-1)) != 0)
1056 ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE)((cinfo)->err->msg_code = (JERR_BAD_ALIGN_TYPE), (*(cinfo
)->err->error_exit) ((j_common_ptr) (cinfo)))
;
1057 /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
1058 * a multiple of SIZEOF(ALIGN_TYPE).
1059 * Again, an "unreachable code" warning may be ignored here.
1060 * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
1061 */
1062 test_mac = (size_t) MAX_ALLOC_CHUNK1000000000L;
1063 if ((long) test_mac != MAX_ALLOC_CHUNK1000000000L ||
1064 (MAX_ALLOC_CHUNK1000000000L % SIZEOF(ALIGN_TYPE)((size_t) sizeof(double))) != 0)
1065 ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK)((cinfo)->err->msg_code = (JERR_BAD_ALLOC_CHUNK), (*(cinfo
)->err->error_exit) ((j_common_ptr) (cinfo)))
;
1066
1067 max_to_use = jpeg_mem_initjMemInit(cinfo); /* system-dependent initialization */
1068
1069 /* Attempt to allocate memory manager's control block */
1070 mem = (my_mem_ptr) jpeg_get_smalljGetSmall(cinfo, SIZEOF(my_memory_mgr)((size_t) sizeof(my_memory_mgr)));
1071
1072 if (mem == NULL((void*)0)) {
1073 jpeg_mem_termjMemTerm(cinfo); /* system-dependent cleanup */
1074 ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0)((cinfo)->err->msg_code = (JERR_OUT_OF_MEMORY), (cinfo)
->err->msg_parm.i[0] = (0), (*(cinfo)->err->error_exit
) ((j_common_ptr) (cinfo)))
;
1075 }
1076
1077 /* OK, fill in the method pointers */
1078 mem->pub.alloc_small = alloc_small;
1079 mem->pub.alloc_large = alloc_large;
1080 mem->pub.alloc_sarray = alloc_sarray;
1081 mem->pub.alloc_barray = alloc_barray;
1082 mem->pub.request_virt_sarray = request_virt_sarray;
1083 mem->pub.request_virt_barray = request_virt_barray;
1084 mem->pub.realize_virt_arrays = realize_virt_arrays;
1085 mem->pub.access_virt_sarray = access_virt_sarray;
1086 mem->pub.access_virt_barray = access_virt_barray;
1087 mem->pub.free_pool = free_pool;
1088 mem->pub.self_destruct = self_destruct;
1089
1090 /* Make MAX_ALLOC_CHUNK accessible to other modules */
1091 mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK1000000000L;
1092
1093 /* Initialize working state */
1094 mem->pub.max_memory_to_use = max_to_use;
1095
1096 for (pool = JPOOL_NUMPOOLS2-1; pool >= JPOOL_PERMANENT0; pool--) {
1097 mem->small_list[pool] = NULL((void*)0);
1098 mem->large_list[pool] = NULL((void*)0);
1099 }
1100 mem->virt_sarray_list = NULL((void*)0);
1101 mem->virt_barray_list = NULL((void*)0);
1102
1103 mem->total_space_allocated = SIZEOF(my_memory_mgr)((size_t) sizeof(my_memory_mgr));
1104
1105 /* Declare ourselves open for business */
1106 cinfo->mem = & mem->pub;
1107
1108 /* Check for an environment variable JPEGMEM; if found, override the
1109 * default max_memory setting from jpeg_mem_init. Note that the
1110 * surrounding application may again override this value.
1111 * If your system doesn't support getenv(), define NO_GETENV to disable
1112 * this feature.
1113 */
1114#ifndef NO_GETENV
1115 { char * memenv;
1116
1117 if ((memenv = getenv("JPEGMEM")) != NULL((void*)0)) {
1118 char ch = 'x';
1119 unsigned int mem_max = 0u;
1120
1121 if (sscanf(memenv, "%u%c", &mem_max, &ch) > 0) {
1122 max_to_use = (size_t)mem_max;
1123 if (ch == 'm' || ch == 'M')
1124 max_to_use *= 1000L;
1125 mem->pub.max_memory_to_use = max_to_use * 1000L;
1126 }
1127 }
1128 }
1129#endif
1130
1131}