jmemmgr.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  1. /*
  2. * jmemmgr.c
  3. *
  4. * Copyright (C) 1991-1997, Thomas G. Lane.
  5. * Modified 2011-2019 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. size_t 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, (long) 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. size_t odd_bytes, min_request, slop;
  223. char * data_ptr;
  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) rowsperchunk * (size_t) samplesperrow * SIZEOF(JSAMPLE));
  365. for (i = rowsperchunk; i > 0; i--) {
  366. result[currow++] = workspace;
  367. workspace += samplesperrow;
  368. }
  369. }
  370. return result;
  371. }
  372. /*
  373. * Creation of 2-D coefficient-block arrays.
  374. * This is essentially the same as the code for sample arrays, above.
  375. */
  376. METHODDEF(JBLOCKARRAY)
  377. alloc_barray (j_common_ptr cinfo, int pool_id,
  378. JDIMENSION blocksperrow, JDIMENSION numrows)
  379. /* Allocate a 2-D coefficient-block array */
  380. {
  381. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  382. JBLOCKARRAY result;
  383. JBLOCKROW workspace;
  384. JDIMENSION rowsperchunk, currow, i;
  385. long ltemp;
  386. /* Calculate max # of rows allowed in one allocation chunk */
  387. ltemp = (MAX_ALLOC_CHUNK - SIZEOF(large_pool_hdr)) /
  388. ((long) blocksperrow * SIZEOF(JBLOCK));
  389. if (ltemp <= 0)
  390. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  391. if (ltemp < (long) numrows)
  392. rowsperchunk = (JDIMENSION) ltemp;
  393. else
  394. rowsperchunk = numrows;
  395. mem->last_rowsperchunk = rowsperchunk;
  396. /* Get space for row pointers (small object) */
  397. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  398. (size_t) numrows * SIZEOF(JBLOCKROW));
  399. /* Get the rows themselves (large objects) */
  400. currow = 0;
  401. while (currow < numrows) {
  402. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  403. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  404. (size_t) rowsperchunk * (size_t) blocksperrow * SIZEOF(JBLOCK));
  405. for (i = rowsperchunk; i > 0; i--) {
  406. result[currow++] = workspace;
  407. workspace += blocksperrow;
  408. }
  409. }
  410. return result;
  411. }
  412. /*
  413. * About virtual array management:
  414. *
  415. * The above "normal" array routines are only used to allocate strip buffers
  416. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  417. * are handled as "virtual" arrays. The array is still accessed a strip at a
  418. * time, but the memory manager must save the whole array for repeated
  419. * accesses. The intended implementation is that there is a strip buffer in
  420. * memory (as high as is possible given the desired memory limit), plus a
  421. * backing file that holds the rest of the array.
  422. *
  423. * The request_virt_array routines are told the total size of the image and
  424. * the maximum number of rows that will be accessed at once. The in-memory
  425. * buffer must be at least as large as the maxaccess value.
  426. *
  427. * The request routines create control blocks but not the in-memory buffers.
  428. * That is postponed until realize_virt_arrays is called. At that time the
  429. * total amount of space needed is known (approximately, anyway), so free
  430. * memory can be divided up fairly.
  431. *
  432. * The access_virt_array routines are responsible for making a specific strip
  433. * area accessible (after reading or writing the backing file, if necessary).
  434. * Note that the access routines are told whether the caller intends to modify
  435. * the accessed strip; during a read-only pass this saves having to rewrite
  436. * data to disk. The access routines are also responsible for pre-zeroing
  437. * any newly accessed rows, if pre-zeroing was requested.
  438. *
  439. * In current usage, the access requests are usually for nonoverlapping
  440. * strips; that is, successive access start_row numbers differ by exactly
  441. * num_rows = maxaccess. This means we can get good performance with simple
  442. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  443. * of the access height; then there will never be accesses across bufferload
  444. * boundaries. The code will still work with overlapping access requests,
  445. * but it doesn't handle bufferload overlaps very efficiently.
  446. */
  447. METHODDEF(jvirt_sarray_ptr)
  448. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  449. JDIMENSION samplesperrow, JDIMENSION numrows,
  450. JDIMENSION maxaccess)
  451. /* Request a virtual 2-D sample array */
  452. {
  453. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  454. jvirt_sarray_ptr result;
  455. /* Only IMAGE-lifetime virtual arrays are currently supported */
  456. if (pool_id != JPOOL_IMAGE)
  457. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  458. /* get control block */
  459. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  460. SIZEOF(struct jvirt_sarray_control));
  461. result->mem_buffer = NULL; /* marks array not yet realized */
  462. result->rows_in_array = numrows;
  463. result->samplesperrow = samplesperrow;
  464. result->maxaccess = maxaccess;
  465. result->pre_zero = pre_zero;
  466. result->b_s_open = FALSE; /* no associated backing-store object */
  467. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  468. mem->virt_sarray_list = result;
  469. return result;
  470. }
  471. METHODDEF(jvirt_barray_ptr)
  472. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  473. JDIMENSION blocksperrow, JDIMENSION numrows,
  474. JDIMENSION maxaccess)
  475. /* Request a virtual 2-D coefficient-block array */
  476. {
  477. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  478. jvirt_barray_ptr result;
  479. /* Only IMAGE-lifetime virtual arrays are currently supported */
  480. if (pool_id != JPOOL_IMAGE)
  481. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  482. /* get control block */
  483. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  484. SIZEOF(struct jvirt_barray_control));
  485. result->mem_buffer = NULL; /* marks array not yet realized */
  486. result->rows_in_array = numrows;
  487. result->blocksperrow = blocksperrow;
  488. result->maxaccess = maxaccess;
  489. result->pre_zero = pre_zero;
  490. result->b_s_open = FALSE; /* no associated backing-store object */
  491. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  492. mem->virt_barray_list = result;
  493. return result;
  494. }
  495. METHODDEF(void)
  496. realize_virt_arrays (j_common_ptr cinfo)
  497. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  498. {
  499. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  500. long bytesperrow, space_per_minheight, maximum_space;
  501. long avail_mem, minheights, max_minheights;
  502. jvirt_sarray_ptr sptr;
  503. jvirt_barray_ptr bptr;
  504. /* Compute the minimum space needed (maxaccess rows in each buffer)
  505. * and the maximum space needed (full image height in each buffer).
  506. * These may be of use to the system-dependent jpeg_mem_available routine.
  507. */
  508. space_per_minheight = 0;
  509. maximum_space = 0;
  510. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  511. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  512. bytesperrow = (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  513. space_per_minheight += (long) sptr->maxaccess * bytesperrow;
  514. maximum_space += (long) sptr->rows_in_array * bytesperrow;
  515. }
  516. }
  517. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  518. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  519. bytesperrow = (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  520. space_per_minheight += (long) bptr->maxaccess * bytesperrow;
  521. maximum_space += (long) bptr->rows_in_array * bytesperrow;
  522. }
  523. }
  524. if (space_per_minheight <= 0)
  525. return; /* no unrealized arrays, no work */
  526. /* Determine amount of memory to actually use; this is system-dependent. */
  527. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  528. (long) mem->total_space_allocated);
  529. /* If the maximum space needed is available, make all the buffers full
  530. * height; otherwise parcel it out with the same number of minheights
  531. * in each buffer.
  532. */
  533. if (avail_mem >= maximum_space)
  534. max_minheights = 1000000000L;
  535. else {
  536. max_minheights = avail_mem / space_per_minheight;
  537. /* If there doesn't seem to be enough space, try to get the minimum
  538. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  539. */
  540. if (max_minheights <= 0)
  541. max_minheights = 1;
  542. }
  543. /* Allocate the in-memory buffers and initialize backing store as needed. */
  544. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  545. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  546. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  547. if (minheights <= max_minheights) {
  548. /* This buffer fits in memory */
  549. sptr->rows_in_mem = sptr->rows_in_array;
  550. } else {
  551. /* It doesn't fit in memory, create backing store. */
  552. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  553. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  554. (long) sptr->rows_in_array *
  555. (long) sptr->samplesperrow *
  556. (long) SIZEOF(JSAMPLE));
  557. sptr->b_s_open = TRUE;
  558. }
  559. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  560. sptr->samplesperrow, sptr->rows_in_mem);
  561. sptr->rowsperchunk = mem->last_rowsperchunk;
  562. sptr->cur_start_row = 0;
  563. sptr->first_undef_row = 0;
  564. sptr->dirty = FALSE;
  565. }
  566. }
  567. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  568. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  569. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  570. if (minheights <= max_minheights) {
  571. /* This buffer fits in memory */
  572. bptr->rows_in_mem = bptr->rows_in_array;
  573. } else {
  574. /* It doesn't fit in memory, create backing store. */
  575. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  576. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  577. (long) bptr->rows_in_array *
  578. (long) bptr->blocksperrow *
  579. (long) SIZEOF(JBLOCK));
  580. bptr->b_s_open = TRUE;
  581. }
  582. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  583. bptr->blocksperrow, bptr->rows_in_mem);
  584. bptr->rowsperchunk = mem->last_rowsperchunk;
  585. bptr->cur_start_row = 0;
  586. bptr->first_undef_row = 0;
  587. bptr->dirty = FALSE;
  588. }
  589. }
  590. }
  591. LOCAL(void)
  592. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  593. /* Do backing store read or write of a virtual sample array */
  594. {
  595. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  596. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  597. file_offset = (long) ptr->cur_start_row * bytesperrow;
  598. /* Loop to read or write each allocation chunk in mem_buffer */
  599. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  600. /* One chunk, but check for short chunk at end of buffer */
  601. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  602. /* Transfer no more than is currently defined */
  603. thisrow = (long) ptr->cur_start_row + i;
  604. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  605. /* Transfer no more than fits in file */
  606. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  607. if (rows <= 0) /* this chunk might be past end of file! */
  608. break;
  609. byte_count = rows * bytesperrow;
  610. if (writing)
  611. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  612. (void FAR *) ptr->mem_buffer[i],
  613. file_offset, byte_count);
  614. else
  615. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  616. (void FAR *) ptr->mem_buffer[i],
  617. file_offset, byte_count);
  618. file_offset += byte_count;
  619. }
  620. }
  621. LOCAL(void)
  622. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  623. /* Do backing store read or write of a virtual coefficient-block array */
  624. {
  625. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  626. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  627. file_offset = (long) ptr->cur_start_row * bytesperrow;
  628. /* Loop to read or write each allocation chunk in mem_buffer */
  629. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  630. /* One chunk, but check for short chunk at end of buffer */
  631. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  632. /* Transfer no more than is currently defined */
  633. thisrow = (long) ptr->cur_start_row + i;
  634. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  635. /* Transfer no more than fits in file */
  636. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  637. if (rows <= 0) /* this chunk might be past end of file! */
  638. break;
  639. byte_count = rows * bytesperrow;
  640. if (writing)
  641. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  642. (void FAR *) ptr->mem_buffer[i],
  643. file_offset, byte_count);
  644. else
  645. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  646. (void FAR *) ptr->mem_buffer[i],
  647. file_offset, byte_count);
  648. file_offset += byte_count;
  649. }
  650. }
  651. METHODDEF(JSAMPARRAY)
  652. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  653. JDIMENSION start_row, JDIMENSION num_rows,
  654. boolean writable)
  655. /* Access the part of a virtual sample array starting at start_row */
  656. /* and extending for num_rows rows. writable is true if */
  657. /* caller intends to modify the accessed area. */
  658. {
  659. JDIMENSION end_row = start_row + num_rows;
  660. JDIMENSION undef_row;
  661. /* debugging check */
  662. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  663. ptr->mem_buffer == NULL)
  664. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  665. /* Make the desired part of the virtual array accessible */
  666. if (start_row < ptr->cur_start_row ||
  667. end_row > ptr->cur_start_row + ptr->rows_in_mem) {
  668. if (! ptr->b_s_open)
  669. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  670. /* Flush old buffer contents if necessary */
  671. if (ptr->dirty) {
  672. do_sarray_io(cinfo, ptr, TRUE);
  673. ptr->dirty = FALSE;
  674. }
  675. /* Decide what part of virtual array to access.
  676. * Algorithm: if target address > current window, assume forward scan,
  677. * load starting at target address. If target address < current window,
  678. * assume backward scan, load so that target area is top of window.
  679. * Note that when switching from forward write to forward read, will have
  680. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  681. */
  682. if (start_row > ptr->cur_start_row) {
  683. ptr->cur_start_row = start_row;
  684. } else {
  685. /* use long arithmetic here to avoid overflow & unsigned problems */
  686. long ltemp;
  687. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  688. if (ltemp < 0)
  689. ltemp = 0; /* don't fall off front end of file */
  690. ptr->cur_start_row = (JDIMENSION) ltemp;
  691. }
  692. /* Read in the selected part of the array.
  693. * During the initial write pass, we will do no actual read
  694. * because the selected part is all undefined.
  695. */
  696. do_sarray_io(cinfo, ptr, FALSE);
  697. }
  698. /* Ensure the accessed part of the array is defined; prezero if needed.
  699. * To improve locality of access, we only prezero the part of the array
  700. * that the caller is about to access, not the entire in-memory array.
  701. */
  702. if (ptr->first_undef_row < end_row) {
  703. if (ptr->first_undef_row < start_row) {
  704. if (writable) /* writer skipped over a section of array */
  705. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  706. undef_row = start_row; /* but reader is allowed to read ahead */
  707. } else {
  708. undef_row = ptr->first_undef_row;
  709. }
  710. if (writable)
  711. ptr->first_undef_row = end_row;
  712. if (ptr->pre_zero) {
  713. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  714. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  715. end_row -= ptr->cur_start_row;
  716. while (undef_row < end_row) {
  717. FMEMZERO((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  718. undef_row++;
  719. }
  720. } else {
  721. if (! writable) /* reader looking at undefined data */
  722. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  723. }
  724. }
  725. /* Flag the buffer dirty if caller will write in it */
  726. if (writable)
  727. ptr->dirty = TRUE;
  728. /* Return address of proper part of the buffer */
  729. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  730. }
  731. METHODDEF(JBLOCKARRAY)
  732. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  733. JDIMENSION start_row, JDIMENSION num_rows,
  734. boolean writable)
  735. /* Access the part of a virtual block array starting at start_row */
  736. /* and extending for num_rows rows. writable is true if */
  737. /* caller intends to modify the accessed area. */
  738. {
  739. JDIMENSION end_row = start_row + num_rows;
  740. JDIMENSION undef_row;
  741. /* debugging check */
  742. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  743. ptr->mem_buffer == NULL)
  744. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  745. /* Make the desired part of the virtual array accessible */
  746. if (start_row < ptr->cur_start_row ||
  747. end_row > ptr->cur_start_row + ptr->rows_in_mem) {
  748. if (! ptr->b_s_open)
  749. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  750. /* Flush old buffer contents if necessary */
  751. if (ptr->dirty) {
  752. do_barray_io(cinfo, ptr, TRUE);
  753. ptr->dirty = FALSE;
  754. }
  755. /* Decide what part of virtual array to access.
  756. * Algorithm: if target address > current window, assume forward scan,
  757. * load starting at target address. If target address < current window,
  758. * assume backward scan, load so that target area is top of window.
  759. * Note that when switching from forward write to forward read, will have
  760. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  761. */
  762. if (start_row > ptr->cur_start_row) {
  763. ptr->cur_start_row = start_row;
  764. } else {
  765. /* use long arithmetic here to avoid overflow & unsigned problems */
  766. long ltemp;
  767. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  768. if (ltemp < 0)
  769. ltemp = 0; /* don't fall off front end of file */
  770. ptr->cur_start_row = (JDIMENSION) ltemp;
  771. }
  772. /* Read in the selected part of the array.
  773. * During the initial write pass, we will do no actual read
  774. * because the selected part is all undefined.
  775. */
  776. do_barray_io(cinfo, ptr, FALSE);
  777. }
  778. /* Ensure the accessed part of the array is defined; prezero if needed.
  779. * To improve locality of access, we only prezero the part of the array
  780. * that the caller is about to access, not the entire in-memory array.
  781. */
  782. if (ptr->first_undef_row < end_row) {
  783. if (ptr->first_undef_row < start_row) {
  784. if (writable) /* writer skipped over a section of array */
  785. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  786. undef_row = start_row; /* but reader is allowed to read ahead */
  787. } else {
  788. undef_row = ptr->first_undef_row;
  789. }
  790. if (writable)
  791. ptr->first_undef_row = end_row;
  792. if (ptr->pre_zero) {
  793. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  794. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  795. end_row -= ptr->cur_start_row;
  796. while (undef_row < end_row) {
  797. FMEMZERO((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  798. undef_row++;
  799. }
  800. } else {
  801. if (! writable) /* reader looking at undefined data */
  802. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  803. }
  804. }
  805. /* Flag the buffer dirty if caller will write in it */
  806. if (writable)
  807. ptr->dirty = TRUE;
  808. /* Return address of proper part of the buffer */
  809. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  810. }
  811. /*
  812. * Release all objects belonging to a specified pool.
  813. */
  814. METHODDEF(void)
  815. free_pool (j_common_ptr cinfo, int pool_id)
  816. {
  817. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  818. small_pool_ptr shdr_ptr;
  819. large_pool_ptr lhdr_ptr;
  820. size_t space_freed;
  821. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  822. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  823. #ifdef MEM_STATS
  824. if (cinfo->err->trace_level > 1)
  825. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  826. #endif
  827. /* If freeing IMAGE pool, close any virtual arrays first */
  828. if (pool_id == JPOOL_IMAGE) {
  829. jvirt_sarray_ptr sptr;
  830. jvirt_barray_ptr bptr;
  831. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  832. if (sptr->b_s_open) { /* there may be no backing store */
  833. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  834. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  835. }
  836. }
  837. mem->virt_sarray_list = NULL;
  838. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  839. if (bptr->b_s_open) { /* there may be no backing store */
  840. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  841. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  842. }
  843. }
  844. mem->virt_barray_list = NULL;
  845. }
  846. /* Release large objects */
  847. lhdr_ptr = mem->large_list[pool_id];
  848. mem->large_list[pool_id] = NULL;
  849. while (lhdr_ptr != NULL) {
  850. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  851. space_freed = lhdr_ptr->hdr.bytes_used +
  852. lhdr_ptr->hdr.bytes_left +
  853. SIZEOF(large_pool_hdr);
  854. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  855. mem->total_space_allocated -= space_freed;
  856. lhdr_ptr = next_lhdr_ptr;
  857. }
  858. /* Release small objects */
  859. shdr_ptr = mem->small_list[pool_id];
  860. mem->small_list[pool_id] = NULL;
  861. while (shdr_ptr != NULL) {
  862. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  863. space_freed = shdr_ptr->hdr.bytes_used +
  864. shdr_ptr->hdr.bytes_left +
  865. SIZEOF(small_pool_hdr);
  866. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  867. mem->total_space_allocated -= space_freed;
  868. shdr_ptr = next_shdr_ptr;
  869. }
  870. }
  871. /*
  872. * Close up shop entirely.
  873. * Note that this cannot be called unless cinfo->mem is non-NULL.
  874. */
  875. METHODDEF(void)
  876. self_destruct (j_common_ptr cinfo)
  877. {
  878. int pool;
  879. /* Close all backing store, release all memory.
  880. * Releasing pools in reverse order might help avoid fragmentation
  881. * with some (brain-damaged) malloc libraries.
  882. */
  883. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  884. free_pool(cinfo, pool);
  885. }
  886. /* Release the memory manager control block too. */
  887. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  888. cinfo->mem = NULL; /* ensures I will be called only once */
  889. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  890. }
  891. /*
  892. * Memory manager initialization.
  893. * When this is called, only the error manager pointer is valid in cinfo!
  894. */
  895. GLOBAL(void)
  896. jinit_memory_mgr (j_common_ptr cinfo)
  897. {
  898. my_mem_ptr mem;
  899. long max_to_use;
  900. int pool;
  901. size_t test_mac;
  902. cinfo->mem = NULL; /* for safety if init fails */
  903. /* Check for configuration errors.
  904. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  905. * doesn't reflect any real hardware alignment requirement.
  906. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  907. * in common if and only if X is a power of 2, ie has only one one-bit.
  908. * Some compilers may give an "unreachable code" warning here; ignore it.
  909. */
  910. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  911. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  912. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  913. * a multiple of SIZEOF(ALIGN_TYPE).
  914. * Again, an "unreachable code" warning may be ignored here.
  915. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  916. */
  917. test_mac = (size_t) MAX_ALLOC_CHUNK;
  918. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  919. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  920. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  921. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  922. /* Attempt to allocate memory manager's control block */
  923. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  924. if (mem == NULL) {
  925. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  926. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  927. }
  928. /* OK, fill in the method pointers */
  929. mem->pub.alloc_small = alloc_small;
  930. mem->pub.alloc_large = alloc_large;
  931. mem->pub.alloc_sarray = alloc_sarray;
  932. mem->pub.alloc_barray = alloc_barray;
  933. mem->pub.request_virt_sarray = request_virt_sarray;
  934. mem->pub.request_virt_barray = request_virt_barray;
  935. mem->pub.realize_virt_arrays = realize_virt_arrays;
  936. mem->pub.access_virt_sarray = access_virt_sarray;
  937. mem->pub.access_virt_barray = access_virt_barray;
  938. mem->pub.free_pool = free_pool;
  939. mem->pub.self_destruct = self_destruct;
  940. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  941. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  942. /* Initialize working state */
  943. mem->pub.max_memory_to_use = max_to_use;
  944. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  945. mem->small_list[pool] = NULL;
  946. mem->large_list[pool] = NULL;
  947. }
  948. mem->virt_sarray_list = NULL;
  949. mem->virt_barray_list = NULL;
  950. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  951. /* Declare ourselves open for business */
  952. cinfo->mem = &mem->pub;
  953. /* Check for an environment variable JPEGMEM; if found, override the
  954. * default max_memory setting from jpeg_mem_init. Note that the
  955. * surrounding application may again override this value.
  956. * If your system doesn't support getenv(), define NO_GETENV to disable
  957. * this feature.
  958. */
  959. #ifndef NO_GETENV
  960. { char * memenv;
  961. if ((memenv = getenv("JPEGMEM")) != NULL) {
  962. char ch = 'x';
  963. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  964. if (ch == 'm' || ch == 'M')
  965. max_to_use *= 1000L;
  966. mem->pub.max_memory_to_use = max_to_use * 1000L;
  967. }
  968. }
  969. }
  970. #endif
  971. }