You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

jmemmgr.c 41KB

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