jmemmgr.c 44 KB

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