jmemmgr.c 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  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. #if !defined(_MSC_VER) || _MSC_VER > 1600
  35. #include <stdint.h>
  36. #endif
  37. #include <limits.h>
  38. #ifndef NO_GETENV
  39. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  40. extern char *getenv(const char *name);
  41. #endif
  42. #endif
  43. LOCAL(size_t)
  44. round_up_pow2(size_t a, size_t b)
  45. /* a rounded up to the next multiple of b, i.e. ceil(a/b)*b */
  46. /* Assumes a >= 0, b > 0, and b is a power of 2 */
  47. {
  48. return ((a + b - 1) & (~(b - 1)));
  49. }
  50. /*
  51. * Some important notes:
  52. * The allocation routines provided here must never return NULL.
  53. * They should exit to error_exit if unsuccessful.
  54. *
  55. * It's not a good idea to try to merge the sarray and barray routines,
  56. * even though they are textually almost the same, because samples are
  57. * usually stored as bytes while coefficients are shorts or ints. Thus,
  58. * in machines where byte pointers have a different representation from
  59. * word pointers, the resulting machine code could not be the same.
  60. */
  61. /*
  62. * Many machines require storage alignment: longs must start on 4-byte
  63. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  64. * always returns pointers that are multiples of the worst-case alignment
  65. * requirement, and we had better do so too.
  66. * There isn't any really portable way to determine the worst-case alignment
  67. * requirement. This module assumes that the alignment requirement is
  68. * multiples of ALIGN_SIZE.
  69. * By default, we define ALIGN_SIZE as sizeof(double). This is necessary on
  70. * some workstations (where doubles really do need 8-byte alignment) and will
  71. * work fine on nearly everything. If your machine has lesser alignment needs,
  72. * you can save a few bytes by making ALIGN_SIZE smaller.
  73. * The only place I know of where this will NOT work is certain Macintosh
  74. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  75. * Doing 10-byte alignment is counterproductive because longwords won't be
  76. * aligned well. Put "#define ALIGN_SIZE 4" in jconfig.h if you have
  77. * such a compiler.
  78. */
  79. #ifndef ALIGN_SIZE /* so can override from jconfig.h */
  80. #ifndef WITH_SIMD
  81. #define ALIGN_SIZE sizeof(double)
  82. #else
  83. #define ALIGN_SIZE 32 /* Most of the SIMD instructions we support require
  84. 16-byte (128-bit) alignment, but AVX2 requires
  85. 32-byte alignment. */
  86. #endif
  87. #endif
  88. /*
  89. * We allocate objects from "pools", where each pool is gotten with a single
  90. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  91. * overhead within a pool, except for alignment padding. Each pool has a
  92. * header with a link to the next pool of the same class.
  93. * Small and large pool headers are identical.
  94. */
  95. typedef struct small_pool_struct *small_pool_ptr;
  96. typedef struct small_pool_struct {
  97. small_pool_ptr next; /* next in list of pools */
  98. size_t bytes_used; /* how many bytes already used within pool */
  99. size_t bytes_left; /* bytes still available in this pool */
  100. } small_pool_hdr;
  101. typedef struct large_pool_struct *large_pool_ptr;
  102. typedef struct large_pool_struct {
  103. large_pool_ptr next; /* next in list of pools */
  104. size_t bytes_used; /* how many bytes already used within pool */
  105. size_t bytes_left; /* bytes still available in this pool */
  106. } large_pool_hdr;
  107. /*
  108. * Here is the full definition of a memory manager object.
  109. */
  110. typedef struct {
  111. struct jpeg_memory_mgr pub; /* public fields */
  112. /* Each pool identifier (lifetime class) names a linked list of pools. */
  113. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  114. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  115. /* Since we only have one lifetime class of virtual arrays, only one
  116. * linked list is necessary (for each datatype). Note that the virtual
  117. * array control blocks being linked together are actually stored somewhere
  118. * in the small-pool list.
  119. */
  120. jvirt_sarray_ptr virt_sarray_list;
  121. jvirt_barray_ptr virt_barray_list;
  122. /* This counts total space obtained from jpeg_get_small/large */
  123. size_t total_space_allocated;
  124. /* alloc_sarray and alloc_barray set this value for use by virtual
  125. * array routines.
  126. */
  127. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  128. } my_memory_mgr;
  129. typedef my_memory_mgr *my_mem_ptr;
  130. /*
  131. * The control blocks for virtual arrays.
  132. * Note that these blocks are allocated in the "small" pool area.
  133. * System-dependent info for the associated backing store (if any) is hidden
  134. * inside the backing_store_info struct.
  135. */
  136. struct jvirt_sarray_control {
  137. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  138. JDIMENSION rows_in_array; /* total virtual array height */
  139. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  140. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  141. JDIMENSION rows_in_mem; /* height of memory buffer */
  142. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  143. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  144. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  145. boolean pre_zero; /* pre-zero mode requested? */
  146. boolean dirty; /* do current buffer contents need written? */
  147. boolean b_s_open; /* is backing-store data valid? */
  148. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  149. backing_store_info b_s_info; /* System-dependent control info */
  150. };
  151. struct jvirt_barray_control {
  152. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  153. JDIMENSION rows_in_array; /* total virtual array height */
  154. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  155. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  156. JDIMENSION rows_in_mem; /* height of memory buffer */
  157. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  158. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  159. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  160. boolean pre_zero; /* pre-zero mode requested? */
  161. boolean dirty; /* do current buffer contents need written? */
  162. boolean b_s_open; /* is backing-store data valid? */
  163. jvirt_barray_ptr next; /* link to next virtual barray control block */
  164. backing_store_info b_s_info; /* System-dependent control info */
  165. };
  166. #ifdef MEM_STATS /* optional extra stuff for statistics */
  167. LOCAL(void)
  168. print_mem_stats(j_common_ptr cinfo, int pool_id)
  169. {
  170. my_mem_ptr mem = (my_mem_ptr)cinfo->mem;
  171. small_pool_ptr shdr_ptr;
  172. large_pool_ptr lhdr_ptr;
  173. /* Since this is only a debugging stub, we can cheat a little by using
  174. * fprintf directly rather than going through the trace message code.
  175. * This is helpful because message parm array can't handle longs.
  176. */
  177. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  178. pool_id, mem->total_space_allocated);
  179. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  180. lhdr_ptr = lhdr_ptr->next) {
  181. fprintf(stderr, " Large chunk used %ld\n", (long)lhdr_ptr->bytes_used);
  182. }
  183. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  184. shdr_ptr = shdr_ptr->next) {
  185. fprintf(stderr, " Small chunk used %ld free %ld\n",
  186. (long)shdr_ptr->bytes_used, (long)shdr_ptr->bytes_left);
  187. }
  188. }
  189. #endif /* MEM_STATS */
  190. LOCAL(void)
  191. out_of_memory(j_common_ptr cinfo, int which)
  192. /* Report an out-of-memory error and stop execution */
  193. /* If we compiled MEM_STATS support, report alloc requests before dying */
  194. {
  195. #ifdef MEM_STATS
  196. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  197. #endif
  198. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  199. }
  200. /*
  201. * Allocation of "small" objects.
  202. *
  203. * For these, we use pooled storage. When a new pool must be created,
  204. * we try to get enough space for the current request plus a "slop" factor,
  205. * where the slop will be the amount of leftover space in the new pool.
  206. * The speed vs. space tradeoff is largely determined by the slop values.
  207. * A different slop value is provided for each pool class (lifetime),
  208. * and we also distinguish the first pool of a class from later ones.
  209. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  210. * machines, but may be too small if longs are 64 bits or more.
  211. *
  212. * Since we do not know what alignment malloc() gives us, we have to
  213. * allocate ALIGN_SIZE-1 extra space per pool to have room for alignment
  214. * adjustment.
  215. */
  216. static const size_t first_pool_slop[JPOOL_NUMPOOLS] = {
  217. 1600, /* first PERMANENT pool */
  218. 16000 /* first IMAGE pool */
  219. };
  220. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] = {
  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, JDIMENSION samplesperrow,
  375. 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, JDIMENSION blocksperrow,
  426. 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, boolean writable)
  714. /* Access the part of a virtual sample array starting at start_row */
  715. /* and extending for num_rows rows. writable is true if */
  716. /* caller intends to modify the accessed area. */
  717. {
  718. JDIMENSION end_row = start_row + num_rows;
  719. JDIMENSION undef_row;
  720. /* debugging check */
  721. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  722. ptr->mem_buffer == NULL)
  723. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  724. /* Make the desired part of the virtual array accessible */
  725. if (start_row < ptr->cur_start_row ||
  726. end_row > ptr->cur_start_row + ptr->rows_in_mem) {
  727. if (!ptr->b_s_open)
  728. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  729. /* Flush old buffer contents if necessary */
  730. if (ptr->dirty) {
  731. do_sarray_io(cinfo, ptr, TRUE);
  732. ptr->dirty = FALSE;
  733. }
  734. /* Decide what part of virtual array to access.
  735. * Algorithm: if target address > current window, assume forward scan,
  736. * load starting at target address. If target address < current window,
  737. * assume backward scan, load so that target area is top of window.
  738. * Note that when switching from forward write to forward read, will have
  739. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  740. */
  741. if (start_row > ptr->cur_start_row) {
  742. ptr->cur_start_row = start_row;
  743. } else {
  744. /* use long arithmetic here to avoid overflow & unsigned problems */
  745. long ltemp;
  746. ltemp = (long)end_row - (long)ptr->rows_in_mem;
  747. if (ltemp < 0)
  748. ltemp = 0; /* don't fall off front end of file */
  749. ptr->cur_start_row = (JDIMENSION)ltemp;
  750. }
  751. /* Read in the selected part of the array.
  752. * During the initial write pass, we will do no actual read
  753. * because the selected part is all undefined.
  754. */
  755. do_sarray_io(cinfo, ptr, FALSE);
  756. }
  757. /* Ensure the accessed part of the array is defined; prezero if needed.
  758. * To improve locality of access, we only prezero the part of the array
  759. * that the caller is about to access, not the entire in-memory array.
  760. */
  761. if (ptr->first_undef_row < end_row) {
  762. if (ptr->first_undef_row < start_row) {
  763. if (writable) /* writer skipped over a section of array */
  764. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  765. undef_row = start_row; /* but reader is allowed to read ahead */
  766. } else {
  767. undef_row = ptr->first_undef_row;
  768. }
  769. if (writable)
  770. ptr->first_undef_row = end_row;
  771. if (ptr->pre_zero) {
  772. size_t bytesperrow = (size_t)ptr->samplesperrow * sizeof(JSAMPLE);
  773. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  774. end_row -= ptr->cur_start_row;
  775. while (undef_row < end_row) {
  776. jzero_far((void *)ptr->mem_buffer[undef_row], bytesperrow);
  777. undef_row++;
  778. }
  779. } else {
  780. if (!writable) /* reader looking at undefined data */
  781. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  782. }
  783. }
  784. /* Flag the buffer dirty if caller will write in it */
  785. if (writable)
  786. ptr->dirty = TRUE;
  787. /* Return address of proper part of the buffer */
  788. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  789. }
  790. METHODDEF(JBLOCKARRAY)
  791. access_virt_barray(j_common_ptr cinfo, jvirt_barray_ptr ptr,
  792. JDIMENSION start_row, JDIMENSION num_rows, boolean writable)
  793. /* Access the part of a virtual block array starting at start_row */
  794. /* and extending for num_rows rows. writable is true if */
  795. /* caller intends to modify the accessed area. */
  796. {
  797. JDIMENSION end_row = start_row + num_rows;
  798. JDIMENSION undef_row;
  799. /* debugging check */
  800. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  801. ptr->mem_buffer == NULL)
  802. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  803. /* Make the desired part of the virtual array accessible */
  804. if (start_row < ptr->cur_start_row ||
  805. end_row > ptr->cur_start_row + ptr->rows_in_mem) {
  806. if (!ptr->b_s_open)
  807. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  808. /* Flush old buffer contents if necessary */
  809. if (ptr->dirty) {
  810. do_barray_io(cinfo, ptr, TRUE);
  811. ptr->dirty = FALSE;
  812. }
  813. /* Decide what part of virtual array to access.
  814. * Algorithm: if target address > current window, assume forward scan,
  815. * load starting at target address. If target address < current window,
  816. * assume backward scan, load so that target area is top of window.
  817. * Note that when switching from forward write to forward read, will have
  818. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  819. */
  820. if (start_row > ptr->cur_start_row) {
  821. ptr->cur_start_row = start_row;
  822. } else {
  823. /* use long arithmetic here to avoid overflow & unsigned problems */
  824. long ltemp;
  825. ltemp = (long)end_row - (long)ptr->rows_in_mem;
  826. if (ltemp < 0)
  827. ltemp = 0; /* don't fall off front end of file */
  828. ptr->cur_start_row = (JDIMENSION)ltemp;
  829. }
  830. /* Read in the selected part of the array.
  831. * During the initial write pass, we will do no actual read
  832. * because the selected part is all undefined.
  833. */
  834. do_barray_io(cinfo, ptr, FALSE);
  835. }
  836. /* Ensure the accessed part of the array is defined; prezero if needed.
  837. * To improve locality of access, we only prezero the part of the array
  838. * that the caller is about to access, not the entire in-memory array.
  839. */
  840. if (ptr->first_undef_row < end_row) {
  841. if (ptr->first_undef_row < start_row) {
  842. if (writable) /* writer skipped over a section of array */
  843. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  844. undef_row = start_row; /* but reader is allowed to read ahead */
  845. } else {
  846. undef_row = ptr->first_undef_row;
  847. }
  848. if (writable)
  849. ptr->first_undef_row = end_row;
  850. if (ptr->pre_zero) {
  851. size_t bytesperrow = (size_t)ptr->blocksperrow * sizeof(JBLOCK);
  852. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  853. end_row -= ptr->cur_start_row;
  854. while (undef_row < end_row) {
  855. jzero_far((void *)ptr->mem_buffer[undef_row], bytesperrow);
  856. undef_row++;
  857. }
  858. } else {
  859. if (!writable) /* reader looking at undefined data */
  860. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  861. }
  862. }
  863. /* Flag the buffer dirty if caller will write in it */
  864. if (writable)
  865. ptr->dirty = TRUE;
  866. /* Return address of proper part of the buffer */
  867. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  868. }
  869. /*
  870. * Release all objects belonging to a specified pool.
  871. */
  872. METHODDEF(void)
  873. free_pool(j_common_ptr cinfo, int pool_id)
  874. {
  875. my_mem_ptr mem = (my_mem_ptr)cinfo->mem;
  876. small_pool_ptr shdr_ptr;
  877. large_pool_ptr lhdr_ptr;
  878. size_t space_freed;
  879. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  880. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  881. #ifdef MEM_STATS
  882. if (cinfo->err->trace_level > 1)
  883. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  884. #endif
  885. /* If freeing IMAGE pool, close any virtual arrays first */
  886. if (pool_id == JPOOL_IMAGE) {
  887. jvirt_sarray_ptr sptr;
  888. jvirt_barray_ptr bptr;
  889. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  890. if (sptr->b_s_open) { /* there may be no backing store */
  891. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  892. (*sptr->b_s_info.close_backing_store) (cinfo, &sptr->b_s_info);
  893. }
  894. }
  895. mem->virt_sarray_list = NULL;
  896. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  897. if (bptr->b_s_open) { /* there may be no backing store */
  898. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  899. (*bptr->b_s_info.close_backing_store) (cinfo, &bptr->b_s_info);
  900. }
  901. }
  902. mem->virt_barray_list = NULL;
  903. }
  904. /* Release large objects */
  905. lhdr_ptr = mem->large_list[pool_id];
  906. mem->large_list[pool_id] = NULL;
  907. while (lhdr_ptr != NULL) {
  908. large_pool_ptr next_lhdr_ptr = lhdr_ptr->next;
  909. space_freed = lhdr_ptr->bytes_used +
  910. lhdr_ptr->bytes_left +
  911. sizeof(large_pool_hdr);
  912. jpeg_free_large(cinfo, (void *)lhdr_ptr, space_freed);
  913. mem->total_space_allocated -= space_freed;
  914. lhdr_ptr = next_lhdr_ptr;
  915. }
  916. /* Release small objects */
  917. shdr_ptr = mem->small_list[pool_id];
  918. mem->small_list[pool_id] = NULL;
  919. while (shdr_ptr != NULL) {
  920. small_pool_ptr next_shdr_ptr = shdr_ptr->next;
  921. space_freed = shdr_ptr->bytes_used + shdr_ptr->bytes_left +
  922. sizeof(small_pool_hdr);
  923. jpeg_free_small(cinfo, (void *)shdr_ptr, space_freed);
  924. mem->total_space_allocated -= space_freed;
  925. shdr_ptr = next_shdr_ptr;
  926. }
  927. }
  928. /*
  929. * Close up shop entirely.
  930. * Note that this cannot be called unless cinfo->mem is non-NULL.
  931. */
  932. METHODDEF(void)
  933. self_destruct(j_common_ptr cinfo)
  934. {
  935. int pool;
  936. /* Close all backing store, release all memory.
  937. * Releasing pools in reverse order might help avoid fragmentation
  938. * with some (brain-damaged) malloc libraries.
  939. */
  940. for (pool = JPOOL_NUMPOOLS - 1; pool >= JPOOL_PERMANENT; pool--) {
  941. free_pool(cinfo, pool);
  942. }
  943. /* Release the memory manager control block too. */
  944. jpeg_free_small(cinfo, (void *)cinfo->mem, sizeof(my_memory_mgr));
  945. cinfo->mem = NULL; /* ensures I will be called only once */
  946. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  947. }
  948. /*
  949. * Memory manager initialization.
  950. * When this is called, only the error manager pointer is valid in cinfo!
  951. */
  952. GLOBAL(void)
  953. jinit_memory_mgr(j_common_ptr cinfo)
  954. {
  955. my_mem_ptr mem;
  956. long max_to_use;
  957. int pool;
  958. size_t test_mac;
  959. cinfo->mem = NULL; /* for safety if init fails */
  960. /* Check for configuration errors.
  961. * sizeof(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  962. * doesn't reflect any real hardware alignment requirement.
  963. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  964. * in common if and only if X is a power of 2, ie has only one one-bit.
  965. * Some compilers may give an "unreachable code" warning here; ignore it.
  966. */
  967. if ((ALIGN_SIZE & (ALIGN_SIZE - 1)) != 0)
  968. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  969. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  970. * a multiple of ALIGN_SIZE.
  971. * Again, an "unreachable code" warning may be ignored here.
  972. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  973. */
  974. test_mac = (size_t)MAX_ALLOC_CHUNK;
  975. if ((long)test_mac != MAX_ALLOC_CHUNK ||
  976. (MAX_ALLOC_CHUNK % ALIGN_SIZE) != 0)
  977. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  978. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  979. /* Attempt to allocate memory manager's control block */
  980. mem = (my_mem_ptr)jpeg_get_small(cinfo, sizeof(my_memory_mgr));
  981. if (mem == NULL) {
  982. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  983. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  984. }
  985. /* OK, fill in the method pointers */
  986. mem->pub.alloc_small = alloc_small;
  987. mem->pub.alloc_large = alloc_large;
  988. mem->pub.alloc_sarray = alloc_sarray;
  989. mem->pub.alloc_barray = alloc_barray;
  990. mem->pub.request_virt_sarray = request_virt_sarray;
  991. mem->pub.request_virt_barray = request_virt_barray;
  992. mem->pub.realize_virt_arrays = realize_virt_arrays;
  993. mem->pub.access_virt_sarray = access_virt_sarray;
  994. mem->pub.access_virt_barray = access_virt_barray;
  995. mem->pub.free_pool = free_pool;
  996. mem->pub.self_destruct = self_destruct;
  997. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  998. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  999. /* Initialize working state */
  1000. mem->pub.max_memory_to_use = max_to_use;
  1001. for (pool = JPOOL_NUMPOOLS - 1; pool >= JPOOL_PERMANENT; pool--) {
  1002. mem->small_list[pool] = NULL;
  1003. mem->large_list[pool] = NULL;
  1004. }
  1005. mem->virt_sarray_list = NULL;
  1006. mem->virt_barray_list = NULL;
  1007. mem->total_space_allocated = sizeof(my_memory_mgr);
  1008. /* Declare ourselves open for business */
  1009. cinfo->mem = &mem->pub;
  1010. /* Check for an environment variable JPEGMEM; if found, override the
  1011. * default max_memory setting from jpeg_mem_init. Note that the
  1012. * surrounding application may again override this value.
  1013. * If your system doesn't support getenv(), define NO_GETENV to disable
  1014. * this feature.
  1015. */
  1016. #ifndef NO_GETENV
  1017. {
  1018. char *memenv;
  1019. if ((memenv = getenv("JPEGMEM")) != NULL) {
  1020. char ch = 'x';
  1021. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  1022. if (ch == 'm' || ch == 'M')
  1023. max_to_use *= 1000L;
  1024. mem->pub.max_memory_to_use = max_to_use * 1000L;
  1025. }
  1026. }
  1027. }
  1028. #endif
  1029. }