jmemmgr.c 44 KB

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