jmemmgr.c 40 KB

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